]> git.lizzy.rs Git - rust.git/blob - src/librustc_codegen_utils/symbol_names.rs
Rollup merge of #60959 - petrochenkov:sassert, r=estebank
[rust.git] / src / librustc_codegen_utils / symbol_names.rs
1 //! The Rust Linkage Model and Symbol Names
2 //! =======================================
3 //!
4 //! The semantic model of Rust linkage is, broadly, that "there's no global
5 //! namespace" between crates. Our aim is to preserve the illusion of this
6 //! model despite the fact that it's not *quite* possible to implement on
7 //! modern linkers. We initially didn't use system linkers at all, but have
8 //! been convinced of their utility.
9 //!
10 //! There are a few issues to handle:
11 //!
12 //!  - Linkers operate on a flat namespace, so we have to flatten names.
13 //!    We do this using the C++ namespace-mangling technique. Foo::bar
14 //!    symbols and such.
15 //!
16 //!  - Symbols for distinct items with the same *name* need to get different
17 //!    linkage-names. Examples of this are monomorphizations of functions or
18 //!    items within anonymous scopes that end up having the same path.
19 //!
20 //!  - Symbols in different crates but with same names "within" the crate need
21 //!    to get different linkage-names.
22 //!
23 //!  - Symbol names should be deterministic: Two consecutive runs of the
24 //!    compiler over the same code base should produce the same symbol names for
25 //!    the same items.
26 //!
27 //!  - Symbol names should not depend on any global properties of the code base,
28 //!    so that small modifications to the code base do not result in all symbols
29 //!    changing. In previous versions of the compiler, symbol names incorporated
30 //!    the SVH (Stable Version Hash) of the crate. This scheme turned out to be
31 //!    infeasible when used in conjunction with incremental compilation because
32 //!    small code changes would invalidate all symbols generated previously.
33 //!
34 //!  - Even symbols from different versions of the same crate should be able to
35 //!    live next to each other without conflict.
36 //!
37 //! In order to fulfill the above requirements the following scheme is used by
38 //! the compiler:
39 //!
40 //! The main tool for avoiding naming conflicts is the incorporation of a 64-bit
41 //! hash value into every exported symbol name. Anything that makes a difference
42 //! to the symbol being named, but does not show up in the regular path needs to
43 //! be fed into this hash:
44 //!
45 //! - Different monomorphizations of the same item have the same path but differ
46 //!   in their concrete type parameters, so these parameters are part of the
47 //!   data being digested for the symbol hash.
48 //!
49 //! - Rust allows items to be defined in anonymous scopes, such as in
50 //!   `fn foo() { { fn bar() {} } { fn bar() {} } }`. Both `bar` functions have
51 //!   the path `foo::bar`, since the anonymous scopes do not contribute to the
52 //!   path of an item. The compiler already handles this case via so-called
53 //!   disambiguating `DefPaths` which use indices to distinguish items with the
54 //!   same name. The DefPaths of the functions above are thus `foo[0]::bar[0]`
55 //!   and `foo[0]::bar[1]`. In order to incorporate this disambiguation
56 //!   information into the symbol name too, these indices are fed into the
57 //!   symbol hash, so that the above two symbols would end up with different
58 //!   hash values.
59 //!
60 //! The two measures described above suffice to avoid intra-crate conflicts. In
61 //! order to also avoid inter-crate conflicts two more measures are taken:
62 //!
63 //! - The name of the crate containing the symbol is prepended to the symbol
64 //!   name, i.e., symbols are "crate qualified". For example, a function `foo` in
65 //!   module `bar` in crate `baz` would get a symbol name like
66 //!   `baz::bar::foo::{hash}` instead of just `bar::foo::{hash}`. This avoids
67 //!   simple conflicts between functions from different crates.
68 //!
69 //! - In order to be able to also use symbols from two versions of the same
70 //!   crate (which naturally also have the same name), a stronger measure is
71 //!   required: The compiler accepts an arbitrary "disambiguator" value via the
72 //!   `-C metadata` command-line argument. This disambiguator is then fed into
73 //!   the symbol hash of every exported item. Consequently, the symbols in two
74 //!   identical crates but with different disambiguators are not in conflict
75 //!   with each other. This facility is mainly intended to be used by build
76 //!   tools like Cargo.
77 //!
78 //! A note on symbol name stability
79 //! -------------------------------
80 //! Previous versions of the compiler resorted to feeding NodeIds into the
81 //! symbol hash in order to disambiguate between items with the same path. The
82 //! current version of the name generation algorithm takes great care not to do
83 //! that, since NodeIds are notoriously unstable: A small change to the
84 //! code base will offset all NodeIds after the change and thus, much as using
85 //! the SVH in the hash, invalidate an unbounded number of symbol names. This
86 //! makes re-using previously compiled code for incremental compilation
87 //! virtually impossible. Thus, symbol hash generation exclusively relies on
88 //! DefPaths which are much more robust in the face of changes to the code base.
89
90 use rustc::hir::def_id::{CrateNum, DefId, LOCAL_CRATE};
91 use rustc::hir::Node;
92 use rustc::hir::CodegenFnAttrFlags;
93 use rustc::hir::map::{DefPathData, DisambiguatedDefPathData};
94 use rustc::ich::NodeIdHashingMode;
95 use rustc::ty::print::{PrettyPrinter, Printer, Print};
96 use rustc::ty::query::Providers;
97 use rustc::ty::subst::{Kind, SubstsRef, UnpackedKind};
98 use rustc::ty::{self, Ty, TyCtxt, TypeFoldable};
99 use rustc::util::common::record_time;
100 use rustc_data_structures::stable_hasher::{HashStable, StableHasher};
101 use rustc_mir::monomorphize::item::{InstantiationMode, MonoItem, MonoItemExt};
102 use rustc_mir::monomorphize::Instance;
103
104 use syntax_pos::symbol::InternedString;
105
106 use log::debug;
107
108 use std::fmt::{self, Write};
109 use std::mem::{self, discriminant};
110
111 pub fn provide(providers: &mut Providers<'_>) {
112     *providers = Providers {
113         symbol_name,
114
115         ..*providers
116     };
117 }
118
119 fn get_symbol_hash<'a, 'tcx>(
120     tcx: TyCtxt<'a, 'tcx, 'tcx>,
121
122     // the DefId of the item this name is for
123     def_id: DefId,
124
125     // instance this name will be for
126     instance: Instance<'tcx>,
127
128     // type of the item, without any generic
129     // parameters substituted; this is
130     // included in the hash as a kind of
131     // safeguard.
132     item_type: Ty<'tcx>,
133
134     // values for generic type parameters,
135     // if any.
136     substs: SubstsRef<'tcx>,
137 ) -> u64 {
138     debug!(
139         "get_symbol_hash(def_id={:?}, parameters={:?})",
140         def_id, substs
141     );
142
143     let mut hasher = StableHasher::<u64>::new();
144     let mut hcx = tcx.create_stable_hashing_context();
145
146     record_time(&tcx.sess.perf_stats.symbol_hash_time, || {
147         // the main symbol name is not necessarily unique; hash in the
148         // compiler's internal def-path, guaranteeing each symbol has a
149         // truly unique path
150         tcx.def_path_hash(def_id).hash_stable(&mut hcx, &mut hasher);
151
152         // Include the main item-type. Note that, in this case, the
153         // assertions about `needs_subst` may not hold, but this item-type
154         // ought to be the same for every reference anyway.
155         assert!(!item_type.has_erasable_regions());
156         hcx.while_hashing_spans(false, |hcx| {
157             hcx.with_node_id_hashing_mode(NodeIdHashingMode::HashDefPath, |hcx| {
158                 item_type.hash_stable(hcx, &mut hasher);
159             });
160         });
161
162         // If this is a function, we hash the signature as well.
163         // This is not *strictly* needed, but it may help in some
164         // situations, see the `run-make/a-b-a-linker-guard` test.
165         if let ty::FnDef(..) = item_type.sty {
166             item_type.fn_sig(tcx).hash_stable(&mut hcx, &mut hasher);
167         }
168
169         // also include any type parameters (for generic items)
170         assert!(!substs.has_erasable_regions());
171         assert!(!substs.needs_subst());
172         substs.hash_stable(&mut hcx, &mut hasher);
173
174         let is_generic = substs.non_erasable_generics().next().is_some();
175         let avoid_cross_crate_conflicts =
176             // If this is an instance of a generic function, we also hash in
177             // the ID of the instantiating crate. This avoids symbol conflicts
178             // in case the same instances is emitted in two crates of the same
179             // project.
180             is_generic ||
181
182             // If we're dealing with an instance of a function that's inlined from
183             // another crate but we're marking it as globally shared to our
184             // compliation (aka we're not making an internal copy in each of our
185             // codegen units) then this symbol may become an exported (but hidden
186             // visibility) symbol. This means that multiple crates may do the same
187             // and we want to be sure to avoid any symbol conflicts here.
188             match MonoItem::Fn(instance).instantiation_mode(tcx) {
189                 InstantiationMode::GloballyShared { may_conflict: true } => true,
190                 _ => false,
191             };
192
193         if avoid_cross_crate_conflicts {
194             let instantiating_crate = if is_generic {
195                 if !def_id.is_local() && tcx.sess.opts.share_generics() {
196                     // If we are re-using a monomorphization from another crate,
197                     // we have to compute the symbol hash accordingly.
198                     let upstream_monomorphizations = tcx.upstream_monomorphizations_for(def_id);
199
200                     upstream_monomorphizations
201                         .and_then(|monos| monos.get(&substs).cloned())
202                         .unwrap_or(LOCAL_CRATE)
203                 } else {
204                     LOCAL_CRATE
205                 }
206             } else {
207                 LOCAL_CRATE
208             };
209
210             (&tcx.original_crate_name(instantiating_crate).as_str()[..])
211                 .hash_stable(&mut hcx, &mut hasher);
212             (&tcx.crate_disambiguator(instantiating_crate)).hash_stable(&mut hcx, &mut hasher);
213         }
214
215         // We want to avoid accidental collision between different types of instances.
216         // Especially, VtableShim may overlap with its original instance without this.
217         discriminant(&instance.def).hash_stable(&mut hcx, &mut hasher);
218     });
219
220     // 64 bits should be enough to avoid collisions.
221     hasher.finish()
222 }
223
224 fn symbol_name(tcx: TyCtxt<'_, 'tcx, 'tcx>, instance: Instance<'tcx>) -> ty::SymbolName {
225     ty::SymbolName {
226         name: compute_symbol_name(tcx, instance),
227     }
228 }
229
230 fn compute_symbol_name(tcx: TyCtxt<'_, 'tcx, 'tcx>, instance: Instance<'tcx>) -> InternedString {
231     let def_id = instance.def_id();
232     let substs = instance.substs;
233
234     debug!("symbol_name(def_id={:?}, substs={:?})", def_id, substs);
235
236     let hir_id = tcx.hir().as_local_hir_id(def_id);
237
238     if def_id.is_local() {
239         if tcx.plugin_registrar_fn(LOCAL_CRATE) == Some(def_id) {
240             let disambiguator = tcx.sess.local_crate_disambiguator();
241             return
242                 InternedString::intern(&tcx.sess.generate_plugin_registrar_symbol(disambiguator));
243         }
244         if tcx.proc_macro_decls_static(LOCAL_CRATE) == Some(def_id) {
245             let disambiguator = tcx.sess.local_crate_disambiguator();
246             return
247                 InternedString::intern(&tcx.sess.generate_proc_macro_decls_symbol(disambiguator));
248         }
249     }
250
251     // FIXME(eddyb) Precompute a custom symbol name based on attributes.
252     let is_foreign = if let Some(id) = hir_id {
253         match tcx.hir().get_by_hir_id(id) {
254             Node::ForeignItem(_) => true,
255             _ => false,
256         }
257     } else {
258         tcx.is_foreign_item(def_id)
259     };
260
261     let attrs = tcx.codegen_fn_attrs(def_id);
262     if is_foreign {
263         if let Some(name) = attrs.link_name {
264             return name.as_interned_str();
265         }
266         // Don't mangle foreign items.
267         return tcx.item_name(def_id);
268     }
269
270     if let Some(name) = &attrs.export_name {
271         // Use provided name
272         return name.as_interned_str();
273     }
274
275     if attrs.flags.contains(CodegenFnAttrFlags::NO_MANGLE) {
276         // Don't mangle
277         return tcx.item_name(def_id);
278     }
279
280     // We want to compute the "type" of this item. Unfortunately, some
281     // kinds of items (e.g., closures) don't have an entry in the
282     // item-type array. So walk back up the find the closest parent
283     // that DOES have an entry.
284     let mut ty_def_id = def_id;
285     let instance_ty;
286     loop {
287         let key = tcx.def_key(ty_def_id);
288         match key.disambiguated_data.data {
289             DefPathData::TypeNs(_) | DefPathData::ValueNs(_) => {
290                 instance_ty = tcx.type_of(ty_def_id);
291                 break;
292             }
293             _ => {
294                 // if we're making a symbol for something, there ought
295                 // to be a value or type-def or something in there
296                 // *somewhere*
297                 ty_def_id.index = key.parent.unwrap_or_else(|| {
298                     bug!(
299                         "finding type for {:?}, encountered def-id {:?} with no \
300                          parent",
301                         def_id,
302                         ty_def_id
303                     );
304                 });
305             }
306         }
307     }
308
309     // Erase regions because they may not be deterministic when hashed
310     // and should not matter anyhow.
311     let instance_ty = tcx.erase_regions(&instance_ty);
312
313     let hash = get_symbol_hash(tcx, def_id, instance, instance_ty, substs);
314
315     let mut printer = SymbolPrinter {
316         tcx,
317         path: SymbolPath::new(),
318         keep_within_component: false,
319     }.print_def_path(def_id, &[]).unwrap();
320
321     if instance.is_vtable_shim() {
322         let _ = printer.write_str("{{vtable-shim}}");
323     }
324
325     InternedString::intern(&printer.path.finish(hash))
326 }
327
328 // Follow C++ namespace-mangling style, see
329 // http://en.wikipedia.org/wiki/Name_mangling for more info.
330 //
331 // It turns out that on macOS you can actually have arbitrary symbols in
332 // function names (at least when given to LLVM), but this is not possible
333 // when using unix's linker. Perhaps one day when we just use a linker from LLVM
334 // we won't need to do this name mangling. The problem with name mangling is
335 // that it seriously limits the available characters. For example we can't
336 // have things like &T in symbol names when one would theoretically
337 // want them for things like impls of traits on that type.
338 //
339 // To be able to work on all platforms and get *some* reasonable output, we
340 // use C++ name-mangling.
341 #[derive(Debug)]
342 struct SymbolPath {
343     result: String,
344     temp_buf: String,
345 }
346
347 impl SymbolPath {
348     fn new() -> Self {
349         let mut result = SymbolPath {
350             result: String::with_capacity(64),
351             temp_buf: String::with_capacity(16),
352         };
353         result.result.push_str("_ZN"); // _Z == Begin name-sequence, N == nested
354         result
355     }
356
357     fn finalize_pending_component(&mut self) {
358         if !self.temp_buf.is_empty() {
359             let _ = write!(self.result, "{}{}", self.temp_buf.len(), self.temp_buf);
360             self.temp_buf.clear();
361         }
362     }
363
364     fn finish(mut self, hash: u64) -> String {
365         self.finalize_pending_component();
366         // E = end name-sequence
367         let _ = write!(self.result, "17h{:016x}E", hash);
368         self.result
369     }
370 }
371
372 struct SymbolPrinter<'a, 'tcx> {
373     tcx: TyCtxt<'a, 'tcx, 'tcx>,
374     path: SymbolPath,
375
376     // When `true`, `finalize_pending_component` isn't used.
377     // This is needed when recursing into `path_qualified`,
378     // or `path_generic_args`, as any nested paths are
379     // logically within one component.
380     keep_within_component: bool,
381 }
382
383 // HACK(eddyb) this relies on using the `fmt` interface to get
384 // `PrettyPrinter` aka pretty printing of e.g. types in paths,
385 // symbol names should have their own printing machinery.
386
387 impl Printer<'tcx, 'tcx> for SymbolPrinter<'_, 'tcx> {
388     type Error = fmt::Error;
389
390     type Path = Self;
391     type Region = Self;
392     type Type = Self;
393     type DynExistential = Self;
394
395     fn tcx(&'a self) -> TyCtxt<'a, 'tcx, 'tcx> {
396         self.tcx
397     }
398
399     fn print_region(
400         self,
401         _region: ty::Region<'_>,
402     ) -> Result<Self::Region, Self::Error> {
403         Ok(self)
404     }
405
406     fn print_type(
407         self,
408         ty: Ty<'tcx>,
409     ) -> Result<Self::Type, Self::Error> {
410         match ty.sty {
411             // Print all nominal types as paths (unlike `pretty_print_type`).
412             ty::FnDef(def_id, substs) |
413             ty::Opaque(def_id, substs) |
414             ty::Projection(ty::ProjectionTy { item_def_id: def_id, substs }) |
415             ty::UnnormalizedProjection(ty::ProjectionTy { item_def_id: def_id, substs }) |
416             ty::Closure(def_id, ty::ClosureSubsts { substs }) |
417             ty::Generator(def_id, ty::GeneratorSubsts { substs }, _) => {
418                 self.print_def_path(def_id, substs)
419             }
420             _ => self.pretty_print_type(ty),
421         }
422     }
423
424     fn print_dyn_existential(
425         mut self,
426         predicates: &'tcx ty::List<ty::ExistentialPredicate<'tcx>>,
427     ) -> Result<Self::DynExistential, Self::Error> {
428         let mut first = false;
429         for p in predicates {
430             if !first {
431                 write!(self, "+")?;
432             }
433             first = false;
434             self = p.print(self)?;
435         }
436         Ok(self)
437     }
438
439     fn path_crate(
440         mut self,
441         cnum: CrateNum,
442     ) -> Result<Self::Path, Self::Error> {
443         self.write_str(&self.tcx.original_crate_name(cnum).as_str())?;
444         Ok(self)
445     }
446     fn path_qualified(
447         self,
448         self_ty: Ty<'tcx>,
449         trait_ref: Option<ty::TraitRef<'tcx>>,
450     ) -> Result<Self::Path, Self::Error> {
451         // Similar to `pretty_path_qualified`, but for the other
452         // types that are printed as paths (see `print_type` above).
453         match self_ty.sty {
454             ty::FnDef(..) |
455             ty::Opaque(..) |
456             ty::Projection(_) |
457             ty::UnnormalizedProjection(_) |
458             ty::Closure(..) |
459             ty::Generator(..)
460                 if trait_ref.is_none() =>
461             {
462                 self.print_type(self_ty)
463             }
464
465             _ => self.pretty_path_qualified(self_ty, trait_ref)
466         }
467     }
468
469     fn path_append_impl(
470         self,
471         print_prefix: impl FnOnce(Self) -> Result<Self::Path, Self::Error>,
472         _disambiguated_data: &DisambiguatedDefPathData,
473         self_ty: Ty<'tcx>,
474         trait_ref: Option<ty::TraitRef<'tcx>>,
475     ) -> Result<Self::Path, Self::Error> {
476         self.pretty_path_append_impl(
477             |mut cx| {
478                 cx = print_prefix(cx)?;
479
480                 if cx.keep_within_component {
481                     // HACK(eddyb) print the path similarly to how `FmtPrinter` prints it.
482                     cx.write_str("::")?;
483                 } else {
484                     cx.path.finalize_pending_component();
485                 }
486
487                 Ok(cx)
488             },
489             self_ty,
490             trait_ref,
491         )
492     }
493     fn path_append(
494         mut self,
495         print_prefix: impl FnOnce(Self) -> Result<Self::Path, Self::Error>,
496         disambiguated_data: &DisambiguatedDefPathData,
497     ) -> Result<Self::Path, Self::Error> {
498         self = print_prefix(self)?;
499
500         // Skip `::{{constructor}}` on tuple/unit structs.
501         match disambiguated_data.data {
502             DefPathData::Ctor => return Ok(self),
503             _ => {}
504         }
505
506         if self.keep_within_component {
507             // HACK(eddyb) print the path similarly to how `FmtPrinter` prints it.
508             self.write_str("::")?;
509         } else {
510             self.path.finalize_pending_component();
511         }
512
513         self.write_str(&disambiguated_data.data.as_interned_str().as_str())?;
514         Ok(self)
515     }
516     fn path_generic_args(
517         mut self,
518         print_prefix: impl FnOnce(Self) -> Result<Self::Path, Self::Error>,
519         args: &[Kind<'tcx>],
520     )  -> Result<Self::Path, Self::Error> {
521         self = print_prefix(self)?;
522
523         let args = args.iter().cloned().filter(|arg| {
524             match arg.unpack() {
525                 UnpackedKind::Lifetime(_) => false,
526                 _ => true,
527             }
528         });
529
530         if args.clone().next().is_some() {
531             self.generic_delimiters(|cx| cx.comma_sep(args))
532         } else {
533             Ok(self)
534         }
535     }
536 }
537
538 impl PrettyPrinter<'tcx, 'tcx> for SymbolPrinter<'_, 'tcx> {
539     fn region_should_not_be_omitted(
540         &self,
541         _region: ty::Region<'_>,
542     ) -> bool {
543         false
544     }
545     fn comma_sep<T>(
546         mut self,
547         mut elems: impl Iterator<Item = T>,
548     ) -> Result<Self, Self::Error>
549         where T: Print<'tcx, 'tcx, Self, Output = Self, Error = Self::Error>
550     {
551         if let Some(first) = elems.next() {
552             self = first.print(self)?;
553             for elem in elems {
554                 self.write_str(",")?;
555                 self = elem.print(self)?;
556             }
557         }
558         Ok(self)
559     }
560
561     fn generic_delimiters(
562         mut self,
563         f: impl FnOnce(Self) -> Result<Self, Self::Error>,
564     ) -> Result<Self, Self::Error> {
565         write!(self, "<")?;
566
567         let kept_within_component =
568             mem::replace(&mut self.keep_within_component, true);
569         self = f(self)?;
570         self.keep_within_component = kept_within_component;
571
572         write!(self, ">")?;
573
574         Ok(self)
575     }
576 }
577
578 impl fmt::Write for SymbolPrinter<'_, '_> {
579     fn write_str(&mut self, s: &str) -> fmt::Result {
580         // Name sanitation. LLVM will happily accept identifiers with weird names, but
581         // gas doesn't!
582         // gas accepts the following characters in symbols: a-z, A-Z, 0-9, ., _, $
583         // NVPTX assembly has more strict naming rules than gas, so additionally, dots
584         // are replaced with '$' there.
585
586         for c in s.chars() {
587             if self.path.temp_buf.is_empty() {
588                 match c {
589                     'a'..='z' | 'A'..='Z' | '_' => {}
590                     _ => {
591                         // Underscore-qualify anything that didn't start as an ident.
592                         self.path.temp_buf.push('_');
593                     }
594                 }
595             }
596             match c {
597                 // Escape these with $ sequences
598                 '@' => self.path.temp_buf.push_str("$SP$"),
599                 '*' => self.path.temp_buf.push_str("$BP$"),
600                 '&' => self.path.temp_buf.push_str("$RF$"),
601                 '<' => self.path.temp_buf.push_str("$LT$"),
602                 '>' => self.path.temp_buf.push_str("$GT$"),
603                 '(' => self.path.temp_buf.push_str("$LP$"),
604                 ')' => self.path.temp_buf.push_str("$RP$"),
605                 ',' => self.path.temp_buf.push_str("$C$"),
606
607                 '-' | ':' | '.' if self.tcx.has_strict_asm_symbol_naming() => {
608                     // NVPTX doesn't support these characters in symbol names.
609                     self.path.temp_buf.push('$')
610                 }
611
612                 // '.' doesn't occur in types and functions, so reuse it
613                 // for ':' and '-'
614                 '-' | ':' => self.path.temp_buf.push('.'),
615
616                 // These are legal symbols
617                 'a'..='z' | 'A'..='Z' | '0'..='9' | '_' | '.' | '$' => self.path.temp_buf.push(c),
618
619                 _ => {
620                     self.path.temp_buf.push('$');
621                     for c in c.escape_unicode().skip(1) {
622                         match c {
623                             '{' => {}
624                             '}' => self.path.temp_buf.push('$'),
625                             c => self.path.temp_buf.push(c),
626                         }
627                     }
628                 }
629             }
630         }
631
632         Ok(())
633     }
634 }