Skip to content

Commit e67a2cf

Browse files
committed
CFI: Rewrite closure and coroutine instances to their trait method
Similar to methods on a trait object, the most common way to indirectly call a closure or coroutine is through the vtable on the appropriate trait. This uses the same approach as we use for trait methods, after backing out the trait arguments from the type.
1 parent 767f963 commit e67a2cf

File tree

5 files changed

+197
-54
lines changed

5 files changed

+197
-54
lines changed

compiler/rustc_symbol_mangling/src/typeid/typeid_itanium_cxx_abi.rs

+81-32
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,7 @@
1010
use rustc_data_structures::base_n;
1111
use rustc_data_structures::fx::FxHashMap;
1212
use rustc_hir as hir;
13+
use rustc_hir::lang_items::LangItem;
1314
use rustc_middle::ty::layout::IntegerExt;
1415
use rustc_middle::ty::TypeVisitableExt;
1516
use rustc_middle::ty::{
@@ -1161,43 +1162,91 @@ pub fn typeid_for_instance<'tcx>(
11611162
};
11621163
let stripped_ty = strip_receiver_auto(tcx, upcast_ty);
11631164
instance.args = tcx.mk_args_trait(stripped_ty, instance.args.into_iter().skip(1));
1165+
} else if let ty::InstanceDef::VTableShim(def_id) = instance.def
1166+
&& let Some(trait_id) = tcx.trait_of_item(def_id)
1167+
{
1168+
// VTableShims may have a trait method, but a concrete Self. This is not suitable for a vtable,
1169+
// as the caller will not know the concrete Self.
1170+
let trait_ref = ty::TraitRef::new(tcx, trait_id, instance.args);
1171+
let invoke_ty = trait_object_ty(tcx, ty::Binder::dummy(trait_ref));
1172+
instance.args = tcx.mk_args_trait(invoke_ty, trait_ref.args.into_iter().skip(1));
11641173
}
11651174

