Skip to content

Commit 448d4c1

Browse files
authored
Rollup merge of rust-lang#123106 - maurer:cfi-closures, r=compiler-errors
CFI: Abstract Closures and Coroutines This will abstract coroutines in a moment, it's just abstracting closures for now to show `@rcvalle` This uses the same principal as the methods on traits - figure out the `dyn` type representing the fn trait, instantiate it, and attach that alias set. We're essentially just computing how we would be called in a dynamic context, and attaching that.
2 parents 58dcd1f + d243f5f commit 448d4c1

File tree

5 files changed

+187
-25
lines changed

5 files changed

+187
-25
lines changed

compiler/rustc_symbol_mangling/src/typeid/typeid_itanium_cxx_abi.rs

+61-3
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::{
@@ -641,9 +642,7 @@ fn encode_ty<'tcx>(
641642
}
642643

643644
// Function types
644-
ty::FnDef(def_id, args)
645-
| ty::Closure(def_id, args)
646-
| ty::CoroutineClosure(def_id, args) => {
645+
ty::FnDef(def_id, args) | ty::Closure(def_id, args) => {
647646
// u<length><name>[I<element-type1..element-typeN>E], where <element-type> is <subst>,
648647
// as vendor extended type.
649648
let mut s = String::new();
@@ -654,6 +653,18 @@ fn encode_ty<'tcx>(
654653
typeid.push_str(&s);
655654
}
656655

656+
ty::CoroutineClosure(def_id, args) => {
657+
// u<length><name>[I<element-type1..element-typeN>E], where <element-type> is <subst>,
658+
// as vendor extended type.
659+
let mut s = String::new();
660+
let name = encode_ty_name(tcx, *def_id);
661+
let _ = write!(s, "u{}{}", name.len(), &name);
662+
let parent_args = tcx.mk_args(args.as_coroutine_closure().parent_args());
663+
s.push_str(&encode_args(tcx, parent_args, dict, options));
664+
compress(dict, DictKey::Ty(ty, TyQ::None), &mut s);
665+
typeid.push_str(&s);
666+
}
667+
657668
ty::Coroutine(def_id, args, ..) => {
658669
// u<length><name>[I<element-type1..element-typeN>E], where <element-type> is <subst>,
659670
// as vendor extended type.
@@ -1142,6 +1153,14 @@ pub fn typeid_for_instance<'tcx>(
11421153
instance.args = tcx.mk_args_trait(self_ty, List::empty());
11431154
} else if matches!(instance.def, ty::InstanceDef::Virtual(..)) {
11441155
instance.args = strip_receiver_auto(tcx, instance.args);
1156+
} else if let ty::InstanceDef::VTableShim(def_id) = instance.def
1157+
&& let Some(trait_id) = tcx.trait_of_item(def_id)
1158+
{
1159+
// VTableShims may have a trait method, but a concrete Self. This is not suitable for a vtable,
1160+
// as the caller will not know the concrete Self.
1161+
let trait_ref = ty::TraitRef::new(tcx, trait_id, instance.args);
1162+
let invoke_ty = trait_object_ty(tcx, ty::Binder::dummy(trait_ref));
1163+
instance.args = tcx.mk_args_trait(invoke_ty, trait_ref.args.into_iter().skip(1));
11451164
}
11461165

11471166
if !options.contains(EncodeTyOptions::NO_SELF_TYPE_ERASURE)
@@ -1180,6 +1199,45 @@ pub fn typeid_for_instance<'tcx>(
11801199
tcx.mk_args_trait(invoke_ty, trait_ref.args.into_iter().skip(1));
11811200
instance.args = instance.args.rebase_onto(tcx, impl_id, abstract_trait_args);
11821201
}
1202+
} else if tcx.is_closure_like(instance.def_id()) {
1203+
// We're either a closure or a coroutine. Our goal is to find the trait we're defined on,
1204+
// instantiate it, and take the type of its only method as our own.
1205+
let closure_ty = instance.ty(tcx, ty::ParamEnv::reveal_all());
1206+
let (trait_id, inputs) = match closure_ty.kind() {
1207+
ty::Closure(..) => {
1208+
let closure_args = instance.args.as_closure();
1209+
let trait_id = tcx.fn_trait_kind_to_def_id(closure_args.kind()).unwrap();
1210+
let tuple_args =
1211+
tcx.instantiate_bound_regions_with_erased(closure_args.sig()).inputs()[0];
1212+
(trait_id, tuple_args)
1213+
}
1214+
ty::Coroutine(..) => (
1215+
tcx.require_lang_item(LangItem::Coroutine, None),
1216+
instance.args.as_coroutine().resume_ty(),
1217+
),
1218+
ty::CoroutineClosure(..) => (
1219+
tcx.require_lang_item(LangItem::FnOnce, None),
1220+
tcx.instantiate_bound_regions_with_erased(
1221+
instance.args.as_coroutine_closure().coroutine_closure_sig(),
1222+
)
1223+
.tupled_inputs_ty,
1224+
),
1225+
x => bug!("Unexpected type kind for closure-like: {x:?}"),
1226+
};
1227+
let trait_ref = ty::TraitRef::new(tcx, trait_id, [closure_ty, inputs]);
1228+
let invoke_ty = trait_object_ty(tcx, ty::Binder::dummy(trait_ref));
1229+
let abstract_args = tcx.mk_args_trait(invoke_ty, trait_ref.args.into_iter().skip(1));
1230+
// There should be exactly one method on this trait, and it should be the one we're
1231+
// defining.
1232+
let call = tcx
1233+
.associated_items(trait_id)
1234+
.in_definition_order()
1235+
.find(|it| it.kind == ty::AssocKind::Fn)
1236+
.expect("No call-family function on closure-like Fn trait?")
1237+
.def_id;
1238+
1239+
instance.def = ty::InstanceDef::Virtual(call, 0);
1240+
instance.args = abstract_args;
11831241
}
11841242

