rustc_sanitizers/cfi/typeid/itanium_cxx_abi/
transform.rs

1//! Transforms instances and types for LLVM CFI and cross-language LLVM CFI support using Itanium
2//! C++ ABI mangling.
3//!
4//! For more information about LLVM CFI and cross-language LLVM CFI support for the Rust compiler,
5//! see design document in the tracking issue #89653.
6
7use std::iter;
8
9use rustc_hir as hir;
10use rustc_hir::LangItem;
11use rustc_middle::bug;
12use rustc_middle::ty::fold::{TypeFolder, TypeSuperFoldable};
13use rustc_middle::ty::{
14    self, ExistentialPredicateStableCmpExt as _, Instance, InstanceKind, IntTy, List, TraitRef, Ty,
15    TyCtxt, TypeFoldable, TypeVisitableExt, UintTy,
16};
17use rustc_span::def_id::DefId;
18use rustc_span::sym;
19use rustc_trait_selection::traits;
20use tracing::{debug, instrument};
21
22use crate::cfi::typeid::TypeIdOptions;
23use crate::cfi::typeid::itanium_cxx_abi::encode::EncodeTyOptions;
24
25/// Options for transform_ty.
26pub(crate) type TransformTyOptions = TypeIdOptions;
27
28pub(crate) struct TransformTy<'tcx> {
29    tcx: TyCtxt<'tcx>,
30    options: TransformTyOptions,
31    parents: Vec<Ty<'tcx>>,
32}
33
34impl<'tcx> TransformTy<'tcx> {
35    pub(crate) fn new(tcx: TyCtxt<'tcx>, options: TransformTyOptions) -> Self {
36        TransformTy { tcx, options, parents: Vec::new() }
37    }
38}
39
40/// Transforms a ty:Ty for being encoded and used in the substitution dictionary.
41///
42/// * Transforms all c_void types into unit types.
43/// * Generalizes pointers if TransformTyOptions::GENERALIZE_POINTERS option is set.
44/// * Normalizes integers if TransformTyOptions::NORMALIZE_INTEGERS option is set.
45/// * Generalizes any repr(transparent) user-defined type that is either a pointer or reference, and
46///   either references itself or any other type that contains or references itself, to avoid a
47///   reference cycle.
48/// * Transforms repr(transparent) types without non-ZST field into ().
49///
50impl<'tcx> TypeFolder<TyCtxt<'tcx>> for TransformTy<'tcx> {
51    // Transforms a ty:Ty for being encoded and used in the substitution dictionary.
52    fn fold_ty(&mut self, t: Ty<'tcx>) -> Ty<'tcx> {
53        match t.kind() {
54            ty::Closure(..)
55            | ty::Coroutine(..)
56            | ty::CoroutineClosure(..)
57            | ty::CoroutineWitness(..)
58            | ty::Dynamic(..)
59            | ty::Float(..)
60            | ty::FnDef(..)
61            | ty::Foreign(..)
62            | ty::Never
63            | ty::Pat(..)
64            | ty::Slice(..)
65            | ty::Str
66            | ty::Tuple(..)
67            | ty::UnsafeBinder(_) => t.super_fold_with(self),
68
69            // Don't transform the type of the array length and keep it as `usize`.
70            // This is required for `try_to_target_usize` to work correctly.
71            &ty::Array(inner, len) => {
72                let inner = self.fold_ty(inner);
73                Ty::new_array_with_const_len(self.tcx, inner, len)
74            }
75
76            ty::Bool => {
77                if self.options.contains(EncodeTyOptions::NORMALIZE_INTEGERS) {
78                    // Note: on all platforms that Rust's currently supports, its size and alignment
79                    // are 1, and its ABI class is INTEGER - see Rust Layout and ABIs.
80                    //
81                    // (See https://rust-lang.github.io/unsafe-code-guidelines/layout/scalars.html#bool.)
82                    //
83                    // Clang represents bool as an 8-bit unsigned integer.
84                    self.tcx.types.u8
85                } else {
86                    t
87                }
88            }
89
90            ty::Char => {
91                if self.options.contains(EncodeTyOptions::NORMALIZE_INTEGERS) {
92                    // Since #118032, char is guaranteed to have the same size, alignment, and
93                    // function call ABI as u32 on all platforms.
94                    self.tcx.types.u32
95                } else {
96                    t
97                }
98            }
99
100            ty::Int(..) | ty::Uint(..) => {
101                if self.options.contains(EncodeTyOptions::NORMALIZE_INTEGERS) {
102                    // Note: C99 7.18.2.4 requires uintptr_t and intptr_t to be at least 16-bit
103                    // wide. All platforms we currently support have a C platform, and as a
104                    // consequence, isize/usize are at least 16-bit wide for all of them.
105                    //
106                    // (See https://rust-lang.github.io/unsafe-code-guidelines/layout/scalars.html#isize-and-usize.)
107                    match t.kind() {
108                        ty::Int(IntTy::Isize) => match self.tcx.sess.target.pointer_width {
109                            16 => self.tcx.types.i16,
110                            32 => self.tcx.types.i32,
111                            64 => self.tcx.types.i64,
112                            128 => self.tcx.types.i128,
113                            _ => bug!(
114                                "fold_ty: unexpected pointer width `{}`",
115                                self.tcx.sess.target.pointer_width
116                            ),
117                        },
118                        ty::Uint(UintTy::Usize) => match self.tcx.sess.target.pointer_width {
119                            16 => self.tcx.types.u16,
120                            32 => self.tcx.types.u32,
121                            64 => self.tcx.types.u64,
122                            128 => self.tcx.types.u128,
123                            _ => bug!(
124                                "fold_ty: unexpected pointer width `{}`",
125                                self.tcx.sess.target.pointer_width
126                            ),
127                        },
128                        _ => t,
129                    }
130                } else {
131                    t
132                }
133            }
134
135            ty::Adt(..) if t.is_c_void(self.tcx) => self.tcx.types.unit,
136
137            ty::Adt(adt_def, args) => {
138                if adt_def.repr().transparent() && adt_def.is_struct() && !self.parents.contains(&t)
139                {
140                    // Don't transform repr(transparent) types with an user-defined CFI encoding to
141                    // preserve the user-defined CFI encoding.
142                    if let Some(_) = self.tcx.get_attr(adt_def.did(), sym::cfi_encoding) {
143                        return t;
144                    }
145                    let variant = adt_def.non_enum_variant();
146                    let typing_env = ty::TypingEnv::post_analysis(self.tcx, variant.def_id);
147                    let field = variant.fields.iter().find(|field| {
148                        let ty = self.tcx.type_of(field.did).instantiate_identity();
149                        let is_zst = self
150                            .tcx
151                            .layout_of(typing_env.as_query_input(ty))
152                            .is_ok_and(|layout| layout.is_zst());
153                        !is_zst
154                    });
155                    if let Some(field) = field {
156                        let ty0 = self.tcx.normalize_erasing_regions(
157                            ty::TypingEnv::fully_monomorphized(),
158                            field.ty(self.tcx, args),
159                        );
160                        // Generalize any repr(transparent) user-defined type that is either a
161                        // pointer or reference, and either references itself or any other type that
162                        // contains or references itself, to avoid a reference cycle.
163
164                        // If the self reference is not through a pointer, for example, due
165                        // to using `PhantomData`, need to skip normalizing it if we hit it again.
166                        self.parents.push(t);
167                        let ty = if ty0.is_any_ptr() && ty0.contains(t) {
168                            let options = self.options;
169                            self.options |= TransformTyOptions::GENERALIZE_POINTERS;
170                            let ty = ty0.fold_with(self);
171                            self.options = options;
172                            ty
173                        } else {
174                            ty0.fold_with(self)
175                        };
176                        self.parents.pop();
177                        ty
178                    } else {
179                        // Transform repr(transparent) types without non-ZST field into ()
180                        self.tcx.types.unit
181                    }
182                } else {
183                    t.super_fold_with(self)
184                }
185            }
186
187            ty::Ref(..) => {
188                if self.options.contains(TransformTyOptions::GENERALIZE_POINTERS) {
189                    if t.is_mutable_ptr() {
190                        Ty::new_mut_ref(self.tcx, self.tcx.lifetimes.re_static, self.tcx.types.unit)
191                    } else {
192                        Ty::new_imm_ref(self.tcx, self.tcx.lifetimes.re_static, self.tcx.types.unit)
193                    }
194                } else {
195                    t.super_fold_with(self)
196                }
197            }
198
199            ty::RawPtr(..) => {
200                if self.options.contains(TransformTyOptions::GENERALIZE_POINTERS) {
201                    if t.is_mutable_ptr() {
202                        Ty::new_mut_ptr(self.tcx, self.tcx.types.unit)
203                    } else {
204                        Ty::new_imm_ptr(self.tcx, self.tcx.types.unit)
205                    }
206                } else {
207                    t.super_fold_with(self)
208                }
209            }
210
211            ty::FnPtr(..) => {
212                if self.options.contains(TransformTyOptions::GENERALIZE_POINTERS) {
213                    Ty::new_imm_ptr(self.tcx, self.tcx.types.unit)
214                } else {
215                    t.super_fold_with(self)
216                }
217            }
218
219            ty::Alias(..) => self.fold_ty(
220                self.tcx.normalize_erasing_regions(ty::TypingEnv::fully_monomorphized(), t),
221            ),
222
223            ty::Bound(..) | ty::Error(..) | ty::Infer(..) | ty::Param(..) | ty::Placeholder(..) => {
224                bug!("fold_ty: unexpected `{:?}`", t.kind());
225            }
226        }
227    }
228
229    fn cx(&self) -> TyCtxt<'tcx> {
230        self.tcx
231    }
232}
233
234#[instrument(skip(tcx), ret)]
235fn trait_object_ty<'tcx>(tcx: TyCtxt<'tcx>, poly_trait_ref: ty::PolyTraitRef<'tcx>) -> Ty<'tcx> {
236    assert!(!poly_trait_ref.has_non_region_param());
237    let principal_pred = poly_trait_ref.map_bound(|trait_ref| {
238        ty::ExistentialPredicate::Trait(ty::ExistentialTraitRef::erase_self_ty(tcx, trait_ref))
239    });
240    let mut assoc_preds: Vec<_> = traits::supertraits(tcx, poly_trait_ref)
241        .flat_map(|super_poly_trait_ref| {
242            tcx.associated_items(super_poly_trait_ref.def_id())
243                .in_definition_order()
244                .filter(|item| item.kind == ty::AssocKind::Type)
245                .filter(|item| !tcx.generics_require_sized_self(item.def_id))
246                .map(move |assoc_ty| {
247                    super_poly_trait_ref.map_bound(|super_trait_ref| {
248                        let alias_ty =
249                            ty::AliasTy::new_from_args(tcx, assoc_ty.def_id, super_trait_ref.args);
250                        let resolved = tcx.normalize_erasing_regions(
251                            ty::TypingEnv::fully_monomorphized(),
252                            alias_ty.to_ty(tcx),
253                        );
254                        debug!("Resolved {:?} -> {resolved}", alias_ty.to_ty(tcx));
255                        ty::ExistentialPredicate::Projection(
256                            ty::ExistentialProjection::erase_self_ty(
257                                tcx,
258                                ty::ProjectionPredicate {
259                                    projection_term: alias_ty.into(),
260                                    term: resolved.into(),
261                                },
262                            ),
263                        )
264                    })
265                })
266        })
267        .collect();
268    assoc_preds.sort_by(|a, b| a.skip_binder().stable_cmp(tcx, &b.skip_binder()));
269    let preds = tcx.mk_poly_existential_predicates_from_iter(
270        iter::once(principal_pred).chain(assoc_preds.into_iter()),
271    );
272    Ty::new_dynamic(tcx, preds, tcx.lifetimes.re_erased, ty::Dyn)
273}
274
275/// Transforms an instance for LLVM CFI and cross-language LLVM CFI support using Itanium C++ ABI
276/// mangling.
277///
278/// typeid_for_instance is called at two locations, initially when declaring/defining functions and
279/// methods, and later during code generation at call sites, after type erasure might have occurred.
280///
281/// In the first call (i.e., when declaring/defining functions and methods), it encodes type ids for
282/// an FnAbi or Instance, and these type ids are attached to functions and methods. (These type ids
283/// are used later by the LowerTypeTests LLVM pass to aggregate functions in groups derived from
284/// these type ids.)
285///
286/// In the second call (i.e., during code generation at call sites), it encodes a type id for an
287/// FnAbi or Instance, after type erasure might have occurred, and this type id is used for testing
288/// if a function is member of the group derived from this type id. Therefore, in the first call to
289/// typeid_for_fnabi (when type ids are attached to functions and methods), it can only include at
290/// most as much information that would be available in the second call (i.e., during code
291/// generation at call sites); otherwise, the type ids would not match.
292///
293/// For this, it:
294///
295/// * Adjust the type ids of DropGlues (see below).
296/// * Adjusts the type ids of VTableShims to the type id expected in the call sites for the
297///   entry in the vtable (i.e., by using the signature of the closure passed as an argument to the
298///   shim, or by just removing self).
299/// * Performs type erasure for calls on trait objects by transforming self into a trait object of
300///   the trait that defines the method.
301/// * Performs type erasure for closures call methods by transforming self into a trait object of
302///   the Fn trait that defines the method (for being attached as a secondary type id).
303///
304#[instrument(level = "trace", skip(tcx))]
305pub(crate) fn transform_instance<'tcx>(
306    tcx: TyCtxt<'tcx>,
307    mut instance: Instance<'tcx>,
308    options: TransformTyOptions,
309) -> Instance<'tcx> {
310    // FIXME: account for async-drop-glue
311    if (matches!(instance.def, ty::InstanceKind::Virtual(..))
312        && tcx.is_lang_item(instance.def_id(), LangItem::DropInPlace))
313        || matches!(instance.def, ty::InstanceKind::DropGlue(..))
314    {
315        // Adjust the type ids of DropGlues
316        //
317        // DropGlues may have indirect calls to one or more given types drop function. Rust allows
318        // for types to be erased to any trait object and retains the drop function for the original
319        // type, which means at the indirect call sites in DropGlues, when typeid_for_fnabi is
320        // called a second time, it only has information after type erasure and it could be a call
321        // on any arbitrary trait object. Normalize them to a synthesized Drop trait object, both on
322        // declaration/definition, and during code generation at call sites so they have the same
323        // type id and match.
324        //
325        // FIXME(rcvalle): This allows a drop call on any trait object to call the drop function of
326        //   any other type.
327        //
328        let def_id = tcx
329            .lang_items()
330            .drop_trait()
331            .unwrap_or_else(|| bug!("typeid_for_instance: couldn't get drop_trait lang item"));
332        let predicate = ty::ExistentialPredicate::Trait(ty::ExistentialTraitRef::new_from_args(
333            tcx,
334            def_id,
335            ty::List::empty(),
336        ));
337        let predicates = tcx.mk_poly_existential_predicates(&[ty::Binder::dummy(predicate)]);
338        let self_ty = Ty::new_dynamic(tcx, predicates, tcx.lifetimes.re_erased, ty::Dyn);
339        instance.args = tcx.mk_args_trait(self_ty, List::empty());
340    } else if let ty::InstanceKind::Virtual(def_id, _) = instance.def {
341        // Transform self into a trait object of the trait that defines the method for virtual
342        // functions to match the type erasure done below.
343        let upcast_ty = match tcx.trait_of_item(def_id) {
344            Some(trait_id) => trait_object_ty(
345                tcx,
346                ty::Binder::dummy(ty::TraitRef::from_method(tcx, trait_id, instance.args)),
347            ),
348            // drop_in_place won't have a defining trait, skip the upcast
349            None => instance.args.type_at(0),
350        };
351        let ty::Dynamic(preds, lifetime, kind) = upcast_ty.kind() else {
352            bug!("Tried to remove autotraits from non-dynamic type {upcast_ty}");
353        };
354        let self_ty = if preds.principal().is_some() {
355            let filtered_preds =
356                tcx.mk_poly_existential_predicates_from_iter(preds.into_iter().filter(|pred| {
357                    !matches!(pred.skip_binder(), ty::ExistentialPredicate::AutoTrait(..))
358                }));
359            Ty::new_dynamic(tcx, filtered_preds, *lifetime, *kind)
360        } else {
361            // If there's no principal type, re-encode it as a unit, since we don't know anything
362            // about it. This technically discards the knowledge that it was a type that was made
363            // into a trait object at some point, but that's not a lot.
364            tcx.types.unit
365        };
366        instance.args = tcx.mk_args_trait(self_ty, instance.args.into_iter().skip(1));
367    } else if let ty::InstanceKind::VTableShim(def_id) = instance.def
368        && let Some(trait_id) = tcx.trait_of_item(def_id)
369    {
370        // Adjust the type ids of VTableShims to the type id expected in the call sites for the
371        // entry in the vtable (i.e., by using the signature of the closure passed as an argument
372        // to the shim, or by just removing self).
373        let trait_ref = ty::TraitRef::new_from_args(tcx, trait_id, instance.args);
374        let invoke_ty = trait_object_ty(tcx, ty::Binder::dummy(trait_ref));
375        instance.args = tcx.mk_args_trait(invoke_ty, trait_ref.args.into_iter().skip(1));
376    }
377
378    if !options.contains(TransformTyOptions::USE_CONCRETE_SELF) {
379        // Perform type erasure for calls on trait objects by transforming self into a trait object
380        // of the trait that defines the method.
381        if let Some((trait_ref, method_id, ancestor)) = implemented_method(tcx, instance) {
382            // Trait methods will have a Self polymorphic parameter, where the concreteized
383            // implementation will not. We need to walk back to the more general trait method
384            let trait_ref = tcx.instantiate_and_normalize_erasing_regions(
385                instance.args,
386                ty::TypingEnv::fully_monomorphized(),
387                trait_ref,
388            );
389            let invoke_ty = trait_object_ty(tcx, ty::Binder::dummy(trait_ref));
390
391            // At the call site, any call to this concrete function through a vtable will be
392            // `Virtual(method_id, idx)` with appropriate arguments for the method. Since we have the
393            // original method id, and we've recovered the trait arguments, we can make the callee
394            // instance we're computing the alias set for match the caller instance.
395            //
396            // Right now, our code ignores the vtable index everywhere, so we use 0 as a placeholder.
397            // If we ever *do* start encoding the vtable index, we will need to generate an alias set
398            // based on which vtables we are putting this method into, as there will be more than one
399            // index value when supertraits are involved.
400            instance.def = ty::InstanceKind::Virtual(method_id, 0);
401            let abstract_trait_args =
402                tcx.mk_args_trait(invoke_ty, trait_ref.args.into_iter().skip(1));
403            instance.args = instance.args.rebase_onto(tcx, ancestor, abstract_trait_args);
404        } else if tcx.is_closure_like(instance.def_id()) {
405            // We're either a closure or a coroutine. Our goal is to find the trait we're defined on,
406            // instantiate it, and take the type of its only method as our own.
407            let closure_ty = instance.ty(tcx, ty::TypingEnv::fully_monomorphized());
408            let (trait_id, inputs) = match closure_ty.kind() {
409                ty::Closure(..) => {
410                    let closure_args = instance.args.as_closure();
411                    let trait_id = tcx.fn_trait_kind_to_def_id(closure_args.kind()).unwrap();
412                    let tuple_args =
413                        tcx.instantiate_bound_regions_with_erased(closure_args.sig()).inputs()[0];
414                    (trait_id, Some(tuple_args))
415                }
416                ty::Coroutine(..) => match tcx.coroutine_kind(instance.def_id()).unwrap() {
417                    hir::CoroutineKind::Coroutine(..) => (
418                        tcx.require_lang_item(LangItem::Coroutine, None),
419                        Some(instance.args.as_coroutine().resume_ty()),
420                    ),
421                    hir::CoroutineKind::Desugared(desugaring, _) => {
422                        let lang_item = match desugaring {
423                            hir::CoroutineDesugaring::Async => LangItem::Future,
424                            hir::CoroutineDesugaring::AsyncGen => LangItem::AsyncIterator,
425                            hir::CoroutineDesugaring::Gen => LangItem::Iterator,
426                        };
427                        (tcx.require_lang_item(lang_item, None), None)
428                    }
429                },
430                ty::CoroutineClosure(..) => (
431                    tcx.require_lang_item(LangItem::FnOnce, None),
432                    Some(
433                        tcx.instantiate_bound_regions_with_erased(
434                            instance.args.as_coroutine_closure().coroutine_closure_sig(),
435                        )
436                        .tupled_inputs_ty,
437                    ),
438                ),
439                x => bug!("Unexpected type kind for closure-like: {x:?}"),
440            };
441            let concrete_args = tcx.mk_args_trait(closure_ty, inputs.map(Into::into));
442            let trait_ref = ty::TraitRef::new_from_args(tcx, trait_id, concrete_args);
443            let invoke_ty = trait_object_ty(tcx, ty::Binder::dummy(trait_ref));
444            let abstract_args = tcx.mk_args_trait(invoke_ty, trait_ref.args.into_iter().skip(1));
445            // There should be exactly one method on this trait, and it should be the one we're
446            // defining.
447            let call = tcx
448                .associated_items(trait_id)
449                .in_definition_order()
450                .find(|it| it.kind == ty::AssocKind::Fn)
451                .expect("No call-family function on closure-like Fn trait?")
452                .def_id;
453
454            instance.def = ty::InstanceKind::Virtual(call, 0);
455            instance.args = abstract_args;
456        }
457    }
458
459    instance
460}
461
462fn implemented_method<'tcx>(
463    tcx: TyCtxt<'tcx>,
464    instance: Instance<'tcx>,
465) -> Option<(ty::EarlyBinder<'tcx, TraitRef<'tcx>>, DefId, DefId)> {
466    let trait_ref;
467    let method_id;
468    let trait_id;
469    let trait_method;
470    let ancestor = if let Some(impl_id) = tcx.impl_of_method(instance.def_id()) {
471        // Implementation in an `impl` block
472        trait_ref = tcx.impl_trait_ref(impl_id)?;
473        let impl_method = tcx.associated_item(instance.def_id());
474        method_id = impl_method.trait_item_def_id?;
475        trait_method = tcx.associated_item(method_id);
476        trait_id = trait_ref.skip_binder().def_id;
477        impl_id
478    } else if let InstanceKind::Item(def_id) = instance.def
479        && let Some(trait_method_bound) = tcx.opt_associated_item(def_id)
480    {
481        // Provided method in a `trait` block
482        trait_method = trait_method_bound;
483        method_id = instance.def_id();
484        trait_id = tcx.trait_of_item(method_id)?;
485        trait_ref = ty::EarlyBinder::bind(TraitRef::from_method(tcx, trait_id, instance.args));
486        trait_id
487    } else {
488        return None;
489    };
490    let vtable_possible = traits::is_vtable_safe_method(tcx, trait_id, trait_method)
491        && tcx.is_dyn_compatible(trait_id);
492    vtable_possible.then_some((trait_ref, method_id, ancestor))
493}