]> git.lizzy.rs Git - rust.git/blob - src/librustc_codegen_utils/symbol_names.rs
ac71ecff96457b59e579ab0e7606360dd2b222bf
[rust.git] / src / librustc_codegen_utils / symbol_names.rs
1 // Copyright 2016 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
4 //
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
10
11 //! The Rust Linkage Model and Symbol Names
12 //! =======================================
13 //!
14 //! The semantic model of Rust linkage is, broadly, that "there's no global
15 //! namespace" between crates. Our aim is to preserve the illusion of this
16 //! model despite the fact that it's not *quite* possible to implement on
17 //! modern linkers. We initially didn't use system linkers at all, but have
18 //! been convinced of their utility.
19 //!
20 //! There are a few issues to handle:
21 //!
22 //!  - Linkers operate on a flat namespace, so we have to flatten names.
23 //!    We do this using the C++ namespace-mangling technique. Foo::bar
24 //!    symbols and such.
25 //!
26 //!  - Symbols for distinct items with the same *name* need to get different
27 //!    linkage-names. Examples of this are monomorphizations of functions or
28 //!    items within anonymous scopes that end up having the same path.
29 //!
30 //!  - Symbols in different crates but with same names "within" the crate need
31 //!    to get different linkage-names.
32 //!
33 //!  - Symbol names should be deterministic: Two consecutive runs of the
34 //!    compiler over the same code base should produce the same symbol names for
35 //!    the same items.
36 //!
37 //!  - Symbol names should not depend on any global properties of the code base,
38 //!    so that small modifications to the code base do not result in all symbols
39 //!    changing. In previous versions of the compiler, symbol names incorporated
40 //!    the SVH (Stable Version Hash) of the crate. This scheme turned out to be
41 //!    infeasible when used in conjunction with incremental compilation because
42 //!    small code changes would invalidate all symbols generated previously.
43 //!
44 //!  - Even symbols from different versions of the same crate should be able to
45 //!    live next to each other without conflict.
46 //!
47 //! In order to fulfill the above requirements the following scheme is used by
48 //! the compiler:
49 //!
50 //! The main tool for avoiding naming conflicts is the incorporation of a 64-bit
51 //! hash value into every exported symbol name. Anything that makes a difference
52 //! to the symbol being named, but does not show up in the regular path needs to
53 //! be fed into this hash:
54 //!
55 //! - Different monomorphizations of the same item have the same path but differ
56 //!   in their concrete type parameters, so these parameters are part of the
57 //!   data being digested for the symbol hash.
58 //!
59 //! - Rust allows items to be defined in anonymous scopes, such as in
60 //!   `fn foo() { { fn bar() {} } { fn bar() {} } }`. Both `bar` functions have
61 //!   the path `foo::bar`, since the anonymous scopes do not contribute to the
62 //!   path of an item. The compiler already handles this case via so-called
63 //!   disambiguating `DefPaths` which use indices to distinguish items with the
64 //!   same name. The DefPaths of the functions above are thus `foo[0]::bar[0]`
65 //!   and `foo[0]::bar[1]`. In order to incorporate this disambiguation
66 //!   information into the symbol name too, these indices are fed into the
67 //!   symbol hash, so that the above two symbols would end up with different
68 //!   hash values.
69 //!
70 //! The two measures described above suffice to avoid intra-crate conflicts. In
71 //! order to also avoid inter-crate conflicts two more measures are taken:
72 //!
73 //! - The name of the crate containing the symbol is prepended to the symbol
74 //!   name, i.e. symbols are "crate qualified". For example, a function `foo` in
75 //!   module `bar` in crate `baz` would get a symbol name like
76 //!   `baz::bar::foo::{hash}` instead of just `bar::foo::{hash}`. This avoids
77 //!   simple conflicts between functions from different crates.
78 //!
79 //! - In order to be able to also use symbols from two versions of the same
80 //!   crate (which naturally also have the same name), a stronger measure is
81 //!   required: The compiler accepts an arbitrary "disambiguator" value via the
82 //!   `-C metadata` commandline argument. This disambiguator is then fed into
83 //!   the symbol hash of every exported item. Consequently, the symbols in two
84 //!   identical crates but with different disambiguators are not in conflict
85 //!   with each other. This facility is mainly intended to be used by build
86 //!   tools like Cargo.
87 //!
88 //! A note on symbol name stability
89 //! -------------------------------
90 //! Previous versions of the compiler resorted to feeding NodeIds into the
91 //! symbol hash in order to disambiguate between items with the same path. The
92 //! current version of the name generation algorithm takes great care not to do
93 //! that, since NodeIds are notoriously unstable: A small change to the
94 //! code base will offset all NodeIds after the change and thus, much as using
95 //! the SVH in the hash, invalidate an unbounded number of symbol names. This
96 //! makes re-using previously compiled code for incremental compilation
97 //! virtually impossible. Thus, symbol hash generation exclusively relies on
98 //! DefPaths which are much more robust in the face of changes to the code base.
99
100 use rustc::hir::def_id::{DefId, LOCAL_CRATE};
101 use rustc::hir::map as hir_map;
102 use rustc::hir::map::definitions::DefPathData;
103 use rustc::ich::NodeIdHashingMode;
104 use rustc::middle::weak_lang_items;
105 use rustc::ty::item_path::{self, ItemPathBuffer, RootMode};
106 use rustc::ty::query::Providers;
107 use rustc::ty::subst::Substs;
108 use rustc::ty::{self, Ty, TyCtxt, TypeFoldable};
109 use rustc::util::common::record_time;
110 use rustc_data_structures::stable_hasher::{HashStable, StableHasher};
111 use rustc_mir::monomorphize::item::{InstantiationMode, MonoItem, MonoItemExt};
112 use rustc_mir::monomorphize::Instance;
113
114 use syntax::attr;
115 use syntax_pos::symbol::Symbol;
116
117 use std::fmt::Write;
118
119 pub fn provide(providers: &mut Providers) {
120     *providers = Providers {
121         def_symbol_name,
122         symbol_name,
123
124         ..*providers
125     };
126 }
127
128 fn get_symbol_hash<'a, 'tcx>(
129     tcx: TyCtxt<'a, 'tcx, 'tcx>,
130
131     // the DefId of the item this name is for
132     def_id: DefId,
133
134     // instance this name will be for
135     instance: Instance<'tcx>,
136
137     // type of the item, without any generic
138     // parameters substituted; this is
139     // included in the hash as a kind of
140     // safeguard.
141     item_type: Ty<'tcx>,
142
143     // values for generic type parameters,
144     // if any.
145     substs: &'tcx Substs<'tcx>,
146 ) -> u64 {
147     debug!(
148         "get_symbol_hash(def_id={:?}, parameters={:?})",
149         def_id, substs
150     );
151
152     let mut hasher = StableHasher::<u64>::new();
153     let mut hcx = tcx.create_stable_hashing_context();
154
155     record_time(&tcx.sess.perf_stats.symbol_hash_time, || {
156         // the main symbol name is not necessarily unique; hash in the
157         // compiler's internal def-path, guaranteeing each symbol has a
158         // truly unique path
159         tcx.def_path_hash(def_id).hash_stable(&mut hcx, &mut hasher);
160
161         // Include the main item-type. Note that, in this case, the
162         // assertions about `needs_subst` may not hold, but this item-type
163         // ought to be the same for every reference anyway.
164         assert!(!item_type.has_erasable_regions());
165         hcx.while_hashing_spans(false, |hcx| {
166             hcx.with_node_id_hashing_mode(NodeIdHashingMode::HashDefPath, |hcx| {
167                 item_type.hash_stable(hcx, &mut hasher);
168             });
169         });
170
171         // If this is a function, we hash the signature as well.
172         // This is not *strictly* needed, but it may help in some
173         // situations, see the `run-make/a-b-a-linker-guard` test.
174         if let ty::TyFnDef(..) = item_type.sty {
175             item_type.fn_sig(tcx).hash_stable(&mut hcx, &mut hasher);
176         }
177
178         // also include any type parameters (for generic items)
179         assert!(!substs.has_erasable_regions());
180         assert!(!substs.needs_subst());
181         substs.hash_stable(&mut hcx, &mut hasher);
182
183         let is_generic = substs.types().next().is_some();
184         let avoid_cross_crate_conflicts =
185             // If this is an instance of a generic function, we also hash in
186             // the ID of the instantiating crate. This avoids symbol conflicts
187             // in case the same instances is emitted in two crates of the same
188             // project.
189             is_generic ||
190
191             // If we're dealing with an instance of a function that's inlined from
192             // another crate but we're marking it as globally shared to our
193             // compliation (aka we're not making an internal copy in each of our
194             // codegen units) then this symbol may become an exported (but hidden
195             // visibility) symbol. This means that multiple crates may do the same
196             // and we want to be sure to avoid any symbol conflicts here.
197             match MonoItem::Fn(instance).instantiation_mode(tcx) {
198                 InstantiationMode::GloballyShared { may_conflict: true } => true,
199                 _ => false,
200             };
201
202         if avoid_cross_crate_conflicts {
203             let instantiating_crate = if is_generic {
204                 if !def_id.is_local() && tcx.share_generics() {
205                     // If we are re-using a monomorphization from another crate,
206                     // we have to compute the symbol hash accordingly.
207                     let upstream_monomorphizations = tcx.upstream_monomorphizations_for(def_id);
208
209                     upstream_monomorphizations
210                         .and_then(|monos| monos.get(&substs).cloned())
211                         .unwrap_or(LOCAL_CRATE)
212                 } else {
213                     LOCAL_CRATE
214                 }
215             } else {
216                 LOCAL_CRATE
217             };
218
219             (&tcx.original_crate_name(instantiating_crate).as_str()[..])
220                 .hash_stable(&mut hcx, &mut hasher);
221             (&tcx.crate_disambiguator(instantiating_crate)).hash_stable(&mut hcx, &mut hasher);
222         }
223     });
224
225     // 64 bits should be enough to avoid collisions.
226     hasher.finish()
227 }
228
229 fn def_symbol_name<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, def_id: DefId) -> ty::SymbolName {
230     let mut buffer = SymbolPathBuffer::new();
231     item_path::with_forced_absolute_paths(|| {
232         tcx.push_item_path(&mut buffer, def_id);
233     });
234     buffer.into_interned()
235 }
236
237 fn symbol_name<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, instance: Instance<'tcx>) -> ty::SymbolName {
238     ty::SymbolName {
239         name: Symbol::intern(&compute_symbol_name(tcx, instance)).as_interned_str(),
240     }
241 }
242
243 fn compute_symbol_name<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, instance: Instance<'tcx>) -> String {
244     let def_id = instance.def_id();
245     let substs = instance.substs;
246
247     debug!("symbol_name(def_id={:?}, substs={:?})", def_id, substs);
248
249     let node_id = tcx.hir.as_local_node_id(def_id);
250
251     if let Some(id) = node_id {
252         if *tcx.sess.plugin_registrar_fn.get() == Some(id) {
253             let disambiguator = tcx.sess.local_crate_disambiguator();
254             return tcx.sess.generate_plugin_registrar_symbol(disambiguator);
255         }
256         if *tcx.sess.derive_registrar_fn.get() == Some(id) {
257             let disambiguator = tcx.sess.local_crate_disambiguator();
258             return tcx.sess.generate_derive_registrar_symbol(disambiguator);
259         }
260     }
261
262     // FIXME(eddyb) Precompute a custom symbol name based on attributes.
263     let attrs = tcx.get_attrs(def_id);
264     let is_foreign = if let Some(id) = node_id {
265         match tcx.hir.get(id) {
266             hir_map::NodeForeignItem(_) => true,
267             _ => false,
268         }
269     } else {
270         tcx.is_foreign_item(def_id)
271     };
272
273     if let Some(name) = weak_lang_items::link_name(&attrs) {
274         return name.to_string();
275     }
276
277     if is_foreign {
278         if let Some(name) = attr::first_attr_value_str_by_name(&attrs, "link_name") {
279             return name.to_string();
280         }
281         // Don't mangle foreign items.
282         return tcx.item_name(def_id).to_string();
283     }
284
285     if let Some(name) = tcx.codegen_fn_attrs(def_id).export_name {
286         // Use provided name
287         return name.to_string();
288     }
289
290     if attr::contains_name(&attrs, "no_mangle") {
291         // Don't mangle
292         return tcx.item_name(def_id).to_string();
293     }
294
295     // We want to compute the "type" of this item. Unfortunately, some
296     // kinds of items (e.g., closures) don't have an entry in the
297     // item-type array. So walk back up the find the closest parent
298     // that DOES have an entry.
299     let mut ty_def_id = def_id;
300     let instance_ty;
301     loop {
302         let key = tcx.def_key(ty_def_id);
303         match key.disambiguated_data.data {
304             DefPathData::TypeNs(_) | DefPathData::ValueNs(_) => {
305                 instance_ty = tcx.type_of(ty_def_id);
306                 break;
307             }
308             _ => {
309                 // if we're making a symbol for something, there ought
310                 // to be a value or type-def or something in there
311                 // *somewhere*
312                 ty_def_id.index = key.parent.unwrap_or_else(|| {
313                     bug!(
314                         "finding type for {:?}, encountered def-id {:?} with no \
315                          parent",
316                         def_id,
317                         ty_def_id
318                     );
319                 });
320             }
321         }
322     }
323
324     // Erase regions because they may not be deterministic when hashed
325     // and should not matter anyhow.
326     let instance_ty = tcx.erase_regions(&instance_ty);
327
328     let hash = get_symbol_hash(tcx, def_id, instance, instance_ty, substs);
329
330     SymbolPathBuffer::from_interned(tcx.def_symbol_name(def_id)).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 struct SymbolPathBuffer {
347     result: String,
348     temp_buf: String,
349 }
350
351 impl SymbolPathBuffer {
352     fn new() -> Self {
353         let mut result = SymbolPathBuffer {
354             result: String::with_capacity(64),
355             temp_buf: String::with_capacity(16),
356         };
357         result.result.push_str("_ZN"); // _Z == Begin name-sequence, N == nested
358         result
359     }
360
361     fn from_interned(symbol: ty::SymbolName) -> Self {
362         let mut result = SymbolPathBuffer {
363             result: String::with_capacity(64),
364             temp_buf: String::with_capacity(16),
365         };
366         result.result.push_str(&symbol.as_str());
367         result
368     }
369
370     fn into_interned(self) -> ty::SymbolName {
371         ty::SymbolName {
372             name: Symbol::intern(&self.result).as_interned_str(),
373         }
374     }
375
376     fn finish(mut self, hash: u64) -> String {
377         // E = end name-sequence
378         let _ = write!(self.result, "17h{:016x}E", hash);
379         self.result
380     }
381 }
382
383 impl ItemPathBuffer for SymbolPathBuffer {
384     fn root_mode(&self) -> &RootMode {
385         const ABSOLUTE: &'static RootMode = &RootMode::Absolute;
386         ABSOLUTE
387     }
388
389     fn push(&mut self, text: &str) {
390         self.temp_buf.clear();
391         let need_underscore = sanitize(&mut self.temp_buf, text);
392         let _ = write!(
393             self.result,
394             "{}",
395             self.temp_buf.len() + (need_underscore as usize)
396         );
397         if need_underscore {
398             self.result.push('_');
399         }
400         self.result.push_str(&self.temp_buf);
401     }
402 }
403
404 // Name sanitation. LLVM will happily accept identifiers with weird names, but
405 // gas doesn't!
406 // gas accepts the following characters in symbols: a-z, A-Z, 0-9, ., _, $
407 //
408 // returns true if an underscore must be added at the start
409 pub fn sanitize(result: &mut String, s: &str) -> bool {
410     for c in s.chars() {
411         match c {
412             // Escape these with $ sequences
413             '@' => result.push_str("$SP$"),
414             '*' => result.push_str("$BP$"),
415             '&' => result.push_str("$RF$"),
416             '<' => result.push_str("$LT$"),
417             '>' => result.push_str("$GT$"),
418             '(' => result.push_str("$LP$"),
419             ')' => result.push_str("$RP$"),
420             ',' => result.push_str("$C$"),
421
422             // '.' doesn't occur in types and functions, so reuse it
423             // for ':' and '-'
424             '-' | ':' => result.push('.'),
425
426             // These are legal symbols
427             'a'..='z' | 'A'..='Z' | '0'..='9' | '_' | '.' | '$' => result.push(c),
428
429             _ => {
430                 result.push('$');
431                 for c in c.escape_unicode().skip(1) {
432                     match c {
433                         '{' => {}
434                         '}' => result.push('$'),
435                         c => result.push(c),
436                     }
437                 }
438             }
439         }
440     }
441
442     // Underscore-qualify anything that didn't start as an ident.
443     !result.is_empty() && result.as_bytes()[0] != '_' as u8
444         && !(result.as_bytes()[0] as char).is_xid_start()
445 }