11851243
let fn_abi = tcx
+32
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
// Check various forms of dynamic closure calls
2+
3+
//@ edition: 2021
4+
//@ revisions: cfi kcfi
5+
// FIXME(#122848) Remove only-linux once OSX CFI binaries work
6+
//@ only-linux
7+
//@ [cfi] needs-sanitizer-cfi
8+
//@ [kcfi] needs-sanitizer-kcfi
9+
//@ compile-flags: -C target-feature=-crt-static
10+
//@ [cfi] compile-flags: -C codegen-units=1 -C lto -C prefer-dynamic=off -C opt-level=0
11+
//@ [cfi] compile-flags: -Z sanitizer=cfi
12+
//@ [kcfi] compile-flags: -Z sanitizer=kcfi
13+
//@ run-pass
14+
15+
#![feature(async_closure)]
16+
#![feature(async_fn_traits)]
17+
18+
use std::ops::AsyncFn;
19+
20+
#[inline(never)]
21+
fn identity<T>(x: T) -> T { x }
22+
23+
// We can't actually create a `dyn AsyncFn()`, because it's not object-safe, but we should check
24+
// that we don't bug out when we encounter one.
25+
26+
fn main() {
27+
let f = identity(async || ());
28+
let _ = f.async_call(());
29+
let _ = f();
30+
let g: Box<dyn FnOnce() -> _> = Box::new(f) as _;
31+
let _ = g();
32+
}

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

-22
This file was deleted.

tests/ui/sanitizer/cfi-closures.rs

+65
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,65 @@
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+
//@ compile-flags: --test
13+
//@ run-pass
14+
15+
#![feature(fn_traits)]
16+
17+
fn foo<'a, T>() -> Box<dyn Fn(&'a T) -> &'a T> {
18+
Box::new(|x| x)
19+
}
20+
21+
#[test]
22+
fn dyn_fn_with_params() {
23+
let x = 3;
24+
let f = foo();
25+
f(&x);
26+
// FIXME remove once drops are working.
27+
std::mem::forget(f);
28+
}
29+
30+
#[test]
31+
fn call_fn_trait() {
32+
let f: &(dyn Fn()) = &(|| {}) as _;
33+
f.call(());
34+
}
35+
36+
#[test]
37+
fn fn_ptr_cast() {
38+
let f: &fn() = &((|| ()) as _);
39+
f();
40+
}
41+
42+
fn use_fnmut<F: FnMut()>(mut f: F) {
43+
f()
44+
}
45+
46+
#[test]
47+
fn fn_to_fnmut() {
48+
let f: &(dyn Fn()) = &(|| {}) as _;
49+
use_fnmut(f);
50+
}
51+
52+
fn hrtb_helper(f: &dyn for<'a> Fn(&'a usize)) {
53+
f(&10)
54+
}
55+
56+
#[test]
57+
fn hrtb_fn() {
58+
hrtb_helper((&|x: &usize| println!("{}", *x)) as _)
59+
}
60+
61+
#[test]
62+
fn fnonce() {
63+
let f: Box<dyn FnOnce()> = Box::new(|| {}) as _;
64+
f();
65+
}

tests/ui/sanitizer/cfi-coroutine.rs

+29
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
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+
//@ compile-flags: --test
13+
//@ run-pass
14+
15+
#![feature(coroutines)]
16+
#![feature(coroutine_trait)]
17+
18+
use std::ops::{Coroutine, CoroutineState};
19+
use std::pin::{pin, Pin};
20+
21+
fn main() {
22+
let mut coro = |x: i32| {
23+
yield x;
24+
"done"
25+
};
26+
let mut abstract_coro: Pin<&mut dyn Coroutine<i32,Yield=i32,Return=&'static str>> = pin!(coro);
27+
assert_eq!(abstract_coro.as_mut().resume(2), CoroutineState::Yielded(2));
28+
assert_eq!(abstract_coro.as_mut().resume(0), CoroutineState::Complete("done"));
29+
}

0 commit comments

Comments
 (0)