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_glue_fn_def_id = tcx.lang_items().drop_glue_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_glue_fn_def_id {
415                        (drop_in_place_fn_def_id, tcx.mk_args(&[ty.into()]))
416                    } else {
417                        // `drop_glue` does not exist, don't try to use it.
418                        continue;
419                    }
420                }
421                ExportedSymbol::AsyncDropGlueCtorShim(ty) => {
422                    if let Some(async_drop_in_place_fn_def_id) = async_drop_in_place_fn_def_id {
423                        (async_drop_in_place_fn_def_id, tcx.mk_args(&[ty.into()]))
424                    } else {
425                        continue;
426                    }
427                }
428                ExportedSymbol::AsyncDropGlue(def_id, ty) => (def_id, tcx.mk_args(&[ty.into()])),
429                ExportedSymbol::NonGeneric(..)
430                | ExportedSymbol::ThreadLocalShim(..)
431                | ExportedSymbol::NoDefId(..) => {
    ::core::panicking::panic_fmt(format_args!("internal error: entered unreachable code: {0}",
            format_args!("{0:?}", exported_symbol)));
}unreachable!("{exported_symbol:?}"),
432            };
433
434            let args_map = instances.entry(def_id).or_default();
435
436            match args_map.entry(args) {
437                Occupied(mut e) => {
438                    // If there are multiple monomorphizations available,
439                    // we select one deterministically.
440                    let other_cnum = *e.get();
441                    if tcx.stable_crate_id(other_cnum) > tcx.stable_crate_id(cnum) {
442                        e.insert(cnum);
443                    }
444                }
445                Vacant(e) => {
446                    e.insert(cnum);
447                }
448            }
449        }
450    }
451
452    instances
453}
454
455fn upstream_monomorphizations_for_provider(
456    tcx: TyCtxt<'_>,
457    def_id: DefId,
458) -> Option<&UnordMap<GenericArgsRef<'_>, CrateNum>> {
459    if !!def_id.is_local() {
    ::core::panicking::panic("assertion failed: !def_id.is_local()")
};assert!(!def_id.is_local());
460    tcx.upstream_monomorphizations(()).get(&def_id)
461}
462
463fn upstream_drop_glue_for_provider<'tcx>(
464    tcx: TyCtxt<'tcx>,
465    args: GenericArgsRef<'tcx>,
466) -> Option<CrateNum> {
467    let def_id = tcx.lang_items().drop_glue_fn()?;
468    tcx.upstream_monomorphizations_for(def_id)?.get(&args).cloned()
469}
470
471fn upstream_async_drop_glue_for_provider<'tcx>(
472    tcx: TyCtxt<'tcx>,
473    args: GenericArgsRef<'tcx>,
474) -> Option<CrateNum> {
475    let def_id = tcx.lang_items().async_drop_in_place_fn()?;
476    tcx.upstream_monomorphizations_for(def_id)?.get(&args).cloned()
477}
478
479fn is_unreachable_local_definition_provider(tcx: TyCtxt<'_>, def_id: LocalDefId) -> bool {
480    !tcx.reachable_set(()).contains(&def_id)
481}
482
483pub(crate) fn provide(providers: &mut Providers) {
484    providers.queries.reachable_non_generics = reachable_non_generics_provider;
485    providers.queries.is_reachable_non_generic = is_reachable_non_generic_provider_local;
486    providers.queries.exported_non_generic_symbols = exported_non_generic_symbols_provider_local;
487    providers.queries.exported_generic_symbols = exported_generic_symbols_provider_local;
488    providers.queries.upstream_monomorphizations = upstream_monomorphizations_provider;
489    providers.queries.is_unreachable_local_definition = is_unreachable_local_definition_provider;
490    providers.queries.upstream_drop_glue_for = upstream_drop_glue_for_provider;
491    providers.queries.upstream_async_drop_glue_for = upstream_async_drop_glue_for_provider;
492    providers.queries.wasm_import_module_map = wasm_import_module_map;
493    providers.extern_queries.is_reachable_non_generic = is_reachable_non_generic_provider_extern;
494    providers.extern_queries.upstream_monomorphizations_for =
495        upstream_monomorphizations_for_provider;
496}
497
498pub(crate) fn allocator_shim_symbols(
499    tcx: TyCtxt<'_>,
500    kind: AllocatorKind,
501) -> impl Iterator<Item = (String, SymbolExportKind)> {
502    allocator_shim_contents(tcx, kind)
503        .into_iter()
504        .map(move |method| mangle_internal_symbol(tcx, global_fn_name(method.name).as_str()))
505        .chain([mangle_internal_symbol(tcx, NO_ALLOC_SHIM_IS_UNSTABLE)])
506        .map(move |symbol_name| {
507            let exported_symbol = ExportedSymbol::NoDefId(SymbolName::new(tcx, &symbol_name));
508
509            (
510                symbol_export::exporting_symbol_name_for_instance_in_crate(
511                    tcx,
512                    exported_symbol,
513                    LOCAL_CRATE,
514                ),
515                SymbolExportKind::Text,
516            )
517        })
518}
519
520fn symbol_export_level(tcx: TyCtxt<'_>, sym_def_id: DefId) -> SymbolExportLevel {
521    // We export anything that's not mangled at the "C" layer as it probably has
522    // to do with ABI concerns. We do not, however, apply such treatment to
523    // special symbols in the standard library for various plumbing between
524    // core/std/allocators/etc. For example symbols used to hook up allocation
525    // are not considered for export
526    let codegen_fn_attrs = tcx.codegen_fn_attrs(sym_def_id);
527    let is_extern = codegen_fn_attrs.contains_extern_indicator();
528    let std_internal =
529        codegen_fn_attrs.flags.contains(CodegenFnAttrFlags::RUSTC_STD_INTERNAL_SYMBOL);
530    let eii = codegen_fn_attrs.flags.contains(CodegenFnAttrFlags::EXTERNALLY_IMPLEMENTABLE_ITEM);
531
532    if is_extern && !std_internal && !eii {
533        let target = &tcx.sess.target.llvm_target;
534        // WebAssembly cannot export data symbols, so reduce their export level
535        // FIXME(jdonszelmann) don't do a substring match here.
536        if target.contains("emscripten") {
537            if let DefKind::Static { .. } = tcx.def_kind(sym_def_id) {
538                return SymbolExportLevel::Rust;
539            }
540        }
541
542        SymbolExportLevel::C
543    } else {
544        SymbolExportLevel::Rust
545    }
546}
547
548/// This is the symbol name of the given instance instantiated in a specific crate.
549pub(crate) fn symbol_name_for_instance_in_crate<'tcx>(
550    tcx: TyCtxt<'tcx>,
551    symbol: ExportedSymbol<'tcx>,
552    instantiating_crate: CrateNum,
553) -> String {
554    // If this is something instantiated in the local crate then we might
555    // already have cached the name as a query result.
556    if instantiating_crate == LOCAL_CRATE {
557        return symbol.symbol_name_for_local_instance(tcx).to_string();
558    }
559
560    // This is something instantiated in an upstream crate, so we have to use
561    // the slower (because uncached) version of computing the symbol name.
562    match symbol {
563        ExportedSymbol::NonGeneric(def_id) => {
564            rustc_symbol_mangling::symbol_name_for_instance_in_crate(
565                tcx,
566                Instance::mono(tcx, def_id),
567                instantiating_crate,
568            )
569        }
570        ExportedSymbol::Generic(def_id, args) => {
571            rustc_symbol_mangling::symbol_name_for_instance_in_crate(
572                tcx,
573                Instance::new_raw(def_id, args),
574                instantiating_crate,
575            )
576        }
577        ExportedSymbol::ThreadLocalShim(def_id) => {
578            rustc_symbol_mangling::symbol_name_for_instance_in_crate(
579                tcx,
580                ty::Instance {
581                    def: ty::InstanceKind::ThreadLocalShim(def_id),
582                    args: ty::GenericArgs::empty(),
583                },
584                instantiating_crate,
585            )
586        }
587        ExportedSymbol::DropGlue(ty) => rustc_symbol_mangling::symbol_name_for_instance_in_crate(
588            tcx,
589            Instance::resolve_drop_glue(tcx, ty),
590            instantiating_crate,
591        ),
592        ExportedSymbol::AsyncDropGlueCtorShim(ty) => {
593            rustc_symbol_mangling::symbol_name_for_instance_in_crate(
594                tcx,
595                Instance::resolve_async_drop_in_place(tcx, ty),
596                instantiating_crate,
597            )
598        }
599        ExportedSymbol::AsyncDropGlue(def_id, ty) => {
600            rustc_symbol_mangling::symbol_name_for_instance_in_crate(
601                tcx,
602                Instance::resolve_async_drop_in_place_poll(tcx, def_id, ty),
603                instantiating_crate,
604            )
605        }
606        ExportedSymbol::NoDefId(symbol_name) => symbol_name.to_string(),
607    }
608}
609
610fn calling_convention_for_symbol<'tcx>(
611    tcx: TyCtxt<'tcx>,
612    symbol: ExportedSymbol<'tcx>,
613) -> (CanonAbi, &'tcx [rustc_target::callconv::ArgAbi<'tcx, Ty<'tcx>>]) {
614    let instance = match symbol {
615        ExportedSymbol::NonGeneric(def_id) | ExportedSymbol::Generic(def_id, _)
616            if tcx.is_static(def_id) =>
617        {
618            None
619        }
620        ExportedSymbol::NonGeneric(def_id) => Some(Instance::mono(tcx, def_id)),
621        ExportedSymbol::Generic(def_id, args) => Some(Instance::new_raw(def_id, args)),
622        // DropGlue always use the Rust calling convention and thus follow the target's default
623        // symbol decoration scheme.
624        ExportedSymbol::DropGlue(..) => None,
625        // AsyncDropGlueCtorShim always use the Rust calling convention and thus follow the
626        // target's default symbol decoration scheme.
627        ExportedSymbol::AsyncDropGlueCtorShim(..) => None,
628        ExportedSymbol::AsyncDropGlue(..) => None,
629        // NoDefId always follow the target's default symbol decoration scheme.
630        ExportedSymbol::NoDefId(..) => None,
631        // ThreadLocalShim always follow the target's default symbol decoration scheme.
632        ExportedSymbol::ThreadLocalShim(..) => None,
633    };
634
635    instance
636        .map(|i| {
637            tcx.fn_abi_of_instance(
638                ty::TypingEnv::fully_monomorphized().as_query_input((i, ty::List::empty())),
639            )
640            .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"))
641        })
642        .map(|fnabi| (fnabi.conv, &fnabi.args[..]))
643        // FIXME(workingjubilee): why don't we know the convention here?
644        .unwrap_or((CanonAbi::Rust, &[]))
645}
646
647/// This is the symbol name of the given instance as seen by the linker.
648///
649/// On 32-bit Windows symbols are decorated according to their calling conventions.
650pub(crate) fn linking_symbol_name_for_instance_in_crate<'tcx>(
651    tcx: TyCtxt<'tcx>,
652    symbol: ExportedSymbol<'tcx>,
653    export_kind: SymbolExportKind,
654    instantiating_crate: CrateNum,
655) -> String {
656    let mut undecorated = symbol_name_for_instance_in_crate(tcx, symbol, instantiating_crate);
657
658    // thread local will not be a function call,
659    // so it is safe to return before windows symbol decoration check.
660    if let Some(name) = maybe_emutls_symbol_name(tcx, symbol, &undecorated) {
661        return name;
662    }
663
664    let target = &tcx.sess.target;
665    if !target.is_like_windows {
666        // Mach-O has a global "_" suffix and `object` crate will handle it.
667        // ELF does not have any symbol decorations.
668        return undecorated;
669    }
670
671    let prefix = match target.arch {
672        Arch::X86 => Some('_'),
673        Arch::X86_64 => None,
674        // Only functions are decorated for arm64ec.
675        Arch::Arm64EC if export_kind == SymbolExportKind::Text => Some('#'),
676        // Only x86/64 and arm64ec use symbol decorations.
677        _ => return undecorated,
678    };
679
680    let (callconv, args) = calling_convention_for_symbol(tcx, symbol);
681
682    // Decorate symbols with prefixes, suffixes and total number of bytes of arguments.
683    // Reference: https://docs.microsoft.com/en-us/cpp/build/reference/decorated-names?view=msvc-170
684    let (prefix, suffix) = match callconv {
685        CanonAbi::X86(X86Call::Fastcall) => ("@", "@"),
686        CanonAbi::X86(X86Call::Stdcall) => ("_", "@"),
687        CanonAbi::X86(X86Call::Vectorcall) => ("", "@@"),
688        _ => {
689            if let Some(prefix) = prefix {
690                undecorated.insert(0, prefix);
691            }
692            return undecorated;
693        }
694    };
695
696    let args_in_bytes: u64 = args
697        .iter()
698        .map(|abi| abi.layout.size.bytes().next_multiple_of(target.pointer_width as u64 / 8))
699        .sum();
700    ::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}")
701}
702
703pub(crate) fn exporting_symbol_name_for_instance_in_crate<'tcx>(
704    tcx: TyCtxt<'tcx>,
705    symbol: ExportedSymbol<'tcx>,
706    cnum: CrateNum,
707) -> String {
708    let undecorated = symbol_name_for_instance_in_crate(tcx, symbol, cnum);
709    maybe_emutls_symbol_name(tcx, symbol, &undecorated).unwrap_or(undecorated)
710}
711
712/// On amdhsa, `gpu-kernel` functions have an associated metadata object with a `.kd` suffix.
713/// Add it to the symbols list for all kernel functions, so that it is exported in the linked
714/// object.
715pub(crate) fn extend_exported_symbols<'tcx>(
716    symbols: &mut Vec<(String, SymbolExportKind)>,
717    tcx: TyCtxt<'tcx>,
718    symbol: ExportedSymbol<'tcx>,
719    instantiating_crate: CrateNum,
720) {
721    let (callconv, _) = calling_convention_for_symbol(tcx, symbol);
722
723    if callconv != CanonAbi::GpuKernel || tcx.sess.target.os != Os::AmdHsa {
724        return;
725    }
726
727    let undecorated = symbol_name_for_instance_in_crate(tcx, symbol, instantiating_crate);
728
729    // Add the symbol for the kernel descriptor (with .kd suffix)
730    // Per https://llvm.org/docs/AMDGPUUsage.html#symbols these will always be `STT_OBJECT` so
731    // export as data.
732    symbols.push((::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{0}.kd", undecorated))
    })format!("{undecorated}.kd"), SymbolExportKind::Data));
