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