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