Skip to main content

rustc_codegen_ssa/back/
symbol_export.rs

1use std::collections::hash_map::Entry::*;
2
3use rustc_abi::{CanonAbi, X86Call};
4use rustc_ast::expand::allocator::{AllocatorKind, NO_ALLOC_SHIM_IS_UNSTABLE, global_fn_name};
5use rustc_data_structures::unord::UnordMap;
6use rustc_hir::def::DefKind;
7use rustc_hir::def_id::{CrateNum, DefId, DefIdMap, LOCAL_CRATE, LocalDefId};
8use rustc_middle::bug;
9use rustc_middle::middle::codegen_fn_attrs::CodegenFnAttrFlags;
10use rustc_middle::middle::exported_symbols::{
11    ExportedSymbol, SymbolExportInfo, SymbolExportKind, SymbolExportLevel,
12};
13use rustc_middle::query::LocalCrate;
14use rustc_middle::ty::{self, GenericArgKind, GenericArgsRef, Instance, SymbolName, Ty, TyCtxt};
15use rustc_middle::util::Providers;
16use rustc_session::config::CrateType;
17use rustc_span::Span;
18use rustc_symbol_mangling::mangle_internal_symbol;
19use rustc_target::spec::{Arch, Os, TlsModel};
20use tracing::debug;
21
22use crate::back::symbol_export;
23use crate::base::allocator_shim_contents;
24
25fn threshold(tcx: TyCtxt<'_>) -> SymbolExportLevel {
26    crates_export_threshold(tcx.crate_types())
27}
28
29fn crate_export_threshold(crate_type: CrateType) -> SymbolExportLevel {
30    match crate_type {
31        CrateType::Executable | CrateType::StaticLib | CrateType::ProcMacro | CrateType::Cdylib => {
32            SymbolExportLevel::C
33        }
34        CrateType::Rlib | CrateType::Dylib | CrateType::Sdylib => SymbolExportLevel::Rust,
35    }
36}
37
38pub fn crates_export_threshold(crate_types: &[CrateType]) -> SymbolExportLevel {
39    if crate_types
40        .iter()
41        .any(|&crate_type| crate_export_threshold(crate_type) == SymbolExportLevel::Rust)
42    {
43        SymbolExportLevel::Rust
44    } else {
45        SymbolExportLevel::C
46    }
47}
48
49fn reachable_non_generics_provider(tcx: TyCtxt<'_>, _: LocalCrate) -> DefIdMap<SymbolExportInfo> {
50    if !tcx.sess.opts.output_types.should_codegen() && !tcx.is_sdylib_interface_build() {
51        return Default::default();
52    }
53
54    let is_compiler_builtins = tcx.is_compiler_builtins(LOCAL_CRATE);
55
56    let mut reachable_non_generics: DefIdMap<_> = tcx
57        .reachable_set(())
58        .items()
59        .filter_map(|&def_id| {
60            // We want to ignore some FFI functions that are not exposed from
61            // this crate. Reachable FFI functions can be lumped into two
62            // categories:
63            //
64            // 1. Those that are included statically via a static library
65            // 2. Those included otherwise (e.g., dynamically or via a framework)
66            //
67            // Although our LLVM module is not literally emitting code for the
68            // statically included symbols, it's an export of our library which
69            // needs to be passed on to the linker and encoded in the metadata.
70            //
71            // As a result, if this id is an FFI item (foreign item) then we only
72            // let it through if it's included statically.
73            if let Some(parent_id) = tcx.opt_local_parent(def_id)
74                && let DefKind::ForeignMod = tcx.def_kind(parent_id)
75            {
76                let library = tcx.native_library(def_id)?;
77                return library.kind.is_statically_included().then_some(def_id);
78            }
79
80            // Only consider nodes that actually have exported symbols.
81            match tcx.def_kind(def_id) {
82                DefKind::Fn | DefKind::Static { .. } => {}
83                DefKind::AssocFn if tcx.impl_of_assoc(def_id.to_def_id()).is_some() => {}
84                _ => return None,
85            };
86
87            let generics = tcx.generics_of(def_id);
88            if generics.requires_monomorphization(tcx) {
89                return None;
90            }
91
92            if Instance::mono(tcx, def_id.into()).def.requires_inline(tcx) {
93                return None;
94            }
95
96            if tcx.cross_crate_inlinable(def_id) { None } else { Some(def_id) }
97        })
98        .map(|def_id| {
99            let export_level = if is_compiler_builtins {
100                // We don't want to export compiler-builtins symbols from any
101                // dylibs, even rust dylibs. Unlike all other crates it gets
102                // duplicated in every linker invocation and it may otherwise
103                // unintentionally override definitions of these symbols by
104                // libgcc or compiler-rt for C code.
105                SymbolExportLevel::Rust
106            } else {
107                symbol_export_level(tcx, def_id.to_def_id())
108            };
109            let codegen_attrs = tcx.codegen_fn_attrs(def_id.to_def_id());
110            {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_codegen_ssa/src/back/symbol_export.rs:110",
                        "rustc_codegen_ssa::back::symbol_export",
                        ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_codegen_ssa/src/back/symbol_export.rs"),
                        ::tracing_core::__macro_support::Option::Some(110u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_codegen_ssa::back::symbol_export"),
                        ::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};
                let mut iter = __CALLSITE.metadata().fields().iter();
                __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                    ::tracing::__macro_support::Option::Some(&format_args!("EXPORTED SYMBOL (local): {0} ({1:?})",
                                                    tcx.symbol_name(Instance::mono(tcx, def_id.to_def_id())),
                                                    export_level) as &dyn Value))])
            });
    } else { ; }
};debug!(
111                "EXPORTED SYMBOL (local): {} ({:?})",
112                tcx.symbol_name(Instance::mono(tcx, def_id.to_def_id())),
113                export_level
114            );
115            let info = SymbolExportInfo {
116                level: export_level,
117                kind: if tcx.is_static(def_id.to_def_id()) {
118                    if codegen_attrs.flags.contains(CodegenFnAttrFlags::THREAD_LOCAL) {
119                        SymbolExportKind::Tls
120                    } else {
121                        SymbolExportKind::Data
122                    }
123                } else {
124                    SymbolExportKind::Text
125                },
126                used: codegen_attrs.flags.contains(CodegenFnAttrFlags::USED_COMPILER)
127                    || codegen_attrs.flags.contains(CodegenFnAttrFlags::USED_LINKER),
128                rustc_std_internal_symbol: codegen_attrs
129                    .flags
130                    .contains(CodegenFnAttrFlags::RUSTC_STD_INTERNAL_SYMBOL)
131                    || codegen_attrs
132                        .flags
133                        .contains(CodegenFnAttrFlags::EXTERNALLY_IMPLEMENTABLE_ITEM),
134            };
135            (def_id.to_def_id(), info)
136        })
137        .into();
138
139    if let Some(id) = tcx.proc_macro_decls_static(()) {
140        reachable_non_generics.insert(
141            id.to_def_id(),
142            SymbolExportInfo {
143                level: SymbolExportLevel::C,
144                kind: SymbolExportKind::Data,
145                used: false,
146                rustc_std_internal_symbol: false,
147            },
148        );
149    }
150
151    reachable_non_generics
152}
153
154fn is_reachable_non_generic_provider_local(tcx: TyCtxt<'_>, def_id: LocalDefId) -> bool {
155    let export_threshold = threshold(tcx);
156
157    if let Some(&info) = tcx.reachable_non_generics(LOCAL_CRATE).get(&def_id.to_def_id()) {
158        info.level.is_below_threshold(export_threshold)
159    } else {
160        false
161    }
162}
163
164fn is_reachable_non_generic_provider_extern(tcx: TyCtxt<'_>, def_id: DefId) -> bool {
165    tcx.reachable_non_generics(def_id.krate).contains_key(&def_id)
166}
167
168fn exported_non_generic_symbols_provider_local<'tcx>(
169    tcx: TyCtxt<'tcx>,
170    _: LocalCrate,
171) -> &'tcx [(ExportedSymbol<'tcx>, SymbolExportInfo)] {
172    if !tcx.sess.opts.output_types.should_codegen() && !tcx.is_sdylib_interface_build() {
173        return &[];
174    }
175
176    // FIXME: Sorting this is unnecessary since we are sorting later anyway.
177    //        Can we skip the later sorting?
178    let sorted = tcx.with_stable_hashing_context(|mut hcx| {
179        tcx.reachable_non_generics(LOCAL_CRATE).to_sorted(&mut hcx, true)
180    });
181
182    let mut symbols: Vec<_> =
183        sorted.iter().map(|&(&def_id, &info)| (ExportedSymbol::NonGeneric(def_id), info)).collect();
184
185    // Export TLS shims
186    if !tcx.sess.target.dll_tls_export {
187        symbols.extend(sorted.iter().filter_map(|&(&def_id, &info)| {
188            tcx.needs_thread_local_shim(def_id).then(|| {
189                (
190                    ExportedSymbol::ThreadLocalShim(def_id),
191                    SymbolExportInfo {
192                        level: info.level,
193                        kind: SymbolExportKind::Text,
194                        used: info.used,
195                        rustc_std_internal_symbol: info.rustc_std_internal_symbol,
196                    },
197                )
198            })
199        }))
200    }
201
202    symbols.extend(sorted.iter().flat_map(|&(&def_id, &info)| {
203        tcx.codegen_fn_attrs(def_id).foreign_item_symbol_aliases.iter().map(
204            move |&(foreign_item, _linkage, _visibility)| {
205                (ExportedSymbol::NonGeneric(foreign_item), info)
206            },
207        )
208    }));
209
210    if tcx.entry_fn(()).is_some() {
211        let exported_symbol =
212            ExportedSymbol::NoDefId(SymbolName::new(tcx, tcx.sess.target.entry_name.as_ref()));
213
214        symbols.push((
215            exported_symbol,
216            SymbolExportInfo {
217                level: SymbolExportLevel::C,
218                kind: SymbolExportKind::Text,
219                used: false,
220                rustc_std_internal_symbol: false,
221            },
222        ));
223    }
224
225    // Sort so we get a stable incr. comp. hash.
226    symbols.sort_by_cached_key(|s| s.0.symbol_name_for_local_instance(tcx));
227
228    tcx.arena.alloc_from_iter(symbols)
229}
230
231fn exported_generic_symbols_provider_local<'tcx>(
232    tcx: TyCtxt<'tcx>,
233    _: LocalCrate,
234) -> &'tcx [(ExportedSymbol<'tcx>, SymbolExportInfo)] {
235    if !tcx.sess.opts.output_types.should_codegen() && !tcx.is_sdylib_interface_build() {
236        return &[];
237    }
238
239    let mut symbols: Vec<_> = ::alloc::vec::Vec::new()vec![];
240
241    if tcx.local_crate_exports_generics() {
242        use rustc_hir::attrs::Linkage;
243        use rustc_middle::mono::{MonoItem, Visibility};
244        use rustc_middle::ty::InstanceKind;
245
246        // Normally, we require that shared monomorphizations are not hidden,
247        // because if we want to re-use a monomorphization from a Rust dylib, it
248        // needs to be exported.
249        // However, on platforms that don't allow for Rust dylibs, having
250        // external linkage is enough for monomorphization to be linked to.
251        let need_visibility = tcx.sess.target.dynamic_linking && !tcx.sess.target.only_cdylib;
252
253        let cgus = tcx.collect_and_partition_mono_items(()).codegen_units;
254
255        // Do not export symbols that cannot be instantiated by downstream crates.
256        let reachable_set = tcx.reachable_set(());
257        let is_local_to_current_crate = |ty: Ty<'_>| {
258            let no_refs = ty.peel_refs();
259            let root_def_id = match no_refs.kind() {
260                ty::Closure(closure, _) => *closure,
261                ty::FnDef(def_id, _) => *def_id,
262                ty::Coroutine(def_id, _) => *def_id,
263                ty::CoroutineClosure(def_id, _) => *def_id,
264                ty::CoroutineWitness(def_id, _) => *def_id,
265                _ => return false,
266            };
267            let Some(root_def_id) = root_def_id.as_local() else {
268                return false;
269            };
270
271            let is_local = !reachable_set.contains(&root_def_id);
272            is_local
273        };
274
275        let is_instantiable_downstream =
276            |did: Option<DefId>, generic_args: GenericArgsRef<'tcx>| {
277                generic_args
278                    .types()
279                    .chain(did.into_iter().map(move |did| tcx.type_of(did).skip_binder()))
280                    .all(move |arg| {
281                        arg.walk().all(|ty| {
282                            ty.as_type().map_or(true, |ty| !is_local_to_current_crate(ty))
283                        })
284                    })
285            };
286
287        // The symbols created in this loop are sorted below it
288        #[allow(rustc::potential_query_instability)]
289        for (mono_item, data) in cgus.iter().flat_map(|cgu| cgu.items().iter()) {
290            if data.linkage != Linkage::External {
291                // We can only re-use things with external linkage, otherwise
292                // we'll get a linker error
293                continue;
294            }
295
296            if need_visibility && data.visibility == Visibility::Hidden {
297                // If we potentially share things from Rust dylibs, they must
298                // not be hidden
299                continue;
300            }
301
302            if !tcx.sess.opts.share_generics() {
303                if tcx.codegen_fn_attrs(mono_item.def_id()).inline
304                    == rustc_hir::attrs::InlineAttr::Never
305                {
306                    // this is OK, we explicitly allow sharing inline(never) across crates even
307                    // without share-generics.
308                } else {
309                    continue;
310                }
311            }
312
313            // Note: These all set rustc_std_internal_symbol to false as generic functions must not
314            // be marked with this attribute and we are only handling generic functions here.
315            match *mono_item {
316                MonoItem::Fn(Instance { def: InstanceKind::Item(def), args }) => {
317                    let has_generics = args.non_erasable_generics().next().is_some();
318
319                    let should_export =
320                        has_generics && is_instantiable_downstream(Some(def), &args);
321
322                    if should_export {
323                        let symbol = ExportedSymbol::Generic(def, args);
324                        symbols.push((
325                            symbol,
326                            SymbolExportInfo {
327                                level: SymbolExportLevel::Rust,
328                                kind: SymbolExportKind::Text,
329                                used: false,
330                                rustc_std_internal_symbol: false,
331                            },
332                        ));
333                    }
334                }
335                MonoItem::Fn(Instance { def: InstanceKind::DropGlue(_, Some(ty)), args }) => {
336                    // A little sanity-check
337                    match (&args.non_erasable_generics().next(), &Some(GenericArgKind::Type(ty)))
    {
    (left_val, right_val) => {
        if !(*left_val == *right_val) {
            let kind = ::core::panicking::AssertKind::Eq;
            ::core::panicking::assert_failed(kind, &*left_val, &*right_val,
                ::core::option::Option::None);
        }
    }
};assert_eq!(args.non_erasable_generics().next(), Some(GenericArgKind::Type(ty)));
338
339                    // Drop glue did is always going to be non-local outside of libcore, thus we don't need to check it's locality (which includes invoking `type_of` query).
340                    let should_export = match ty.kind() {
341                        ty::Adt(_, args) => is_instantiable_downstream(None, args),
342                        ty::Closure(_, args) => is_instantiable_downstream(None, args),
343                        _ => true,
344                    };
345
346                    if should_export {
347                        symbols.push((
348                            ExportedSymbol::DropGlue(ty),
349                            SymbolExportInfo {
350                                level: SymbolExportLevel::Rust,
351                                kind: SymbolExportKind::Text,
352                                used: false,
353                                rustc_std_internal_symbol: false,
354                            },
355                        ));
356                    }
357                }
358                MonoItem::Fn(Instance {
359                    def: InstanceKind::AsyncDropGlueCtorShim(_, ty),
360                    args,
361                }) => {
362                    // A little sanity-check
363                    match (&args.non_erasable_generics().next(), &Some(GenericArgKind::Type(ty)))
    {
    (left_val, right_val) => {
        if !(*left_val == *right_val) {
            let kind = ::core::panicking::AssertKind::Eq;
            ::core::panicking::assert_failed(kind, &*left_val, &*right_val,
                ::core::option::Option::None);
        }
    }
};assert_eq!(args.non_erasable_generics().next(), Some(GenericArgKind::Type(ty)));
364                    symbols.push((
365                        ExportedSymbol::AsyncDropGlueCtorShim(ty),
366                        SymbolExportInfo {
367                            level: SymbolExportLevel::Rust,
368                            kind: SymbolExportKind::Text,
369                            used: false,
370                            rustc_std_internal_symbol: false,
371                        },
372                    ));
373                }
374                MonoItem::Fn(Instance { def: InstanceKind::AsyncDropGlue(def, ty), args: _ }) => {
375                    symbols.push((
376                        ExportedSymbol::AsyncDropGlue(def, ty),
377                        SymbolExportInfo {
378                            level: SymbolExportLevel::Rust,
379                            kind: SymbolExportKind::Text,
380                            used: false,
381                            rustc_std_internal_symbol: false,
382                        },
383                    ));
384                }
385                _ => {
386                    // Any other symbols don't qualify for sharing
387                }
388            }
389        }
390    }
391
392    // Sort so we get a stable incr. comp. hash.
393    symbols.sort_by_cached_key(|s| s.0.symbol_name_for_local_instance(tcx));
394
395    tcx.arena.alloc_from_iter(symbols)
396}
397
398fn upstream_monomorphizations_provider(
399    tcx: TyCtxt<'_>,
400    (): (),
401) -> DefIdMap<UnordMap<GenericArgsRef<'_>, CrateNum>> {
402    let cnums = tcx.crates(());
403
404    let mut instances: DefIdMap<UnordMap<_, _>> = Default::default();
405
406    let drop_in_place_fn_def_id = tcx.lang_items().drop_in_place_fn();
407    let async_drop_in_place_fn_def_id = tcx.lang_items().async_drop_in_place_fn();
408
409    for &cnum in cnums.iter() {
410        for (exported_symbol, _) in tcx.exported_generic_symbols(cnum).iter() {
411            let (def_id, args) = match *exported_symbol {
412                ExportedSymbol::Generic(def_id, args) => (def_id, args),
413                ExportedSymbol::DropGlue(ty) => {
414                    if let Some(drop_in_place_fn_def_id) = drop_in_place_fn_def_id {
415                        (drop_in_place_fn_def_id, tcx.mk_args(&[ty.into()]))
416                    } else {
417                        // `drop_in_place` in place does not exist, don't try
418                        // to use it.
419                        continue;
420                    }
421                }
422                ExportedSymbol::AsyncDropGlueCtorShim(ty) => {
423                    if let Some(async_drop_in_place_fn_def_id) = async_drop_in_place_fn_def_id {
424                        (async_drop_in_place_fn_def_id, tcx.mk_args(&[ty.into()]))
425                    } else {
426                        continue;
427                    }
428                }
429                ExportedSymbol::AsyncDropGlue(def_id, ty) => (def_id, tcx.mk_args(&[ty.into()])),
430                ExportedSymbol::NonGeneric(..)
431                | ExportedSymbol::ThreadLocalShim(..)
432                | ExportedSymbol::NoDefId(..) => {
    ::core::panicking::panic_fmt(format_args!("internal error: entered unreachable code: {0}",
            format_args!("{0:?}", exported_symbol)));
}unreachable!("{exported_symbol:?}"),
433            };
434
435            let args_map = instances.entry(def_id).or_default();
436
437            match args_map.entry(args) {
438                Occupied(mut e) => {
439                    // If there are multiple monomorphizations available,
440                    // we select one deterministically.
441                    let other_cnum = *e.get();
442                    if tcx.stable_crate_id(other_cnum) > tcx.stable_crate_id(cnum) {
443                        e.insert(cnum);
444                    }
445                }
446                Vacant(e) => {
447                    e.insert(cnum);
448                }
449            }
450        }
451    }
452
453    instances
454}
455
456fn upstream_monomorphizations_for_provider(
457    tcx: TyCtxt<'_>,
458    def_id: DefId,
459) -> Option<&UnordMap<GenericArgsRef<'_>, CrateNum>> {
460    if !!def_id.is_local() {
    ::core::panicking::panic("assertion failed: !def_id.is_local()")
};assert!(!def_id.is_local());
461    tcx.upstream_monomorphizations(()).get(&def_id)
462}
463
464fn upstream_drop_glue_for_provider<'tcx>(
465    tcx: TyCtxt<'tcx>,
466    args: GenericArgsRef<'tcx>,
467) -> Option<CrateNum> {
468    let def_id = tcx.lang_items().drop_in_place_fn()?;
469    tcx.upstream_monomorphizations_for(def_id)?.get(&args).cloned()
470}
471
472fn upstream_async_drop_glue_for_provider<'tcx>(
473    tcx: TyCtxt<'tcx>,
474    args: GenericArgsRef<'tcx>,
475) -> Option<CrateNum> {
476    let def_id = tcx.lang_items().async_drop_in_place_fn()?;
477    tcx.upstream_monomorphizations_for(def_id)?.get(&args).cloned()
478}
479
480fn is_unreachable_local_definition_provider(tcx: TyCtxt<'_>, def_id: LocalDefId) -> bool {
481    !tcx.reachable_set(()).contains(&def_id)
482}
483
484pub(crate) fn provide(providers: &mut Providers) {
485    providers.queries.reachable_non_generics = reachable_non_generics_provider;
486    providers.queries.is_reachable_non_generic = is_reachable_non_generic_provider_local;
487    providers.queries.exported_non_generic_symbols = exported_non_generic_symbols_provider_local;
488    providers.queries.exported_generic_symbols = exported_generic_symbols_provider_local;
489    providers.queries.upstream_monomorphizations = upstream_monomorphizations_provider;
490    providers.queries.is_unreachable_local_definition = is_unreachable_local_definition_provider;
491    providers.queries.upstream_drop_glue_for = upstream_drop_glue_for_provider;
492    providers.queries.upstream_async_drop_glue_for = upstream_async_drop_glue_for_provider;
493    providers.queries.wasm_import_module_map = wasm_import_module_map;
494    providers.extern_queries.is_reachable_non_generic = is_reachable_non_generic_provider_extern;
495    providers.extern_queries.upstream_monomorphizations_for =
496        upstream_monomorphizations_for_provider;
497}
498
499pub(crate) fn allocator_shim_symbols(
500    tcx: TyCtxt<'_>,
501    kind: AllocatorKind,
502) -> impl Iterator<Item = (String, SymbolExportKind)> {
503    allocator_shim_contents(tcx, kind)
504        .into_iter()
505        .map(move |method| mangle_internal_symbol(tcx, global_fn_name(method.name).as_str()))
506        .chain([mangle_internal_symbol(tcx, NO_ALLOC_SHIM_IS_UNSTABLE)])
507        .map(move |symbol_name| {
508            let exported_symbol = ExportedSymbol::NoDefId(SymbolName::new(tcx, &symbol_name));
509
510            (
511                symbol_export::exporting_symbol_name_for_instance_in_crate(
512                    tcx,
513                    exported_symbol,
514                    LOCAL_CRATE,
515                ),
516                SymbolExportKind::Text,
517            )
518        })
519}
520
521fn symbol_export_level(tcx: TyCtxt<'_>, sym_def_id: DefId) -> SymbolExportLevel {
522    // We export anything that's not mangled at the "C" layer as it probably has
523    // to do with ABI concerns. We do not, however, apply such treatment to
524    // special symbols in the standard library for various plumbing between
525    // core/std/allocators/etc. For example symbols used to hook up allocation
526    // are not considered for export
527    let codegen_fn_attrs = tcx.codegen_fn_attrs(sym_def_id);
528    let is_extern = codegen_fn_attrs.contains_extern_indicator();
529    let std_internal =
530        codegen_fn_attrs.flags.contains(CodegenFnAttrFlags::RUSTC_STD_INTERNAL_SYMBOL);
531    let eii = codegen_fn_attrs.flags.contains(CodegenFnAttrFlags::EXTERNALLY_IMPLEMENTABLE_ITEM);
532
533    if is_extern && !std_internal && !eii {
534        let target = &tcx.sess.target.llvm_target;
535        // WebAssembly cannot export data symbols, so reduce their export level
536        // FIXME(jdonszelmann) don't do a substring match here.
537        if target.contains("emscripten") {
538            if let DefKind::Static { .. } = tcx.def_kind(sym_def_id) {
539                return SymbolExportLevel::Rust;
540            }
541        }
542
543        SymbolExportLevel::C
544    } else {
545        SymbolExportLevel::Rust
546    }
547}
548
549/// This is the symbol name of the given instance instantiated in a specific crate.
550pub(crate) fn symbol_name_for_instance_in_crate<'tcx>(
551    tcx: TyCtxt<'tcx>,
552    symbol: ExportedSymbol<'tcx>,
553    instantiating_crate: CrateNum,
554) -> String {
555    // If this is something instantiated in the local crate then we might
556    // already have cached the name as a query result.
557    if instantiating_crate == LOCAL_CRATE {
558        return symbol.symbol_name_for_local_instance(tcx).to_string();
559    }
560
561    // This is something instantiated in an upstream crate, so we have to use
562    // the slower (because uncached) version of computing the symbol name.
563    match symbol {
564        ExportedSymbol::NonGeneric(def_id) => {
565            rustc_symbol_mangling::symbol_name_for_instance_in_crate(
566                tcx,
567                Instance::mono(tcx, def_id),
568                instantiating_crate,
569            )
570        }
571        ExportedSymbol::Generic(def_id, args) => {
572            rustc_symbol_mangling::symbol_name_for_instance_in_crate(
573                tcx,
574                Instance::new_raw(def_id, args),
575                instantiating_crate,
576            )
577        }
578        ExportedSymbol::ThreadLocalShim(def_id) => {
579            rustc_symbol_mangling::symbol_name_for_instance_in_crate(
580                tcx,
581                ty::Instance {
582                    def: ty::InstanceKind::ThreadLocalShim(def_id),
583                    args: ty::GenericArgs::empty(),
584                },
585                instantiating_crate,
586            )
587        }
588        ExportedSymbol::DropGlue(ty) => rustc_symbol_mangling::symbol_name_for_instance_in_crate(
589            tcx,
590            Instance::resolve_drop_in_place(tcx, ty),
591            instantiating_crate,
592        ),
593        ExportedSymbol::AsyncDropGlueCtorShim(ty) => {
594            rustc_symbol_mangling::symbol_name_for_instance_in_crate(
595                tcx,
596                Instance::resolve_async_drop_in_place(tcx, ty),
597                instantiating_crate,
598            )
599        }
600        ExportedSymbol::AsyncDropGlue(def_id, ty) => {
601            rustc_symbol_mangling::symbol_name_for_instance_in_crate(
602                tcx,
603                Instance::resolve_async_drop_in_place_poll(tcx, def_id, ty),
604                instantiating_crate,
605            )
606        }
607        ExportedSymbol::NoDefId(symbol_name) => symbol_name.to_string(),
608    }
609}
610
611fn calling_convention_for_symbol<'tcx>(
612    tcx: TyCtxt<'tcx>,
613    symbol: ExportedSymbol<'tcx>,
614) -> (CanonAbi, &'tcx [rustc_target::callconv::ArgAbi<'tcx, Ty<'tcx>>]) {
615    let instance = match symbol {
616        ExportedSymbol::NonGeneric(def_id) | ExportedSymbol::Generic(def_id, _)
617            if tcx.is_static(def_id) =>
618        {
619            None
620        }
621        ExportedSymbol::NonGeneric(def_id) => Some(Instance::mono(tcx, def_id)),
622        ExportedSymbol::Generic(def_id, args) => Some(Instance::new_raw(def_id, args)),
623        // DropGlue always use the Rust calling convention and thus follow the target's default
624        // symbol decoration scheme.
625        ExportedSymbol::DropGlue(..) => None,
626        // AsyncDropGlueCtorShim always use the Rust calling convention and thus follow the
627        // target's default symbol decoration scheme.
628        ExportedSymbol::AsyncDropGlueCtorShim(..) => None,
629        ExportedSymbol::AsyncDropGlue(..) => None,
630        // NoDefId always follow the target's default symbol decoration scheme.
631        ExportedSymbol::NoDefId(..) => None,
632        // ThreadLocalShim always follow the target's default symbol decoration scheme.
633        ExportedSymbol::ThreadLocalShim(..) => None,
634    };
635
636    instance
637        .map(|i| {
638            tcx.fn_abi_of_instance(
639                ty::TypingEnv::fully_monomorphized().as_query_input((i, ty::List::empty())),
640            )
641            .unwrap_or_else(|_| ::rustc_middle::util::bug::bug_fmt(format_args!("fn_abi_of_instance({0:?}) failed",
        i))bug!("fn_abi_of_instance({i:?}) failed"))
642        })
643        .map(|fnabi| (fnabi.conv, &fnabi.args[..]))
644        // FIXME(workingjubilee): why don't we know the convention here?
645        .unwrap_or((CanonAbi::Rust, &[]))
646}
647
648/// This is the symbol name of the given instance as seen by the linker.
649///
650/// On 32-bit Windows symbols are decorated according to their calling conventions.
651pub(crate) fn linking_symbol_name_for_instance_in_crate<'tcx>(
652    tcx: TyCtxt<'tcx>,
653    symbol: ExportedSymbol<'tcx>,
654    export_kind: SymbolExportKind,
655    instantiating_crate: CrateNum,
656) -> String {
657    let mut undecorated = symbol_name_for_instance_in_crate(tcx, symbol, instantiating_crate);
658
659    // thread local will not be a function call,
660    // so it is safe to return before windows symbol decoration check.
661    if let Some(name) = maybe_emutls_symbol_name(tcx, symbol, &undecorated) {
662        return name;
663    }
664
665    let target = &tcx.sess.target;
666    if !target.is_like_windows {
667        // Mach-O has a global "_" suffix and `object` crate will handle it.
668        // ELF does not have any symbol decorations.
669        return undecorated;
670    }
671
672    let prefix = match target.arch {
673        Arch::X86 => Some('_'),
674        Arch::X86_64 => None,
675        // Only functions are decorated for arm64ec.
676        Arch::Arm64EC if export_kind == SymbolExportKind::Text => Some('#'),
677        // Only x86/64 and arm64ec use symbol decorations.
678        _ => return undecorated,
679    };
680
681    let (callconv, args) = calling_convention_for_symbol(tcx, symbol);
682
683    // Decorate symbols with prefixes, suffixes and total number of bytes of arguments.
684    // Reference: https://docs.microsoft.com/en-us/cpp/build/reference/decorated-names?view=msvc-170
685    let (prefix, suffix) = match callconv {
686        CanonAbi::X86(X86Call::Fastcall) => ("@", "@"),
687        CanonAbi::X86(X86Call::Stdcall) => ("_", "@"),
688        CanonAbi::X86(X86Call::Vectorcall) => ("", "@@"),
689        _ => {
690            if let Some(prefix) = prefix {
691                undecorated.insert(0, prefix);
692            }
693            return undecorated;
694        }
695    };
696
697    let args_in_bytes: u64 = args
698        .iter()
699        .map(|abi| abi.layout.size.bytes().next_multiple_of(target.pointer_width as u64 / 8))
700        .sum();
701    ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{0}{1}{2}{3}", prefix, undecorated,
                suffix, args_in_bytes))
    })format!("{prefix}{undecorated}{suffix}{args_in_bytes}")
