rustc_symbol_mangling/lib.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// tidy-alphabetical-start
91#![allow(internal_features)]
92#![doc(html_root_url = "https://doc.rust-lang.org/nightly/nightly-rustc/")]
93#![doc(rust_logo)]
94#![feature(assert_matches)]
95#![feature(rustdoc_internals)]
96// tidy-alphabetical-end
97
98use rustc_hir::def::DefKind;
99use rustc_hir::def_id::{CrateNum, LOCAL_CRATE};
100use rustc_middle::middle::codegen_fn_attrs::{CodegenFnAttrFlags, CodegenFnAttrs};
101use rustc_middle::mir::mono::{InstantiationMode, MonoItem};
102use rustc_middle::query::Providers;
103use rustc_middle::ty::{self, Instance, TyCtxt};
104use rustc_session::config::SymbolManglingVersion;
105use tracing::debug;
106
107mod export;
108mod hashed;
109mod legacy;
110mod v0;
111
112pub mod errors;
113pub mod test;
114
115pub use v0::mangle_internal_symbol;
116
117/// This function computes the symbol name for the given `instance` and the
118/// given instantiating crate. That is, if you know that instance X is
119/// instantiated in crate Y, this is the symbol name this instance would have.
120pub fn symbol_name_for_instance_in_crate<'tcx>(
121 tcx: TyCtxt<'tcx>,
122 instance: Instance<'tcx>,
123 instantiating_crate: CrateNum,
124) -> String {
125 compute_symbol_name(tcx, instance, || instantiating_crate)
126}
127
128pub fn provide(providers: &mut Providers) {
129 *providers = Providers { symbol_name: symbol_name_provider, ..*providers };
130}
131
132// The `symbol_name` query provides the symbol name for calling a given
133// instance from the local crate. In particular, it will also look up the
134// correct symbol name of instances from upstream crates.
135fn symbol_name_provider<'tcx>(tcx: TyCtxt<'tcx>, instance: Instance<'tcx>) -> ty::SymbolName<'tcx> {
136 let symbol_name = compute_symbol_name(tcx, instance, || {
137 // This closure determines the instantiating crate for instances that
138 // need an instantiating-crate-suffix for their symbol name, in order
139 // to differentiate between local copies.
140 if is_generic(instance) {
141 // For generics we might find re-usable upstream instances. If there
142 // is one, we rely on the symbol being instantiated locally.
143 instance.upstream_monomorphization(tcx).unwrap_or(LOCAL_CRATE)
144 } else {
145 // For non-generic things that need to avoid naming conflicts, we
146 // always instantiate a copy in the local crate.
147 LOCAL_CRATE
148 }
149 });
150
151 ty::SymbolName::new(tcx, &symbol_name)
152}
153
154pub fn typeid_for_trait_ref<'tcx>(
155 tcx: TyCtxt<'tcx>,
156 trait_ref: ty::ExistentialTraitRef<'tcx>,
157) -> String {
158 v0::mangle_typeid_for_trait_ref(tcx, trait_ref)
159}
160
161/// Computes the symbol name for the given instance. This function will call
162/// `compute_instantiating_crate` if it needs to factor the instantiating crate
163/// into the symbol name.
164fn compute_symbol_name<'tcx>(
165 tcx: TyCtxt<'tcx>,
166 instance: Instance<'tcx>,
167 compute_instantiating_crate: impl FnOnce() -> CrateNum,
168) -> String {
169 let def_id = instance.def_id();
170 let args = instance.args;
171
172 debug!("symbol_name(def_id={:?}, args={:?})", def_id, args);
173
174 if let Some(def_id) = def_id.as_local() {
175 if tcx.proc_macro_decls_static(()) == Some(def_id) {
176 let stable_crate_id = tcx.stable_crate_id(LOCAL_CRATE);
177 return tcx.sess.generate_proc_macro_decls_symbol(stable_crate_id);
178 }
179 }
180
181 // FIXME(eddyb) Precompute a custom symbol name based on attributes.
182 let attrs = if tcx.def_kind(def_id).has_codegen_attrs() {
183 &tcx.codegen_instance_attrs(instance.def)
184 } else {
185 CodegenFnAttrs::EMPTY
186 };
187
188 if attrs.flags.contains(CodegenFnAttrFlags::RUSTC_STD_INTERNAL_SYMBOL) {
189 // Items marked as #[rustc_std_internal_symbol] need to have a fixed
190 // symbol name because it is used to import items from another crate
191 // without a direct dependency. As such it is not possible to look up
192 // the mangled name for the `Instance` from the crate metadata of the
193 // defining crate.
194 // Weak lang items automatically get #[rustc_std_internal_symbol]
195 // applied by the code computing the CodegenFnAttrs.
196 // We are mangling all #[rustc_std_internal_symbol] items as a
197 // combination of the rustc version and the unmangled linkage name.
198 // This is to ensure that if we link against a staticlib compiled by a
199 // different rustc version, we don't get symbol conflicts or even UB
200 // due to a different implementation/ABI. Rust staticlibs currently
201 // export all symbols, including those that are hidden in cdylibs.
202 // We are using the v0 symbol mangling scheme here as we need to be
203 // consistent across all crates and in some contexts the legacy symbol
204 // mangling scheme can't be used. For example both the GCC backend and
205 // Rust-for-Linux don't support some of the characters used by the
206 // legacy symbol mangling scheme.
207 let name = if let Some(name) = attrs.symbol_name { name } else { tcx.item_name(def_id) };
208
209 return v0::mangle_internal_symbol(tcx, name.as_str());
210 }
211
212 let wasm_import_module_exception_force_mangling = {
213 // * On the wasm32 targets there is a bug (or feature) in LLD [1] where the
214 // same-named symbol when imported from different wasm modules will get
215 // hooked up incorrectly. As a result foreign symbols, on the wasm target,
216 // with a wasm import module, get mangled. Additionally our codegen will
217 // deduplicate symbols based purely on the symbol name, but for wasm this
218 // isn't quite right because the same-named symbol on wasm can come from
219 // different modules. For these reasons if `#[link(wasm_import_module)]`
220 // is present we mangle everything on wasm because the demangled form will
221 // show up in the `wasm-import-name` custom attribute in LLVM IR.
222 //
223 // [1]: https://bugs.llvm.org/show_bug.cgi?id=44316
224 //
225 // So, on wasm if a foreign item loses its `#[no_mangle]`, it might *still*
226 // be mangled if we're forced to. Note: I don't like this.
227 // These kinds of exceptions should be added during the `codegen_attrs` query.
228 // However, we don't have the wasm import module map there yet.
229 tcx.is_foreign_item(def_id)
230 && tcx.sess.target.is_like_wasm
231 && tcx.wasm_import_module_map(LOCAL_CRATE).contains_key(&def_id.into())
232 };
233
234 if !wasm_import_module_exception_force_mangling {
235 if let Some(name) = attrs.symbol_name {
236 // Use provided name
237 return name.to_string();
238 }
239
240 if attrs.flags.contains(CodegenFnAttrFlags::NO_MANGLE) {
241 // Don't mangle
242 return tcx.item_name(def_id).to_string();
243 }
244 }
245
246 // If we're dealing with an instance of a function that's inlined from
247 // another crate but we're marking it as globally shared to our
248 // compilation (aka we're not making an internal copy in each of our
249 // codegen units) then this symbol may become an exported (but hidden
250 // visibility) symbol. This means that multiple crates may do the same
251 // and we want to be sure to avoid any symbol conflicts here.
252 let is_globally_shared_function = matches!(
253 tcx.def_kind(instance.def_id()),
254 DefKind::Fn
255 | DefKind::AssocFn
256 | DefKind::Closure
257 | DefKind::SyntheticCoroutineBody
258 | DefKind::Ctor(..)
259 ) && matches!(
260 MonoItem::Fn(instance).instantiation_mode(tcx),
261 InstantiationMode::GloballyShared { may_conflict: true }
262 );
263
264 // If this is an instance of a generic function, we also hash in
265 // the ID of the instantiating crate. This avoids symbol conflicts
266 // in case the same instances is emitted in two crates of the same
267 // project.
268 let avoid_cross_crate_conflicts = is_generic(instance) || is_globally_shared_function;
269
270 let instantiating_crate = avoid_cross_crate_conflicts.then(compute_instantiating_crate);
271
272 // Pick the crate responsible for the symbol mangling version, which has to:
273 // 1. be stable for each instance, whether it's being defined or imported
274 // 2. obey each crate's own `-C symbol-mangling-version`, as much as possible
275 // We solve these as follows:
276 // 1. because symbol names depend on both `def_id` and `instantiating_crate`,
277 // both their `CrateNum`s are stable for any given instance, so we can pick
278 // either and have a stable choice of symbol mangling version
279 // 2. we favor `instantiating_crate` where possible (i.e. when `Some`)
280 let mangling_version_crate = instantiating_crate.unwrap_or(def_id.krate);
281 let mangling_version = if mangling_version_crate == LOCAL_CRATE {
282 tcx.sess.opts.get_symbol_mangling_version()
283 } else {
284 tcx.symbol_mangling_version(mangling_version_crate)
285 };
286
287 let symbol = match tcx.is_exportable(def_id) {
288 true => format!(
289 "{}.{}",
290 v0::mangle(tcx, instance, instantiating_crate, true),
291 export::compute_hash_of_export_fn(tcx, instance)
292 ),
293 false => match mangling_version {
294 SymbolManglingVersion::Legacy => legacy::mangle(tcx, instance, instantiating_crate),
295 SymbolManglingVersion::V0 => v0::mangle(tcx, instance, instantiating_crate, false),
296 SymbolManglingVersion::Hashed => {
297 hashed::mangle(tcx, instance, instantiating_crate, || {
298 v0::mangle(tcx, instance, instantiating_crate, false)
299 })
300 }
301 },
302 };
303
304 debug_assert!(
305 rustc_demangle::try_demangle(&symbol).is_ok(),
306 "compute_symbol_name: `{symbol}` cannot be demangled"
307 );
308
309 symbol
310}
311
312fn is_generic<'tcx>(instance: Instance<'tcx>) -> bool {
313 instance.args.non_erasable_generics().next().is_some()
314}