1 //! The Rust Linkage Model and Symbol Names
2 //! =======================================
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.
10 //! There are a few issues to handle:
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
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.
20 //! - Symbols in different crates but with same names "within" the crate need
21 //! to get different linkage-names.
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
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.
34 //! - Even symbols from different versions of the same crate should be able to
35 //! live next to each other without conflict.
37 //! In order to fulfill the above requirements the following scheme is used by
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:
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.
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
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:
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.
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
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.
90 use rustc::middle::codegen_fn_attrs::CodegenFnAttrFlags;
91 use rustc::mir::mono::{InstantiationMode, MonoItem};
92 use rustc::session::config::SymbolManglingVersion;
93 use rustc::ty::query::Providers;
94 use rustc::ty::subst::SubstsRef;
95 use rustc::ty::{self, Instance, TyCtxt};
96 use rustc_hir::def_id::{CrateNum, LOCAL_CRATE};
99 use rustc_span::symbol::Symbol;
106 /// This function computes the symbol name for the given `instance` and the
107 /// given instantiating crate. That is, if you know that instance X is
108 /// instantiated in crate Y, this is the symbol name this instance would have.
109 pub fn symbol_name_for_instance_in_crate(
111 instance: Instance<'tcx>,
112 instantiating_crate: CrateNum,
114 compute_symbol_name(tcx, instance, || instantiating_crate)
117 pub fn provide(providers: &mut Providers<'_>) {
118 *providers = Providers { symbol_name: symbol_name_provider, ..*providers };
121 // The `symbol_name` query provides the symbol name for calling a given
122 // instance from the local crate. In particular, it will also look up the
123 // correct symbol name of instances from upstream crates.
124 fn symbol_name_provider(tcx: TyCtxt<'tcx>, instance: Instance<'tcx>) -> ty::SymbolName {
125 let symbol_name = compute_symbol_name(tcx, instance, || {
126 // This closure determines the instantiating crate for instances that
127 // need an instantiating-crate-suffix for their symbol name, in order
128 // to differentiate between local copies.
130 // For generics we might find re-usable upstream instances. For anything
131 // else we rely on their being a local copy available.
133 if is_generic(instance.substs) {
134 let def_id = instance.def_id();
136 if !def_id.is_local() && tcx.sess.opts.share_generics() {
137 // If we are re-using a monomorphization from another crate,
138 // we have to compute the symbol hash accordingly.
139 let upstream_monomorphizations = tcx.upstream_monomorphizations_for(def_id);
141 upstream_monomorphizations
142 .and_then(|monos| monos.get(&instance.substs).cloned())
143 // If there is no instance available upstream, there'll be
144 // one in the current crate.
145 .unwrap_or(LOCAL_CRATE)
147 // For generic functions defined in the current crate, there
148 // can be no upstream instances. Also, if we don't share
149 // generics, we'll instantiate a local copy too.
153 // For non-generic things that need to avoid naming conflicts, we
154 // always instantiate a copy in the local crate.
159 ty::SymbolName { name: Symbol::intern(&symbol_name) }
162 /// Computes the symbol name for the given instance. This function will call
163 /// `compute_instantiating_crate` if it needs to factor the instantiating crate
164 /// into the symbol name.
165 fn compute_symbol_name(
167 instance: Instance<'tcx>,
168 compute_instantiating_crate: impl FnOnce() -> CrateNum,
170 let def_id = instance.def_id();
171 let substs = instance.substs;
173 debug!("symbol_name(def_id={:?}, substs={:?})", def_id, substs);
175 let hir_id = tcx.hir().as_local_hir_id(def_id);
177 if def_id.is_local() {
178 if tcx.plugin_registrar_fn(LOCAL_CRATE) == Some(def_id) {
179 let disambiguator = tcx.sess.local_crate_disambiguator();
180 return tcx.sess.generate_plugin_registrar_symbol(disambiguator);
182 if tcx.proc_macro_decls_static(LOCAL_CRATE) == Some(def_id) {
183 let disambiguator = tcx.sess.local_crate_disambiguator();
184 return tcx.sess.generate_proc_macro_decls_symbol(disambiguator);
188 // FIXME(eddyb) Precompute a custom symbol name based on attributes.
189 let is_foreign = if let Some(id) = hir_id {
190 match tcx.hir().get(id) {
191 Node::ForeignItem(_) => true,
195 tcx.is_foreign_item(def_id)
198 let attrs = tcx.codegen_fn_attrs(def_id);
200 // Foreign items by default use no mangling for their symbol name. There's a
201 // few exceptions to this rule though:
203 // * This can be overridden with the `#[link_name]` attribute
205 // * On the wasm32 targets there is a bug (or feature) in LLD [1] where the
206 // same-named symbol when imported from different wasm modules will get
207 // hooked up incorectly. As a result foreign symbols, on the wasm target,
208 // with a wasm import module, get mangled. Additionally our codegen will
209 // deduplicate symbols based purely on the symbol name, but for wasm this
210 // isn't quite right because the same-named symbol on wasm can come from
211 // different modules. For these reasons if `#[link(wasm_import_module)]`
212 // is present we mangle everything on wasm because the demangled form will
213 // show up in the `wasm-import-name` custom attribute in LLVM IR.
215 // [1]: https://bugs.llvm.org/show_bug.cgi?id=44316
217 if tcx.sess.target.target.arch != "wasm32"
218 || !tcx.wasm_import_module_map(def_id.krate).contains_key(&def_id)
220 if let Some(name) = attrs.link_name {
221 return name.to_string();
223 return tcx.item_name(def_id).to_string();
227 if let Some(name) = attrs.export_name {
229 return name.to_string();
232 if attrs.flags.contains(CodegenFnAttrFlags::NO_MANGLE) {
234 return tcx.item_name(def_id).to_string();
237 let avoid_cross_crate_conflicts =
238 // If this is an instance of a generic function, we also hash in
239 // the ID of the instantiating crate. This avoids symbol conflicts
240 // in case the same instances is emitted in two crates of the same
242 is_generic(substs) ||
244 // If we're dealing with an instance of a function that's inlined from
245 // another crate but we're marking it as globally shared to our
246 // compliation (aka we're not making an internal copy in each of our
247 // codegen units) then this symbol may become an exported (but hidden
248 // visibility) symbol. This means that multiple crates may do the same
249 // and we want to be sure to avoid any symbol conflicts here.
250 match MonoItem::Fn(instance).instantiation_mode(tcx) {
251 InstantiationMode::GloballyShared { may_conflict: true } => true,
255 let instantiating_crate =
256 if avoid_cross_crate_conflicts { Some(compute_instantiating_crate()) } else { None };
258 // Pick the crate responsible for the symbol mangling version, which has to:
259 // 1. be stable for each instance, whether it's being defined or imported
260 // 2. obey each crate's own `-Z symbol-mangling-version`, as much as possible
261 // We solve these as follows:
262 // 1. because symbol names depend on both `def_id` and `instantiating_crate`,
263 // both their `CrateNum`s are stable for any given instance, so we can pick
264 // either and have a stable choice of symbol mangling version
265 // 2. we favor `instantiating_crate` where possible (i.e. when `Some`)
266 let mangling_version_crate = instantiating_crate.unwrap_or(def_id.krate);
267 let mangling_version = if mangling_version_crate == LOCAL_CRATE {
268 tcx.sess.opts.debugging_opts.symbol_mangling_version
270 tcx.symbol_mangling_version(mangling_version_crate)
273 match mangling_version {
274 SymbolManglingVersion::Legacy => legacy::mangle(tcx, instance, instantiating_crate),
275 SymbolManglingVersion::V0 => v0::mangle(tcx, instance, instantiating_crate),
279 fn is_generic(substs: SubstsRef<'_>) -> bool {
280 substs.non_erasable_generics().next().is_some()