Skip to content

Commit 03d4d5f

Browse files
committed
Fix a bunch of bugs
* segfault due to not copying drop flag when coercing * fat pointer casts * segfault due to not checking drop flag properly * debuginfo for DST smart pointers * unreachable code in drop glue
1 parent 7d95353 commit 03d4d5f

File tree

10 files changed

+114
-54
lines changed

10 files changed

+114
-54
lines changed

src/liballoc/rc.rs

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -544,7 +544,8 @@ impl<T: ?Sized> Drop for Rc<T> {
544544
fn drop(&mut self) {
545545
unsafe {
546546
let ptr = *self._ptr;
547-
if !(*(&ptr as *const _ as *const *const ())).is_null() {
547+
if !(*(&ptr as *const _ as *const *const ())).is_null() &&
548+
ptr as usize != mem::POST_DROP_USIZE {
548549
self.dec_strong();
549550
if self.strong() == 0 {
550551
// destroy the contained object
@@ -1010,7 +1011,8 @@ impl<T: ?Sized> Drop for Weak<T> {
10101011
fn drop(&mut self) {
10111012
unsafe {
10121013
let ptr = *self._ptr;
1013-
if !(*(&ptr as *const _ as *const *const ())).is_null() {
1014+
if !(*(&ptr as *const _ as *const *const ())).is_null() &&
1015+
ptr as usize != mem::POST_DROP_USIZE {
10141016
self.dec_weak();
10151017
// the weak count starts at 1, and will only go to zero if all
10161018
// the strong pointers have disappeared.

src/librustc/middle/ty.rs

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -5606,8 +5606,7 @@ impl DtorKind {
56065606
}
56075607
}
56085608

5609-
/* If struct_id names a struct with a dtor, return Some(the dtor's id).
5610-
Otherwise return none. */
5609+
/* If struct_id names a struct with a dtor. */
56115610
pub fn ty_dtor(cx: &ctxt, struct_id: DefId) -> DtorKind {
56125611
match cx.destructor_for_type.borrow().get(&struct_id) {
56135612
Some(&method_def_id) => {

src/librustc_trans/trans/adt.rs

Lines changed: 9 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -141,7 +141,8 @@ pub fn represent_node<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
141141

142142
/// Decides how to represent a given type.
143143
pub fn represent_type<'a, 'tcx>(cx: &CrateContext<'a, 'tcx>,
144-
t: Ty<'tcx>) -> Rc<Repr<'tcx>> {
144+
t: Ty<'tcx>)
145+
-> Rc<Repr<'tcx>> {
145146
debug!("Representing: {}", ty_to_string(cx.tcx(), t));
146147
match cx.adt_reprs().borrow().get(&t) {
147148
Some(repr) => return repr.clone(),
@@ -216,7 +217,9 @@ fn represent_type_uncached<'a, 'tcx>(cx: &CrateContext<'a, 'tcx>,
216217
}).collect::<Vec<_>>();
217218
let packed = ty::lookup_packed(cx.tcx(), def_id);
218219
let dtor = ty::ty_dtor(cx.tcx(), def_id).has_drop_flag();
219-
if dtor { ftys.push(cx.tcx().dtor_type()); }
220+
if dtor {
221+
ftys.push(cx.tcx().dtor_type());
222+
}
220223

221224
Univariant(mk_struct(cx, &ftys[..], packed, t), dtor_to_init_u8(dtor))
222225
}
@@ -517,8 +520,7 @@ fn mk_struct<'a, 'tcx>(cx: &CrateContext<'a, 'tcx>,
517520
-> Struct<'tcx> {
518521
let sized = tys.iter().all(|&ty| type_is_sized(cx.tcx(), ty));
519522
let lltys : Vec<Type> = if sized {
520-
tys.iter()
521-
.map(|&ty| type_of::sizing_type_of(cx, ty)).collect()
523+
tys.iter().map(|&ty| type_of::sizing_type_of(cx, ty)).collect()
522524
} else {
523525
tys.iter().filter(|&ty| type_is_sized(cx.tcx(), *ty))
524526
.map(|&ty| type_of::sizing_type_of(cx, ty)).collect()
@@ -1060,7 +1062,9 @@ pub fn fold_variants<'blk, 'tcx, F>(bcx: Block<'blk, 'tcx>,
10601062
}
10611063

10621064
/// Access the struct drop flag, if present.
1063-
pub fn trans_drop_flag_ptr<'blk, 'tcx>(mut bcx: Block<'blk, 'tcx>, r: &Repr<'tcx>, val: ValueRef)
1065+
pub fn trans_drop_flag_ptr<'blk, 'tcx>(mut bcx: Block<'blk, 'tcx>,
1066+
r: &Repr<'tcx>,
1067+
val: ValueRef)
10641068
-> datum::DatumBlock<'blk, 'tcx, datum::Expr>
10651069
{
10661070
let tcx = bcx.tcx();

src/librustc_trans/trans/expr.rs

Lines changed: 32 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -58,7 +58,7 @@ use middle::check_const;
5858
use middle::def;
5959
use middle::lang_items::CoerceUnsizedTraitLangItem;
6060
use middle::mem_categorization::Typer;
61-
use middle::subst::{Subst, Substs, VecPerParamSpace};
61+
use middle::subst::{Substs, VecPerParamSpace};
6262
use middle::traits;
6363
use trans::{_match, adt, asm, base, callee, closure, consts, controlflow};
6464
use trans::base::*;
@@ -476,8 +476,8 @@ fn coerce_unsized<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
476476
}
477477

478478
// This can be extended to enums and tuples in the future.
479-
// (&ty::ty_enum(def_id_a, substs_a), &ty::ty_enum(def_id_b, substs_b)) |
480-
(&ty::ty_struct(def_id_a, substs_a), &ty::ty_struct(def_id_b, substs_b)) => {
479+
// (&ty::ty_enum(def_id_a, _), &ty::ty_enum(def_id_b, _)) |
480+
(&ty::ty_struct(def_id_a, _), &ty::ty_struct(def_id_b, _)) => {
481481
assert_eq!(def_id_a, def_id_b);
482482

483483
// The target is already by-ref because it's to be written to.
@@ -504,35 +504,41 @@ fn coerce_unsized<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
504504
};
505505

506506
let repr_source = adt::represent_type(bcx.ccx(), source.ty);
507+
let src_fields = match &*repr_source {
508+
&adt::Repr::Univariant(ref s, _) => &s.fields,
509+
_ => bcx.sess().span_bug(span,
510+
&format!("Non univariant struct? (repr_source: {:?})",
511+
repr_source)),
512+
};
507513
let repr_target = adt::represent_type(bcx.ccx(), target.ty);
508-
let fields = ty::lookup_struct_fields(bcx.tcx(), def_id_a);
514+
let target_fields = match &*repr_target {
515+
&adt::Repr::Univariant(ref s, _) => &s.fields,
516+
_ => bcx.sess().span_bug(span,
517+
&format!("Non univariant struct? (repr_target: {:?})",
518+
repr_target)),
519+
};
509520

510521
let coerce_index = match kind {
511522
ty::CustomCoerceUnsized::Struct(i) => i
512523
};
513-
assert!(coerce_index < fields.len());
524+
assert!(coerce_index < src_fields.len() && src_fields.len() == target_fields.len());
514525

515-
for (i, field) in fields.iter().enumerate() {
526+
let iter = src_fields.iter().zip(target_fields.iter()).enumerate();
527+
for (i, (src_ty, target_ty)) in iter {
516528
let ll_source = adt::trans_field_ptr(bcx, &repr_source, source.val, 0, i);
517529
let ll_target = adt::trans_field_ptr(bcx, &repr_target, target.val, 0, i);
518530

519-
let ty = ty::lookup_field_type_unsubstituted(bcx.tcx(),
520-
def_id_a,
521-
field.id);
522-
let field_source = ty.subst(bcx.tcx(), substs_a);
523-
let field_target = ty.subst(bcx.tcx(), substs_b);
524-
525531
// If this is the field we need to coerce, recurse on it.
526532
if i == coerce_index {
527533
coerce_unsized(bcx, span,
528-
Datum::new(ll_source, field_source,
534+
Datum::new(ll_source, src_ty,
529535
Rvalue::new(ByRef)),
530-
Datum::new(ll_target, field_target,
536+
Datum::new(ll_target, target_ty,
531537
Rvalue::new(ByRef)));
532538
} else {
533539
// Otherwise, simply copy the data from the source.
534-
assert_eq!(field_source, field_target);
535-
memcpy_ty(bcx, ll_target, ll_source, field_source);
540+
assert_eq!(src_ty, target_ty);
541+
memcpy_ty(bcx, ll_target, ll_source, src_ty);
536542
}
537543
}
538544
}
@@ -2013,6 +2019,7 @@ fn float_cast(bcx: Block,
20132019
#[derive(Copy, Clone, PartialEq, Debug)]
20142020
pub enum cast_kind {
20152021
cast_pointer,
2022+
cast_fat_ptr,
20162023
cast_integral,
20172024
cast_float,
20182025
cast_enum,
@@ -2027,7 +2034,7 @@ pub fn cast_type_kind<'tcx>(tcx: &ty::ctxt<'tcx>, t: Ty<'tcx>) -> cast_kind {
20272034
if type_is_sized(tcx, mt.ty) {
20282035
cast_pointer
20292036
} else {
2030-
cast_other
2037+
cast_fat_ptr
20312038
}
20322039
}
20332040
ty::ty_bare_fn(..) => cast_pointer,
@@ -2103,10 +2110,18 @@ fn trans_imm_cast<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
21032110
let llexpr = datum.to_llscalarish(bcx);
21042111
PtrToInt(bcx, llexpr, ll_t_out)
21052112
}
2113+
(cast_fat_ptr, cast_integral) => {
2114+
let data_ptr = Load(bcx, get_dataptr(bcx, datum.val));
2115+
PtrToInt(bcx, data_ptr, ll_t_out)
2116+
}
21062117
(cast_pointer, cast_pointer) => {
21072118
let llexpr = datum.to_llscalarish(bcx);
21082119
PointerCast(bcx, llexpr, ll_t_out)
21092120
}
2121+
(cast_fat_ptr, cast_pointer) => {
2122+
let data_ptr = Load(bcx, get_dataptr(bcx, datum.val));
2123+
PointerCast(bcx, data_ptr, ll_t_out)
2124+
}
21102125
(cast_enum, cast_integral) |
21112126
(cast_enum, cast_float) => {
21122127
let mut bcx = bcx;

src/librustc_trans/trans/glue.rs

Lines changed: 4 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -278,18 +278,14 @@ fn get_drop_glue_core<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>,
278278

279279
fn trans_struct_drop_flag<'blk, 'tcx>(mut bcx: Block<'blk, 'tcx>,
280280
t: Ty<'tcx>,
281-
v0: ValueRef,
281+
struct_data: ValueRef,
282282
dtor_did: ast::DefId,
283283
class_did: ast::DefId,
284284
substs: &subst::Substs<'tcx>)
285285
-> Block<'blk, 'tcx> {
286+
assert!(type_is_sized(bcx.tcx(), t), "Precondition: caller must ensure t is sized");
287+
286288
let repr = adt::represent_type(bcx.ccx(), t);
287-
let struct_data = if type_is_sized(bcx.tcx(), t) {
288-
v0
289-
} else {
290-
let llval = GEPi(bcx, v0, &[0, abi::FAT_PTR_ADDR]);
291-
Load(bcx, llval)
292-
};
293289
let drop_flag = unpack_datum!(bcx, adt::trans_drop_flag_ptr(bcx, &*repr, struct_data));
294290
let loaded = load_ty(bcx, drop_flag.val, bcx.tcx().dtor_type());
295291
let drop_flag_llty = type_of(bcx.fcx.ccx, bcx.tcx().dtor_type());
@@ -313,9 +309,8 @@ fn trans_struct_drop_flag<'blk, 'tcx>(mut bcx: Block<'blk, 'tcx>,
313309

314310
let drop_flag_dtor_needed = ICmp(bcx, llvm::IntEQ, loaded, init_val, DebugLoc::None);
315311
with_cond(bcx, drop_flag_dtor_needed, |cx| {
316-
trans_struct_drop(cx, t, v0, dtor_did, class_did, substs)
312+
trans_struct_drop(cx, t, struct_data, dtor_did, class_did, substs)
317313
})
318-
319314
}
320315

321316
pub fn get_res_dtor<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>,

src/librustc_trans/trans/machine.rs

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -101,7 +101,8 @@ pub fn llalign_of_min(cx: &CrateContext, ty: Type) -> llalign {
101101

102102
pub fn llelement_offset(cx: &CrateContext, struct_ty: Type, element: usize) -> u64 {
103103
unsafe {
104-
return llvm::LLVMOffsetOfElement(cx.td().lltd, struct_ty.to_ref(),
104+
return llvm::LLVMOffsetOfElement(cx.td().lltd,
105+
struct_ty.to_ref(),
105106
element as u32);
106107
}
107108
}

src/librustc_typeck/check/cast.rs

Lines changed: 8 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -99,6 +99,7 @@ pub fn check_cast<'a, 'tcx>(fcx: &FnCtxt<'a, 'tcx>, cast: &CastCheck<'tcx>) {
9999
let t_1_is_bare_fn = ty::type_is_bare_fn(t_1);
100100
let t_1_is_float = ty::type_is_floating_point(t_1);
101101
let t_1_is_c_enum = ty::type_is_c_like_enum(fcx.tcx(), t_1);
102+
let t1_is_fat_ptr = fcx.type_is_fat_ptr(t_1, span);
102103

103104
// casts to scalars other than `char` and `bare fn` are trivial
104105
let t_1_is_trivial = t_1_is_scalar && !t_1_is_char && !t_1_is_bare_fn;
@@ -170,18 +171,16 @@ pub fn check_cast<'a, 'tcx>(fcx: &FnCtxt<'a, 'tcx>, cast: &CastCheck<'tcx>) {
170171
demand::coerce(fcx, e.span, t_1, &e);
171172
}
172173
}
173-
} else if fcx.type_is_fat_ptr(t_e, span) != fcx.type_is_fat_ptr(t_1, span) {
174+
} else if t1_is_fat_ptr {
175+
// FIXME This should be allowed where the lefthandside is also a fat
176+
// pointer and is the same kind of fat pointer, i.e., array to array,
177+
// trait object to trait object.
174178
fcx.type_error_message(span, |actual| {
175-
format!("illegal cast; cast to or from fat pointer: `{}` as `{}` \
176-
involving incompatible type.",
177-
actual, fcx.infcx().ty_to_string(t_1))
179+
format!("cast to fat pointer: `{}` as `{}`",
180+
actual,
181+
fcx.infcx().ty_to_string(t_1))
178182
}, t_e, None);
179183
} else if !(t_e_is_scalar && t_1_is_trivial) {
180-
/*
181-
If more type combinations should be supported than are
182-
supported here, then file an enhancement issue and
183-
record the issue number in this comment.
184-
*/
185184
fcx.type_error_message(span, |actual| {
186185
format!("non-scalar cast: `{}` as `{}`",
187186
actual,

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

Lines changed: 4 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -15,17 +15,13 @@ pub trait Trait {}
1515
fn main() {
1616
let a: &[i32] = &[1, 2, 3];
1717
let b: Box<[i32]> = Box::new([1, 2, 3]);
18-
let p = a as *const [i32];
19-
let q = a.as_ptr();
2018

2119
a as usize; //~ ERROR illegal cast
2220
b as usize; //~ ERROR illegal cast
23-
p as usize; //~ ERROR illegal cast
2421

25-
// #22955
26-
q as *const [i32]; //~ ERROR illegal cast
22+
let a: usize = 42;
23+
a as *const [i32]; //~ ERROR cast to fat pointer: `usize` as `*const [i32]`
2724

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
25+
let a: *const u8 = &42;
26+
a as *const [u8]; //~ ERROR cast to fat pointer: `*const u8` as `*const [u8]`
3127
}

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

Lines changed: 1 addition & 1 deletion
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 illegal cast
12+
0 as &std::any::Any; //~ ERROR cast to fat pointer: `i32` as `&core::any::Any`
1313
}

src/test/run-pass/fat-ptr-cast.rs

Lines changed: 49 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,49 @@
1+
// Copyright 2015 The Rust Project Developers. See the COPYRIGHT
2+
// file at the top-level directory of this distribution and at
3+
// http://rust-lang.org/COPYRIGHT.
4+
//
5+
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6+
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7+
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8+
// option. This file may not be copied, modified, or distributed
9+
// except according to those terms.
10+
11+
#![feature(core)]
12+
13+
use std::mem;
14+
use std::raw;
15+
16+
trait Foo {
17+
fn foo(&self) {}
18+
}
19+
20+
struct Bar;
21+
22+
impl Foo for Bar {}
23+
24+
fn main() {
25+
// Test we can turn a fat pointer to array back into a thin pointer.
26+
let a: *const [i32] = &[1, 2, 3];
27+
let b = a as *const [i32; 2];
28+
unsafe {
29+
assert!(*b == [1, 2]);
30+
}
31+
32+
// Test conversion to an address (usize).
33+
let a: *const [i32; 3] = &[1, 2, 3];
34+
let b: *const [i32] = a;
35+
assert!(a as usize == b as usize);
36+
37+
// And conversion to a void pointer/address for trait objects too.
38+
let a: *mut Foo = &mut Bar;
39+
let b = a as *mut ();
40+
let c = a as usize;
41+
42+
let d = unsafe {
43+
let r: raw::TraitObject = mem::transmute(a);
44+
r.data
45+
};
46+
47+
assert!(b == d);
48+
assert!(c == d as usize);
49+
}

0 commit comments

Comments
 (0)