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