702}
703
704pub(crate) fn exporting_symbol_name_for_instance_in_crate<'tcx>(
705    tcx: TyCtxt<'tcx>,
706    symbol: ExportedSymbol<'tcx>,
707    cnum: CrateNum,
708) -> String {
709    let undecorated = symbol_name_for_instance_in_crate(tcx, symbol, cnum);
710    maybe_emutls_symbol_name(tcx, symbol, &undecorated).unwrap_or(undecorated)
711}
712
713/// On amdhsa, `gpu-kernel` functions have an associated metadata object with a `.kd` suffix.
714/// Add it to the symbols list for all kernel functions, so that it is exported in the linked
715/// object.
716pub(crate) fn extend_exported_symbols<'tcx>(
717    symbols: &mut Vec<(String, SymbolExportKind)>,
718    tcx: TyCtxt<'tcx>,
719    symbol: ExportedSymbol<'tcx>,
720    instantiating_crate: CrateNum,
721) {
722    let (callconv, _) = calling_convention_for_symbol(tcx, symbol);
723
724    if callconv != CanonAbi::GpuKernel || tcx.sess.target.os != Os::AmdHsa {
725        return;
726    }
727
728    let undecorated = symbol_name_for_instance_in_crate(tcx, symbol, instantiating_crate);
729
730    // Add the symbol for the kernel descriptor (with .kd suffix)
731    // Per https://llvm.org/docs/AMDGPUUsage.html#symbols these will always be `STT_OBJECT` so
732    // export as data.
733    symbols.push((::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{0}.kd", undecorated))
    })format!("{undecorated}.kd"), SymbolExportKind::Data));
