1use std::any::Any;
2use std::env::consts::{DLL_PREFIX, DLL_SUFFIX};
3use std::path::{Path, PathBuf};
4use std::sync::atomic::{AtomicBool, Ordering};
5use std::sync::{Arc, OnceLock};
6use std::{env, thread};
7
8use rustc_ast as ast;
9use rustc_attr_parsing::{ShouldEmit, validate_attr};
10use rustc_codegen_ssa::back::archive::{ArArchiveBuilderBuilder, ArchiveBuilderBuilder};
11use rustc_codegen_ssa::back::link::link_binary;
12use rustc_codegen_ssa::target_features::cfg_target_feature;
13use rustc_codegen_ssa::traits::CodegenBackend;
14use rustc_codegen_ssa::{CodegenResults, CrateInfo, TargetConfig};
15use rustc_data_structures::fx::FxIndexMap;
16use rustc_data_structures::jobserver::Proxy;
17use rustc_data_structures::sync;
18use rustc_errors::LintBuffer;
19use rustc_metadata::{DylibError, EncodedMetadata, load_symbol_from_dylib};
20use rustc_middle::dep_graph::{WorkProduct, WorkProductId};
21use rustc_middle::ty::{CurrentGcx, TyCtxt};
22use rustc_session::config::{
23 Cfg, CrateType, OutFileName, OutputFilenames, OutputTypes, Sysroot, host_tuple,
24};
25use rustc_session::output::{CRATE_TYPES, categorize_crate_type};
26use rustc_session::{EarlyDiagCtxt, Session, filesearch, lint};
27use rustc_span::edit_distance::find_best_match_for_name;
28use rustc_span::edition::Edition;
29use rustc_span::source_map::SourceMapInputs;
30use rustc_span::{SessionGlobals, Symbol, sym};
31use rustc_target::spec::Target;
32use tracing::info;
33
34use crate::errors;
35use crate::passes::parse_crate_name;
36
37type MakeBackendFn = fn() -> Box<dyn CodegenBackend>;
39
40pub(crate) fn add_configuration(
46 cfg: &mut Cfg,
47 sess: &mut Session,
48 codegen_backend: &dyn CodegenBackend,
49) {
50 let tf = sym::target_feature;
51 let tf_cfg = codegen_backend.target_config(sess);
52
53 sess.unstable_target_features.extend(tf_cfg.unstable_target_features.iter().copied());
54 sess.target_features.extend(tf_cfg.target_features.iter().copied());
55
56 cfg.extend(tf_cfg.target_features.into_iter().map(|feat| (tf, Some(feat))));
57
58 if tf_cfg.has_reliable_f16 {
59 cfg.insert((sym::target_has_reliable_f16, None));
60 }
61 if tf_cfg.has_reliable_f16_math {
62 cfg.insert((sym::target_has_reliable_f16_math, None));
63 }
64 if tf_cfg.has_reliable_f128 {
65 cfg.insert((sym::target_has_reliable_f128, None));
66 }
67 if tf_cfg.has_reliable_f128_math {
68 cfg.insert((sym::target_has_reliable_f128_math, None));
69 }
70
71 if sess.crt_static(None) {
72 cfg.insert((tf, Some(sym::crt_dash_static)));
73 }
74}
75
76pub(crate) fn check_abi_required_features(sess: &Session) {
79 let abi_feature_constraints = sess.target.abi_required_features();
80 for feature in
84 abi_feature_constraints.required.iter().chain(abi_feature_constraints.incompatible.iter())
85 {
86 assert!(
87 sess.target.rust_target_features().iter().any(|(name, ..)| feature == name),
88 "target feature {feature} is required/incompatible for the current ABI but not a recognized feature for this target"
89 );
90 }
91
92 for feature in abi_feature_constraints.required {
93 if !sess.unstable_target_features.contains(&Symbol::intern(feature)) {
94 sess.dcx().emit_warn(errors::AbiRequiredTargetFeature { feature, enabled: "enabled" });
95 }
96 }
97 for feature in abi_feature_constraints.incompatible {
98 if sess.unstable_target_features.contains(&Symbol::intern(feature)) {
99 sess.dcx().emit_warn(errors::AbiRequiredTargetFeature { feature, enabled: "disabled" });
100 }
101 }
102}
103
104pub static STACK_SIZE: OnceLock<usize> = OnceLock::new();
105pub const DEFAULT_STACK_SIZE: usize = 8 * 1024 * 1024;
106
107fn init_stack_size(early_dcx: &EarlyDiagCtxt) -> usize {
108 *STACK_SIZE.get_or_init(|| {
110 env::var_os("RUST_MIN_STACK")
111 .as_ref()
112 .map(|os_str| os_str.to_string_lossy())
113 .filter(|s| !s.trim().is_empty())
117 .map(|s| {
121 let s = s.trim();
122 #[allow(rustc::untranslatable_diagnostic, rustc::diagnostic_outside_of_impl)]
124 s.parse::<usize>().unwrap_or_else(|_| {
125 let mut err = early_dcx.early_struct_fatal(format!(
126 r#"`RUST_MIN_STACK` should be a number of bytes, but was "{s}""#,
127 ));
128 err.note("you can also unset `RUST_MIN_STACK` to use the default stack size");
129 err.emit()
130 })
131 })
132 .unwrap_or(DEFAULT_STACK_SIZE)
134 })
135}
136
137fn run_in_thread_with_globals<F: FnOnce(CurrentGcx, Arc<Proxy>) -> R + Send, R: Send>(
138 thread_stack_size: usize,
139 edition: Edition,
140 sm_inputs: SourceMapInputs,
141 extra_symbols: &[&'static str],
142 f: F,
143) -> R {
144 let builder = thread::Builder::new().name("rustc".to_string()).stack_size(thread_stack_size);
151
152 thread::scope(|s| {
155 let r = builder
158 .spawn_scoped(s, move || {
159 rustc_span::create_session_globals_then(
160 edition,
161 extra_symbols,
162 Some(sm_inputs),
163 || f(CurrentGcx::new(), Proxy::new()),
164 )
165 })
166 .unwrap()
167 .join();
168
169 match r {
170 Ok(v) => v,
171 Err(e) => std::panic::resume_unwind(e),
172 }
173 })
174}
175
176pub(crate) fn run_in_thread_pool_with_globals<
177 F: FnOnce(CurrentGcx, Arc<Proxy>) -> R + Send,
178 R: Send,
179>(
180 thread_builder_diag: &EarlyDiagCtxt,
181 edition: Edition,
182 threads: usize,
183 extra_symbols: &[&'static str],
184 sm_inputs: SourceMapInputs,
185 f: F,
186) -> R {
187 use std::process;
188
189 use rustc_data_structures::defer;
190 use rustc_data_structures::sync::FromDyn;
191 use rustc_middle::ty::tls;
192 use rustc_query_impl::QueryCtxt;
193 use rustc_query_system::query::{QueryContext, break_query_cycles};
194
195 let thread_stack_size = init_stack_size(thread_builder_diag);
196
197 let registry = sync::Registry::new(std::num::NonZero::new(threads).unwrap());
198
199 if !sync::is_dyn_thread_safe() {
200 return run_in_thread_with_globals(
201 thread_stack_size,
202 edition,
203 sm_inputs,
204 extra_symbols,
205 |current_gcx, jobserver_proxy| {
206 registry.register();
208
209 f(current_gcx, jobserver_proxy)
210 },
211 );
212 }
213
214 let current_gcx = FromDyn::from(CurrentGcx::new());
215 let current_gcx2 = current_gcx.clone();
216
217 let proxy = Proxy::new();
218
219 let proxy_ = Arc::clone(&proxy);
220 let proxy__ = Arc::clone(&proxy);
221 let builder = rustc_thread_pool::ThreadPoolBuilder::new()
222 .thread_name(|_| "rustc".to_string())
223 .acquire_thread_handler(move || proxy_.acquire_thread())
224 .release_thread_handler(move || proxy__.release_thread())
225 .num_threads(threads)
226 .deadlock_handler(move || {
227 let current_gcx2 = current_gcx2.clone();
231 let registry = rustc_thread_pool::Registry::current();
232 let session_globals = rustc_span::with_session_globals(|session_globals| {
233 session_globals as *const SessionGlobals as usize
234 });
235 thread::Builder::new()
236 .name("rustc query cycle handler".to_string())
237 .spawn(move || {
238 let on_panic = defer(|| {
239 eprintln!("internal compiler error: query cycle handler thread panicked, aborting process");
240 process::abort();
243 });
244
245 current_gcx2.access(|gcx| {
248 tls::enter_context(&tls::ImplicitCtxt::new(gcx), || {
249 tls::with(|tcx| {
250 let query_map = rustc_span::set_session_globals_then(unsafe { &*(session_globals as *const SessionGlobals) }, || {
253 QueryCtxt::new(tcx).collect_active_jobs(false).expect("failed to collect active queries in deadlock handler")
256 });
257 break_query_cycles(query_map, ®istry);
258 })
259 })
260 });
261
262 on_panic.disable();
263 })
264 .unwrap();
265 })
266 .stack_size(thread_stack_size);
267
268 rustc_span::create_session_globals_then(edition, extra_symbols, Some(sm_inputs), || {
273 rustc_span::with_session_globals(|session_globals| {
274 let session_globals = FromDyn::from(session_globals);
275 builder
276 .build_scoped(
277 move |thread: rustc_thread_pool::ThreadBuilder| {
279 registry.register();
281
282 rustc_span::set_session_globals_then(session_globals.into_inner(), || {
283 thread.run()
284 })
285 },
286 move |pool: &rustc_thread_pool::ThreadPool| {
288 pool.install(|| f(current_gcx.into_inner(), proxy))
289 },
290 )
291 .unwrap_or_else(|err| {
292 let mut diag = thread_builder_diag.early_struct_fatal(format!(
293 "failed to spawn compiler thread pool: could not create {threads} threads ({err})",
294 ));
295 diag.help(
296 "try lowering `-Z threads` or checking the operating system's resource limits",
297 );
298 diag.emit();
299 })
300 })
301 })
302}
303
304#[allow(rustc::untranslatable_diagnostic)] fn load_backend_from_dylib(early_dcx: &EarlyDiagCtxt, path: &Path) -> MakeBackendFn {
306 match unsafe { load_symbol_from_dylib::<MakeBackendFn>(path, "__rustc_codegen_backend") } {
307 Ok(backend_sym) => backend_sym,
308 Err(DylibError::DlOpen(path, err)) => {
309 let err = format!("couldn't load codegen backend {path}{err}");
310 early_dcx.early_fatal(err);
311 }
312 Err(DylibError::DlSym(_path, err)) => {
313 let e = format!(
314 "`__rustc_codegen_backend` symbol lookup in the codegen backend failed{err}",
315 );
316 early_dcx.early_fatal(e);
317 }
318 }
319}
320
321pub fn get_codegen_backend(
325 early_dcx: &EarlyDiagCtxt,
326 sysroot: &Sysroot,
327 backend_name: Option<&str>,
328 target: &Target,
329) -> Box<dyn CodegenBackend> {
330 static LOAD: OnceLock<unsafe fn() -> Box<dyn CodegenBackend>> = OnceLock::new();
331
332 let load = LOAD.get_or_init(|| {
333 let backend = backend_name
334 .or(target.default_codegen_backend.as_deref())
335 .or(option_env!("CFG_DEFAULT_CODEGEN_BACKEND"))
336 .unwrap_or("dummy");
337
338 match backend {
339 filename if filename.contains('.') => {
340 load_backend_from_dylib(early_dcx, filename.as_ref())
341 }
342 "dummy" => || Box::new(DummyCodegenBackend { target_config_override: None }),
343 #[cfg(feature = "llvm")]
344 "llvm" => rustc_codegen_llvm::LlvmCodegenBackend::new,
345 backend_name => get_codegen_sysroot(early_dcx, sysroot, backend_name),
346 }
347 });
348
349 unsafe { load() }
353}
354
355pub struct DummyCodegenBackend {
356 pub target_config_override: Option<Box<dyn Fn(&Session) -> TargetConfig>>,
357}
358
359impl CodegenBackend for DummyCodegenBackend {
360 fn locale_resource(&self) -> &'static str {
361 ""
362 }
363
364 fn name(&self) -> &'static str {
365 "dummy"
366 }
367
368 fn target_config(&self, sess: &Session) -> TargetConfig {
369 if let Some(target_config_override) = &self.target_config_override {
370 return target_config_override(sess);
371 }
372
373 let abi_required_features = sess.target.abi_required_features();
374 let (target_features, unstable_target_features) = cfg_target_feature::<0>(
375 sess,
376 |_feature| Default::default(),
377 |feature| {
378 abi_required_features.required.contains(&feature)
383 },
384 );
385
386 TargetConfig {
387 target_features,
388 unstable_target_features,
389 has_reliable_f16: true,
390 has_reliable_f16_math: true,
391 has_reliable_f128: true,
392 has_reliable_f128_math: true,
393 }
394 }
395
396 fn supported_crate_types(&self, _sess: &Session) -> Vec<CrateType> {
397 vec![CrateType::Rlib, CrateType::Executable]
402 }
403
404 fn codegen_crate<'tcx>(&self, tcx: TyCtxt<'tcx>) -> Box<dyn Any> {
405 Box::new(CodegenResults {
406 modules: vec![],
407 allocator_module: None,
408 crate_info: CrateInfo::new(tcx, String::new()),
409 })
410 }
411
412 fn join_codegen(
413 &self,
414 ongoing_codegen: Box<dyn Any>,
415 _sess: &Session,
416 _outputs: &OutputFilenames,
417 ) -> (CodegenResults, FxIndexMap<WorkProductId, WorkProduct>) {
418 (*ongoing_codegen.downcast().unwrap(), FxIndexMap::default())
419 }
420
421 fn link(
422 &self,
423 sess: &Session,
424 codegen_results: CodegenResults,
425 metadata: EncodedMetadata,
426 outputs: &OutputFilenames,
427 ) {
428 #[allow(rustc::bad_opt_access)]
430 if let Some(&crate_type) = codegen_results
431 .crate_info
432 .crate_types
433 .iter()
434 .find(|&&crate_type| crate_type != CrateType::Rlib)
435 && outputs.outputs.should_link()
436 {
437 #[allow(rustc::untranslatable_diagnostic)]
438 #[allow(rustc::diagnostic_outside_of_impl)]
439 sess.dcx().fatal(format!(
440 "crate type {crate_type} not supported by the dummy codegen backend"
441 ));
442 }
443
444 link_binary(
445 sess,
446 &DummyArchiveBuilderBuilder,
447 codegen_results,
448 metadata,
449 outputs,
450 self.name(),
451 );
452 }
453}
454
455struct DummyArchiveBuilderBuilder;
456
457impl ArchiveBuilderBuilder for DummyArchiveBuilderBuilder {
458 fn new_archive_builder<'a>(
459 &self,
460 sess: &'a Session,
461 ) -> Box<dyn rustc_codegen_ssa::back::archive::ArchiveBuilder + 'a> {
462 ArArchiveBuilderBuilder.new_archive_builder(sess)
463 }
464
465 fn create_dll_import_lib(
466 &self,
467 sess: &Session,
468 _lib_name: &str,
469 _items: Vec<rustc_codegen_ssa::back::archive::ImportLibraryItem>,
470 output_path: &Path,
471 ) {
472 ArArchiveBuilderBuilder.new_archive_builder(sess).build(output_path);
474 }
475}
476
477pub fn rustc_path<'a>(sysroot: &Sysroot) -> Option<&'a Path> {
481 static RUSTC_PATH: OnceLock<Option<PathBuf>> = OnceLock::new();
482
483 RUSTC_PATH
484 .get_or_init(|| {
485 let candidate = sysroot
486 .default
487 .join(env!("RUSTC_INSTALL_BINDIR"))
488 .join(if cfg!(target_os = "windows") { "rustc.exe" } else { "rustc" });
489 candidate.exists().then_some(candidate)
490 })
491 .as_deref()
492}
493
494#[allow(rustc::untranslatable_diagnostic)] fn get_codegen_sysroot(
496 early_dcx: &EarlyDiagCtxt,
497 sysroot: &Sysroot,
498 backend_name: &str,
499) -> MakeBackendFn {
500 static LOADED: AtomicBool = AtomicBool::new(false);
506 assert!(
507 !LOADED.fetch_or(true, Ordering::SeqCst),
508 "cannot load the default codegen backend twice"
509 );
510
511 let target = host_tuple();
512
513 let sysroot = sysroot
514 .all_paths()
515 .map(|sysroot| {
516 filesearch::make_target_lib_path(sysroot, target).with_file_name("codegen-backends")
517 })
518 .find(|f| {
519 info!("codegen backend candidate: {}", f.display());
520 f.exists()
521 })
522 .unwrap_or_else(|| {
523 let candidates = sysroot
524 .all_paths()
525 .map(|p| p.display().to_string())
526 .collect::<Vec<_>>()
527 .join("\n* ");
528 let err = format!(
529 "failed to find a `codegen-backends` folder in the sysroot candidates:\n\
530 * {candidates}"
531 );
532 early_dcx.early_fatal(err);
533 });
534
535 info!("probing {} for a codegen backend", sysroot.display());
536
537 let d = sysroot.read_dir().unwrap_or_else(|e| {
538 let err = format!(
539 "failed to load default codegen backend, couldn't read `{}`: {e}",
540 sysroot.display(),
541 );
542 early_dcx.early_fatal(err);
543 });
544
545 let mut file: Option<PathBuf> = None;
546
547 let expected_names = &[
548 format!("rustc_codegen_{}-{}", backend_name, env!("CFG_RELEASE")),
549 format!("rustc_codegen_{backend_name}"),
550 ];
551 for entry in d.filter_map(|e| e.ok()) {
552 let path = entry.path();
553 let Some(filename) = path.file_name().and_then(|s| s.to_str()) else { continue };
554 if !(filename.starts_with(DLL_PREFIX) && filename.ends_with(DLL_SUFFIX)) {
555 continue;
556 }
557 let name = &filename[DLL_PREFIX.len()..filename.len() - DLL_SUFFIX.len()];
558 if !expected_names.iter().any(|expected| expected == name) {
559 continue;
560 }
561 if let Some(ref prev) = file {
562 let err = format!(
563 "duplicate codegen backends found\n\
564 first: {}\n\
565 second: {}\n\
566 ",
567 prev.display(),
568 path.display()
569 );
570 early_dcx.early_fatal(err);
571 }
572 file = Some(path.clone());
573 }
574
575 match file {
576 Some(ref s) => load_backend_from_dylib(early_dcx, s),
577 None => {
578 let err = format!("unsupported builtin codegen backend `{backend_name}`");
579 early_dcx.early_fatal(err);
580 }
581 }
582}
583
584pub(crate) fn check_attr_crate_type(
585 sess: &Session,
586 attrs: &[ast::Attribute],
587 lint_buffer: &mut LintBuffer,
588) {
589 for a in attrs.iter() {
591 if a.has_name(sym::crate_type) {
592 if let Some(n) = a.value_str() {
593 if categorize_crate_type(n).is_some() {
594 return;
595 }
596
597 if let ast::MetaItemKind::NameValue(spanned) = a.meta_kind().unwrap() {
598 let span = spanned.span;
599 let candidate = find_best_match_for_name(
600 &CRATE_TYPES.iter().map(|(k, _)| *k).collect::<Vec<_>>(),
601 n,
602 None,
603 );
604 lint_buffer.buffer_lint(
605 lint::builtin::UNKNOWN_CRATE_TYPES,
606 ast::CRATE_NODE_ID,
607 span,
608 errors::UnknownCrateTypes {
609 sugg: candidate
610 .map(|cand| errors::UnknownCrateTypesSub { span, snippet: cand }),
611 },
612 );
613 }
614 } else {
615 validate_attr::emit_fatal_malformed_builtin_attribute(
623 &sess.psess,
624 a,
625 sym::crate_type,
626 );
627 }
628 }
629 }
630}
631
632fn multiple_output_types_to_stdout(
633 output_types: &OutputTypes,
634 single_output_file_is_stdout: bool,
635) -> bool {
636 use std::io::IsTerminal;
637 if std::io::stdout().is_terminal() {
638 let named_text_types = output_types
641 .iter()
642 .filter(|(f, o)| f.is_text_output() && *o == &Some(OutFileName::Stdout))
643 .count();
644 let unnamed_text_types =
645 output_types.iter().filter(|(f, o)| f.is_text_output() && o.is_none()).count();
646 named_text_types > 1 || unnamed_text_types > 1 && single_output_file_is_stdout
647 } else {
648 let named_types =
650 output_types.values().filter(|o| *o == &Some(OutFileName::Stdout)).count();
651 let unnamed_types = output_types.values().filter(|o| o.is_none()).count();
652 named_types > 1 || unnamed_types > 1 && single_output_file_is_stdout
653 }
654}
655
656pub fn build_output_filenames(attrs: &[ast::Attribute], sess: &Session) -> OutputFilenames {
657 if multiple_output_types_to_stdout(
658 &sess.opts.output_types,
659 sess.io.output_file == Some(OutFileName::Stdout),
660 ) {
661 sess.dcx().emit_fatal(errors::MultipleOutputTypesToStdout);
662 }
663
664 let crate_name =
665 sess.opts.crate_name.clone().or_else(|| {
666 parse_crate_name(sess, attrs, ShouldEmit::Nothing).map(|i| i.0.to_string())
667 });
668
669 match sess.io.output_file {
670 None => {
671 let dirpath = sess.io.output_dir.clone().unwrap_or_default();
675
676 let stem = crate_name.clone().unwrap_or_else(|| sess.io.input.filestem().to_owned());
678
679 OutputFilenames::new(
680 dirpath,
681 crate_name.unwrap_or_else(|| stem.replace('-', "_")),
682 stem,
683 None,
684 sess.io.temps_dir.clone(),
685 sess.opts.unstable_opts.split_dwarf_out_dir.clone(),
686 sess.opts.cg.extra_filename.clone(),
687 sess.opts.output_types.clone(),
688 )
689 }
690
691 Some(ref out_file) => {
692 let unnamed_output_types =
693 sess.opts.output_types.values().filter(|a| a.is_none()).count();
694 let ofile = if unnamed_output_types > 1 {
695 sess.dcx().emit_warn(errors::MultipleOutputTypesAdaption);
696 None
697 } else {
698 if !sess.opts.cg.extra_filename.is_empty() {
699 sess.dcx().emit_warn(errors::IgnoringExtraFilename);
700 }
701 Some(out_file.clone())
702 };
703 if sess.io.output_dir.is_some() {
704 sess.dcx().emit_warn(errors::IgnoringOutDir);
705 }
706
707 let out_filestem =
708 out_file.filestem().unwrap_or_default().to_str().unwrap().to_string();
709 OutputFilenames::new(
710 out_file.parent().unwrap_or_else(|| Path::new("")).to_path_buf(),
711 crate_name.unwrap_or_else(|| out_filestem.replace('-', "_")),
712 out_filestem,
713 ofile,
714 sess.io.temps_dir.clone(),
715 sess.opts.unstable_opts.split_dwarf_out_dir.clone(),
716 sess.opts.cg.extra_filename.clone(),
717 sess.opts.output_types.clone(),
718 )
719 }
720 }
721}
722
723pub macro version_str() {
725 option_env!("CFG_VERSION")
726}
727
728pub fn rustc_version_str() -> Option<&'static str> {
730 version_str!()
731}