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