734}
735
736fn maybe_emutls_symbol_name<'tcx>(
737    tcx: TyCtxt<'tcx>,
738    symbol: ExportedSymbol<'tcx>,
739    undecorated: &str,
740) -> Option<String> {
741    if #[allow(non_exhaustive_omitted_patterns)] match tcx.sess.tls_model() {
    TlsModel::Emulated => true,
    _ => false,
}matches!(tcx.sess.tls_model(), TlsModel::Emulated)
742        && let ExportedSymbol::NonGeneric(def_id) = symbol
743        && tcx.is_thread_local_static(def_id)
744    {
745        // When using emutls, LLVM will add the `__emutls_v.` prefix to thread local symbols,
746        // and exported symbol name need to match this.
747        Some(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("__emutls_v.{0}", undecorated))
    })format!("__emutls_v.{undecorated}"))
748    } else {
749        None
750    }
751}
752
753fn wasm_import_module_map(tcx: TyCtxt<'_>, cnum: CrateNum) -> DefIdMap<String> {
754    // Build up a map from DefId to a `NativeLib` structure, where
755    // `NativeLib` internally contains information about
756    // `#[link(wasm_import_module = "...")]` for example.
757    let native_libs = tcx.native_libraries(cnum);
758
759    let def_id_to_native_lib = native_libs
760        .iter()
761        .filter_map(|lib| lib.foreign_module.map(|id| (id, lib)))
762        .collect::<DefIdMap<_>>();
763
764    let mut ret = DefIdMap::default();
765    for (def_id, lib) in tcx.foreign_modules(cnum).iter() {
766        let module = def_id_to_native_lib.get(def_id).and_then(|s| s.wasm_import_module());
767        let Some(module) = module else { continue };
768        ret.extend(lib.foreign_items.iter().map(|id| {
769            match (&id.krate, &cnum) {
    (left_val, right_val) => {
        if !(*left_val == *right_val) {
            let kind = ::core::panicking::AssertKind::Eq;
            ::core::panicking::assert_failed(kind, &*left_val, &*right_val,
                ::core::option::Option::None);
        }
    }
};assert_eq!(id.krate, cnum);
770            (*id, module.to_string())
771        }));
772    }
773
774    ret
775}
776
777pub fn escape_symbol_name(tcx: TyCtxt<'_>, symbol: &str, span: Span) -> String {
778    // https://github.com/llvm/llvm-project/blob/a55fbab0cffc9b4af497b9e4f187b61143743e06/llvm/lib/MC/MCSymbol.cpp
779    use rustc_target::spec::{Arch, BinaryFormat};
780    if !symbol.is_empty()
781        && symbol.chars().all(|c| #[allow(non_exhaustive_omitted_patterns)] match c {
    '0'..='9' | 'A'..='Z' | 'a'..='z' | '_' | '$' | '.' => true,
    _ => false,
}matches!(c, '0'..='9' | 'A'..='Z' | 'a'..='z' | '_' | '$' | '.'))
782    {
783        return symbol.to_string();
784    }
785    if tcx.sess.target.binary_format == BinaryFormat::Xcoff {
786        tcx.sess.dcx().span_fatal(
787            span,
788            ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("symbol escaping is not supported for the binary format {0}",
                tcx.sess.target.binary_format))
    })format!(
789                "symbol escaping is not supported for the binary format {}",
790                tcx.sess.target.binary_format
791            ),
792        );
793    }
794    if tcx.sess.target.arch == Arch::Nvptx64 {
795        tcx.sess.dcx().span_fatal(
796            span,
797            ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("symbol escaping is not supported for the architecture {0}",
                tcx.sess.target.arch))
    })format!(
798                "symbol escaping is not supported for the architecture {}",
799                tcx.sess.target.arch
800            ),
801        );
802    }
803    let mut escaped_symbol = String::new();
804    escaped_symbol.push('\"');
805    for c in symbol.chars() {
806        match c {
807            '\n' => escaped_symbol.push_str("\\\n"),
808            '"' => escaped_symbol.push_str("\\\""),
809            '\\' => escaped_symbol.push_str("\\\\"),
810            c => escaped_symbol.push(c),
811        }
812    }
813    escaped_symbol.push('\"');
814    escaped_symbol
815}