]> git.lizzy.rs Git - rust.git/blob - src/librustc_codegen_utils/symbol_names.rs
Rollup merge of #61499 - varkor:issue-53457, r=oli-obk
[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_id::LOCAL_CRATE;
91 use rustc::hir::Node;
92 use rustc::hir::CodegenFnAttrFlags;
93 use rustc::session::config::SymbolManglingVersion;
94 use rustc::ty::query::Providers;
95 use rustc::ty::{self, TyCtxt, Instance};
96 use rustc::mir::mono::{MonoItem, InstantiationMode};
97
98 use syntax_pos::symbol::InternedString;
99
100 use log::debug;
101
102 mod legacy;
103 mod v0;
104
105 pub fn provide(providers: &mut Providers<'_>) {
106     *providers = Providers {
107         symbol_name: |tcx, instance| ty::SymbolName {
108             name: symbol_name(tcx, instance),
109         },
110
111         ..*providers
112     };
113 }
114
115 fn symbol_name(tcx: TyCtxt<'_, 'tcx, 'tcx>, instance: Instance<'tcx>) -> InternedString {
116     let def_id = instance.def_id();
117     let substs = instance.substs;
118
119     debug!("symbol_name(def_id={:?}, substs={:?})", def_id, substs);
120
121     let hir_id = tcx.hir().as_local_hir_id(def_id);
122
123     if def_id.is_local() {
124         if tcx.plugin_registrar_fn(LOCAL_CRATE) == Some(def_id) {
125             let disambiguator = tcx.sess.local_crate_disambiguator();
126             return
127                 InternedString::intern(&tcx.sess.generate_plugin_registrar_symbol(disambiguator));
128         }
129         if tcx.proc_macro_decls_static(LOCAL_CRATE) == Some(def_id) {
130             let disambiguator = tcx.sess.local_crate_disambiguator();
131             return
132                 InternedString::intern(&tcx.sess.generate_proc_macro_decls_symbol(disambiguator));
133         }
134     }
135
136     // FIXME(eddyb) Precompute a custom symbol name based on attributes.
137     let is_foreign = if let Some(id) = hir_id {
138         match tcx.hir().get_by_hir_id(id) {
139             Node::ForeignItem(_) => true,
140             _ => false,
141         }
142     } else {
143         tcx.is_foreign_item(def_id)
144     };
145
146     let attrs = tcx.codegen_fn_attrs(def_id);
147     if is_foreign {
148         if let Some(name) = attrs.link_name {
149             return name.as_interned_str();
150         }
151         // Don't mangle foreign items.
152         return tcx.item_name(def_id).as_interned_str();
153     }
154
155     if let Some(name) = &attrs.export_name {
156         // Use provided name
157         return name.as_interned_str();
158     }
159
160     if attrs.flags.contains(CodegenFnAttrFlags::NO_MANGLE) {
161         // Don't mangle
162         return tcx.item_name(def_id).as_interned_str();
163     }
164
165
166     let is_generic = substs.non_erasable_generics().next().is_some();
167     let avoid_cross_crate_conflicts =
168         // If this is an instance of a generic function, we also hash in
169         // the ID of the instantiating crate. This avoids symbol conflicts
170         // in case the same instances is emitted in two crates of the same
171         // project.
172         is_generic ||
173
174         // If we're dealing with an instance of a function that's inlined from
175         // another crate but we're marking it as globally shared to our
176         // compliation (aka we're not making an internal copy in each of our
177         // codegen units) then this symbol may become an exported (but hidden
178         // visibility) symbol. This means that multiple crates may do the same
179         // and we want to be sure to avoid any symbol conflicts here.
180         match MonoItem::Fn(instance).instantiation_mode(tcx) {
181             InstantiationMode::GloballyShared { may_conflict: true } => true,
182             _ => false,
183         };
184
185     let instantiating_crate = if avoid_cross_crate_conflicts {
186         Some(if is_generic {
187             if !def_id.is_local() && tcx.sess.opts.share_generics() {
188                 // If we are re-using a monomorphization from another crate,
189                 // we have to compute the symbol hash accordingly.
190                 let upstream_monomorphizations = tcx.upstream_monomorphizations_for(def_id);
191
192                 upstream_monomorphizations
193                     .and_then(|monos| monos.get(&substs).cloned())
194                     .unwrap_or(LOCAL_CRATE)
195             } else {
196                 LOCAL_CRATE
197             }
198         } else {
199             LOCAL_CRATE
200         })
201     } else {
202         None
203     };
204
205     // Pick the crate responsible for the symbol mangling version, which has to:
206     // 1. be stable for each instance, whether it's being defined or imported
207     // 2. obey each crate's own `-Z symbol-mangling-version`, as much as possible
208     // We solve these as follows:
209     // 1. because symbol names depend on both `def_id` and `instantiating_crate`,
210     // both their `CrateNum`s are stable for any given instance, so we can pick
211     // either and have a stable choice of symbol mangling version
212     // 2. we favor `instantiating_crate` where possible (i.e. when `Some`)
213     let mangling_version_crate = instantiating_crate.unwrap_or(def_id.krate);
214     let mangling_version = if mangling_version_crate == LOCAL_CRATE {
215         tcx.sess.opts.debugging_opts.symbol_mangling_version
216     } else {
217         tcx.symbol_mangling_version(mangling_version_crate)
218     };
219
220     let mangled = match mangling_version {
221         SymbolManglingVersion::Legacy => legacy::mangle(tcx, instance, instantiating_crate),
222         SymbolManglingVersion::V0 => v0::mangle(tcx, instance, instantiating_crate),
223     };
224
225     InternedString::intern(&mangled)
226 }