Skip to main content

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