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 p = LegacySymbolMangler { tcx, path: SymbolPath::new(), keep_within_component: false };
62    p.print_def_path(
63        def_id,
64        if let ty::InstanceKind::DropGlue(_, _)
65        | ty::InstanceKind::AsyncDropGlueCtorShim(_, _)
66        | ty::InstanceKind::FutureDropPollShim(_, _, _) = instance.def
67        {
68            // Add the name of the dropped type to the symbol name
69            &*instance.args
70        } else if let ty::InstanceKind::AsyncDropGlue(_, ty) = instance.def {
71            let ty::Coroutine(_, cor_args) = ty.kind() else {
72                bug!();
73            };
74            let drop_ty = cor_args.first().unwrap().expect_ty();
75            tcx.mk_args(&[GenericArg::from(drop_ty)])
76        } else {
77            &[]
78        },
79    )
80    .unwrap();
81
82    match instance.def {
83        ty::InstanceKind::ThreadLocalShim(..) => {
84            p.write_str("{{tls-shim}}").unwrap();
85        }
86        ty::InstanceKind::VTableShim(..) => {
87            p.write_str("{{vtable-shim}}").unwrap();
88        }
89        ty::InstanceKind::ReifyShim(_, reason) => {
90            p.write_str("{{reify-shim").unwrap();
91            match reason {
92                Some(ReifyReason::FnPtr) => p.write_str("-fnptr").unwrap(),
93                Some(ReifyReason::Vtable) => p.write_str("-vtable").unwrap(),
94                None => (),
95            }
96            p.write_str("}}").unwrap();
97        }
98        // FIXME(async_closures): This shouldn't be needed when we fix
99        // `Instance::ty`/`Instance::def_id`.
100        ty::InstanceKind::ConstructCoroutineInClosureShim { receiver_by_ref, .. } => {
101            p.write_str(if receiver_by_ref { "{{by-move-shim}}" } else { "{{by-ref-shim}}" })
102                .unwrap();
103        }
104        _ => {}
105    }
106
107    if let ty::InstanceKind::FutureDropPollShim(..) = instance.def {
108        let _ = p.write_str("{{drop-shim}}");
109    }
110
111    p.path.finish(hash)
112}
113
114fn get_symbol_hash<'tcx>(
115    tcx: TyCtxt<'tcx>,
116
117    // instance this name will be for
118    instance: Instance<'tcx>,
119
120    // type of the item, without any generic
121    // parameters instantiated; this is
122    // included in the hash as a kind of
123    // safeguard.
124    item_type: Ty<'tcx>,
125
126    instantiating_crate: Option<CrateNum>,
127) -> Hash64 {
128    let def_id = instance.def_id();
129    let args = instance.args;
130    debug!("get_symbol_hash(def_id={:?}, parameters={:?})", def_id, args);
131
132    tcx.with_stable_hashing_context(|mut hcx| {
133        let mut hasher = StableHasher::new();
134
135        // the main symbol name is not necessarily unique; hash in the
136        // compiler's internal def-path, guaranteeing each symbol has a
137        // truly unique path
138        tcx.def_path_hash(def_id).hash_stable(&mut hcx, &mut hasher);
139
140        // Include the main item-type. Note that, in this case, the
141        // assertions about `has_param` may not hold, but this item-type
142        // ought to be the same for every reference anyway.
143        assert!(!item_type.has_erasable_regions());
144        hcx.while_hashing_spans(false, |hcx| {
145            item_type.hash_stable(hcx, &mut hasher);
146
147            // If this is a function, we hash the signature as well.
148            // This is not *strictly* needed, but it may help in some
149            // situations, see the `run-make/a-b-a-linker-guard` test.
150            if let ty::FnDef(..) = item_type.kind() {
151                item_type.fn_sig(tcx).hash_stable(hcx, &mut hasher);
152            }
153
154            // also include any type parameters (for generic items)
155            args.hash_stable(hcx, &mut hasher);
156
157            if let Some(instantiating_crate) = instantiating_crate {
158                tcx.def_path_hash(instantiating_crate.as_def_id())
159                    .stable_crate_id()
160                    .hash_stable(hcx, &mut hasher);
161            }
162
163            // We want to avoid accidental collision between different types of instances.
164            // Especially, `VTableShim`s and `ReifyShim`s may overlap with their original
165            // instances without this.
166            discriminant(&instance.def).hash_stable(hcx, &mut hasher);
167        });
168
169        // 64 bits should be enough to avoid collisions.
170        hasher.finish::<Hash64>()
171    })
172}
173
174// Follow C++ namespace-mangling style, see
175// https://en.wikipedia.org/wiki/Name_mangling for more info.
176//
177// It turns out that on macOS you can actually have arbitrary symbols in
178// function names (at least when given to LLVM), but this is not possible
179// when using unix's linker. Perhaps one day when we just use a linker from LLVM
180// we won't need to do this name mangling. The problem with name mangling is
181// that it seriously limits the available characters. For example we can't
182// have things like &T in symbol names when one would theoretically
183// want them for things like impls of traits on that type.
184//
185// To be able to work on all platforms and get *some* reasonable output, we
186// use C++ name-mangling.
187#[derive(Debug)]
188struct SymbolPath {
189    result: String,
190    temp_buf: String,
191}
192
193impl SymbolPath {
194    fn new() -> Self {
195        let mut result =
196            SymbolPath { result: String::with_capacity(64), temp_buf: String::with_capacity(16) };
197        result.result.push_str("_ZN"); // _Z == Begin name-sequence, N == nested
198        result
199    }
200
201    fn finalize_pending_component(&mut self) {
202        if !self.temp_buf.is_empty() {
203            let _ = write!(self.result, "{}{}", self.temp_buf.len(), self.temp_buf);
204            self.temp_buf.clear();
205        }
206    }
207
208    fn finish(mut self, hash: Hash64) -> String {
209        self.finalize_pending_component();
210        // E = end name-sequence
211        let _ = write!(self.result, "17h{hash:016x}E");
212        self.result
213    }
214}
215
216struct LegacySymbolMangler<'tcx> {
217    tcx: TyCtxt<'tcx>,
218    path: SymbolPath,
219
220    // When `true`, `finalize_pending_component` isn't used.
221    // This is needed when recursing into `print_path_with_qualified`,
222    // or `print_path_with_generic_args`, as any nested paths are
223    // logically within one component.
224    keep_within_component: bool,
225}
226
227// HACK(eddyb) this relies on using the `fmt` interface to get
228// `PrettyPrinter` aka pretty printing of e.g. types in paths,
229// symbol names should have their own printing machinery.
230
231impl<'tcx> Printer<'tcx> for LegacySymbolMangler<'tcx> {
232    fn tcx(&self) -> TyCtxt<'tcx> {
233        self.tcx
234    }
235
236    fn print_region(&mut self, _region: ty::Region<'_>) -> Result<(), PrintError> {
237        // This might be reachable (via `pretty_print_dyn_existential`) even though
238        // `<Self As PrettyPrinter>::should_print_region` returns false. See #144994.
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 print_crate_name(&mut self, cnum: CrateNum) -> Result<(), PrintError> {
309        self.write_str(self.tcx.crate_name(cnum).as_str())?;
310        Ok(())
311    }
312
313    fn print_path_with_qualified(
314        &mut self,
315        self_ty: Ty<'tcx>,
316        trait_ref: Option<ty::TraitRef<'tcx>>,
317    ) -> Result<(), PrintError> {
318        // Similar to `pretty_print_path_with_qualified`, but for the other
319        // types that are printed as paths (see `print_type` above).
320        match self_ty.kind() {
321            ty::FnDef(..)
322            | ty::Alias(..)
323            | ty::Closure(..)
324            | ty::CoroutineClosure(..)
325            | ty::Coroutine(..)
326                if trait_ref.is_none() =>
327            {
328                self.print_type(self_ty)
329            }
330
331            _ => self.pretty_print_path_with_qualified(self_ty, trait_ref),
332        }
333    }
334
335    fn print_path_with_impl(
336        &mut self,
337        print_prefix: impl FnOnce(&mut Self) -> Result<(), PrintError>,
338        self_ty: Ty<'tcx>,
339        trait_ref: Option<ty::TraitRef<'tcx>>,
340    ) -> Result<(), PrintError> {
341        self.pretty_print_path_with_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
359    fn print_path_with_simple(
360        &mut self,
361        print_prefix: impl FnOnce(&mut Self) -> Result<(), PrintError>,
362        disambiguated_data: &DisambiguatedDefPathData,
363    ) -> Result<(), PrintError> {
364        print_prefix(self)?;
365
366        // Skip `::{{extern}}` blocks and `::{{constructor}}` on tuple/unit structs.
367        if let DefPathData::ForeignMod | DefPathData::Ctor = disambiguated_data.data {
368            return Ok(());
369        }
370
371        if self.keep_within_component {
372            // HACK(eddyb) print the path similarly to how `FmtPrinter` prints it.
373            self.write_str("::")?;
374        } else {
375            self.path.finalize_pending_component();
376        }
377
378        write!(self, "{}", disambiguated_data.data)?;
379
380        Ok(())
381    }
382
383    fn print_path_with_generic_args(
384        &mut self,
385        print_prefix: impl FnOnce(&mut Self) -> Result<(), PrintError>,
386        args: &[GenericArg<'tcx>],
387    ) -> Result<(), PrintError> {
388        print_prefix(self)?;
389
390        let args =
391            args.iter().cloned().filter(|arg| !matches!(arg.kind(), GenericArgKind::Lifetime(_)));
392
393        if args.clone().next().is_some() {
394            self.generic_delimiters(|cx| cx.comma_sep(args))
395        } else {
396            Ok(())
397        }
398    }
399
400    fn print_impl_path(
401        &mut self,
402        impl_def_id: DefId,
403        args: &'tcx [GenericArg<'tcx>],
404    ) -> Result<(), PrintError> {
405        let self_ty = self.tcx.type_of(impl_def_id);
406        let impl_trait_ref = self.tcx.impl_trait_ref(impl_def_id);
407        let generics = self.tcx.generics_of(impl_def_id);
408        // We have two cases to worry about here:
409        // 1. We're printing a nested item inside of an impl item, like an inner
410        // function inside of a method. Due to the way that def path printing works,
411        // we'll render this something like `<Ty as Trait>::method::inner_fn`
412        // but we have no substs for this impl since it's not really inheriting
413        // generics from the outer item. We need to use the identity substs, and
414        // to normalize we need to use the correct param-env too.
415        // 2. We're mangling an item with identity substs. This seems to only happen
416        // when generating coverage, since we try to generate coverage for unused
417        // items too, and if something isn't monomorphized then we necessarily don't
418        // have anything to substitute the instance with.
419        // NOTE: We don't support mangling partially substituted but still polymorphic
420        // instances, like `impl<A> Tr<A> for ()` where `A` is substituted w/ `(T,)`.
421        let (typing_env, mut self_ty, mut impl_trait_ref) = if generics.count() > args.len()
422            || &args[..generics.count()]
423                == self
424                    .tcx
425                    .erase_regions(ty::GenericArgs::identity_for_item(self.tcx, impl_def_id))
426                    .as_slice()
427        {
428            (
429                ty::TypingEnv::post_analysis(self.tcx, impl_def_id),
430                self_ty.instantiate_identity(),
431                impl_trait_ref.map(|impl_trait_ref| impl_trait_ref.instantiate_identity()),
432            )
433        } else {
434            assert!(
435                !args.has_non_region_param(),
436                "should not be mangling partially substituted \
437                polymorphic instance: {impl_def_id:?} {args:?}"
438            );
439            (
440                ty::TypingEnv::fully_monomorphized(),
441                self_ty.instantiate(self.tcx, args),
442                impl_trait_ref.map(|impl_trait_ref| impl_trait_ref.instantiate(self.tcx, args)),
443            )
444        };
445
446        match &mut impl_trait_ref {
447            Some(impl_trait_ref) => {
448                assert_eq!(impl_trait_ref.self_ty(), self_ty);
449                *impl_trait_ref = self.tcx.normalize_erasing_regions(typing_env, *impl_trait_ref);
450                self_ty = impl_trait_ref.self_ty();
451            }
452            None => {
453                self_ty = self.tcx.normalize_erasing_regions(typing_env, self_ty);
454            }
455        }
456
457        self.default_print_impl_path(impl_def_id, self_ty, impl_trait_ref)
458    }
459}
460
461impl<'tcx> PrettyPrinter<'tcx> for LegacySymbolMangler<'tcx> {
462    fn should_print_region(&self, _region: ty::Region<'_>) -> bool {
463        false
464    }
465
466    // Identical to `PrettyPrinter::comma_sep` except there is no space after each comma.
467    fn comma_sep<T>(&mut self, mut elems: impl Iterator<Item = T>) -> Result<(), PrintError>
468    where
469        T: Print<'tcx, Self>,
470    {
471        if let Some(first) = elems.next() {
472            first.print(self)?;
473            for elem in elems {
474                self.write_str(",")?;
475                elem.print(self)?;
476            }
477        }
478        Ok(())
479    }
480
481    fn generic_delimiters(
482        &mut self,
483        f: impl FnOnce(&mut Self) -> Result<(), PrintError>,
484    ) -> Result<(), PrintError> {
485        write!(self, "<")?;
486
487        let kept_within_component = mem::replace(&mut self.keep_within_component, true);
488        f(self)?;
489        self.keep_within_component = kept_within_component;
490
491        write!(self, ">")?;
492
493        Ok(())
494    }
495}
496
497impl fmt::Write for LegacySymbolMangler<'_> {
498    fn write_str(&mut self, s: &str) -> fmt::Result {
499        // Name sanitation. LLVM will happily accept identifiers with weird names, but
500        // gas doesn't!
501        // gas accepts the following characters in symbols: a-z, A-Z, 0-9, ., _, $
502        // NVPTX assembly has more strict naming rules than gas, so additionally, dots
503        // are replaced with '$' there.
504
505        for c in s.chars() {
506            if self.path.temp_buf.is_empty() {
507                match c {
508                    'a'..='z' | 'A'..='Z' | '_' => {}
509                    _ => {
510                        // Underscore-qualify anything that didn't start as an ident.
511                        self.path.temp_buf.push('_');
512                    }
513                }
514            }
515            match c {
516                // Escape these with $ sequences
517                '@' => self.path.temp_buf.push_str("$SP$"),
518                '*' => self.path.temp_buf.push_str("$BP$"),
519                '&' => self.path.temp_buf.push_str("$RF$"),
520                '<' => self.path.temp_buf.push_str("$LT$"),
521                '>' => self.path.temp_buf.push_str("$GT$"),
522                '(' => self.path.temp_buf.push_str("$LP$"),
523                ')' => self.path.temp_buf.push_str("$RP$"),
524                ',' => self.path.temp_buf.push_str("$C$"),
525
526                '-' | ':' | '.' if self.tcx.has_strict_asm_symbol_naming() => {
527                    // NVPTX doesn't support these characters in symbol names.
528                    self.path.temp_buf.push('$')
529                }
530
531                // '.' doesn't occur in types and functions, so reuse it
532                // for ':' and '-'
533                '-' | ':' => self.path.temp_buf.push('.'),
534
535                // Avoid crashing LLVM in certain (LTO-related) situations, see #60925.
536                'm' if self.path.temp_buf.ends_with(".llv") => self.path.temp_buf.push_str("$u6d$"),
537
538                // These are legal symbols
539                'a'..='z' | 'A'..='Z' | '0'..='9' | '_' | '.' | '$' => self.path.temp_buf.push(c),
540
541                _ => {
542                    self.path.temp_buf.push('$');
543                    for c in c.escape_unicode().skip(1) {
544                        match c {
545                            '{' => {}
546                            '}' => self.path.temp_buf.push('$'),
547                            c => self.path.temp_buf.push(c),
548                        }
549                    }
550                }
551            }
552        }
553
554        Ok(())
555    }
556}