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, GenericArgs, 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 let instance = Instance::mono(tcx, def_id.into());
109
110 if instance.def.requires_inline(tcx) {
111 return None;
112 }
113
114 if tcx.cross_crate_inlinable(def_id) {
115 return None;
116 }
117
118 if tcx.instantiate_and_check_impossible_clauses((instance.def_id(), instance.args)) {
119 return None;
120 }
121
122 Some(def_id)
123 })
124 .map(|def_id| {
125 let export_level = if is_compiler_builtins {
126 SymbolExportLevel::Rust
132 } else {
133 symbol_export_level(tcx, def_id.to_def_id())
134 };
135 let codegen_attrs = tcx.codegen_fn_attrs(def_id.to_def_id());
136 {
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event /rustc-dev/5f4effd579500175af844241eb179e756190f1e7/compiler/rustc_codegen_ssa/src/back/symbol_export.rs:136",
"rustc_codegen_ssa::back::symbol_export",
::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/5f4effd579500175af844241eb179e756190f1e7/compiler/rustc_codegen_ssa/src/back/symbol_export.rs"),
::tracing_core::__macro_support::Option::Some(136u32),
::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!(
137 "EXPORTED SYMBOL (local): {} ({:?})",
138 tcx.symbol_name(Instance::mono(tcx, def_id.to_def_id())),
139 export_level
140 );
141 let info = SymbolExportInfo {
142 level: export_level,
143 kind: if tcx.is_static(def_id.to_def_id()) {
144 if codegen_attrs.flags.contains(CodegenFnAttrFlags::THREAD_LOCAL) {
145 SymbolExportKind::Tls
146 } else {
147 SymbolExportKind::Data
148 }
149 } else {
150 SymbolExportKind::Text
151 },
152 used: codegen_attrs.flags.contains(CodegenFnAttrFlags::USED_COMPILER)
153 || codegen_attrs.flags.contains(CodegenFnAttrFlags::USED_LINKER),
154 rustc_std_internal_symbol: codegen_attrs
155 .flags
156 .contains(CodegenFnAttrFlags::RUSTC_STD_INTERNAL_SYMBOL)
157 || codegen_attrs
158 .flags
159 .contains(CodegenFnAttrFlags::EXTERNALLY_IMPLEMENTABLE_ITEM),
160 };
161 (def_id.to_def_id(), info)
162 })
163 .into();
164
165 if let Some(id) = tcx.proc_macro_decls_static(()) {
166 reachable_non_generics.insert(
167 id.to_def_id(),
168 SymbolExportInfo {
169 level: SymbolExportLevel::C,
170 kind: SymbolExportKind::Data,
171 used: false,
172 rustc_std_internal_symbol: false,
173 },
174 );
175 }
176
177 reachable_non_generics
178}
179
180fn is_reachable_non_generic_provider_local(tcx: TyCtxt<'_>, def_id: LocalDefId) -> bool {
181 let export_threshold = threshold(tcx);
182
183 if let Some(&info) = tcx.reachable_non_generics(LOCAL_CRATE).get(&def_id.to_def_id()) {
184 info.level.is_below_threshold(export_threshold)
185 } else {
186 false
187 }
188}
189
190fn is_reachable_non_generic_provider_extern(tcx: TyCtxt<'_>, def_id: DefId) -> bool {
191 tcx.reachable_non_generics(def_id.krate).contains_key(&def_id)
192}
193
194fn exported_non_generic_symbols_provider_local<'tcx>(
195 tcx: TyCtxt<'tcx>,
196 _: LocalCrate,
197) -> &'tcx [(ExportedSymbol<'tcx>, SymbolExportInfo)] {
198 if !tcx.sess.opts.output_types.should_codegen() && !tcx.is_sdylib_interface_build() {
199 return &[];
200 }
201
202 exported_non_generic_symbols_helper(tcx)
203}
204
205pub fn exported_non_generic_symbols_helper<'tcx>(
207 tcx: TyCtxt<'tcx>,
208) -> &'tcx [(ExportedSymbol<'tcx>, SymbolExportInfo)] {
209 let sorted = tcx.with_stable_hashing_context(|mut hcx| {
212 tcx.reachable_non_generics(LOCAL_CRATE).to_sorted(&mut hcx, true)
213 });
214
215 let mut symbols: Vec<_> =
216 sorted.iter().map(|&(&def_id, &info)| (ExportedSymbol::NonGeneric(def_id), info)).collect();
217
218 if !tcx.sess.target.dll_tls_export {
220 symbols.extend(sorted.iter().filter_map(|&(&def_id, &info)| {
221 tcx.needs_thread_local_shim(def_id).then(|| {
222 (
223 ExportedSymbol::ThreadLocalShim(def_id),
224 SymbolExportInfo {
225 level: info.level,
226 kind: SymbolExportKind::Text,
227 used: info.used,
228 rustc_std_internal_symbol: info.rustc_std_internal_symbol,
229 },
230 )
231 })
232 }))
233 }
234
235 symbols.extend(sorted.iter().flat_map(|&(&def_id, &info)| {
236 tcx.codegen_fn_attrs(def_id).foreign_item_symbol_aliases.iter().map(
237 move |&(foreign_item, _linkage, _visibility)| {
238 (ExportedSymbol::NonGeneric(foreign_item), info)
239 },
240 )
241 }));
242
243 if tcx.entry_fn(()).is_some() {
244 let exported_symbol =
245 ExportedSymbol::NoDefId(SymbolName::new(tcx, tcx.sess.target.entry_name.as_ref()));
246
247 symbols.push((
248 exported_symbol,
249 SymbolExportInfo {
250 level: SymbolExportLevel::C,
251 kind: SymbolExportKind::Text,
252 used: false,
253 rustc_std_internal_symbol: false,
254 },
255 ));
256 }
257
258 let is_device_offload = tcx
259 .sess
260 .opts
261 .unstable_opts
262 .offload
263 .iter()
264 .any(|o| #[allow(non_exhaustive_omitted_patterns)] match o {
rustc_session::config::Offload::Device(_) => true,
_ => false,
}matches!(o, rustc_session::config::Offload::Device(_)));
265 if is_device_offload {
266 let crate_items = tcx.hir_crate_items(());
267 let mut seen: rustc_data_structures::fx::FxHashSet<DefId> = symbols
268 .iter()
269 .filter_map(|(s, _)| match s {
270 ExportedSymbol::NonGeneric(d) => Some(*d),
271 _ => None,
272 })
273 .collect();
274
275 let mut try_emit_offload_kernel = |def_id: DefId, seen: &mut FxHashSet<DefId>| {
276 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) {
277 return;
278 }
279 if !tcx.generics_of(def_id).requires_monomorphization(tcx)
280 && is_offload_kernel(tcx.codegen_fn_attrs(def_id))
281 && seen.insert(def_id)
282 {
283 symbols.push((
284 ExportedSymbol::NonGeneric(def_id),
285 SymbolExportInfo {
286 level: SymbolExportLevel::C,
287 kind: SymbolExportKind::Text,
288 used: false,
289 rustc_std_internal_symbol: false,
290 },
291 ));
292 }
293 };
294
295 for id in crate_items.free_items() {
296 try_emit_offload_kernel(id.owner_id.to_def_id(), &mut seen);
297 }
298 for id in crate_items.impl_items() {
299 try_emit_offload_kernel(id.owner_id.to_def_id(), &mut seen);
300 }
301 }
302
303 symbols.sort_by_cached_key(|s| s.0.symbol_name_for_local_instance(tcx));
305
306 tcx.arena.alloc_from_iter(symbols)
307}
308
309fn exported_generic_symbols_provider_local<'tcx>(
310 tcx: TyCtxt<'tcx>,
311 _: LocalCrate,
312) -> &'tcx [(ExportedSymbol<'tcx>, SymbolExportInfo)] {
313 if !tcx.sess.opts.output_types.should_codegen() && !tcx.is_sdylib_interface_build() {
314 return &[];
315 }
316
317 let mut symbols: Vec<_> = ::alloc::vec::Vec::new()vec![];
318
319 let export_generics = tcx.local_crate_exports_generics();
320 let is_device_offload = tcx
321 .sess
322 .opts
323 .unstable_opts
324 .offload
325 .iter()
326 .any(|o| #[allow(non_exhaustive_omitted_patterns)] match o {
rustc_session::config::Offload::Device(_) => true,
_ => false,
}matches!(o, rustc_session::config::Offload::Device(_)));
327
328 if export_generics || is_device_offload {
329 use rustc_attr_ir::{InlineAttr, Linkage};
330 use rustc_middle::mono::{MonoItem, Visibility};
331 use rustc_middle::ty::InstanceKind;
332
333 let need_visibility = tcx.sess.target.dynamic_linking && !tcx.sess.target.only_cdylib;
339
340 let cgus = tcx.collect_and_partition_mono_items(()).codegen_units;
341
342 let reachable_set = tcx.reachable_set(());
344 let is_local_to_current_crate = |ty: Ty<'_>| {
345 let no_refs = ty.peel_refs();
346 let root_def_id = match no_refs.kind() {
347 ty::Closure(closure, _) => *closure,
348 ty::FnDef(def_id, _) => *def_id,
349 ty::Coroutine(def_id, _) => *def_id,
350 ty::CoroutineClosure(def_id, _) => *def_id,
351 ty::CoroutineWitness(def_id, _) => *def_id,
352 _ => return false,
353 };
354 let Some(root_def_id) = root_def_id.as_local() else {
355 return false;
356 };
357
358 let is_local = !reachable_set.contains(&root_def_id);
359 is_local
360 };
361
362 let is_instantiable_downstream = |did: Option<DefId>, generic_args: GenericArgs<'tcx>| {
363 generic_args
364 .types()
365 .chain(did.into_iter().map(move |did| tcx.type_of(did).skip_binder()))
366 .all(move |arg| {
367 arg.walk()
368 .all(|ty| ty.as_type().is_none_or(|ty| !is_local_to_current_crate(ty)))
369 })
370 };
371
372 let is_offload_instance = |mono_item: &MonoItem<'tcx>| {
373 if let MonoItem::Fn(instance) = mono_item {
374 is_offload_kernel(tcx.codegen_fn_attrs(instance.def_id()))
375 } else {
376 false
377 }
378 };
379
380 #[allow(rustc::potential_query_instability)]
382 for (mono_item, data) in cgus.iter().flat_map(|cgu| cgu.items().iter()) {
383 if data.linkage != Linkage::External {
384 continue;
387 }
388
389 if need_visibility && data.visibility == Visibility::Hidden {
390 continue;
393 }
394
395 let item_is_offload = is_offload_instance(mono_item);
396
397 if !item_is_offload && !tcx.sess.opts.share_generics() {
398 if tcx.codegen_fn_attrs(mono_item.def_id()).inline == InlineAttr::Never {
399 } else {
402 continue;
403 }
404 }
405
406 match *mono_item {
409 MonoItem::Fn(Instance { def: InstanceKind::Item(def), args }) => {
410 let has_generics = args.non_erasable_generics().next().is_some();
411
412 let should_export = if item_is_offload {
413 has_generics
414 } else {
415 has_generics && is_instantiable_downstream(Some(def), args)
416 };
417
418 if should_export {
419 let symbol = ExportedSymbol::Generic(def, args);
420 symbols.push((
421 symbol,
422 SymbolExportInfo {
423 level: if item_is_offload {
424 SymbolExportLevel::C
425 } else {
426 SymbolExportLevel::Rust
427 },
428 kind: SymbolExportKind::Text,
429 used: false,
430 rustc_std_internal_symbol: false,
431 },
432 ));
433 }
434 }
435 MonoItem::Fn(Instance {
436 def: InstanceKind::Shim(ShimKind::DropGlue(_, Some(ty))),
437 args,
438 }) => {
439 {
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)));
441
442 let should_export = match ty.kind() {
444 ty::Adt(_, args) => is_instantiable_downstream(None, *args),
445 ty::Closure(_, args) => is_instantiable_downstream(None, *args),
446 _ => true,
447 };
448
449 if should_export {
450 symbols.push((
451 ExportedSymbol::DropGlue(ty),
452 SymbolExportInfo {
453 level: SymbolExportLevel::Rust,
454 kind: SymbolExportKind::Text,
455 used: false,
456 rustc_std_internal_symbol: false,
457 },
458 ));
459 }
460 }
461 MonoItem::Fn(Instance {
462 def: InstanceKind::Shim(ShimKind::AsyncDropGlueCtor(_, ty)),
463 args,
464 }) => {
465 {
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)));
467 symbols.push((
468 ExportedSymbol::AsyncDropGlueCtorShim(ty),
469 SymbolExportInfo {
470 level: SymbolExportLevel::Rust,
471 kind: SymbolExportKind::Text,
472 used: false,
473 rustc_std_internal_symbol: false,
474 },
475 ));
476 }
477 MonoItem::Fn(Instance {
478 def: InstanceKind::Shim(ShimKind::AsyncDropGlue(def, ty)),
479 args: _,
480 }) => {
481 symbols.push((
482 ExportedSymbol::AsyncDropGlue(def, ty),
483 SymbolExportInfo {
484 level: SymbolExportLevel::Rust,
485 kind: SymbolExportKind::Text,
486 used: false,
487 rustc_std_internal_symbol: false,
488 },
489 ));
490 }
491 _ => {
492 }
494 }
495 }
496 }
497
498 symbols.sort_by_cached_key(|s| s.0.symbol_name_for_local_instance(tcx));
500
501 tcx.arena.alloc_from_iter(symbols)
502}
503
504fn upstream_monomorphizations_provider(
505 tcx: TyCtxt<'_>,
506 (): (),
507) -> DefIdMap<UnordMap<GenericArgs<'_>, CrateNum>> {
508 let cnums = tcx.crates(());
509
510 let mut instances: DefIdMap<UnordMap<_, _>> = Default::default();
511
512 let drop_glue_fn_def_id = tcx.lang_items().drop_glue_fn();
513 let async_drop_in_place_fn_def_id = tcx.lang_items().async_drop_in_place_fn();
514
515 for &cnum in cnums.iter() {
516 if tcx.crate_dep_kind(cnum) == CrateDepKind::Conditional {
521 continue;
522 }
523
524 for (exported_symbol, _) in tcx.exported_generic_symbols(cnum).iter() {
525 let (def_id, args) = match *exported_symbol {
526 ExportedSymbol::Generic(def_id, args) => (def_id, args),
527 ExportedSymbol::DropGlue(ty) => {
528 if let Some(drop_in_place_fn_def_id) = drop_glue_fn_def_id {
529 (drop_in_place_fn_def_id, tcx.mk_args(&[ty.into()]))
530 } else {
531 continue;
533 }
534 }
535 ExportedSymbol::AsyncDropGlueCtorShim(ty) => {
536 if let Some(async_drop_in_place_fn_def_id) = async_drop_in_place_fn_def_id {
537 (async_drop_in_place_fn_def_id, tcx.mk_args(&[ty.into()]))
538 } else {
539 continue;
540 }
541 }
542 ExportedSymbol::AsyncDropGlue(def_id, ty) => (def_id, tcx.mk_args(&[ty.into()])),
543 ExportedSymbol::NonGeneric(..)
544 | ExportedSymbol::ThreadLocalShim(..)
545 | ExportedSymbol::NoDefId(..) => {
::core::panicking::panic_fmt(format_args!("internal error: entered unreachable code: {0}",
format_args!("{0:?}", exported_symbol)));
}unreachable!("{exported_symbol:?}"),
546 };
547
548 let args_map = instances.entry(def_id).or_default();
549
550 match args_map.entry(args) {
551 Occupied(mut e) => {
552 let other_cnum = *e.get();
555 if tcx.stable_crate_id(other_cnum) > tcx.stable_crate_id(cnum) {
556 e.insert(cnum);
557 }
558 }
559 Vacant(e) => {
560 e.insert(cnum);
561 }
562 }
563 }
564 }
565
566 instances
567}
568
569fn upstream_monomorphizations_for_provider(
570 tcx: TyCtxt<'_>,
571 def_id: DefId,
572) -> Option<&UnordMap<GenericArgs<'_>, CrateNum>> {
573 if !!def_id.is_local() {
::core::panicking::panic("assertion failed: !def_id.is_local()")
};assert!(!def_id.is_local());
574 tcx.upstream_monomorphizations(()).get(&def_id)
575}
576
577fn upstream_drop_glue_for_provider<'tcx>(
578 tcx: TyCtxt<'tcx>,
579 args: GenericArgs<'tcx>,
580) -> Option<CrateNum> {
581 let def_id = tcx.lang_items().drop_glue_fn()?;
582 tcx.upstream_monomorphizations_for(def_id)?.get(&args).cloned()
583}
584
585fn upstream_async_drop_glue_for_provider<'tcx>(
586 tcx: TyCtxt<'tcx>,
587 args: GenericArgs<'tcx>,
588) -> Option<CrateNum> {
589 let def_id = tcx.lang_items().async_drop_in_place_fn()?;
590 tcx.upstream_monomorphizations_for(def_id)?.get(&args).cloned()
591}
592
593fn is_unreachable_local_definition_provider(tcx: TyCtxt<'_>, def_id: LocalDefId) -> bool {
594 !tcx.reachable_set(()).contains(&def_id)
595}
596
597pub(crate) fn provide(providers: &mut Providers) {
598 providers.queries.reachable_non_generics = reachable_non_generics_provider;
599 providers.queries.is_reachable_non_generic = is_reachable_non_generic_provider_local;
600 providers.queries.exported_non_generic_symbols = exported_non_generic_symbols_provider_local;
601 providers.queries.exported_generic_symbols = exported_generic_symbols_provider_local;
602 providers.queries.upstream_monomorphizations = upstream_monomorphizations_provider;
603 providers.queries.is_unreachable_local_definition = is_unreachable_local_definition_provider;
604 providers.queries.upstream_drop_glue_for = upstream_drop_glue_for_provider;
605 providers.queries.upstream_async_drop_glue_for = upstream_async_drop_glue_for_provider;
606 providers.queries.wasm_import_module_map = wasm_import_module_map;
607 providers.extern_queries.is_reachable_non_generic = is_reachable_non_generic_provider_extern;
608 providers.extern_queries.upstream_monomorphizations_for =
609 upstream_monomorphizations_for_provider;
610}
611
612pub(crate) fn allocator_shim_symbols(
613 tcx: TyCtxt<'_>,
614 kind: AllocatorKind,
615) -> impl Iterator<Item = (String, SymbolExportKind)> {
616 allocator_shim_contents(tcx, kind)
617 .into_iter()
618 .map(move |method| mangle_internal_symbol(tcx, global_fn_name(method.name).as_str()))
619 .chain([mangle_internal_symbol(tcx, NO_ALLOC_SHIM_IS_UNSTABLE)])
620 .map(move |symbol_name| {
621 let exported_symbol = ExportedSymbol::NoDefId(SymbolName::new(tcx, &symbol_name));
622
623 (
624 symbol_export::exporting_symbol_name_for_instance_in_crate(
625 tcx,
626 exported_symbol,
627 LOCAL_CRATE,
628 ),
629 SymbolExportKind::Text,
630 )
631 })
632}
633
634fn symbol_export_level(tcx: TyCtxt<'_>, sym_def_id: DefId) -> SymbolExportLevel {
635 let codegen_fn_attrs = tcx.codegen_fn_attrs(sym_def_id);
641 let is_extern = codegen_fn_attrs.contains_extern_indicator();
642 let std_internal =
643 codegen_fn_attrs.flags.contains(CodegenFnAttrFlags::RUSTC_STD_INTERNAL_SYMBOL);
644 let eii = codegen_fn_attrs.flags.contains(CodegenFnAttrFlags::EXTERNALLY_IMPLEMENTABLE_ITEM);
645
646 if is_extern && !std_internal && !eii {
647 let target = &tcx.sess.target.llvm_target;
648 if target.contains("emscripten") {
651 if let DefKind::Static { .. } = tcx.def_kind(sym_def_id) {
652 return SymbolExportLevel::Rust;
653 }
654 }
655
656 SymbolExportLevel::C
657 } else {
658 SymbolExportLevel::Rust
659 }
660}
661
662pub(crate) fn symbol_name_for_instance_in_crate<'tcx>(
664 tcx: TyCtxt<'tcx>,
665 symbol: ExportedSymbol<'tcx>,
666 instantiating_crate: CrateNum,
667) -> String {
668 if instantiating_crate == LOCAL_CRATE {
671 return symbol.symbol_name_for_local_instance(tcx).to_string();
672 }
673
674 match symbol {
677 ExportedSymbol::NonGeneric(def_id) => {
678 rustc_symbol_mangling::symbol_name_for_instance_in_crate(
679 tcx,
680 Instance::mono(tcx, def_id),
681 instantiating_crate,
682 )
683 }
684 ExportedSymbol::Generic(def_id, args) => {
685 rustc_symbol_mangling::symbol_name_for_instance_in_crate(
686 tcx,
687 Instance::new_raw(def_id, args),
688 instantiating_crate,
689 )
690 }
691 ExportedSymbol::ThreadLocalShim(def_id) => {
692 rustc_symbol_mangling::symbol_name_for_instance_in_crate(
693 tcx,
694 ty::Instance {
695 def: ty::InstanceKind::Shim(ty::ShimKind::ThreadLocal(def_id)),
696 args: ty::GenericArgs::empty(),
697 },
698 instantiating_crate,
699 )
700 }
701 ExportedSymbol::DropGlue(ty) => rustc_symbol_mangling::symbol_name_for_instance_in_crate(
702 tcx,
703 Instance::resolve_drop_glue(tcx, ty),
704 instantiating_crate,
705 ),
706 ExportedSymbol::AsyncDropGlueCtorShim(ty) => {
707 rustc_symbol_mangling::symbol_name_for_instance_in_crate(
708 tcx,
709 Instance::resolve_async_drop_in_place(tcx, ty),
710 instantiating_crate,
711 )
712 }
713 ExportedSymbol::AsyncDropGlue(def_id, ty) => {
714 rustc_symbol_mangling::symbol_name_for_instance_in_crate(
715 tcx,
716 Instance::resolve_async_drop_in_place_poll(tcx, def_id, ty),
717 instantiating_crate,
718 )
719 }
720 ExportedSymbol::NoDefId(symbol_name) => symbol_name.to_string(),
721 }
722}
723
724fn calling_convention_for_symbol<'tcx>(
725 tcx: TyCtxt<'tcx>,
726 symbol: ExportedSymbol<'tcx>,
727) -> (CanonAbi, &'tcx [rustc_target::callconv::ArgAbi<'tcx, Ty<'tcx>>]) {
728 let instance = match symbol {
729 ExportedSymbol::NonGeneric(def_id) | ExportedSymbol::Generic(def_id, _)
730 if tcx.is_static(def_id) =>
731 {
732 None
733 }
734 ExportedSymbol::NonGeneric(def_id) => Some(Instance::mono(tcx, def_id)),
735 ExportedSymbol::Generic(def_id, args) => Some(Instance::new_raw(def_id, args)),
736 ExportedSymbol::DropGlue(..) => None,
739 ExportedSymbol::AsyncDropGlueCtorShim(..) => None,
742 ExportedSymbol::AsyncDropGlue(..) => None,
743 ExportedSymbol::NoDefId(..) => None,
745 ExportedSymbol::ThreadLocalShim(..) => None,
747 };
748
749 instance
750 .map(|i| {
751 tcx.fn_abi_of_instance(
752 ty::TypingEnv::fully_monomorphized().as_query_input((i, ty::List::empty())),
753 )
754 .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"))
755 })
756 .map(|fnabi| (fnabi.conv, &fnabi.args[..]))
757 .unwrap_or((CanonAbi::Rust, &[]))
759}
760
761pub(crate) fn linking_symbol_name_for_instance_in_crate<'tcx>(
765 tcx: TyCtxt<'tcx>,
766 symbol: ExportedSymbol<'tcx>,
767 export_kind: SymbolExportKind,
768 instantiating_crate: CrateNum,
769) -> String {
770 let mut undecorated = symbol_name_for_instance_in_crate(tcx, symbol, instantiating_crate);
771
772 if let Some(name) = maybe_emutls_symbol_name(tcx, symbol, &undecorated) {
775 return name;
776 }
777
778 let target = &tcx.sess.target;
779 if !target.is_like_windows {
780 return undecorated;
783 }
784
785 let prefix = match target.arch {
786 Arch::X86 => Some('_'),
787 Arch::X86_64 => None,
788 Arch::Arm64EC if export_kind == SymbolExportKind::Text => Some('#'),
790 _ => return undecorated,
792 };
793
794 let (callconv, args) = calling_convention_for_symbol(tcx, symbol);
795
796 let (prefix, suffix) = match callconv {
799 CanonAbi::X86(X86Call::Fastcall) => ("@", "@"),
800 CanonAbi::X86(X86Call::Stdcall) => ("_", "@"),
801 CanonAbi::X86(X86Call::Vectorcall) => ("", "@@"),
802 _ => {
803 if let Some(prefix) = prefix {
804 undecorated.insert(0, prefix);
805 }
806 return undecorated;
807 }
808 };
809
810 let args_in_bytes: u64 = args
811 .iter()
812 .map(|abi| abi.layout.size.bytes().next_multiple_of(target.pointer_width as u64 / 8))
813 .sum();
814 ::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}")
815}
816
817pub(crate) fn exporting_symbol_name_for_instance_in_crate<'tcx>(
818 tcx: TyCtxt<'tcx>,
819 symbol: ExportedSymbol<'tcx>,
820 cnum: CrateNum,
821) -> String {
822 let undecorated = symbol_name_for_instance_in_crate(tcx, symbol, cnum);
823 maybe_emutls_symbol_name(tcx, symbol, &undecorated).unwrap_or(undecorated)
824}
825
826fn strip_numeric_suffix<'a>(base: &'a str, suffix: impl AsRef<str>, fallback: &'a str) -> &'a str {
827 if suffix.as_ref().parse::<u32>().is_ok() { base } else { fallback }
828}
829
830pub(super) fn coff_machine_for_arch(arch: &Arch) -> Option<u16> {
832 match *arch {
833 Arch::X86 => Some(pe::IMAGE_FILE_MACHINE_I386),
834 Arch::X86_64 => Some(pe::IMAGE_FILE_MACHINE_AMD64),
835 Arch::Arm64EC => Some(pe::IMAGE_FILE_MACHINE_ARM64EC),
836 _ => None,
837 }
838}
839
840pub(super) fn undecorate_coff_symbol<'a>(
842 name: &'a str,
843 machine: u16,
844 kind: SymbolExportKind,
845) -> &'a str {
846 if name.starts_with('?') {
850 return name;
851 }
852 match machine {
853 pe::IMAGE_FILE_MACHINE_I386 => {
854 if let Some(rest) = name.strip_prefix('@') {
855 rest.rsplit_once('@')
857 .map(|(base, suffix)| strip_numeric_suffix(base, suffix, name))
858 .unwrap_or(name)
859 } else if let Some(stripped) = name.strip_prefix('_') {
860 if let Some((base, suffix)) = stripped.rsplit_once('@') {
861 strip_numeric_suffix(base, suffix, stripped)
863 } else {
864 stripped
866 }
867 } else {
868 name.rsplit_once("@@")
870 .map(|(base, suffix)| strip_numeric_suffix(base, suffix, name))
871 .unwrap_or(name)
872 }
873 }
874 pe::IMAGE_FILE_MACHINE_AMD64 => {
875 name.rsplit_once("@@")
877 .map(|(base, suffix)| strip_numeric_suffix(base, suffix, name))
878 .unwrap_or(name)
879 }
880 pe::IMAGE_FILE_MACHINE_ARM64EC if kind == SymbolExportKind::Text => {
881 name.strip_prefix('#').unwrap_or(name)
883 }
884 _ => name,
885 }
886}
887
888pub(crate) fn extend_exported_symbols<'tcx>(
892 symbols: &mut Vec<SymbolExport>,
893 tcx: TyCtxt<'tcx>,
894 symbol: ExportedSymbol<'tcx>,
895 instantiating_crate: CrateNum,
896) {
897 let (callconv, _) = calling_convention_for_symbol(tcx, symbol);
898
899 if callconv != CanonAbi::GpuKernel || tcx.sess.target.os != Os::AmdHsa {
900 return;
901 }
902
903 let undecorated = symbol_name_for_instance_in_crate(tcx, symbol, instantiating_crate);
904
905 symbols.push(SymbolExport::new(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0}.kd", undecorated))
})format!("{undecorated}.kd"), SymbolExportKind::Data));
909}
910
911fn maybe_emutls_symbol_name<'tcx>(
912 tcx: TyCtxt<'tcx>,
913 symbol: ExportedSymbol<'tcx>,
914 undecorated: &str,
915) -> Option<String> {
916 if #[allow(non_exhaustive_omitted_patterns)] match tcx.sess.tls_model() {
TlsModel::Emulated => true,
_ => false,
}matches!(tcx.sess.tls_model(), TlsModel::Emulated)
917 && let ExportedSymbol::NonGeneric(def_id) = symbol
918 && tcx.is_thread_local_static(def_id)
919 {
920 Some(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("__emutls_v.{0}", undecorated))
})format!("__emutls_v.{undecorated}"))
923 } else {
924 None
925 }
926}
927
928fn wasm_import_module_map(tcx: TyCtxt<'_>, cnum: CrateNum) -> DefIdMap<String> {
929 let native_libs = tcx.native_libraries(cnum);
933
934 let def_id_to_native_lib = native_libs
935 .iter()
936 .filter_map(|lib| lib.foreign_module.map(|id| (id, lib)))
937 .collect::<DefIdMap<_>>();
938
939 let mut ret = DefIdMap::default();
940 for (def_id, lib) in tcx.foreign_modules(cnum).iter() {
941 let module = def_id_to_native_lib.get(def_id).and_then(|s| s.wasm_import_module());
942 let Some(module) = module else { continue };
943 ret.extend(lib.foreign_items.iter().map(|id| {
944 {
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);
945 (*id, module.to_string())
946 }));
947 }
948
949 ret
950}
951
952pub fn escape_symbol_name(tcx: TyCtxt<'_>, symbol: &str, span: Span) -> String {
953 use rustc_target::spec::{Arch, BinaryFormat};
955 if !symbol.is_empty()
956 && 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' | '_' | '$' | '.'))
957 {
958 return symbol.to_string();
959 }
960 if tcx.sess.target.binary_format == BinaryFormat::Xcoff {
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 binary format {0}",
tcx.sess.target.binary_format))
})format!(
964 "symbol escaping is not supported for the binary format {}",
965 tcx.sess.target.binary_format
966 ),
967 );
968 }
969 if tcx.sess.target.arch == Arch::Nvptx64 {
970 tcx.sess.dcx().span_fatal(
971 span,
972 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("symbol escaping is not supported for the architecture {0}",
tcx.sess.target.arch))
})format!(
973 "symbol escaping is not supported for the architecture {}",
974 tcx.sess.target.arch
975 ),
976 );
977 }
978 let mut escaped_symbol = String::new();
979 escaped_symbol.push('\"');
980 for c in symbol.chars() {
981 match c {
982 '\n' => escaped_symbol.push_str("\\\n"),
983 '"' => escaped_symbol.push_str("\\\""),
984 '\\' => escaped_symbol.push_str("\\\\"),
985 c => escaped_symbol.push(c),
986 }
987 }
988 escaped_symbol.push('\"');
989 escaped_symbol
990}