1166-
if !options.contains(EncodeTyOptions::NO_SELF_TYPE_ERASURE)
1167-
&& let Some(impl_id) = tcx.impl_of_method(instance.def_id())
1168-
&& let Some(trait_ref) = tcx.impl_trait_ref(impl_id)
1169-
{
1170-
let impl_method = tcx.associated_item(instance.def_id());
1171-
let method_id = impl_method
1172-
.trait_item_def_id
1173-
.expect("Part of a trait implementation, but not linked to the def_id?");
1174-
let trait_method = tcx.associated_item(method_id);
1175-
let trait_id = trait_ref.skip_binder().def_id;
1176-
if traits::is_vtable_safe_method(tcx, trait_id, trait_method)
1177-
&& tcx.object_safety_violations(trait_id).is_empty()
1175+
if !options.contains(EncodeTyOptions::NO_SELF_TYPE_ERASURE) {
1176+
if let Some(impl_id) = tcx.impl_of_method(instance.def_id())
1177+
&& let Some(trait_ref) = tcx.impl_trait_ref(impl_id)
11781178
{
1179-
// Trait methods will have a Self polymorphic parameter, where the concreteized
1180-
// implementatation will not. We need to walk back to the more general trait method
1181-
let trait_ref = tcx.instantiate_and_normalize_erasing_regions(
1182-
instance.args,
1183-
ty::ParamEnv::reveal_all(),
1184-
trait_ref,
1185-
);
1179+
let impl_method = tcx.associated_item(instance.def_id());
1180+
let method_id = impl_method
1181+
.trait_item_def_id
1182+
.expect("Part of a trait implementation, but not linked to the def_id?");
1183+
let trait_method = tcx.associated_item(method_id);
1184+
let trait_id = trait_ref.skip_binder().def_id;
1185+
if traits::is_vtable_safe_method(tcx, trait_id, trait_method)
1186+
&& tcx.object_safety_violations(trait_id).is_empty()
1187+
{
1188+
// Trait methods will have a Self polymorphic parameter, where the concreteized
1189+
// implementatation will not. We need to walk back to the more general trait method
1190+
let trait_ref = tcx.instantiate_and_normalize_erasing_regions(
1191+
instance.args,
1192+
ty::ParamEnv::reveal_all(),
1193+
trait_ref,
1194+
);
1195+
let invoke_ty = trait_object_ty(tcx, ty::Binder::dummy(trait_ref));
1196+
1197+
// At the call site, any call to this concrete function through a vtable will be
1198+
// `Virtual(method_id, idx)` with appropriate arguments for the method. Since we have the
1199+
// original method id, and we've recovered the trait arguments, we can make the callee
1200+
// instance we're computing the alias set for match the caller instance.
1201+
//
1202+
// Right now, our code ignores the vtable index everywhere, so we use 0 as a placeholder.
1203+
// If we ever *do* start encoding the vtable index, we will need to generate an alias set
1204+
// based on which vtables we are putting this method into, as there will be more than one
1205+
// index value when supertraits are involved.
1206+
instance.def = ty::InstanceDef::Virtual(method_id, 0);
1207+
let abstract_trait_args =
1208+
tcx.mk_args_trait(invoke_ty, trait_ref.args.into_iter().skip(1));
1209+
instance.args = instance.args.rebase_onto(tcx, impl_id, abstract_trait_args);
1210+
}
1211+
} else if tcx.is_closure_like(instance.def_id()) {
1212+
// We're either a closure or a coroutine. Our goal is to find the trait we're defined on,
1213+
// instantiate it, and take the type of its only method as our own.
1214+
let closure_ty = instance.ty(tcx, ty::ParamEnv::reveal_all());
1215+
let (trait_id, inputs) = match closure_ty.kind() {
1216+
ty::Closure(..) => {
1217+
let closure_args = instance.args.as_closure();
1218+
let trait_id = tcx.fn_trait_kind_to_def_id(closure_args.kind()).unwrap();
1219+
let tuple_args =
1220+
tcx.instantiate_bound_regions_with_erased(closure_args.sig()).inputs()[0];
1221+
(trait_id, tuple_args)
1222+
}
1223+
ty::Coroutine(..) => (
1224+
tcx.require_lang_item(LangItem::Coroutine, None),
1225+
instance.args.as_coroutine().resume_ty(),
1226+
),
1227+
ty::CoroutineClosure(..) => (
1228+
tcx.require_lang_item(LangItem::FnOnce, None),
1229+
tcx.instantiate_bound_regions_with_erased(
1230+
instance.args.as_coroutine_closure().coroutine_closure_sig(),
1231+
)
1232+
.tupled_inputs_ty,
1233+
),
1234+
x => bug!("Unexpected type kind for closure-like: {x:?}"),
1235+
};
1236+
let trait_ref = ty::TraitRef::new(tcx, trait_id, [closure_ty, inputs]);
11861237
let invoke_ty = trait_object_ty(tcx, ty::Binder::dummy(trait_ref));
1238+
let abstract_args = tcx.mk_args_trait(invoke_ty, trait_ref.args.into_iter().skip(1));
1239+
// There should be exactly one method on this trait, and it should be the one we're
1240+
// defining.
1241+
let call = tcx
1242+
.associated_items(trait_id)
1243+
.in_definition_order()
1244+
.find(|it| it.kind == ty::AssocKind::Fn)
1245+
.expect("No call-family function on closure-like Fn trait?")
1246+
.def_id;
11871247

1188-
// At the call site, any call to this concrete function through a vtable will be
1189-
// `Virtual(method_id, idx)` with appropriate arguments for the method. Since we have the
1190-
// original method id, and we've recovered the trait arguments, we can make the callee
1191-
// instance we're computing the alias set for match the caller instance.
1192-
//
1193-
// Right now, our code ignores the vtable index everywhere, so we use 0 as a placeholder.
1194-
// If we ever *do* start encoding the vtable index, we will need to generate an alias set
1195-
// based on which vtables we are putting this method into, as there will be more than one
1196-
// index value when supertraits are involved.
1197-
instance.def = ty::InstanceDef::Virtual(method_id, 0);
1198-
let abstract_trait_args =
1199-
tcx.mk_args_trait(invoke_ty, trait_ref.args.into_iter().skip(1));
1200-
instance.args = instance.args.rebase_onto(tcx, impl_id, abstract_trait_args);
1248+
instance.def = ty::InstanceDef::Virtual(call, 0);
1249+
instance.args = abstract_args;
12011250
}
12021251
}
12031252

tests/ui/sanitizer/cfi-async-closures.rs

+3
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,7 @@
1010
//@ [cfi] compile-flags: -C codegen-units=1 -C lto -C prefer-dynamic=off -C opt-level=0
1111
//@ [cfi] compile-flags: -Z sanitizer=cfi
1212
//@ [kcfi] compile-flags: -Z sanitizer=kcfi
13+
//@ [kcfi] compile-flags: -C panic=abort -Z panic-abort-tests -C prefer-dynamic=off
1314
//@ run-pass
1415

1516
#![feature(async_closure)]
@@ -27,4 +28,6 @@ fn main() {
2728
let f = identity(async || ());
2829
let _ = f.async_call(());
2930
let _ = f();
31+
let g: Box<dyn FnOnce() -> _> = Box::new(f) as _;
32+
let _ = g();
3033
}

tests/ui/sanitizer/cfi-closure-fn-ptr-cast.rs

-22
This file was deleted.

tests/ui/sanitizer/cfi-closures.rs

+83
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,83 @@
1+
// Check various forms of dynamic closure calls
2+
3+
//@ revisions: cfi kcfi
4+
// FIXME(#122848) Remove only-linux once OSX CFI binaries work
5+
//@ only-linux
6+
//@ [cfi] needs-sanitizer-cfi
7+
//@ [kcfi] needs-sanitizer-kcfi
8+
//@ compile-flags: -C target-feature=-crt-static
9+
//@ [cfi] compile-flags: -C codegen-units=1 -C lto -C prefer-dynamic=off -C opt-level=0
10+
//@ [cfi] compile-flags: -Z sanitizer=cfi
11+
//@ [kcfi] compile-flags: -Z sanitizer=kcfi
12+
//@ [kcfi] compile-flags: -C panic=abort -Z panic-abort-tests -C prefer-dynamic=off
13+
//@ compile-flags: --test
14+
//@ run-pass
15+
16+
#![feature(fn_traits)]
17+
#![feature(unboxed_closures)]
18+
#![feature(cfg_sanitize)]
19+
20+
fn foo<'a, T>() -> Box<dyn Fn(&'a T) -> &'a T> {
21+
Box::new(|x| x)
22+
}
23+
24+
#[test]
25+
fn dyn_fn_with_params() {
26+
let x = 3;
27+
let f = foo();
28+
f(&x);
29+
// FIXME remove once drops are working.
30+
std::mem::forget(f);
31+
}
32+
33+
#[test]
34+
fn call_fn_trait() {
35+
let f: &(dyn Fn()) = &(|| {}) as _;
36+
f.call(());
37+
}
38+
39+
#[test]
40+
fn fn_ptr_cast() {
41+
let f: &fn() = &((|| ()) as _);
42+
f();
43+
}
44+
45+
fn use_fnmut<F: FnMut()>(mut f: F) {
46+
f()
47+
}
48+
49+
#[test]
50+
fn fn_to_fnmut() {
51+
let f: &(dyn Fn()) = &(|| {}) as _;
52+
use_fnmut(f);
53+
}
54+
55+
fn hrtb_helper(f: &dyn for<'a> Fn(&'a usize)) {
56+
f(&10)
57+
}
58+
59+
#[test]
60+
fn hrtb_fn() {
61+
hrtb_helper((&|x: &usize| println!("{}", *x)) as _)
62+
}
63+
64+
#[test]
65+
fn fnonce() {
66+
let f: Box<dyn FnOnce()> = Box::new(|| {}) as _;
67+
f();
68+
}
69+
70+
fn use_closure<C>(call: extern "rust-call" fn(&C, ()) -> i32, f: &C) -> i32 {
71+
call(f, ())
72+
}
73+
74+
#[test]
75+
// FIXME after KCFI reify support is added, remove this
76+
// It will appear to work if you test locally, set -C opt-level=0 to see it fail.
77+
#[cfg_attr(sanitize = "kcfi", ignore)]
78+
fn closure_addr_taken() {
79+
let x = 3i32;
80+
let f = || x;
81+
let call = Fn::<()>::call;
82+
use_closure(call, &f);
83+
}

