rustc_sanitizers/cfi/typeid/itanium_cxx_abi/
encode.rs

1//! Encodes type metadata identifiers for LLVM CFI and cross-language LLVM CFI support using Itanium
2//! C++ ABI mangling for encoding with vendor extended type qualifiers and types for Rust types that
3//! are not used across the FFI boundary.
4//!
5//! For more information about LLVM CFI and cross-language LLVM CFI support for the Rust compiler,
6//! see design document in the tracking issue #89653.
7
8use std::fmt::Write as _;
9
10use rustc_abi::{ExternAbi, Integer};
11use rustc_data_structures::base_n::{ALPHANUMERIC_ONLY, CASE_INSENSITIVE, ToBaseN};
12use rustc_data_structures::fx::FxHashMap;
13use rustc_hir as hir;
14use rustc_hir::attrs::AttributeKind;
15use rustc_hir::find_attr;
16use rustc_middle::bug;
17use rustc_middle::ty::layout::IntegerExt;
18use rustc_middle::ty::{
19    self, Const, ExistentialPredicate, FloatTy, FnSig, GenericArg, GenericArgKind, GenericArgsRef,
20    IntTy, List, Region, RegionKind, TermKind, Ty, TyCtxt, TypeFoldable, UintTy,
21};
22use rustc_span::def_id::DefId;
23use tracing::instrument;
24
25use crate::cfi::typeid::TypeIdOptions;
26use crate::cfi::typeid::itanium_cxx_abi::transform::{TransformTy, TransformTyOptions};
27
28/// Options for encode_ty.
29pub(crate) type EncodeTyOptions = TypeIdOptions;
30
31/// Substitution dictionary key.
32#[derive(Eq, Hash, PartialEq)]
33pub(crate) enum DictKey<'tcx> {
34    Ty(Ty<'tcx>, TyQ),
35    Region(Region<'tcx>),
36    Const(Const<'tcx>),
37    Predicate(ExistentialPredicate<'tcx>),
38}
39
40/// Type and extended type qualifiers.
41#[derive(Eq, Hash, PartialEq)]
42pub(crate) enum TyQ {
43    None,
44    Const,
45    Mut,
46}
47
48/// Substitutes a component if found in the substitution dictionary (see
49/// <https://itanium-cxx-abi.github.io/cxx-abi/abi.html#mangling-compression>).
50fn compress<'tcx>(
51    dict: &mut FxHashMap<DictKey<'tcx>, usize>,
52    key: DictKey<'tcx>,
53    comp: &mut String,
54) {
55    match dict.get(&key) {
56        Some(num) => {
57            comp.clear();
58            let _ = write!(comp, "S{}_", to_seq_id(*num));
59        }
60        None => {
61            dict.insert(key, dict.len());
62        }
63    }
64}
65
66/// Encodes args using the Itanium C++ ABI with vendor extended type qualifiers and types for Rust
67/// types that are not used at the FFI boundary.
68fn encode_args<'tcx>(
69    tcx: TyCtxt<'tcx>,
70    args: GenericArgsRef<'tcx>,
71    for_def: DefId,
72    has_erased_self: bool,
73    dict: &mut FxHashMap<DictKey<'tcx>, usize>,
74    options: EncodeTyOptions,
75) -> String {
76    // [I<subst1..substN>E] as part of vendor extended type
77    let mut s = String::new();
78    let args: Vec<GenericArg<'_>> = args.iter().collect();
79    if !args.is_empty() {
80        s.push('I');
81        let def_generics = tcx.generics_of(for_def);
82        for (n, arg) in args.iter().enumerate() {
83            match arg.kind() {
84                GenericArgKind::Lifetime(region) => {
85                    s.push_str(&encode_region(region, dict));
86                }
87                GenericArgKind::Type(ty) => {
88                    s.push_str(&encode_ty(tcx, ty, dict, options));
89                }
90                GenericArgKind::Const(c) => {
91                    let n = n + (has_erased_self as usize);
92                    let ct_ty =
93                        tcx.type_of(def_generics.param_at(n, tcx).def_id).instantiate_identity();
94                    s.push_str(&encode_const(tcx, c, ct_ty, dict, options));
95                }
96            }
97        }
98        s.push('E');
99    }
100    s
101}
102
103/// Encodes a const using the Itanium C++ ABI as a literal argument (see
104/// <https://itanium-cxx-abi.github.io/cxx-abi/abi.html#mangling.literal>).
105fn encode_const<'tcx>(
106    tcx: TyCtxt<'tcx>,
107    ct: Const<'tcx>,
108    ct_ty: Ty<'tcx>,
109    dict: &mut FxHashMap<DictKey<'tcx>, usize>,
110    options: EncodeTyOptions,
111) -> String {
112    // L<element-type>[n][<element-value>]E as literal argument
113    let mut s = String::from('L');
114
115    match ct.kind() {
116        // Const parameters
117        ty::ConstKind::Param(..) => {
118            // L<element-type>E as literal argument
119
120            // Element type
121            s.push_str(&encode_ty(tcx, ct_ty, dict, options));
122        }
123
124        // Literal arguments
125        ty::ConstKind::Value(cv) => {
126            // L<element-type>[n]<element-value>E as literal argument
127
128            // Element type
129            s.push_str(&encode_ty(tcx, cv.ty, dict, options));
130
131            // The only allowed types of const values are bool, u8, u16, u32,
132            // u64, u128, usize i8, i16, i32, i64, i128, isize, and char. The
133            // bool value false is encoded as 0 and true as 1.
134            match cv.ty.kind() {
135                ty::Int(ity) => {
136                    let bits = cv
137                        .try_to_bits(tcx, ty::TypingEnv::fully_monomorphized())
138                        .expect("expected monomorphic const in cfi");
139                    let val = Integer::from_int_ty(&tcx, *ity).size().sign_extend(bits) as i128;
140                    if val < 0 {
141                        s.push('n');
142                    }
143                    let _ = write!(s, "{val}");
144                }
145                ty::Uint(_) => {
146                    let val = cv
147                        .try_to_bits(tcx, ty::TypingEnv::fully_monomorphized())
148                        .expect("expected monomorphic const in cfi");
149                    let _ = write!(s, "{val}");
150                }
151                ty::Bool => {
152                    let val = cv.try_to_bool().expect("expected monomorphic const in cfi");
153                    let _ = write!(s, "{val}");
154                }
155                _ => {
156                    bug!("encode_const: unexpected type `{:?}`", cv.ty);
157                }
158            }
159        }
160
161        _ => {
162            bug!("encode_const: unexpected kind `{:?}`", ct.kind());
163        }
164    }
165
166    // Close the "L..E" pair
167    s.push('E');
168
169    compress(dict, DictKey::Const(ct), &mut s);
170
171    s
172}
173
174/// Encodes a FnSig using the Itanium C++ ABI with vendor extended type qualifiers and types for
175/// Rust types that are not used at the FFI boundary.
176fn encode_fnsig<'tcx>(
177    tcx: TyCtxt<'tcx>,
178    fn_sig: &FnSig<'tcx>,
179    dict: &mut FxHashMap<DictKey<'tcx>, usize>,
180    options: TypeIdOptions,
181) -> String {
182    // Function types are delimited by an "F..E" pair
183    let mut s = String::from("F");
184
185    let mut encode_ty_options = EncodeTyOptions::from_bits(options.bits())
186        .unwrap_or_else(|| bug!("encode_fnsig: invalid option(s) `{:?}`", options.bits()));
187    match fn_sig.abi {
188        ExternAbi::C { .. } => {
189            encode_ty_options.insert(EncodeTyOptions::GENERALIZE_REPR_C);
190        }
191        _ => {
192            encode_ty_options.remove(EncodeTyOptions::GENERALIZE_REPR_C);
193        }
194    }
195
196    // Encode the return type
197    let transform_ty_options = TransformTyOptions::from_bits(options.bits())
198        .unwrap_or_else(|| bug!("encode_fnsig: invalid option(s) `{:?}`", options.bits()));
199    let mut type_folder = TransformTy::new(tcx, transform_ty_options);
200    let ty = fn_sig.output().fold_with(&mut type_folder);
201    s.push_str(&encode_ty(tcx, ty, dict, encode_ty_options));
202
203    // Encode the parameter types
204    let tys = fn_sig.inputs();
205    if !tys.is_empty() {
206        for ty in tys {
207            let ty = ty.fold_with(&mut type_folder);
208            s.push_str(&encode_ty(tcx, ty, dict, encode_ty_options));
209        }
210
211        if fn_sig.c_variadic {
212            s.push('z');
213        }
214    } else if fn_sig.c_variadic {
215        s.push('z');
216    } else {
217        // Empty parameter lists, whether declared as () or conventionally as (void), are
218        // encoded with a void parameter specifier "v".
219        s.push('v')
220    }
221
222    // Close the "F..E" pair
223    s.push('E');
224
225    s
226}
227
228/// Encodes a predicate using the Itanium C++ ABI with vendor extended type qualifiers and types for
229/// Rust types that are not used at the FFI boundary.
230fn encode_predicate<'tcx>(
231    tcx: TyCtxt<'tcx>,
232    predicate: ty::PolyExistentialPredicate<'tcx>,
233    dict: &mut FxHashMap<DictKey<'tcx>, usize>,
234    options: EncodeTyOptions,
235) -> String {
236    // u<length><name>[I<element-type1..element-typeN>E], where <element-type> is <subst>, as vendor
237    // extended type.
238    let mut s = String::new();
239    match predicate.as_ref().skip_binder() {
240        ty::ExistentialPredicate::Trait(trait_ref) => {
241            let name = encode_ty_name(tcx, trait_ref.def_id);
242            let _ = write!(s, "u{}{}", name.len(), name);
243            s.push_str(&encode_args(tcx, trait_ref.args, trait_ref.def_id, true, dict, options));
244        }
245        ty::ExistentialPredicate::Projection(projection) => {
246            let name = encode_ty_name(tcx, projection.def_id);
247            let _ = write!(s, "u{}{}", name.len(), name);
248            s.push_str(&encode_args(tcx, projection.args, projection.def_id, true, dict, options));
249            match projection.term.kind() {
250                TermKind::Ty(ty) => s.push_str(&encode_ty(tcx, ty, dict, options)),
251                TermKind::Const(c) => s.push_str(&encode_const(
252                    tcx,
253                    c,
254                    tcx.type_of(projection.def_id).instantiate(tcx, projection.args),
255                    dict,
256                    options,
257                )),
258            }
259        }
260        ty::ExistentialPredicate::AutoTrait(def_id) => {
261            let name = encode_ty_name(tcx, *def_id);
262            let _ = write!(s, "u{}{}", name.len(), name);
263        }
264    };
265    compress(dict, DictKey::Predicate(*predicate.as_ref().skip_binder()), &mut s);
266    s
267}
268
269/// Encodes predicates using the Itanium C++ ABI with vendor extended type qualifiers and types for
270/// Rust types that are not used at the FFI boundary.
271fn encode_predicates<'tcx>(
272    tcx: TyCtxt<'tcx>,
273    predicates: &List<ty::PolyExistentialPredicate<'tcx>>,
274    dict: &mut FxHashMap<DictKey<'tcx>, usize>,
275    options: EncodeTyOptions,
276) -> String {
277    // <predicate1[..predicateN]>E as part of vendor extended type
278    let mut s = String::new();
279    let predicates: Vec<ty::PolyExistentialPredicate<'tcx>> = predicates.iter().collect();
280    for predicate in predicates {
281        s.push_str(&encode_predicate(tcx, predicate, dict, options));
282    }
283    s
284}
285
286/// Encodes a region using the Itanium C++ ABI as a vendor extended type.
287fn encode_region<'tcx>(region: Region<'tcx>, dict: &mut FxHashMap<DictKey<'tcx>, usize>) -> String {
288    // u6region[I[<region-disambiguator>][<region-index>]E] as vendor extended type
289    let mut s = String::new();
290    match region.kind() {
291        RegionKind::ReBound(ty::BoundVarIndexKind::Bound(debruijn), r) => {
292            s.push_str("u6regionI");
293            // Debruijn index, which identifies the binder, as region disambiguator
294            let num = debruijn.index() as u64;
295            if num > 0 {
296                s.push_str(&to_disambiguator(num));
297            }
298            // Index within the binder
299            let _ = write!(s, "{}", r.var.index() as u64);
300            s.push('E');
301            compress(dict, DictKey::Region(region), &mut s);
302        }
303        RegionKind::ReErased => {
304            s.push_str("u6region");
305            compress(dict, DictKey::Region(region), &mut s);
306        }
307        RegionKind::ReBound(ty::BoundVarIndexKind::Canonical, _)
308        | RegionKind::ReEarlyParam(..)
309        | RegionKind::ReLateParam(..)
310        | RegionKind::ReStatic
311        | RegionKind::ReError(_)
312        | RegionKind::ReVar(..)
313        | RegionKind::RePlaceholder(..) => {
314            bug!("encode_region: unexpected `{:?}`", region.kind());
315        }
316    }
317    s
318}
319
320/// Encodes a ty:Ty using the Itanium C++ ABI with vendor extended type qualifiers and types for
321/// Rust types that are not used at the FFI boundary.
322#[instrument(level = "trace", skip(tcx, dict))]
323pub(crate) fn encode_ty<'tcx>(
324    tcx: TyCtxt<'tcx>,
325    ty: Ty<'tcx>,
326    dict: &mut FxHashMap<DictKey<'tcx>, usize>,
327    options: EncodeTyOptions,
328) -> String {
329    let mut typeid = String::new();
330
331    match ty.kind() {
332        // Primitive types
333
334        // Rust's bool has the same layout as C17's _Bool, that is, its size and alignment are
335        // implementation-defined. Any bool can be cast into an integer, taking on the values 1
336        // (true) or 0 (false).
337        //
338        // (See https://rust-lang.github.io/unsafe-code-guidelines/layout/scalars.html#bool.)
339        ty::Bool => {
340            typeid.push('b');
341        }
342
343        ty::Int(..) | ty::Uint(..) => {
344            // u<length><type-name> as vendor extended type
345            let mut s = String::from(match ty.kind() {
346                ty::Int(IntTy::I8) => "u2i8",
347                ty::Int(IntTy::I16) => "u3i16",
348                ty::Int(IntTy::I32) => "u3i32",
349                ty::Int(IntTy::I64) => "u3i64",
350                ty::Int(IntTy::I128) => "u4i128",
351                ty::Int(IntTy::Isize) => "u5isize",
352                ty::Uint(UintTy::U8) => "u2u8",
353                ty::Uint(UintTy::U16) => "u3u16",
354                ty::Uint(UintTy::U32) => "u3u32",
355                ty::Uint(UintTy::U64) => "u3u64",
356                ty::Uint(UintTy::U128) => "u4u128",
357                ty::Uint(UintTy::Usize) => "u5usize",
358                _ => bug!("encode_ty: unexpected `{:?}`", ty.kind()),
359            });
360            compress(dict, DictKey::Ty(ty, TyQ::None), &mut s);
361            typeid.push_str(&s);
362        }
363
364        // Rust's f16, f32, f64, and f126 half (16-bit), single (32-bit), double (64-bit), and
365        // quad (128-bit)  precision floating-point types have IEEE-754 binary16, binary32,
366        // binary64, and binary128 floating-point layouts, respectively.
367        //
368        // (See https://rust-lang.github.io/unsafe-code-guidelines/layout/scalars.html#fixed-width-floating-point-types.)
369        ty::Float(float_ty) => {
370            typeid.push_str(match float_ty {
371                FloatTy::F16 => "Dh",
372                FloatTy::F32 => "f",
373                FloatTy::F64 => "d",
374                FloatTy::F128 => "g",
375            });
376        }
377
378        ty::Char => {
379            // u4char as vendor extended type
380            let mut s = String::from("u4char");
381            compress(dict, DictKey::Ty(ty, TyQ::None), &mut s);
382            typeid.push_str(&s);
383        }
384
385        ty::Str => {
386            // u3str as vendor extended type
387            let mut s = String::from("u3str");
388            compress(dict, DictKey::Ty(ty, TyQ::None), &mut s);
389            typeid.push_str(&s);
390        }
391
392        ty::Never => {
393            // u5never as vendor extended type
394            let mut s = String::from("u5never");
395            compress(dict, DictKey::Ty(ty, TyQ::None), &mut s);
396            typeid.push_str(&s);
397        }
398
399        // Compound types
400        // () in Rust is equivalent to void return type in C
401        _ if ty.is_unit() => {
402            typeid.push('v');
403        }
404
405        // Sequence types
406        ty::Tuple(tys) => {
407            // u5tupleI<element-type1..element-typeN>E as vendor extended type
408            let mut s = String::from("u5tupleI");
409            for ty in tys.iter() {
410                s.push_str(&encode_ty(tcx, ty, dict, options));
411            }
412            s.push('E');
413            compress(dict, DictKey::Ty(ty, TyQ::None), &mut s);
414            typeid.push_str(&s);
415        }
416
417        ty::Array(ty0, len) => {
418            // A<array-length><element-type>
419            let len = len.try_to_target_usize(tcx).expect("expected monomorphic const in cfi");
420            let mut s = String::from("A");
421            let _ = write!(s, "{len}");
422            s.push_str(&encode_ty(tcx, *ty0, dict, options));
423            compress(dict, DictKey::Ty(ty, TyQ::None), &mut s);
424            typeid.push_str(&s);
425        }
426
427        ty::Pat(ty0, pat) => {
428            // u3patI<element-type><pattern>E as vendor extended type
429            let mut s = String::from("u3patI");
430            s.push_str(&encode_ty(tcx, *ty0, dict, options));
431            write!(s, "{:?}", **pat).unwrap();
432            s.push('E');
433            compress(dict, DictKey::Ty(ty, TyQ::None), &mut s);
434            typeid.push_str(&s);
435        }
436
437        ty::Slice(ty0) => {
438            // u5sliceI<element-type>E as vendor extended type
439            let mut s = String::from("u5sliceI");
440            s.push_str(&encode_ty(tcx, *ty0, dict, options));
441            s.push('E');
442            compress(dict, DictKey::Ty(ty, TyQ::None), &mut s);
443            typeid.push_str(&s);
444        }
445
446        // User-defined types
447        ty::Adt(adt_def, args) => {
448            let mut s = String::new();
449            let def_id = adt_def.did();
450            if let Some(encoding) = find_attr!(tcx.get_all_attrs(def_id), AttributeKind::CfiEncoding { encoding } => encoding)
451            {
452                let encoding = encoding.as_str().trim();
453                // Use user-defined CFI encoding for type
454                s.push_str(&encoding);
455                // Don't compress user-defined builtin types (see
456                // https://itanium-cxx-abi.github.io/cxx-abi/abi.html#mangling-builtin and
457                // https://itanium-cxx-abi.github.io/cxx-abi/abi.html#mangling-compression).
458                let builtin_types = [
459                    "v", "w", "b", "c", "a", "h", "s", "t", "i", "j", "l", "m", "x", "y", "n", "o",
460                    "f", "d", "e", "g", "z", "Dh",
461                ];
462                if !builtin_types.contains(&encoding) {
463                    compress(dict, DictKey::Ty(ty, TyQ::None), &mut s);
464                }
465            } else if options.contains(EncodeTyOptions::GENERALIZE_REPR_C) && adt_def.repr().c() {
466                // For cross-language LLVM CFI support, the encoding must be compatible at the FFI
467                // boundary. For instance:
468                //
469                //     struct type1 {};
470                //     void foo(struct type1* bar) {}
471                //
472                // Is encoded as:
473                //
474                //     _ZTSFvP5type1E
475                //
476                // So, encode any repr(C) user-defined type for extern function types with the "C"
477                // calling convention (or extern types [i.e., ty::Foreign]) as <length><name>, where
478                // <name> is <unscoped-name>.
479                let name = tcx.item_name(def_id).to_string();
480                let _ = write!(s, "{}{}", name.len(), name);
481                compress(dict, DictKey::Ty(ty, TyQ::None), &mut s);
482            } else {
483                // u<length><name>[I<element-type1..element-typeN>E], where <element-type> is
484                // <subst>, as vendor extended type.
485                let name = encode_ty_name(tcx, def_id);
486                let _ = write!(s, "u{}{}", name.len(), name);
487                s.push_str(&encode_args(tcx, args, def_id, false, dict, options));
488                compress(dict, DictKey::Ty(ty, TyQ::None), &mut s);
489            }
490            typeid.push_str(&s);
491        }
492
493        ty::Foreign(def_id) => {
494            // <length><name>, where <name> is <unscoped-name>
495            let mut s = String::new();
496
497            if let Some(encoding) = find_attr!(tcx.get_all_attrs(*def_id), AttributeKind::CfiEncoding {encoding} => encoding)
498            {
499                // Use user-defined CFI encoding for type
500                s.push_str(encoding.as_str().trim());
501            } else {
502                let name = tcx.item_name(*def_id).to_string();
503                let _ = write!(s, "{}{}", name.len(), name);
504            }
505            compress(dict, DictKey::Ty(ty, TyQ::None), &mut s);
506            typeid.push_str(&s);
507        }
508
509        // Function types
510        ty::FnDef(def_id, args) | ty::Closure(def_id, args) => {
511            // u<length><name>[I<element-type1..element-typeN>E], where <element-type> is <subst>,
512            // as vendor extended type.
513            let mut s = String::new();
514            let name = encode_ty_name(tcx, *def_id);
515            let _ = write!(s, "u{}{}", name.len(), name);
516            s.push_str(&encode_args(tcx, args, *def_id, false, dict, options));
517            compress(dict, DictKey::Ty(ty, TyQ::None), &mut s);
518            typeid.push_str(&s);
519        }
520
521        ty::CoroutineClosure(def_id, args) => {
522            // u<length><name>[I<element-type1..element-typeN>E], where <element-type> is <subst>,
523            // as vendor extended type.
524            let mut s = String::new();
525            let name = encode_ty_name(tcx, *def_id);
526            let _ = write!(s, "u{}{}", name.len(), name);
527            let parent_args = tcx.mk_args(args.as_coroutine_closure().parent_args());
528            s.push_str(&encode_args(tcx, parent_args, *def_id, false, dict, options));
529            compress(dict, DictKey::Ty(ty, TyQ::None), &mut s);
530            typeid.push_str(&s);
531        }
532
533        ty::Coroutine(def_id, args, ..) => {
534            // u<length><name>[I<element-type1..element-typeN>E], where <element-type> is <subst>,
535            // as vendor extended type.
536            let mut s = String::new();
537            let name = encode_ty_name(tcx, *def_id);
538            let _ = write!(s, "u{}{}", name.len(), name);
539            // Encode parent args only
540            s.push_str(&encode_args(
541                tcx,
542                tcx.mk_args(args.as_coroutine().parent_args()),
543                *def_id,
544                false,
545                dict,
546                options,
547            ));
548            compress(dict, DictKey::Ty(ty, TyQ::None), &mut s);
549            typeid.push_str(&s);
550        }
551
552        // Pointer types
553        ty::Ref(region, ty0, ..) => {
554            // [U3mut]u3refI<element-type>E as vendor extended type qualifier and type
555            let mut s = String::new();
556            s.push_str("u3refI");
557            s.push_str(&encode_ty(tcx, *ty0, dict, options));
558            s.push('E');
559            compress(dict, DictKey::Ty(Ty::new_imm_ref(tcx, *region, *ty0), TyQ::None), &mut s);
560            if ty.is_mutable_ptr() {
561                s = format!("{}{}", "U3mut", s);
562                compress(dict, DictKey::Ty(ty, TyQ::Mut), &mut s);
563            }
564            typeid.push_str(&s);
565        }
566
567        ty::RawPtr(ptr_ty, _mutbl) => {
568            // FIXME: This can definitely not be so spaghettified.
569            // P[K]<element-type>
570            let mut s = String::new();
571            s.push_str(&encode_ty(tcx, *ptr_ty, dict, options));
572            if !ty.is_mutable_ptr() {
573                s = format!("{}{}", "K", s);
574                compress(dict, DictKey::Ty(*ptr_ty, TyQ::Const), &mut s);
575            };
576            s = format!("{}{}", "P", s);
577            compress(dict, DictKey::Ty(ty, TyQ::None), &mut s);
578            typeid.push_str(&s);
579        }
580
581        ty::FnPtr(sig_tys, hdr) => {
582            // PF<return-type><parameter-type1..parameter-typeN>E
583            let mut s = String::from("P");
584            s.push_str(&encode_fnsig(
585                tcx,
586                &sig_tys.with(*hdr).skip_binder(),
587                dict,
588                TypeIdOptions::empty(),
589            ));
590            compress(dict, DictKey::Ty(ty, TyQ::None), &mut s);
591            typeid.push_str(&s);
592        }
593
594        // FIXME(unsafe_binders): Implement this.
595        ty::UnsafeBinder(_) => {
596            todo!()
597        }
598
599        // Trait types
600        ty::Dynamic(predicates, region) => {
601            // u3dynI<element-type1[..element-typeN]>E, where <element-type> is <predicate>, as
602            // vendor extended type.
603            let mut s = String::from("u3dynI");
604            s.push_str(&encode_predicates(tcx, predicates, dict, options));
605            s.push_str(&encode_region(*region, dict));
606            s.push('E');
607            compress(dict, DictKey::Ty(ty, TyQ::None), &mut s);
608            typeid.push_str(&s);
609        }
610
611        // Type parameters
612        ty::Param(..) => {
613            // u5param as vendor extended type
614            let mut s = String::from("u5param");
615            compress(dict, DictKey::Ty(ty, TyQ::None), &mut s);
616            typeid.push_str(&s);
617        }
618
619        // Unexpected types
620        ty::Alias(..)
621        | ty::Bound(..)
622        | ty::Error(..)
623        | ty::CoroutineWitness(..)
624        | ty::Infer(..)
625        | ty::Placeholder(..) => {
626            bug!("encode_ty: unexpected `{:?}`", ty.kind());
627        }
628    };
629
630    typeid
631}
632
633/// Encodes a ty:Ty name, including its crate and path disambiguators and names.
634fn encode_ty_name(tcx: TyCtxt<'_>, def_id: DefId) -> String {
635    // Encode <name> for use in u<length><name>[I<element-type1..element-typeN>E], where
636    // <element-type> is <subst>, using v0's <path> without v0's extended form of paths:
637    //
638    // N<namespace-tagN>..N<namespace-tag1>
639    // C<crate-disambiguator><crate-name>
640    // <path-disambiguator1><path-name1>..<path-disambiguatorN><path-nameN>
641    //
642    // With additional tags for DefPathData::Impl and DefPathData::ForeignMod. For instance:
643    //
644    //     pub type Type1 = impl Send;
645    //     let _: Type1 = <Struct1<i32>>::foo;
646    //     fn foo1(_: Type1) { }
647    //
648    //     pub type Type2 = impl Send;
649    //     let _: Type2 = <Trait1<i32>>::foo;
650    //     fn foo2(_: Type2) { }
651    //
652    //     pub type Type3 = impl Send;
653    //     let _: Type3 = <i32 as Trait1<i32>>::foo;
654    //     fn foo3(_: Type3) { }
655    //
656    //     pub type Type4 = impl Send;
657    //     let _: Type4 = <Struct1<i32> as Trait1<i32>>::foo;
658    //     fn foo3(_: Type4) { }
659    //
660    // Are encoded as:
661    //
662    //     _ZTSFvu29NvNIC1234_5crate8{{impl}}3fooIu3i32EE
663    //     _ZTSFvu27NvNtC1234_5crate6Trait13fooIu3dynIu21NtC1234_5crate6Trait1Iu3i32Eu6regionES_EE
664    //     _ZTSFvu27NvNtC1234_5crate6Trait13fooIu3i32S_EE
665    //     _ZTSFvu27NvNtC1234_5crate6Trait13fooIu22NtC1234_5crate7Struct1Iu3i32ES_EE
666    //
667    // The reason for not using v0's extended form of paths is to use a consistent and simpler
668    // encoding, as the reasoning for using it isn't relevant for type metadata identifiers (i.e.,
669    // keep symbol names close to how methods are represented in error messages). See
670    // https://rust-lang.github.io/rfcs/2603-rust-symbol-name-mangling-v0.html#methods.
671    let mut s = String::new();
672
673    // Start and namespace tags
674    let mut def_path = tcx.def_path(def_id);
675    def_path.data.reverse();
676    for disambiguated_data in &def_path.data {
677        s.push('N');
678        s.push_str(match disambiguated_data.data {
679            hir::definitions::DefPathData::Impl => "I", // Not specified in v0's <namespace>
680            hir::definitions::DefPathData::ForeignMod => "F", // Not specified in v0's <namespace>
681            hir::definitions::DefPathData::TypeNs(..) => "t",
682            hir::definitions::DefPathData::ValueNs(..) => "v",
683            hir::definitions::DefPathData::Closure => "C",
684            hir::definitions::DefPathData::Ctor => "c",
685            hir::definitions::DefPathData::AnonConst => "K",
686            hir::definitions::DefPathData::LateAnonConst => "k",
687            hir::definitions::DefPathData::OpaqueTy => "i",
688            hir::definitions::DefPathData::SyntheticCoroutineBody => "s",
689            hir::definitions::DefPathData::NestedStatic => "n",
690            hir::definitions::DefPathData::CrateRoot
691            | hir::definitions::DefPathData::Use
692            | hir::definitions::DefPathData::GlobalAsm
693            | hir::definitions::DefPathData::MacroNs(..)
694            | hir::definitions::DefPathData::OpaqueLifetime(..)
695            | hir::definitions::DefPathData::LifetimeNs(..)
696            | hir::definitions::DefPathData::DesugaredAnonymousLifetime
697            | hir::definitions::DefPathData::AnonAssocTy(..) => {
698                bug!("encode_ty_name: unexpected `{:?}`", disambiguated_data.data);
699            }
700        });
701    }
702
703    // Crate disambiguator and name
704    s.push('C');
705    s.push_str(&to_disambiguator(tcx.stable_crate_id(def_path.krate).as_u64()));
706    let crate_name = tcx.crate_name(def_path.krate).to_string();
707    let _ = write!(s, "{}{}", crate_name.len(), crate_name);
708
709    // Disambiguators and names
710    def_path.data.reverse();
711    for disambiguated_data in &def_path.data {
712        let num = disambiguated_data.disambiguator as u64;
713        if num > 0 {
714            s.push_str(&to_disambiguator(num));
715        }
716
717        let name = disambiguated_data.data.to_string();
718        let _ = write!(s, "{}", name.len());
719
720        // Prepend a '_' if name starts with a digit or '_'
721        if let Some(first) = name.as_bytes().first() {
722            if first.is_ascii_digit() || *first == b'_' {
723                s.push('_');
724            }
725        } else {
726            bug!("encode_ty_name: invalid name `{:?}`", name);
727        }
728
729        s.push_str(&name);
730    }
731
732    s
733}
734
735/// Converts a number to a disambiguator (see
736/// <https://rust-lang.github.io/rfcs/2603-rust-symbol-name-mangling-v0.html>).
737fn to_disambiguator(num: u64) -> String {
738    if let Some(num) = num.checked_sub(1) {
739        format!("s{}_", num.to_base(ALPHANUMERIC_ONLY))
740    } else {
741        "s_".to_string()
742    }
743}
744
745/// Converts a number to a sequence number (see
746/// <https://itanium-cxx-abi.github.io/cxx-abi/abi.html#mangle.seq-id>).
747fn to_seq_id(num: usize) -> String {
748    if let Some(num) = num.checked_sub(1) {
749        (num as u64).to_base(CASE_INSENSITIVE).to_uppercase()
750    } else {
751        "".to_string()
752    }
753}