733}
734
735fn maybe_emutls_symbol_name<'tcx>(
736    tcx: TyCtxt<'tcx>,
737    symbol: ExportedSymbol<'tcx>,
738    undecorated: &str,
739) -> Option<String> {
740    if #[allow(non_exhaustive_omitted_patterns)] match tcx.sess.tls_model() {
    TlsModel::Emulated => true,
    _ => false,
}matches!(tcx.sess.tls_model(), TlsModel::Emulated)
741        && let ExportedSymbol::NonGeneric(def_id) = symbol
742        && tcx.is_thread_local_static(def_id)
743    {
744        // When using emutls, LLVM will add the `__emutls_v.` prefix to thread local symbols,
745        // and exported symbol name need to match this.
746        Some(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("__emutls_v.{0}", undecorated))
    })format!("__emutls_v.{undecorated}"))
747    } else {
748        None
749    }
750}
751
752fn wasm_import_module_map(tcx: TyCtxt<'_>, cnum: CrateNum) -> DefIdMap<String> {
753    // Build up a map from DefId to a `NativeLib` structure, where
754    // `NativeLib` internally contains information about
755    // `#[link(wasm_import_module = "...")]` for example.
756    let native_libs = tcx.native_libraries(cnum);
757
758    let def_id_to_native_lib = native_libs
759        .iter()
760        .filter_map(|lib| lib.foreign_module.map(|id| (id, lib)))
761        .collect::<DefIdMap<_>>();
762
763    let mut ret = DefIdMap::default();
764    for (def_id, lib) in tcx.foreign_modules(cnum).iter() {
765        let module = def_id_to_native_lib.get(def_id).and_then(|s| s.wasm_import_module());
766        let Some(module) = module else { continue };
767        ret.extend(lib.foreign_items.iter().map(|id| {
768            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);
769            (*id, module.to_string())
770        }));
771    }
772
773    ret
774}
775
776pub fn escape_symbol_name(tcx: TyCtxt<'_>, symbol: &str, span: Span) -> String {
777    // https://github.com/llvm/llvm-project/blob/a55fbab0cffc9b4af497b9e4f187b61143743e06/llvm/lib/MC/MCSymbol.cpp
778    use rustc_target::spec::{Arch, BinaryFormat};
779    if !symbol.is_empty()
780        && 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' | '_' | '$' | '.'))
781    {
782        return symbol.to_string();
783    }
784    if tcx.sess.target.binary_format == BinaryFormat::Xcoff {
785        tcx.sess.dcx().span_fatal(
786            span,
787            ::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!(
788                "symbol escaping is not supported for the binary format {}",
789                tcx.sess.target.binary_format
790            ),
791        );
792    }
793    if tcx.sess.target.arch == Arch::Nvptx64 {
794        tcx.sess.dcx().span_fatal(
795            span,
796            ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("symbol escaping is not supported for the architecture {0}",
                tcx.sess.target.arch))
    })format!(
797                "symbol escaping is not supported for the architecture {}",
798                tcx.sess.target.arch
799            ),
800        );
801    }
802    let mut escaped_symbol = String::new();
803    escaped_symbol.push('\"');
804    for c in symbol.chars() {
805        match c {
806            '\n' => escaped_symbol.push_str("\\\n"),
807            '"' => escaped_symbol.push_str("\\\""),
808            '\\' => escaped_symbol.push_str("\\\\"),
809            c => escaped_symbol.push(c),
810        }
811    }
812    escaped_symbol.push('\"');
813    escaped_symbol
814}