tests/ui/sanitizer/cfi-coroutine.rs

+30
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
// Verifies that we can call dynamic coroutines
2+
3+
//@ revisions: cfi kcfi
4+
// FIXME(#122848) Remove only-linux once OSX CFI binaries work
5+
//@ only-linux
6+
//@ [cfi] needs-sanitizer-cfi
7+
//@ [kcfi] needs-sanitizer-kcfi
8+
//@ compile-flags: -C target-feature=-crt-static
9+
//@ [cfi] compile-flags: -C codegen-units=1 -C lto -C prefer-dynamic=off -C opt-level=0
10+
//@ [cfi] compile-flags: -Z sanitizer=cfi
11+
//@ [kcfi] compile-flags: -Z sanitizer=kcfi
12+
//@ [kcfi] compile-flags: -C panic=abort -Z panic-abort-tests -C prefer-dynamic=off
13+
//@ compile-flags: --test
14+
//@ run-pass
15+
16+
#![feature(coroutines)]
17+
#![feature(coroutine_trait)]
18+
19+
use std::ops::{Coroutine, CoroutineState};
20+
use std::pin::{pin, Pin};
21+
22+
fn main() {
23+
let mut coro = |x: i32| {
24+
yield x;
25+
"done"
26+
};
27+
let mut abstract_coro: Pin<&mut dyn Coroutine<i32,Yield=i32,Return=&'static str>> = pin!(coro);
28+
assert_eq!(abstract_coro.as_mut().resume(2), CoroutineState::Yielded(2));
29+
assert_eq!(abstract_coro.as_mut().resume(0), CoroutineState::Complete("done"));
30+
}

0 commit comments

Comments
 (0)