]> git.lizzy.rs Git - rust.git/blob - src/librustc_codegen_utils/symbol_names.rs
40dc22309664a1a90d06379ae5f3d90fde1073fa
[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::Namespace;
91 use rustc::hir::def_id::{CrateNum, DefId, LOCAL_CRATE};
92 use rustc::hir::Node;
93 use rustc::hir::CodegenFnAttrFlags;
94 use rustc::hir::map::definitions::DefPathData;
95 use rustc::ich::NodeIdHashingMode;
96 use rustc::ty::print::{PrettyPrinter, PrintCx, Printer};
97 use rustc::ty::query::Providers;
98 use rustc::ty::subst::SubstsRef;
99 use rustc::ty::{self, Ty, TyCtxt, TypeFoldable};
100 use rustc::util::common::record_time;
101 use rustc_data_structures::stable_hasher::{HashStable, StableHasher};
102 use rustc_mir::monomorphize::item::{InstantiationMode, MonoItem, MonoItemExt};
103 use rustc_mir::monomorphize::Instance;
104
105 use syntax_pos::symbol::Symbol;
106
107 use log::debug;
108
109 use std::fmt::{self, Write};
110 use std::iter;
111 use std::mem::{self, discriminant};
112
113 pub fn provide(providers: &mut Providers<'_>) {
114     *providers = Providers {
115         def_symbol_name,
116         symbol_name,
117
118         ..*providers
119     };
120 }
121
122 fn get_symbol_hash<'a, 'tcx>(
123     tcx: TyCtxt<'a, 'tcx, 'tcx>,
124
125     // the DefId of the item this name is for
126     def_id: DefId,
127
128     // instance this name will be for
129     instance: Instance<'tcx>,
130
131     // type of the item, without any generic
132     // parameters substituted; this is
133     // included in the hash as a kind of
134     // safeguard.
135     item_type: Ty<'tcx>,
136
137     // values for generic type parameters,
138     // if any.
139     substs: SubstsRef<'tcx>,
140 ) -> u64 {
141     debug!(
142         "get_symbol_hash(def_id={:?}, parameters={:?})",
143         def_id, substs
144     );
145
146     let mut hasher = StableHasher::<u64>::new();
147     let mut hcx = tcx.create_stable_hashing_context();
148
149     record_time(&tcx.sess.perf_stats.symbol_hash_time, || {
150         // the main symbol name is not necessarily unique; hash in the
151         // compiler's internal def-path, guaranteeing each symbol has a
152         // truly unique path
153         tcx.def_path_hash(def_id).hash_stable(&mut hcx, &mut hasher);
154
155         // Include the main item-type. Note that, in this case, the
156         // assertions about `needs_subst` may not hold, but this item-type
157         // ought to be the same for every reference anyway.
158         assert!(!item_type.has_erasable_regions());
159         hcx.while_hashing_spans(false, |hcx| {
160             hcx.with_node_id_hashing_mode(NodeIdHashingMode::HashDefPath, |hcx| {
161                 item_type.hash_stable(hcx, &mut hasher);
162             });
163         });
164
165         // If this is a function, we hash the signature as well.
166         // This is not *strictly* needed, but it may help in some
167         // situations, see the `run-make/a-b-a-linker-guard` test.
168         if let ty::FnDef(..) = item_type.sty {
169             item_type.fn_sig(tcx).hash_stable(&mut hcx, &mut hasher);
170         }
171
172         // also include any type parameters (for generic items)
173         assert!(!substs.has_erasable_regions());
174         assert!(!substs.needs_subst());
175         substs.hash_stable(&mut hcx, &mut hasher);
176
177         let is_generic = substs.non_erasable_generics().next().is_some();
178         let avoid_cross_crate_conflicts =
179             // If this is an instance of a generic function, we also hash in
180             // the ID of the instantiating crate. This avoids symbol conflicts
181             // in case the same instances is emitted in two crates of the same
182             // project.
183             is_generic ||
184
185             // If we're dealing with an instance of a function that's inlined from
186             // another crate but we're marking it as globally shared to our
187             // compliation (aka we're not making an internal copy in each of our
188             // codegen units) then this symbol may become an exported (but hidden
189             // visibility) symbol. This means that multiple crates may do the same
190             // and we want to be sure to avoid any symbol conflicts here.
191             match MonoItem::Fn(instance).instantiation_mode(tcx) {
192                 InstantiationMode::GloballyShared { may_conflict: true } => true,
193                 _ => false,
194             };
195
196         if avoid_cross_crate_conflicts {
197             let instantiating_crate = if is_generic {
198                 if !def_id.is_local() && tcx.sess.opts.share_generics() {
199                     // If we are re-using a monomorphization from another crate,
200                     // we have to compute the symbol hash accordingly.
201                     let upstream_monomorphizations = tcx.upstream_monomorphizations_for(def_id);
202
203                     upstream_monomorphizations
204                         .and_then(|monos| monos.get(&substs).cloned())
205                         .unwrap_or(LOCAL_CRATE)
206                 } else {
207                     LOCAL_CRATE
208                 }
209             } else {
210                 LOCAL_CRATE
211             };
212
213             (&tcx.original_crate_name(instantiating_crate).as_str()[..])
214                 .hash_stable(&mut hcx, &mut hasher);
215             (&tcx.crate_disambiguator(instantiating_crate)).hash_stable(&mut hcx, &mut hasher);
216         }
217
218         // We want to avoid accidental collision between different types of instances.
219         // Especially, VtableShim may overlap with its original instance without this.
220         discriminant(&instance.def).hash_stable(&mut hcx, &mut hasher);
221     });
222
223     // 64 bits should be enough to avoid collisions.
224     hasher.finish()
225 }
226
227 fn def_symbol_name<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, def_id: DefId) -> ty::SymbolName {
228     PrintCx::with(tcx, SymbolPath::new(tcx), |cx| {
229         cx.print_def_path(def_id, None, Namespace::ValueNS, iter::empty())
230             .unwrap()
231             .into_interned()
232     })
233 }
234
235 fn symbol_name<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, instance: Instance<'tcx>) -> ty::SymbolName {
236     ty::SymbolName {
237         name: Symbol::intern(&compute_symbol_name(tcx, instance)).as_interned_str(),
238     }
239 }
240
241 fn compute_symbol_name<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, instance: Instance<'tcx>) -> String {
242     let def_id = instance.def_id();
243     let substs = instance.substs;
244
245     debug!("symbol_name(def_id={:?}, substs={:?})", def_id, substs);
246
247     let hir_id = tcx.hir().as_local_hir_id(def_id);
248
249     if def_id.is_local() {
250         if tcx.plugin_registrar_fn(LOCAL_CRATE) == Some(def_id) {
251             let disambiguator = tcx.sess.local_crate_disambiguator();
252             return tcx.sess.generate_plugin_registrar_symbol(disambiguator);
253         }
254         if tcx.proc_macro_decls_static(LOCAL_CRATE) == Some(def_id) {
255             let disambiguator = tcx.sess.local_crate_disambiguator();
256             return tcx.sess.generate_proc_macro_decls_symbol(disambiguator);
257         }
258     }
259
260     // FIXME(eddyb) Precompute a custom symbol name based on attributes.
261     let is_foreign = if let Some(id) = hir_id {
262         match tcx.hir().get_by_hir_id(id) {
263             Node::ForeignItem(_) => true,
264             _ => false,
265         }
266     } else {
267         tcx.is_foreign_item(def_id)
268     };
269
270     let attrs = tcx.codegen_fn_attrs(def_id);
271     if is_foreign {
272         if let Some(name) = attrs.link_name {
273             return name.to_string();
274         }
275         // Don't mangle foreign items.
276         return tcx.item_name(def_id).to_string();
277     }
278
279     if let Some(name) = &attrs.export_name {
280         // Use provided name
281         return name.to_string();
282     }
283
284     if attrs.flags.contains(CodegenFnAttrFlags::NO_MANGLE) {
285         // Don't mangle
286         return tcx.item_name(def_id).to_string();
287     }
288
289     // We want to compute the "type" of this item. Unfortunately, some
290     // kinds of items (e.g., closures) don't have an entry in the
291     // item-type array. So walk back up the find the closest parent
292     // that DOES have an entry.
293     let mut ty_def_id = def_id;
294     let instance_ty;
295     loop {
296         let key = tcx.def_key(ty_def_id);
297         match key.disambiguated_data.data {
298             DefPathData::TypeNs(_) | DefPathData::ValueNs(_) => {
299                 instance_ty = tcx.type_of(ty_def_id);
300                 break;
301             }
302             _ => {
303                 // if we're making a symbol for something, there ought
304                 // to be a value or type-def or something in there
305                 // *somewhere*
306                 ty_def_id.index = key.parent.unwrap_or_else(|| {
307                     bug!(
308                         "finding type for {:?}, encountered def-id {:?} with no \
309                          parent",
310                         def_id,
311                         ty_def_id
312                     );
313                 });
314             }
315         }
316     }
317
318     // Erase regions because they may not be deterministic when hashed
319     // and should not matter anyhow.
320     let instance_ty = tcx.erase_regions(&instance_ty);
321
322     let hash = get_symbol_hash(tcx, def_id, instance, instance_ty, substs);
323
324     let mut buf = SymbolPath::from_interned(tcx.def_symbol_name(def_id), tcx);
325
326     if instance.is_vtable_shim() {
327         let _ = buf.write_str("{{vtable-shim}}");
328     }
329
330     buf.finish(hash)
331 }
332
333 // Follow C++ namespace-mangling style, see
334 // http://en.wikipedia.org/wiki/Name_mangling for more info.
335 //
336 // It turns out that on macOS you can actually have arbitrary symbols in
337 // function names (at least when given to LLVM), but this is not possible
338 // when using unix's linker. Perhaps one day when we just use a linker from LLVM
339 // we won't need to do this name mangling. The problem with name mangling is
340 // that it seriously limits the available characters. For example we can't
341 // have things like &T in symbol names when one would theoretically
342 // want them for things like impls of traits on that type.
343 //
344 // To be able to work on all platforms and get *some* reasonable output, we
345 // use C++ name-mangling.
346 #[derive(Debug)]
347 struct SymbolPath {
348     result: String,
349     temp_buf: String,
350     strict_naming: bool,
351
352     // When `true`, `finalize_pending_component` isn't used.
353     // This is needed when recursing into `path_qualified`,
354     // or `path_generic_args`, as any nested paths are
355     // logically within one component.
356     keep_within_component: bool,
357 }
358
359 impl SymbolPath {
360     fn new(tcx: TyCtxt<'_, '_, '_>) -> Self {
361         let mut result = SymbolPath {
362             result: String::with_capacity(64),
363             temp_buf: String::with_capacity(16),
364             strict_naming: tcx.has_strict_asm_symbol_naming(),
365             keep_within_component: false,
366         };
367         result.result.push_str("_ZN"); // _Z == Begin name-sequence, N == nested
368         result
369     }
370
371     fn from_interned(symbol: ty::SymbolName, tcx: TyCtxt<'_, '_, '_>) -> Self {
372         let mut result = SymbolPath {
373             result: String::with_capacity(64),
374             temp_buf: String::with_capacity(16),
375             strict_naming: tcx.has_strict_asm_symbol_naming(),
376             keep_within_component: false,
377         };
378         result.result.push_str(&symbol.as_str());
379         result
380     }
381
382     fn into_interned(mut self) -> ty::SymbolName {
383         self.finalize_pending_component();
384         ty::SymbolName {
385             name: Symbol::intern(&self.result).as_interned_str(),
386         }
387     }
388
389     fn finalize_pending_component(&mut self) {
390         if !self.temp_buf.is_empty() {
391             let _ = write!(self.result, "{}{}", self.temp_buf.len(), self.temp_buf);
392             self.temp_buf.clear();
393         }
394     }
395
396     fn finish(mut self, hash: u64) -> String {
397         self.finalize_pending_component();
398         // E = end name-sequence
399         let _ = write!(self.result, "17h{:016x}E", hash);
400         self.result
401     }
402 }
403
404 // HACK(eddyb) this relies on using the `fmt` interface to get
405 // `PrettyPrinter` aka pretty printing of e.g. types in paths,
406 // symbol names should have their own printing machinery.
407
408 impl Printer for SymbolPath {
409     type Error = fmt::Error;
410
411     type Path = Self;
412     type Region = Self;
413     type Type = Self;
414
415     fn print_region(
416         self: PrintCx<'_, '_, '_, Self>,
417         _region: ty::Region<'_>,
418     ) -> Result<Self::Region, Self::Error> {
419         Ok(self.printer)
420     }
421
422     fn print_type(
423         self: PrintCx<'_, '_, 'tcx, Self>,
424         ty: Ty<'tcx>,
425     ) -> Result<Self::Type, Self::Error> {
426         self.pretty_print_type(ty)
427     }
428
429     fn path_crate(
430         mut self: PrintCx<'_, '_, '_, Self>,
431         cnum: CrateNum,
432     ) -> Result<Self::Path, Self::Error> {
433         self.printer.write_str(&self.tcx.original_crate_name(cnum).as_str())?;
434         Ok(self.printer)
435     }
436     fn path_qualified(
437         self: PrintCx<'_, '_, 'tcx, Self>,
438         self_ty: Ty<'tcx>,
439         trait_ref: Option<ty::TraitRef<'tcx>>,
440         ns: Namespace,
441     ) -> Result<Self::Path, Self::Error> {
442         self.pretty_path_qualified(self_ty, trait_ref, ns)
443     }
444
445     fn path_append_impl<'gcx, 'tcx>(
446         self: PrintCx<'_, 'gcx, 'tcx, Self>,
447         print_prefix: impl FnOnce(
448             PrintCx<'_, 'gcx, 'tcx, Self>,
449         ) -> Result<Self::Path, Self::Error>,
450         self_ty: Ty<'tcx>,
451         trait_ref: Option<ty::TraitRef<'tcx>>,
452     ) -> Result<Self::Path, Self::Error> {
453         self.pretty_path_append_impl(
454             |cx| cx.path_append(print_prefix, ""),
455             self_ty,
456             trait_ref,
457         )
458     }
459     fn path_append<'gcx, 'tcx>(
460         self: PrintCx<'_, 'gcx, 'tcx, Self>,
461         print_prefix: impl FnOnce(
462             PrintCx<'_, 'gcx, 'tcx, Self>,
463         ) -> Result<Self::Path, Self::Error>,
464         text: &str,
465     ) -> Result<Self::Path, Self::Error> {
466         let mut path = print_prefix(self)?;
467
468         if path.keep_within_component {
469             // HACK(eddyb) print the path similarly to how `FmtPrinter` prints it.
470             path.write_str("::")?;
471         } else {
472             path.finalize_pending_component();
473         }
474
475         path.write_str(text)?;
476         Ok(path)
477     }
478     fn path_generic_args<'gcx, 'tcx>(
479         self: PrintCx<'_, 'gcx, 'tcx, Self>,
480         print_prefix: impl FnOnce(
481             PrintCx<'_, 'gcx, 'tcx, Self>,
482         ) -> Result<Self::Path, Self::Error>,
483         params: &[ty::GenericParamDef],
484         substs: SubstsRef<'tcx>,
485         ns: Namespace,
486         projections: impl Iterator<Item = ty::ExistentialProjection<'tcx>>,
487     )  -> Result<Self::Path, Self::Error> {
488         self.pretty_path_generic_args(print_prefix, params, substs, ns, projections)
489     }
490 }
491
492 impl PrettyPrinter for SymbolPath {
493     fn print_region_outputs_anything(
494         self: &PrintCx<'_, '_, '_, Self>,
495         _region: ty::Region<'_>,
496     ) -> bool {
497         false
498     }
499
500     fn generic_delimiters<'gcx, 'tcx>(
501         mut self: PrintCx<'_, 'gcx, 'tcx, Self>,
502         f: impl FnOnce(PrintCx<'_, 'gcx, 'tcx, Self>) -> Result<Self, Self::Error>,
503     ) -> Result<Self, Self::Error> {
504         write!(self.printer, "<")?;
505
506         let kept_within_component =
507             mem::replace(&mut self.printer.keep_within_component, true);
508         let mut path = f(self)?;
509         path.keep_within_component = kept_within_component;
510
511         write!(path, ">")?;
512
513         Ok(path)
514     }
515 }
516
517 impl fmt::Write for SymbolPath {
518     fn write_str(&mut self, s: &str) -> fmt::Result {
519         // Name sanitation. LLVM will happily accept identifiers with weird names, but
520         // gas doesn't!
521         // gas accepts the following characters in symbols: a-z, A-Z, 0-9, ., _, $
522         // NVPTX assembly has more strict naming rules than gas, so additionally, dots
523         // are replaced with '$' there.
524
525         for c in s.chars() {
526             if self.temp_buf.is_empty() {
527                 match c {
528                     'a'..='z' | 'A'..='Z' | '_' => {}
529                     _ => {
530                         // Underscore-qualify anything that didn't start as an ident.
531                         self.temp_buf.push('_');
532                     }
533                 }
534             }
535             match c {
536                 // Escape these with $ sequences
537                 '@' => self.temp_buf.push_str("$SP$"),
538                 '*' => self.temp_buf.push_str("$BP$"),
539                 '&' => self.temp_buf.push_str("$RF$"),
540                 '<' => self.temp_buf.push_str("$LT$"),
541                 '>' => self.temp_buf.push_str("$GT$"),
542                 '(' => self.temp_buf.push_str("$LP$"),
543                 ')' => self.temp_buf.push_str("$RP$"),
544                 ',' => self.temp_buf.push_str("$C$"),
545
546                 '-' | ':' | '.' if self.strict_naming => {
547                     // NVPTX doesn't support these characters in symbol names.
548                     self.temp_buf.push('$')
549                 }
550
551                 // '.' doesn't occur in types and functions, so reuse it
552                 // for ':' and '-'
553                 '-' | ':' => self.temp_buf.push('.'),
554
555                 // These are legal symbols
556                 'a'..='z' | 'A'..='Z' | '0'..='9' | '_' | '.' | '$' => self.temp_buf.push(c),
557
558                 _ => {
559                     self.temp_buf.push('$');
560                     for c in c.escape_unicode().skip(1) {
561                         match c {
562                             '{' => {}
563                             '}' => self.temp_buf.push('$'),
564                             c => self.temp_buf.push(c),
565                         }
566                     }
567                 }
568             }
569         }
570
571         Ok(())
572     }
573 }