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.
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.
11 //! The Rust Linkage Model and Symbol Names
12 //! =======================================
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.
20 //! There are a few issues to handle:
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
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.
30 //! - Symbols in different crates but with same names "within" the crate need
31 //! to get different linkage-names.
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
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.
44 //! - Even symbols from different versions of the same crate should be able to
45 //! live next to each other without conflict.
47 //! In order to fulfill the above requirements the following scheme is used by
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:
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.
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
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:
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.
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
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.
100 use common::SharedCrateContext;
101 use monomorphize::Instance;
103 use rustc::middle::weak_lang_items;
104 use rustc::hir::def_id::DefId;
105 use rustc::hir::map as hir_map;
106 use rustc::ty::{self, Ty, TypeFoldable};
107 use rustc::ty::fold::TypeVisitor;
108 use rustc::ty::item_path::{self, ItemPathBuffer, RootMode};
109 use rustc::ty::subst::Substs;
110 use rustc::hir::map::definitions::DefPathData;
111 use rustc::util::common::record_time;
114 use syntax::symbol::{Symbol, InternedString};
116 fn get_symbol_hash<'a, 'tcx>(scx: &SharedCrateContext<'a, 'tcx>,
118 // the DefId of the item this name is for
119 def_id: Option<DefId>,
121 // type of the item, without any generic
122 // parameters substituted; this is
123 // included in the hash as a kind of
127 // values for generic type parameters,
129 substs: Option<&'tcx Substs<'tcx>>)
131 debug!("get_symbol_hash(def_id={:?}, parameters={:?})", def_id, substs);
135 let mut hasher = ty::util::TypeIdHasher::<u64>::new(tcx);
137 record_time(&tcx.sess.perf_stats.symbol_hash_time, || {
138 // the main symbol name is not necessarily unique; hash in the
139 // compiler's internal def-path, guaranteeing each symbol has a
141 hasher.hash(def_id.map(|def_id| tcx.def_path_hash(def_id)));
143 // Include the main item-type. Note that, in this case, the
144 // assertions about `needs_subst` may not hold, but this item-type
145 // ought to be the same for every reference anyway.
146 assert!(!item_type.has_erasable_regions());
147 hasher.visit_ty(item_type);
149 // also include any type parameters (for generic items)
150 if let Some(substs) = substs {
151 assert!(!substs.has_erasable_regions());
152 assert!(!substs.needs_subst());
153 substs.visit_with(&mut hasher);
155 // If this is an instance of a generic function, we also hash in
156 // the ID of the instantiating crate. This avoids symbol conflicts
157 // in case the same instances is emitted in two crates of the same
159 if substs.types().next().is_some() {
160 hasher.hash(scx.tcx().crate_name.as_str());
161 hasher.hash(scx.sess().local_crate_disambiguator().as_str());
166 // 64 bits should be enough to avoid collisions.
167 format!("h{:016x}", hasher.finish())
170 pub fn symbol_name<'a, 'tcx>(instance: Instance<'tcx>,
171 scx: &SharedCrateContext<'a, 'tcx>) -> String {
172 let def_id = instance.def_id();
173 let substs = instance.substs;
175 debug!("symbol_name(def_id={:?}, substs={:?})",
178 let node_id = scx.tcx().hir.as_local_node_id(def_id);
180 if let Some(id) = node_id {
181 if scx.sess().plugin_registrar_fn.get() == Some(id) {
182 let idx = def_id.index;
183 let disambiguator = scx.sess().local_crate_disambiguator();
184 return scx.sess().generate_plugin_registrar_symbol(disambiguator, idx);
186 if scx.sess().derive_registrar_fn.get() == Some(id) {
187 let idx = def_id.index;
188 let disambiguator = scx.sess().local_crate_disambiguator();
189 return scx.sess().generate_derive_registrar_symbol(disambiguator, idx);
193 // FIXME(eddyb) Precompute a custom symbol name based on attributes.
194 let attrs = scx.tcx().get_attrs(def_id);
195 let is_foreign = if let Some(id) = node_id {
196 match scx.tcx().hir.get(id) {
197 hir_map::NodeForeignItem(_) => true,
201 scx.sess().cstore.is_foreign_item(def_id)
204 if let Some(name) = weak_lang_items::link_name(&attrs) {
205 return name.to_string();
209 if let Some(name) = attr::first_attr_value_str_by_name(&attrs, "link_name") {
210 return name.to_string();
212 // Don't mangle foreign items.
213 return scx.tcx().item_name(def_id).as_str().to_string();
216 if let Some(name) = attr::find_export_name_attr(scx.sess().diagnostic(), &attrs) {
218 return name.to_string();
221 if attr::contains_name(&attrs, "no_mangle") {
223 return scx.tcx().item_name(def_id).as_str().to_string();
226 // We want to compute the "type" of this item. Unfortunately, some
227 // kinds of items (e.g., closures) don't have an entry in the
228 // item-type array. So walk back up the find the closest parent
229 // that DOES have an entry.
230 let mut ty_def_id = def_id;
233 let key = scx.tcx().def_key(ty_def_id);
234 match key.disambiguated_data.data {
235 DefPathData::TypeNs(_) |
236 DefPathData::ValueNs(_) => {
237 instance_ty = scx.tcx().item_type(ty_def_id);
241 // if we're making a symbol for something, there ought
242 // to be a value or type-def or something in there
244 ty_def_id.index = key.parent.unwrap_or_else(|| {
245 bug!("finding type for {:?}, encountered def-id {:?} with no \
246 parent", def_id, ty_def_id);
252 // Erase regions because they may not be deterministic when hashed
253 // and should not matter anyhow.
254 let instance_ty = scx.tcx().erase_regions(&instance_ty);
256 let hash = get_symbol_hash(scx, Some(def_id), instance_ty, Some(substs));
258 let mut buffer = SymbolPathBuffer {
262 item_path::with_forced_absolute_paths(|| {
263 scx.tcx().push_item_path(&mut buffer, def_id);
266 mangle(buffer.names.into_iter(), &hash)
269 struct SymbolPathBuffer {
270 names: Vec<InternedString>,
273 impl ItemPathBuffer for SymbolPathBuffer {
274 fn root_mode(&self) -> &RootMode {
275 const ABSOLUTE: &'static RootMode = &RootMode::Absolute;
279 fn push(&mut self, text: &str) {
280 self.names.push(Symbol::intern(text).as_str());
284 pub fn exported_name_from_type_and_prefix<'a, 'tcx>(scx: &SharedCrateContext<'a, 'tcx>,
288 let hash = get_symbol_hash(scx, None, t, None);
289 let path = [Symbol::intern(prefix).as_str()];
290 mangle(path.iter().cloned(), &hash)
293 // Name sanitation. LLVM will happily accept identifiers with weird names, but
295 // gas accepts the following characters in symbols: a-z, A-Z, 0-9, ., _, $
296 pub fn sanitize(s: &str) -> String {
297 let mut result = String::new();
300 // Escape these with $ sequences
301 '@' => result.push_str("$SP$"),
302 '*' => result.push_str("$BP$"),
303 '&' => result.push_str("$RF$"),
304 '<' => result.push_str("$LT$"),
305 '>' => result.push_str("$GT$"),
306 '(' => result.push_str("$LP$"),
307 ')' => result.push_str("$RP$"),
308 ',' => result.push_str("$C$"),
310 // '.' doesn't occur in types and functions, so reuse it
312 '-' | ':' => result.push('.'),
314 // These are legal symbols
318 | '_' | '.' | '$' => result.push(c),
322 for c in c.escape_unicode().skip(1) {
325 '}' => result.push('$'),
333 // Underscore-qualify anything that didn't start as an ident.
334 if !result.is_empty() &&
335 result.as_bytes()[0] != '_' as u8 &&
336 ! (result.as_bytes()[0] as char).is_xid_start() {
337 return format!("_{}", result);
343 fn mangle<PI: Iterator<Item=InternedString>>(path: PI, hash: &str) -> String {
344 // Follow C++ namespace-mangling style, see
345 // http://en.wikipedia.org/wiki/Name_mangling for more info.
347 // It turns out that on macOS you can actually have arbitrary symbols in
348 // function names (at least when given to LLVM), but this is not possible
349 // when using unix's linker. Perhaps one day when we just use a linker from LLVM
350 // we won't need to do this name mangling. The problem with name mangling is
351 // that it seriously limits the available characters. For example we can't
352 // have things like &T in symbol names when one would theoretically
353 // want them for things like impls of traits on that type.
355 // To be able to work on all platforms and get *some* reasonable output, we
356 // use C++ name-mangling.
358 let mut n = String::from("_ZN"); // _Z == Begin name-sequence, N == nested
360 fn push(n: &mut String, s: &str) {
361 let sani = sanitize(s);
362 n.push_str(&format!("{}{}", sani.len(), sani));
365 // First, connect each component with <len, name> pairs.
372 n.push('E'); // End name-sequence.