1use std::collections::hash_map::Entry::*;
2
3use object::pe;
4use rustc_abi::{CanonAbi, X86Call};
5use rustc_ast::expand::allocator::{AllocatorKind, NO_ALLOC_SHIM_IS_UNSTABLE, global_fn_name};
6use rustc_crate_store::CrateDepKind;
7use rustc_data_structures::fx::FxHashSet;
8use rustc_data_structures::unord::UnordMap;
9use rustc_hir as hir;
10use rustc_hir::def::DefKind;
11use rustc_hir::def_id::{CrateNum, DefId, DefIdMap, LOCAL_CRATE, LocalDefId};
12use rustc_middle::middle::codegen_fn_attrs::CodegenFnAttrFlags;
13use rustc_middle::middle::exported_symbols::{
14 ExportedSymbol, SymbolExportInfo, SymbolExportKind, SymbolExportLevel,
15};
16use rustc_middle::query::LocalCrate;
17use rustc_middle::ty::{
18 self, GenericArgKind, GenericArgsRef, Instance, ShimKind, SymbolName, Ty, TyCtxt,
19};
20use rustc_middle::util::Providers;
21use rustc_span::{Span, bug};
22use rustc_structures::CrateType;
23use rustc_symbol_mangling::{is_offload_kernel, mangle_internal_symbol};
24use rustc_target::spec::{Arch, Os, TlsModel};
25use tracing::debug;
26
27use crate::SymbolExport;
28use crate::back::symbol_export;
29use crate::base::allocator_shim_contents;
30
31fn threshold(tcx: TyCtxt<'_>) -> SymbolExportLevel {
32 crates_export_threshold(tcx.crate_types())
33}
34
35fn crate_export_threshold(crate_type: CrateType) -> SymbolExportLevel {
36 match crate_type {
37 CrateType::Executable | CrateType::StaticLib | CrateType::ProcMacro | CrateType::Cdylib => {
38 SymbolExportLevel::C
39 }
40 CrateType::Rlib | CrateType::Dylib | CrateType::Sdylib => SymbolExportLevel::Rust,
41 }
42}
43
44pub fn crates_export_threshold(crate_types: &[CrateType]) -> SymbolExportLevel {
45 if crate_types
46 .iter()
47 .any(|&crate_type| crate_export_threshold(crate_type) == SymbolExportLevel::Rust)
48 {
49 SymbolExportLevel::Rust
50 } else {
51 SymbolExportLevel::C
52 }
53}
54
55fn reachable_non_generics_provider(tcx: TyCtxt<'_>, _: LocalCrate) -> DefIdMap<SymbolExportInfo> {
56 if !tcx.sess.opts.output_types.should_codegen() && !tcx.is_sdylib_interface_build() {
57 return Default::default();
58 }
59
60 reachable_non_generics_helper(tcx)
61}
62
63pub fn reachable_non_generics_helper(tcx: TyCtxt<'_>) -> DefIdMap<SymbolExportInfo> {
65 let is_compiler_builtins = tcx.is_compiler_builtins(LOCAL_CRATE);
66
67 let mut reachable_non_generics: DefIdMap<_> = tcx
68 .reachable_set(())
69 .items()
70 .filter_map(|&def_id| {
71 if let Some(parent_id) = tcx.opt_local_parent(def_id)
85 && let DefKind::ForeignMod = tcx.def_kind(parent_id)
86 {
87 let library = tcx.native_library(def_id)?;
88 return library.kind.is_statically_included().then_some(def_id);
89 }
90
91 match tcx.def_kind(def_id) {
93 DefKind::Fn | DefKind::AssocFn
94 if tcx.constness(def_id) == hir::Constness::Const { always: true } =>
95 {
96 return None;
97 }
98 DefKind::Fn | DefKind::Static { .. } => {}
99 DefKind::AssocFn if tcx.impl_of_assoc(def_id.to_def_id()).is_some() => {}
100 _ => return None,
101 };
102
103 let generics = tcx.generics_of(def_id);
104 if generics.requires_monomorphization(tcx) {
105 return None;
106 }
107
108 if Instance::mono(tcx, def_id.into()).def.requires_inline(tcx) {
109 return None;
110 }
111
112 if tcx.cross_crate_inlinable(def_id) { None } else { Some(def_id) }
113 })
114 .map(|def_id| {
115 let export_level = if is_compiler_builtins {
116 SymbolExportLevel::Rust
122 } else {
123 symbol_export_level(tcx, def_id.to_def_id())
124 };
125 let codegen_attrs = tcx.codegen_fn_attrs(def_id.to_def_id());
126 {
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event /rustc-dev/a30aa9064df6a504b6a323c6884a2f4cfbfff666/compiler/rustc_codegen_ssa/src/back/symbol_export.rs:126",
"rustc_codegen_ssa::back::symbol_export",
::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/a30aa9064df6a504b6a323c6884a2f4cfbfff666/compiler/rustc_codegen_ssa/src/back/symbol_export.rs"),
::tracing_core::__macro_support::Option::Some(126u32),
::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!(
127 "EXPORTED SYMBOL (local): {} ({:?})",
128 tcx.symbol_name(Instance::mono(tcx, def_id.to_def_id())),
129 export_level
130 );
131 let info = SymbolExportInfo {
132 level: export_level,
133 kind: if tcx.is_static(def_id.to_def_id()) {
134 if codegen_attrs.flags.contains(CodegenFnAttrFlags::THREAD_LOCAL) {
135 SymbolExportKind::Tls
136 } else {
137 SymbolExportKind::Data
138 }
139 } else {
140 SymbolExportKind::Text
141 },
142 used: codegen_attrs.flags.contains(CodegenFnAttrFlags::USED_COMPILER)
143 || codegen_attrs.flags.contains(CodegenFnAttrFlags::USED_LINKER),
144 rustc_std_internal_symbol: codegen_attrs
145 .flags
146 .contains(CodegenFnAttrFlags::RUSTC_STD_INTERNAL_SYMBOL)
147 || codegen_attrs
148 .flags
149 .contains(CodegenFnAttrFlags::EXTERNALLY_IMPLEMENTABLE_ITEM),
150 };
151 (def_id.to_def_id(), info)
152 })
153 .into();
154
155 if let Some(id) = tcx.proc_macro_decls_static(()) {
156 reachable_non_generics.insert(
157 id.to_def_id(),
158 SymbolExportInfo {
159 level: SymbolExportLevel::C,
160 kind: SymbolExportKind::Data,
161 used: false,
162 rustc_std_internal_symbol: false,
163 },
164 );
165 }
166
167 reachable_non_generics
168}
169
170fn is_reachable_non_generic_provider_local(tcx: TyCtxt<'_>, def_id: LocalDefId) -> bool {
171 let export_threshold = threshold(tcx);
172
173 if let Some(&info) = tcx.reachable_non_generics(LOCAL_CRATE).get(&def_id.to_def_id()) {
174 info.level.is_below_threshold(export_threshold)
175 } else {
176 false
177 }
178}
179
180fn is_reachable_non_generic_provider_extern(tcx: TyCtxt<'_>, def_id: DefId) -> bool {
181 tcx.reachable_non_generics(def_id.krate).contains_key(&def_id)
182}
183
184fn exported_non_generic_symbols_provider_local<'tcx>(
185 tcx: TyCtxt<'tcx>,
186 _: LocalCrate,
187) -> &'tcx [(ExportedSymbol<'tcx>, SymbolExportInfo)] {
188 if !tcx.sess.opts.output_types.should_codegen() && !tcx.is_sdylib_interface_build() {
189 return &[];
190 }
191
192 exported_non_generic_symbols_helper(tcx)
193}
194
195pub fn exported_non_generic_symbols_helper<'tcx>(
197 tcx: TyCtxt<'tcx>,
198) -> &'tcx [(ExportedSymbol<'tcx>, SymbolExportInfo)] {
199 let sorted = tcx.with_stable_hashing_context(|mut hcx| {
202 tcx.reachable_non_generics(LOCAL_CRATE).to_sorted(&mut hcx, true)
203 });
204
205 let mut symbols: Vec<_> =
206 sorted.iter().map(|&(&def_id, &info)| (ExportedSymbol::NonGeneric(def_id), info)).collect();
207
208 if !tcx.sess.target.dll_tls_export {
210 symbols.extend(sorted.iter().filter_map(|&(&def_id, &info)| {
211 tcx.needs_thread_local_shim(def_id).then(|| {
212 (
213 ExportedSymbol::ThreadLocalShim(def_id),
214 SymbolExportInfo {
215 level: info.level,
216 kind: SymbolExportKind::Text,
217 used: info.used,
218 rustc_std_internal_symbol: info.rustc_std_internal_symbol,
219 },
220 )
221 })
222 }))
223 }
224
225 symbols.extend(sorted.iter().flat_map(|&(&def_id, &info)| {
226 tcx.codegen_fn_attrs(def_id).foreign_item_symbol_aliases.iter().map(
227 move |&(foreign_item, _linkage, _visibility)| {
228 (ExportedSymbol::NonGeneric(foreign_item), info)
229 },
230 )
231 }));
232
233 if tcx.entry_fn(()).is_some() {
234 let exported_symbol =
235 ExportedSymbol::NoDefId(SymbolName::new(tcx, tcx.sess.target.entry_name.as_ref()));
236
237 symbols.push((
238 exported_symbol,
239 SymbolExportInfo {
240 level: SymbolExportLevel::C,
241 kind: SymbolExportKind::Text,
242 used: false,
243 rustc_std_internal_symbol: false,
244 },
245 ));
246 }
247
248 let is_device_offload = tcx
249 .sess
250 .opts
251 .unstable_opts
252 .offload
253 .iter()
254 .any(|o| #[allow(non_exhaustive_omitted_patterns)] match o {
rustc_session::config::Offload::Device(_) => true,
_ => false,
}matches!(o, rustc_session::config::Offload::Device(_)));
255 if is_device_offload {
256 let crate_items = tcx.hir_crate_items(());
257 let mut seen: rustc_data_structures::fx::FxHashSet<DefId> = symbols
258 .iter()
259 .filter_map(|(s, _)| match s {
260 ExportedSymbol::NonGeneric(d) => Some(*d),
261 _ => None,
262 })
263 .collect();
264
265 let mut try_emit_offload_kernel = |def_id: DefId, seen: &mut FxHashSet<DefId>| {
266 if !#[allow(non_exhaustive_omitted_patterns)] match tcx.def_kind(def_id) {
DefKind::Fn | DefKind::AssocFn => true,
_ => false,
}matches!(tcx.def_kind(def_id), DefKind::Fn | DefKind::AssocFn) {
267 return;
268 }
269 if !tcx.generics_of(def_id).requires_monomorphization(tcx)
270 && is_offload_kernel(tcx.codegen_fn_attrs(def_id))
271 && seen.insert(def_id)
272 {
273 symbols.push((
274 ExportedSymbol::NonGeneric(def_id),
275 SymbolExportInfo {
276 level: SymbolExportLevel::C,
277 kind: SymbolExportKind::Text,
278 used: false,
279 rustc_std_internal_symbol: false,
280 },
281 ));
282 }
283 };
284
285 for id in crate_items.free_items() {
286 try_emit_offload_kernel(id.owner_id.to_def_id(), &mut seen);
287 }
288 for id in crate_items.impl_items() {
289 try_emit_offload_kernel(id.owner_id.to_def_id(), &mut seen);
290 }
291 }
292
293 symbols.sort_by_cached_key(|s| s.0.symbol_name_for_local_instance(tcx));
295
296 tcx.arena.alloc_from_iter(symbols)
297}
298
299fn exported_generic_symbols_provider_local<'tcx>(
300 tcx: TyCtxt<'tcx>,
301 _: LocalCrate,
302) -> &'tcx [(ExportedSymbol<'tcx>, SymbolExportInfo)] {
303 if !tcx.sess.opts.output_types.should_codegen() && !tcx.is_sdylib_interface_build() {
304 return &[];
305 }
306
307 let mut symbols: Vec<_> = ::alloc::vec::Vec::new()vec![];
308
309 let export_generics = tcx.local_crate_exports_generics();
310 let is_device_offload = tcx
311 .sess
312 .opts
313 .unstable_opts
314 .offload
315 .iter()
316 .any(|o| #[allow(non_exhaustive_omitted_patterns)] match o {
rustc_session::config::Offload::Device(_) => true,
_ => false,
}matches!(o, rustc_session::config::Offload::Device(_)));
317
318 if export_generics || is_device_offload {
319 use rustc_attr_ir::{InlineAttr, Linkage};
320 use rustc_middle::mono::{MonoItem, Visibility};
321 use rustc_middle::ty::InstanceKind;
322
323 let need_visibility = tcx.sess.target.dynamic_linking && !tcx.sess.target.only_cdylib;
329
330 let cgus = tcx.collect_and_partition_mono_items(()).codegen_units;
331
332 let reachable_set = tcx.reachable_set(());
334 let is_local_to_current_crate = |ty: Ty<'_>| {
335 let no_refs = ty.peel_refs();
336 let root_def_id = match no_refs.kind() {
337 ty::Closure(closure, _) => *closure,
338 ty::FnDef(def_id, _) => *def_id,
339 ty::Coroutine(def_id, _) => *def_id,
340 ty::CoroutineClosure(def_id, _) => *def_id,
341 ty::CoroutineWitness(def_id, _) => *def_id,
342 _ => return false,
343 };
344 let Some(root_def_id) = root_def_id.as_local() else {
345 return false;
346 };
347
348 let is_local = !reachable_set.contains(&root_def_id);
349 is_local
350 };
351
352 let is_instantiable_downstream =
353 |did: Option<DefId>, generic_args: GenericArgsRef<'tcx>| {
354 generic_args
355 .types()
356 .chain(did.into_iter().map(move |did| tcx.type_of(did).skip_binder()))
357 .all(move |arg| {
358 arg.walk()
359 .all(|ty| ty.as_type().is_none_or(|ty| !is_local_to_current_crate(ty)))
360 })
361 };
362
363 let is_offload_instance = |mono_item: &MonoItem<'tcx>| {
364 if let MonoItem::Fn(instance) = mono_item {
365 is_offload_kernel(tcx.codegen_fn_attrs(instance.def_id()))
366 } else {
367 false
368 }
369 };
370
371 #[allow(rustc::potential_query_instability)]
373 for (mono_item, data) in cgus.iter().flat_map(|cgu| cgu.items().iter()) {
374 if data.linkage != Linkage::External {
375 continue;
378 }
379
380 if need_visibility && data.visibility == Visibility::Hidden {
381 continue;
384 }
385
386 let item_is_offload = is_offload_instance(mono_item);
387
388 if !item_is_offload && !tcx.sess.opts.share_generics() {
389 if tcx.codegen_fn_attrs(mono_item.def_id()).inline == InlineAttr::Never {
390 } else {
393 continue;
394 }
395 }
396
397 match *mono_item {
400 MonoItem::Fn(Instance { def: InstanceKind::Item(def), args }) => {
401 let has_generics = args.non_erasable_generics().next().is_some();
402
403 let should_export = if item_is_offload {
404 has_generics
405 } else {
406 has_generics && is_instantiable_downstream(Some(def), &args)
407 };
408
409 if should_export {
410 let symbol = ExportedSymbol::Generic(def, args);
411 symbols.push((
412 symbol,
413 SymbolExportInfo {
414 level: if item_is_offload {
415 SymbolExportLevel::C
416 } else {
417 SymbolExportLevel::Rust
418 },
419 kind: SymbolExportKind::Text,
420 used: false,
421 rustc_std_internal_symbol: false,
422 },
423 ));
424 }
425 }
426 MonoItem::Fn(Instance {
427 def: InstanceKind::Shim(ShimKind::DropGlue(_, Some(ty))),
428 args,
429 }) => {
430 {
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)));
432
433 let should_export = match ty.kind() {
435 ty::Adt(_, args) => is_instantiable_downstream(None, args),
436 ty::Closure(_, args) => is_instantiable_downstream(None, args),
437 _ => true,
438 };
439
440 if should_export {
441 symbols.push((
442 ExportedSymbol::DropGlue(ty),
443 SymbolExportInfo {
444 level: SymbolExportLevel::Rust,
445 kind: SymbolExportKind::Text,
446 used: false,
447 rustc_std_internal_symbol: false,
448 },
449 ));
450 }
451 }
452 MonoItem::Fn(Instance {
453 def: InstanceKind::Shim(ShimKind::AsyncDropGlueCtor(_, ty)),
454 args,
455 }) => {
456 {
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)));
458 symbols.push((
459 ExportedSymbol::AsyncDropGlueCtorShim(ty),
460 SymbolExportInfo {
461 level: SymbolExportLevel::Rust,
462 kind: SymbolExportKind::Text,
463 used: false,
464 rustc_std_internal_symbol: false,
465 },
466 ));
467 }
468 MonoItem::Fn(Instance {
469 def: InstanceKind::Shim(ShimKind::AsyncDropGlue(def, ty)),
470 args: _,
471 }) => {
472 symbols.push((
473 ExportedSymbol::AsyncDropGlue(def, ty),
474 SymbolExportInfo {
475 level: SymbolExportLevel::Rust,
476 kind: SymbolExportKind::Text,
477 used: false,
478 rustc_std_internal_symbol: false,
479 },
480 ));
481 }
482 _ => {
483 }
485 }
486 }
487 }
488
489 symbols.sort_by_cached_key(|s| s.0.symbol_name_for_local_instance(tcx));
491
492 tcx.arena.alloc_from_iter(symbols)
493}
494
495fn upstream_monomorphizations_provider(
496 tcx: TyCtxt<'_>,
497 (): (),
498) -> DefIdMap<UnordMap<GenericArgsRef<'_>, CrateNum>> {
499 let cnums = tcx.crates(());
500
501 let mut instances: DefIdMap<UnordMap<_, _>> = Default::default();
502
503 let drop_glue_fn_def_id = tcx.lang_items().drop_glue_fn();
504 let async_drop_in_place_fn_def_id = tcx.lang_items().async_drop_in_place_fn();
505
506 for &cnum in cnums.iter() {
507 if tcx.crate_dep_kind(cnum) == CrateDepKind::Conditional {
512 continue;
513 }
514
515 for (exported_symbol, _) in tcx.exported_generic_symbols(cnum).iter() {
516 let (def_id, args) = match *exported_symbol {
517 ExportedSymbol::Generic(def_id, args) => (def_id, args),
518 ExportedSymbol::DropGlue(ty) => {
519 if let Some(drop_in_place_fn_def_id) = drop_glue_fn_def_id {
520 (drop_in_place_fn_def_id, tcx.mk_args(&[ty.into()]))
521 } else {
522 continue;
524 }
525 }
526 ExportedSymbol::AsyncDropGlueCtorShim(ty) => {
527 if let Some(async_drop_in_place_fn_def_id) = async_drop_in_place_fn_def_id {
528 (async_drop_in_place_fn_def_id, tcx.mk_args(&[ty.into()]))
529 } else {
530 continue;
531 }
532 }
533 ExportedSymbol::AsyncDropGlue(def_id, ty) => (def_id, tcx.mk_args(&[ty.into()])),
534 ExportedSymbol::NonGeneric(..)
535 | ExportedSymbol::ThreadLocalShim(..)
536 | ExportedSymbol::NoDefId(..) => {
::core::panicking::panic_fmt(format_args!("internal error: entered unreachable code: {0}",
format_args!("{0:?}", exported_symbol)));
}unreachable!("{exported_symbol:?}"),
537 };
538
539 let args_map = instances.entry(def_id).or_default();
540
541 match args_map.entry(args) {
542 Occupied(mut e) => {
543 let other_cnum = *e.get();
546 if tcx.stable_crate_id(other_cnum) > tcx.stable_crate_id(cnum) {
547 e.insert(cnum);
548 }
549 }
550 Vacant(e) => {
551 e.insert(cnum);
552 }
553 }
554 }
555 }
556
557 instances
558}
559
560fn upstream_monomorphizations_for_provider(
561 tcx: TyCtxt<'_>,
562 def_id: DefId,
563) -> Option<&UnordMap<GenericArgsRef<'_>, CrateNum>> {
564 if !!def_id.is_local() {
::core::panicking::panic("assertion failed: !def_id.is_local()")
};assert!(!def_id.is_local());
565 tcx.upstream_monomorphizations(()).get(&def_id)
566}
567
568fn upstream_drop_glue_for_provider<'tcx>(
569 tcx: TyCtxt<'tcx>,
570 args: GenericArgsRef<'tcx>,
571) -> Option<CrateNum> {
572 let def_id = tcx.lang_items().drop_glue_fn()?;
573 tcx.upstream_monomorphizations_for(def_id)?.get(&args).cloned()
574}
575
576fn upstream_async_drop_glue_for_provider<'tcx>(
577 tcx: TyCtxt<'tcx>,
578 args: GenericArgsRef<'tcx>,
579) -> Option<CrateNum> {
580 let def_id = tcx.lang_items().async_drop_in_place_fn()?;
581 tcx.upstream_monomorphizations_for(def_id)?.get(&args).cloned()
582}
583
584fn is_unreachable_local_definition_provider(tcx: TyCtxt<'_>, def_id: LocalDefId) -> bool {
585 !tcx.reachable_set(()).contains(&def_id)
586}
587
588pub(crate) fn provide(providers: &mut Providers) {
589 providers.queries.reachable_non_generics = reachable_non_generics_provider;
590 providers.queries.is_reachable_non_generic = is_reachable_non_generic_provider_local;
591 providers.queries.exported_non_generic_symbols = exported_non_generic_symbols_provider_local;
592 providers.queries.exported_generic_symbols = exported_generic_symbols_provider_local;
593 providers.queries.upstream_monomorphizations = upstream_monomorphizations_provider;
594 providers.queries.is_unreachable_local_definition = is_unreachable_local_definition_provider;
595 providers.queries.upstream_drop_glue_for = upstream_drop_glue_for_provider;
596 providers.queries.upstream_async_drop_glue_for = upstream_async_drop_glue_for_provider;
597 providers.queries.wasm_import_module_map = wasm_import_module_map;
598 providers.extern_queries.is_reachable_non_generic = is_reachable_non_generic_provider_extern;
599 providers.extern_queries.upstream_monomorphizations_for =
600 upstream_monomorphizations_for_provider;
601}
602
603pub(crate) fn allocator_shim_symbols(
604 tcx: TyCtxt<'_>,
605 kind: AllocatorKind,
606) -> impl Iterator<Item = (String, SymbolExportKind)> {
607 allocator_shim_contents(tcx, kind)
608 .into_iter()
609 .map(move |method| mangle_internal_symbol(tcx, global_fn_name(method.name).as_str()))
610 .chain([mangle_internal_symbol(tcx, NO_ALLOC_SHIM_IS_UNSTABLE)])
611 .map(move |symbol_name| {
612 let exported_symbol = ExportedSymbol::NoDefId(SymbolName::new(tcx, &symbol_name));
613
614 (
615 symbol_export::exporting_symbol_name_for_instance_in_crate(
616 tcx,
617 exported_symbol,
618 LOCAL_CRATE,
619 ),
620 SymbolExportKind::Text,
621 )
622 })
623}
624
625fn symbol_export_level(tcx: TyCtxt<'_>, sym_def_id: DefId) -> SymbolExportLevel {
626 let codegen_fn_attrs = tcx.codegen_fn_attrs(sym_def_id);
632 let is_extern = codegen_fn_attrs.contains_extern_indicator();
633 let std_internal =
634 codegen_fn_attrs.flags.contains(CodegenFnAttrFlags::RUSTC_STD_INTERNAL_SYMBOL);
635 let eii = codegen_fn_attrs.flags.contains(CodegenFnAttrFlags::EXTERNALLY_IMPLEMENTABLE_ITEM);
636
637 if is_extern && !std_internal && !eii {
638 let target = &tcx.sess.target.llvm_target;
639 if target.contains("emscripten") {
642 if let DefKind::Static { .. } = tcx.def_kind(sym_def_id) {
643 return SymbolExportLevel::Rust;
644 }
645 }
646
647 SymbolExportLevel::C
648 } else {
649 SymbolExportLevel::Rust
650 }
651}
652
653pub(crate) fn symbol_name_for_instance_in_crate<'tcx>(
655 tcx: TyCtxt<'tcx>,
656 symbol: ExportedSymbol<'tcx>,
657 instantiating_crate: CrateNum,
658) -> String {
659 if instantiating_crate == LOCAL_CRATE {
662 return symbol.symbol_name_for_local_instance(tcx).to_string();
663 }
664
665 match symbol {
668 ExportedSymbol::NonGeneric(def_id) => {
669 rustc_symbol_mangling::symbol_name_for_instance_in_crate(
670 tcx,
671 Instance::mono(tcx, def_id),
672 instantiating_crate,
673 )
674 }
675 ExportedSymbol::Generic(def_id, args) => {
676 rustc_symbol_mangling::symbol_name_for_instance_in_crate(
677 tcx,
678 Instance::new_raw(def_id, args),
679 instantiating_crate,
680 )
681 }
682 ExportedSymbol::ThreadLocalShim(def_id) => {
683 rustc_symbol_mangling::symbol_name_for_instance_in_crate(
684 tcx,
685 ty::Instance {
686 def: ty::InstanceKind::Shim(ty::ShimKind::ThreadLocal(def_id)),
687 args: ty::GenericArgs::empty(),
688 },
689 instantiating_crate,
690 )
691 }
692 ExportedSymbol::DropGlue(ty) => rustc_symbol_mangling::symbol_name_for_instance_in_crate(
693 tcx,
694 Instance::resolve_drop_glue(tcx, ty),
695 instantiating_crate,
696 ),
697 ExportedSymbol::AsyncDropGlueCtorShim(ty) => {
698 rustc_symbol_mangling::symbol_name_for_instance_in_crate(
699 tcx,
700 Instance::resolve_async_drop_in_place(tcx, ty),
701 instantiating_crate,
702 )
703 }
704 ExportedSymbol::AsyncDropGlue(def_id, ty) => {
705 rustc_symbol_mangling::symbol_name_for_instance_in_crate(
706 tcx,
707 Instance::resolve_async_drop_in_place_poll(tcx, def_id, ty),
708 instantiating_crate,
709 )
710 }
711 ExportedSymbol::NoDefId(symbol_name) => symbol_name.to_string(),
712 }
713}
714
715fn calling_convention_for_symbol<'tcx>(
716 tcx: TyCtxt<'tcx>,
717 symbol: ExportedSymbol<'tcx>,
718) -> (CanonAbi, &'tcx [rustc_target::callconv::ArgAbi<'tcx, Ty<'tcx>>]) {
719 let instance = match symbol {
720 ExportedSymbol::NonGeneric(def_id) | ExportedSymbol::Generic(def_id, _)
721 if tcx.is_static(def_id) =>
722 {
723 None
724 }
725 ExportedSymbol::NonGeneric(def_id) => Some(Instance::mono(tcx, def_id)),
726 ExportedSymbol::Generic(def_id, args) => Some(Instance::new_raw(def_id, args)),
727 ExportedSymbol::DropGlue(..) => None,
730 ExportedSymbol::AsyncDropGlueCtorShim(..) => None,
733 ExportedSymbol::AsyncDropGlue(..) => None,
734 ExportedSymbol::NoDefId(..) => None,
736 ExportedSymbol::ThreadLocalShim(..) => None,
738 };
739
740 instance
741 .map(|i| {
742 tcx.fn_abi_of_instance(
743 ty::TypingEnv::fully_monomorphized().as_query_input((i, ty::List::empty())),
744 )
745 .unwrap_or_else(|_| ::rustc_span::macros::bug_impl(None,
format_args!("fn_abi_of_instance({0:?}) failed", i), Location::caller())bug!("fn_abi_of_instance({i:?}) failed"))
746 })
747 .map(|fnabi| (fnabi.conv, &fnabi.args[..]))
748 .unwrap_or((CanonAbi::Rust, &[]))
750}
751
752pub(crate) fn linking_symbol_name_for_instance_in_crate<'tcx>(
756 tcx: TyCtxt<'tcx>,
757 symbol: ExportedSymbol<'tcx>,
758 export_kind: SymbolExportKind,
759 instantiating_crate: CrateNum,
760) -> String {
761 let mut undecorated = symbol_name_for_instance_in_crate(tcx, symbol, instantiating_crate);
762
763 if let Some(name) = maybe_emutls_symbol_name(tcx, symbol, &undecorated) {
766 return name;
767 }
768
769 let target = &tcx.sess.target;
770 if !target.is_like_windows {
771 return undecorated;
774 }
775
776 let prefix = match target.arch {
777 Arch::X86 => Some('_'),
778 Arch::X86_64 => None,
779 Arch::Arm64EC if export_kind == SymbolExportKind::Text => Some('#'),
781 _ => return undecorated,
783 };
784
785 let (callconv, args) = calling_convention_for_symbol(tcx, symbol);
786
787 let (prefix, suffix) = match callconv {
790 CanonAbi::X86(X86Call::Fastcall) => ("@", "@"),
791 CanonAbi::X86(X86Call::Stdcall) => ("_", "@"),
792 CanonAbi::X86(X86Call::Vectorcall) => ("", "@@"),
793 _ => {
794 if let Some(prefix) = prefix {
795 undecorated.insert(0, prefix);
796 }
797 return undecorated;
798 }
799 };
800
801 let args_in_bytes: u64 = args
802 .iter()
803 .map(|abi| abi.layout.size.bytes().next_multiple_of(target.pointer_width as u64 / 8))
804 .sum();
805 ::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}")
806}
807
808pub(crate) fn exporting_symbol_name_for_instance_in_crate<'tcx>(
809 tcx: TyCtxt<'tcx>,
810 symbol: ExportedSymbol<'tcx>,
811 cnum: CrateNum,
812) -> String {
813 let undecorated = symbol_name_for_instance_in_crate(tcx, symbol, cnum);
814 maybe_emutls_symbol_name(tcx, symbol, &undecorated).unwrap_or(undecorated)
815}
816
817fn strip_numeric_suffix<'a>(base: &'a str, suffix: impl AsRef<str>, fallback: &'a str) -> &'a str {
818 if suffix.as_ref().parse::<u32>().is_ok() { base } else { fallback }
819}
820
821pub(super) fn coff_machine_for_arch(arch: &Arch) -> Option<u16> {
823 match *arch {
824 Arch::X86 => Some(pe::IMAGE_FILE_MACHINE_I386),
825 Arch::X86_64 => Some(pe::IMAGE_FILE_MACHINE_AMD64),
826 Arch::Arm64EC => Some(pe::IMAGE_FILE_MACHINE_ARM64EC),
827 _ => None,
828 }
829}
830
831pub(super) fn undecorate_coff_symbol<'a>(
833 name: &'a str,
834 machine: u16,
835 kind: SymbolExportKind,
836) -> &'a str {
837 if name.starts_with('?') {
841 return name;
842 }
843 match machine {
844 pe::IMAGE_FILE_MACHINE_I386 => {
845 if let Some(rest) = name.strip_prefix('@') {
846 rest.rsplit_once('@')
848 .map(|(base, suffix)| strip_numeric_suffix(base, suffix, name))
849 .unwrap_or(name)
850 } else if let Some(stripped) = name.strip_prefix('_') {
851 if let Some((base, suffix)) = stripped.rsplit_once('@') {
852 strip_numeric_suffix(base, suffix, stripped)
854 } else {
855 stripped
857 }
858 } else {
859 name.rsplit_once("@@")
861 .map(|(base, suffix)| strip_numeric_suffix(base, suffix, name))
862 .unwrap_or(name)
863 }
864 }
865 pe::IMAGE_FILE_MACHINE_AMD64 => {
866 name.rsplit_once("@@")
868 .map(|(base, suffix)| strip_numeric_suffix(base, suffix, name))
869 .unwrap_or(name)
870 }
871 pe::IMAGE_FILE_MACHINE_ARM64EC if kind == SymbolExportKind::Text => {
872 name.strip_prefix('#').unwrap_or(name)
874 }
875 _ => name,
876 }
877}
878
879pub(crate) fn extend_exported_symbols<'tcx>(
883 symbols: &mut Vec<SymbolExport>,
884 tcx: TyCtxt<'tcx>,
885 symbol: ExportedSymbol<'tcx>,
886 instantiating_crate: CrateNum,
887) {
888 let (callconv, _) = calling_convention_for_symbol(tcx, symbol);
889
890 if callconv != CanonAbi::GpuKernel || tcx.sess.target.os != Os::AmdHsa {
891 return;
892 }
893
894 let undecorated = symbol_name_for_instance_in_crate(tcx, symbol, instantiating_crate);
895
896 symbols.push(SymbolExport::new(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0}.kd", undecorated))
})format!("{undecorated}.kd"), SymbolExportKind::Data));
900}
901
902fn maybe_emutls_symbol_name<'tcx>(
903 tcx: TyCtxt<'tcx>,
904 symbol: ExportedSymbol<'tcx>,
905 undecorated: &str,
906) -> Option<String> {
907 if #[allow(non_exhaustive_omitted_patterns)] match tcx.sess.tls_model() {
TlsModel::Emulated => true,
_ => false,
}matches!(tcx.sess.tls_model(), TlsModel::Emulated)
908 && let ExportedSymbol::NonGeneric(def_id) = symbol
909 && tcx.is_thread_local_static(def_id)
910 {
911 Some(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("__emutls_v.{0}", undecorated))
})format!("__emutls_v.{undecorated}"))
914 } else {
915 None
916 }
917}
918
919fn wasm_import_module_map(tcx: TyCtxt<'_>, cnum: CrateNum) -> DefIdMap<String> {
920 let native_libs = tcx.native_libraries(cnum);
924
925 let def_id_to_native_lib = native_libs
926 .iter()
927 .filter_map(|lib| lib.foreign_module.map(|id| (id, lib)))
928 .collect::<DefIdMap<_>>();
929
930 let mut ret = DefIdMap::default();
931 for (def_id, lib) in tcx.foreign_modules(cnum).iter() {
932 let module = def_id_to_native_lib.get(def_id).and_then(|s| s.wasm_import_module());
933 let Some(module) = module else { continue };
934 ret.extend(lib.foreign_items.iter().map(|id| {
935 {
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);
936 (*id, module.to_string())
937 }));
938 }
939
940 ret
941}
942
943pub fn escape_symbol_name(tcx: TyCtxt<'_>, symbol: &str, span: Span) -> String {
944 use rustc_target::spec::{Arch, BinaryFormat};
946 if !symbol.is_empty()
947 && 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' | '_' | '$' | '.'))
948 {
949 return symbol.to_string();
950 }
951 if tcx.sess.target.binary_format == BinaryFormat::Xcoff {
952 tcx.sess.dcx().span_fatal(
953 span,
954 ::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!(
955 "symbol escaping is not supported for the binary format {}",
956 tcx.sess.target.binary_format
957 ),
958 );
959 }
960 if tcx.sess.target.arch == Arch::Nvptx64 {
961 tcx.sess.dcx().span_fatal(
962 span,
963 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("symbol escaping is not supported for the architecture {0}",
tcx.sess.target.arch))
})format!(
964 "symbol escaping is not supported for the architecture {}",
965 tcx.sess.target.arch
966 ),
967 );
968 }
969 let mut escaped_symbol = String::new();
970 escaped_symbol.push('\"');
971 for c in symbol.chars() {
972 match c {
973 '\n' => escaped_symbol.push_str("\\\n"),
974 '"' => escaped_symbol.push_str("\\\""),
975 '\\' => escaped_symbol.push_str("\\\\"),
976 c => escaped_symbol.push(c),
977 }
978 }
979 escaped_symbol.push('\"');
980 escaped_symbol
981}