Skip to content

Commit 4806fb2

Browse files
author
Ulrik Sverdrup
committed
typeck: Make sure casts to or from fat pointers are illegal
Fixes ICEs where non-fat pointers and scalars are cast to fat pointers, Fixes #21397 Fixes #22955 Fixes #23237 Fixes #24100
1 parent 2568a4d commit 4806fb2

File tree

4 files changed

+23
-10
lines changed

4 files changed

+23
-10
lines changed

src/librustc_typeck/check/cast.rs

+3-2
Original file line numberDiff line numberDiff line change
@@ -170,9 +170,10 @@ pub fn check_cast<'a, 'tcx>(fcx: &FnCtxt<'a, 'tcx>, cast: &CastCheck<'tcx>) {
170170
demand::coerce(fcx, e.span, t_1, &e);
171171
}
172172
}
173-
} else if fcx.type_is_fat_ptr(t_e, span) && !fcx.type_is_fat_ptr(t_1, span) {
173+
} else if fcx.type_is_fat_ptr(t_e, span) != fcx.type_is_fat_ptr(t_1, span) {
174174
fcx.type_error_message(span, |actual| {
175-
format!("illegal cast; cast from fat pointer: `{}` as `{}`",
175+
format!("illegal cast; cast to or from fat pointer: `{}` as `{}` \
176+
involving incompatible type.",
176177
actual, fcx.infcx().ty_to_string(t_1))
177178
}, t_e, None);
178179
} else if !(t_e_is_scalar && t_1_is_trivial) {

src/test/compile-fail/fat-ptr-cast.rs

+15-3
Original file line numberDiff line numberDiff line change
@@ -8,12 +8,24 @@
88
// option. This file may not be copied, modified, or distributed
99
// except according to those terms.
1010

11+
// Make sure casts between thin pointer <-> fat pointer are illegal.
12+
13+
pub trait Trait {}
14+
1115
fn main() {
1216
let a: &[i32] = &[1, 2, 3];
1317
let b: Box<[i32]> = Box::new([1, 2, 3]);
1418
let p = a as *const [i32];
19+
let q = a.as_ptr();
20+
21+
a as usize; //~ ERROR illegal cast
22+
b as usize; //~ ERROR illegal cast
23+
p as usize; //~ ERROR illegal cast
24+
25+
// #22955
26+
q as *const [i32]; //~ ERROR illegal cast
1527

16-
a as usize; //~ ERROR cast from fat pointer
17-
b as usize; //~ ERROR cast from fat pointer
18-
p as usize; //~ ERROR cast from fat pointer
28+
// #21397
29+
let t: *mut (Trait + 'static) = 0 as *mut _; //~ ERROR illegal cast
30+
let mut fail: *const str = 0 as *const str; //~ ERROR illegal cast
1931
}

src/test/compile-fail/issue-22034.rs

+4-4
Original file line numberDiff line numberDiff line change
@@ -11,9 +11,9 @@
1111
extern crate libc;
1212

1313
fn main() {
14-
let foo: *mut libc::c_void;
15-
let cb: &mut Fn() = unsafe {
16-
&mut *(foo as *mut Fn())
17-
//~^ ERROR use of possibly uninitialized variable: `foo`
14+
let ptr: *mut () = 0 as *mut _;
15+
let _: &mut Fn() = unsafe {
16+
&mut *(ptr as *mut Fn())
17+
//~^ ERROR illegal cast
1818
};
1919
}

src/test/compile-fail/issue-22289.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -9,5 +9,5 @@
99
// except according to those terms.
1010

1111
fn main() {
12-
0 as &std::any::Any; //~ ERROR non-scalar cast: `i32` as `&core::any::Any`
12+
0 as &std::any::Any; //~ ERROR illegal cast
1313
}

0 commit comments

Comments
 (0)