rustc_symbol_mangling/
legacy.rs

1use std::fmt::{self, Write};
2use std::mem::{self, discriminant};
3
4use rustc_data_structures::stable_hasher::{HashStable, StableHasher};
5use rustc_hashes::Hash64;
6use rustc_hir::def_id::{CrateNum, DefId};
7use rustc_hir::definitions::{DefPathData, DisambiguatedDefPathData};
8use rustc_middle::bug;
9use rustc_middle::ty::print::{PrettyPrinter, Print, PrintError, Printer};
10use rustc_middle::ty::{
11    self, GenericArg, GenericArgKind, Instance, ReifyReason, Ty, TyCtxt, TypeVisitableExt,
12};
13use tracing::debug;
14
15pub(super) fn mangle<'tcx>(
16    tcx: TyCtxt<'tcx>,
17    instance: Instance<'tcx>,
18    instantiating_crate: Option<CrateNum>,
19) -> String {
20    let def_id = instance.def_id();
21
22    // We want to compute the "type" of this item. Unfortunately, some
23    // kinds of items (e.g., synthetic static allocations from const eval)
24    // don't have a proper implementation for the `type_of` query. So walk
25    // back up the find the closest parent that DOES have a type.
26    let mut ty_def_id = def_id;
27    let instance_ty;
28    loop {
29        let key = tcx.def_key(ty_def_id);
30        match key.disambiguated_data.data {
31            DefPathData::TypeNs(_)
32            | DefPathData::ValueNs(_)
33            | DefPathData::Closure
34            | DefPathData::SyntheticCoroutineBody => {
35                instance_ty = tcx.type_of(ty_def_id).instantiate_identity();
36                debug!(?instance_ty);
37                break;
38            }
39            _ => {
40                // if we're making a symbol for something, there ought
41                // to be a value or type-def or something in there
42                // *somewhere*
43                ty_def_id.index = key.parent.unwrap_or_else(|| {
44                    bug!(
45                        "finding type for {:?}, encountered def-id {:?} with no \
46                         parent",
47                        def_id,
48                        ty_def_id
49                    );
50                });
51            }
52        }
53    }
54
55    // Erase regions because they may not be deterministic when hashed
56    // and should not matter anyhow.
57    let instance_ty = tcx.erase_regions(instance_ty);
58
59    let hash = get_symbol_hash(tcx, instance, instance_ty, instantiating_crate);
60
61    let mut printer = SymbolPrinter { tcx, path: SymbolPath::new(), keep_within_component: false };
62    printer
63        .print_def_path(
64            def_id,
65            if let ty::InstanceKind::DropGlue(_, _)
66            | ty::InstanceKind::AsyncDropGlueCtorShim(_, _)
67            | ty::InstanceKind::FutureDropPollShim(_, _, _) = instance.def
68            {
69                // Add the name of the dropped type to the symbol name
70                &*instance.args
71            } else if let ty::InstanceKind::AsyncDropGlue(_, ty) = instance.def {
72                let ty::Coroutine(_, cor_args) = ty.kind() else {
73                    bug!();
74                };
75                let drop_ty = cor_args.first().unwrap().expect_ty();
76                tcx.mk_args(&[GenericArg::from(drop_ty)])
77            } else {
78                &[]
79            },
80        )
81        .unwrap();
82
83    match instance.def {
84        ty::InstanceKind::ThreadLocalShim(..) => {
85            printer.write_str("{{tls-shim}}").unwrap();
86        }
87        ty::InstanceKind::VTableShim(..) => {
88            printer.write_str("{{vtable-shim}}").unwrap();
89        }
90        ty::InstanceKind::ReifyShim(_, reason) => {
91            printer.write_str("{{reify-shim").unwrap();
92            match reason {
93                Some(ReifyReason::FnPtr) => printer.write_str("-fnptr").unwrap(),
94                Some(ReifyReason::Vtable) => printer.write_str("-vtable").unwrap(),
95                None => (),
96            }
97            printer.write_str("}}").unwrap();
98        }
99        // FIXME(async_closures): This shouldn't be needed when we fix
100        // `Instance::ty`/`Instance::def_id`.
101        ty::InstanceKind::ConstructCoroutineInClosureShim { receiver_by_ref, .. } => {
102            printer
103                .write_str(if receiver_by_ref { "{{by-move-shim}}" } else { "{{by-ref-shim}}" })
104                .unwrap();
105        }
106        _ => {}
107    }
108
109    if let ty::InstanceKind::FutureDropPollShim(..) = instance.def {
110        let _ = printer.write_str("{{drop-shim}}");
111    }
112
113    printer.path.finish(hash)
114}
115
116fn get_symbol_hash<'tcx>(
117    tcx: TyCtxt<'tcx>,
118
119    // instance this name will be for
120    instance: Instance<'tcx>,
121
122    // type of the item, without any generic
123    // parameters instantiated; this is
124    // included in the hash as a kind of
125    // safeguard.
126    item_type: Ty<'tcx>,
127
128    instantiating_crate: Option<CrateNum>,
129) -> Hash64 {
130    let def_id = instance.def_id();
131    let args = instance.args;
132    debug!("get_symbol_hash(def_id={:?}, parameters={:?})", def_id, args);
133
134    tcx.with_stable_hashing_context(|mut hcx| {
135        let mut hasher = StableHasher::new();
136
137        // the main symbol name is not necessarily unique; hash in the
138        // compiler's internal def-path, guaranteeing each symbol has a
139        // truly unique path
140        tcx.def_path_hash(def_id).hash_stable(&mut hcx, &mut hasher);
141
142        // Include the main item-type. Note that, in this case, the
143        // assertions about `has_param` may not hold, but this item-type
144        // ought to be the same for every reference anyway.
145        assert!(!item_type.has_erasable_regions());
146        hcx.while_hashing_spans(false, |hcx| {
147            item_type.hash_stable(hcx, &mut hasher);
148
149            // If this is a function, we hash the signature as well.
150            // This is not *strictly* needed, but it may help in some
151            // situations, see the `run-make/a-b-a-linker-guard` test.
152            if let ty::FnDef(..) = item_type.kind() {
153                item_type.fn_sig(tcx).hash_stable(hcx, &mut hasher);
154            }
155
156            // also include any type parameters (for generic items)
157            args.hash_stable(hcx, &mut hasher);
158
159            if let Some(instantiating_crate) = instantiating_crate {
160                tcx.def_path_hash(instantiating_crate.as_def_id())
161                    .stable_crate_id()
162                    .hash_stable(hcx, &mut hasher);
163            }
164
165            // We want to avoid accidental collision between different types of instances.
166            // Especially, `VTableShim`s and `ReifyShim`s may overlap with their original
167            // instances without this.
168            discriminant(&instance.def).hash_stable(hcx, &mut hasher);
169        });
170
171        // 64 bits should be enough to avoid collisions.
172        hasher.finish::<Hash64>()
173    })
174}
175
176// Follow C++ namespace-mangling style, see
177// https://en.wikipedia.org/wiki/Name_mangling for more info.
178//
179// It turns out that on macOS you can actually have arbitrary symbols in
180// function names (at least when given to LLVM), but this is not possible
181// when using unix's linker. Perhaps one day when we just use a linker from LLVM
182// we won't need to do this name mangling. The problem with name mangling is
183// that it seriously limits the available characters. For example we can't
184// have things like &T in symbol names when one would theoretically
185// want them for things like impls of traits on that type.
186//
187// To be able to work on all platforms and get *some* reasonable output, we
188// use C++ name-mangling.
189#[derive(Debug)]
190struct SymbolPath {
191    result: String,
192    temp_buf: String,
193}
194
195impl SymbolPath {
196    fn new() -> Self {
197        let mut result =
198            SymbolPath { result: String::with_capacity(64), temp_buf: String::with_capacity(16) };
199        result.result.push_str("_ZN"); // _Z == Begin name-sequence, N == nested
200        result
201    }
202
203    fn finalize_pending_component(&mut self) {
204        if !self.temp_buf.is_empty() {
205            let _ = write!(self.result, "{}{}", self.temp_buf.len(), self.temp_buf);
206            self.temp_buf.clear();
207        }
208    }
209
210    fn finish(mut self, hash: Hash64) -> String {
211        self.finalize_pending_component();
212        // E = end name-sequence
213        let _ = write!(self.result, "17h{hash:016x}E");
214        self.result
215    }
216}
217
218struct SymbolPrinter<'tcx> {
219    tcx: TyCtxt<'tcx>,
220    path: SymbolPath,
221
222    // When `true`, `finalize_pending_component` isn't used.
223    // This is needed when recursing into `path_qualified`,
224    // or `path_generic_args`, as any nested paths are
225    // logically within one component.
226    keep_within_component: bool,
227}
228
229// HACK(eddyb) this relies on using the `fmt` interface to get
230// `PrettyPrinter` aka pretty printing of e.g. types in paths,
231// symbol names should have their own printing machinery.
232
233impl<'tcx> Printer<'tcx> for SymbolPrinter<'tcx> {
234    fn tcx(&self) -> TyCtxt<'tcx> {
235        self.tcx
236    }
237
238    fn print_region(&mut self, _region: ty::Region<'_>) -> Result<(), PrintError> {
239        Ok(())
240    }
241
242    fn print_type(&mut self, ty: Ty<'tcx>) -> Result<(), PrintError> {
243        match *ty.kind() {
244            // Print all nominal types as paths (unlike `pretty_print_type`).
245            ty::FnDef(def_id, args)
246            | ty::Alias(ty::Projection | ty::Opaque, ty::AliasTy { def_id, args, .. })
247            | ty::Closure(def_id, args)
248            | ty::CoroutineClosure(def_id, args)
249            | ty::Coroutine(def_id, args) => self.print_def_path(def_id, args),
250
251            // The `pretty_print_type` formatting of array size depends on
252            // -Zverbose-internals flag, so we cannot reuse it here.
253            ty::Array(ty, size) => {
254                self.write_str("[")?;
255                self.print_type(ty)?;
256                self.write_str("; ")?;
257                if let Some(size) = size.try_to_target_usize(self.tcx()) {
258                    write!(self, "{size}")?
259                } else if let ty::ConstKind::Param(param) = size.kind() {
260                    param.print(self)?
261                } else {
262                    self.write_str("_")?
263                }
264                self.write_str("]")?;
265                Ok(())
266            }
267
268            ty::Alias(ty::Inherent, _) => panic!("unexpected inherent projection"),
269
270            _ => self.pretty_print_type(ty),
271        }
272    }
273
274    fn print_dyn_existential(
275        &mut self,
276        predicates: &'tcx ty::List<ty::PolyExistentialPredicate<'tcx>>,
277    ) -> Result<(), PrintError> {
278        let mut first = true;
279        for p in predicates {
280            if !first {
281                write!(self, "+")?;
282            }
283            first = false;
284            p.print(self)?;
285        }
286        Ok(())
287    }
288
289    fn print_const(&mut self, ct: ty::Const<'tcx>) -> Result<(), PrintError> {
290        // only print integers
291        match ct.kind() {
292            ty::ConstKind::Value(cv) if cv.ty.is_integral() => {
293                // The `pretty_print_const` formatting depends on -Zverbose-internals
294                // flag, so we cannot reuse it here.
295                let scalar = cv.valtree.unwrap_leaf();
296                let signed = matches!(cv.ty.kind(), ty::Int(_));
297                write!(
298                    self,
299                    "{:#?}",
300                    ty::ConstInt::new(scalar, signed, cv.ty.is_ptr_sized_integral())
301                )?;
302            }
303            _ => self.write_str("_")?,
304        }
305        Ok(())
306    }
307
308    fn path_crate(&mut self, cnum: CrateNum) -> Result<(), PrintError> {
309        self.write_str(self.tcx.crate_name(cnum).as_str())?;
310        Ok(())
311    }
312    fn path_qualified(
313        &mut self,
314        self_ty: Ty<'tcx>,
315        trait_ref: Option<ty::TraitRef<'tcx>>,
316    ) -> Result<(), PrintError> {
317        // Similar to `pretty_path_qualified`, but for the other
318        // types that are printed as paths (see `print_type` above).
319        match self_ty.kind() {
320            ty::FnDef(..)
321            | ty::Alias(..)
322            | ty::Closure(..)
323            | ty::CoroutineClosure(..)
324            | ty::Coroutine(..)
325                if trait_ref.is_none() =>
326            {
327                self.print_type(self_ty)
328            }
329
330            _ => self.pretty_path_qualified(self_ty, trait_ref),
331        }
332    }
333
334    fn path_append_impl(
335        &mut self,
336        print_prefix: impl FnOnce(&mut Self) -> Result<(), PrintError>,
337        _disambiguated_data: &DisambiguatedDefPathData,
338        self_ty: Ty<'tcx>,
339        trait_ref: Option<ty::TraitRef<'tcx>>,
340    ) -> Result<(), PrintError> {
341        self.pretty_path_append_impl(
342            |cx| {
343                print_prefix(cx)?;
344
345                if cx.keep_within_component {
346                    // HACK(eddyb) print the path similarly to how `FmtPrinter` prints it.
347                    cx.write_str("::")?;
348                } else {
349                    cx.path.finalize_pending_component();
350                }
351
352                Ok(())
353            },
354            self_ty,
355            trait_ref,
356        )
357    }
358    fn path_append(
359        &mut self,
360        print_prefix: impl FnOnce(&mut Self) -> Result<(), PrintError>,
361        disambiguated_data: &DisambiguatedDefPathData,
362    ) -> Result<(), PrintError> {
363        print_prefix(self)?;
364
365        // Skip `::{{extern}}` blocks and `::{{constructor}}` on tuple/unit structs.
366        if let DefPathData::ForeignMod | DefPathData::Ctor = disambiguated_data.data {
367            return Ok(());
368        }
369
370        if self.keep_within_component {
371            // HACK(eddyb) print the path similarly to how `FmtPrinter` prints it.
372            self.write_str("::")?;
373        } else {
374            self.path.finalize_pending_component();
375        }
376
377        write!(self, "{}", disambiguated_data.data)?;
378
379        Ok(())
380    }
381    fn path_generic_args(
382        &mut self,
383        print_prefix: impl FnOnce(&mut Self) -> Result<(), PrintError>,
384        args: &[GenericArg<'tcx>],
385    ) -> Result<(), PrintError> {
386        print_prefix(self)?;
387
388        let args =
389            args.iter().cloned().filter(|arg| !matches!(arg.kind(), GenericArgKind::Lifetime(_)));
390
391        if args.clone().next().is_some() {
392            self.generic_delimiters(|cx| cx.comma_sep(args))
393        } else {
394            Ok(())
395        }
396    }
397
398    fn print_impl_path(
399        &mut self,
400        impl_def_id: DefId,
401        args: &'tcx [GenericArg<'tcx>],
402    ) -> Result<(), PrintError> {
403        let self_ty = self.tcx.type_of(impl_def_id);
404        let impl_trait_ref = self.tcx.impl_trait_ref(impl_def_id);
405        let generics = self.tcx.generics_of(impl_def_id);
406        // We have two cases to worry about here:
407        // 1. We're printing a nested item inside of an impl item, like an inner
408        // function inside of a method. Due to the way that def path printing works,
409        // we'll render this something like `<Ty as Trait>::method::inner_fn`
410        // but we have no substs for this impl since it's not really inheriting
411        // generics from the outer item. We need to use the identity substs, and
412        // to normalize we need to use the correct param-env too.
413        // 2. We're mangling an item with identity substs. This seems to only happen
414        // when generating coverage, since we try to generate coverage for unused
415        // items too, and if something isn't monomorphized then we necessarily don't
416        // have anything to substitute the instance with.
417        // NOTE: We don't support mangling partially substituted but still polymorphic
418        // instances, like `impl<A> Tr<A> for ()` where `A` is substituted w/ `(T,)`.
419        let (typing_env, mut self_ty, mut impl_trait_ref) = if generics.count() > args.len()
420            || &args[..generics.count()]
421                == self
422                    .tcx
423                    .erase_regions(ty::GenericArgs::identity_for_item(self.tcx, impl_def_id))
424                    .as_slice()
425        {
426            (
427                ty::TypingEnv::post_analysis(self.tcx, impl_def_id),
428                self_ty.instantiate_identity(),
429                impl_trait_ref.map(|impl_trait_ref| impl_trait_ref.instantiate_identity()),
430            )
431        } else {
432            assert!(
433                !args.has_non_region_param(),
434                "should not be mangling partially substituted \
435                polymorphic instance: {impl_def_id:?} {args:?}"
436            );
437            (
438                ty::TypingEnv::fully_monomorphized(),
439                self_ty.instantiate(self.tcx, args),
440                impl_trait_ref.map(|impl_trait_ref| impl_trait_ref.instantiate(self.tcx, args)),
441            )
442        };
443
444        match &mut impl_trait_ref {
445            Some(impl_trait_ref) => {
446                assert_eq!(impl_trait_ref.self_ty(), self_ty);
447                *impl_trait_ref = self.tcx.normalize_erasing_regions(typing_env, *impl_trait_ref);
448                self_ty = impl_trait_ref.self_ty();
449            }
450            None => {
451                self_ty = self.tcx.normalize_erasing_regions(typing_env, self_ty);
452            }
453        }
454
455        self.default_print_impl_path(impl_def_id, self_ty, impl_trait_ref)
456    }
457}
458
459impl<'tcx> PrettyPrinter<'tcx> for SymbolPrinter<'tcx> {
460    fn should_print_region(&self, _region: ty::Region<'_>) -> bool {
461        false
462    }
463    fn comma_sep<T>(&mut self, mut elems: impl Iterator<Item = T>) -> Result<(), PrintError>
464    where
465        T: Print<'tcx, Self>,
466    {
467        if let Some(first) = elems.next() {
468            first.print(self)?;
469            for elem in elems {
470                self.write_str(",")?;
471                elem.print(self)?;
472            }
473        }
474        Ok(())
475    }
476
477    fn generic_delimiters(
478        &mut self,
479        f: impl FnOnce(&mut Self) -> Result<(), PrintError>,
480    ) -> Result<(), PrintError> {
481        write!(self, "<")?;
482
483        let kept_within_component = mem::replace(&mut self.keep_within_component, true);
484        f(self)?;
485        self.keep_within_component = kept_within_component;
486
487        write!(self, ">")?;
488
489        Ok(())
490    }
491}
492
493impl fmt::Write for SymbolPrinter<'_> {
494    fn write_str(&mut self, s: &str) -> fmt::Result {
495        // Name sanitation. LLVM will happily accept identifiers with weird names, but
496        // gas doesn't!
497        // gas accepts the following characters in symbols: a-z, A-Z, 0-9, ., _, $
498        // NVPTX assembly has more strict naming rules than gas, so additionally, dots
499        // are replaced with '$' there.
500
501        for c in s.chars() {
502            if self.path.temp_buf.is_empty() {
503                match c {
504                    'a'..='z' | 'A'..='Z' | '_' => {}
505                    _ => {
506                        // Underscore-qualify anything that didn't start as an ident.
507                        self.path.temp_buf.push('_');
508                    }
509                }
510            }
511            match c {
512                // Escape these with $ sequences
513                '@' => self.path.temp_buf.push_str("$SP$"),
514                '*' => self.path.temp_buf.push_str("$BP$"),
515                '&' => self.path.temp_buf.push_str("$RF$"),
516                '<' => self.path.temp_buf.push_str("$LT$"),
517                '>' => self.path.temp_buf.push_str("$GT$"),
518                '(' => self.path.temp_buf.push_str("$LP$"),
519                ')' => self.path.temp_buf.push_str("$RP$"),
520                ',' => self.path.temp_buf.push_str("$C$"),
521
522                '-' | ':' | '.' if self.tcx.has_strict_asm_symbol_naming() => {
523                    // NVPTX doesn't support these characters in symbol names.
524                    self.path.temp_buf.push('$')
525                }
526
527                // '.' doesn't occur in types and functions, so reuse it
528                // for ':' and '-'
529                '-' | ':' => self.path.temp_buf.push('.'),
530
531                // Avoid crashing LLVM in certain (LTO-related) situations, see #60925.
532                'm' if self.path.temp_buf.ends_with(".llv") => self.path.temp_buf.push_str("$u6d$"),
533
534                // These are legal symbols
535                'a'..='z' | 'A'..='Z' | '0'..='9' | '_' | '.' | '$' => self.path.temp_buf.push(c),
536
537                _ => {
538                    self.path.temp_buf.push('$');
539                    for c in c.escape_unicode().skip(1) {
540                        match c {
541                            '{' => {}
542                            '}' => self.path.temp_buf.push('$'),
543                            c => self.path.temp_buf.push(c),
544                        }
545                    }
546                }
547            }
548        }
549
550        Ok(())
551    }
552}