1use std::env::consts::{DLL_PREFIX, DLL_SUFFIX};
2use std::path::{Path, PathBuf};
3use std::sync::atomic::{AtomicBool, Ordering};
4use std::sync::{Arc, OnceLock};
5use std::{env, thread};
6
7use rustc_ast as ast;
8use rustc_attr_parsing::{ShouldEmit, validate_attr};
9use rustc_codegen_ssa::traits::CodegenBackend;
10use rustc_data_structures::jobserver::Proxy;
11use rustc_data_structures::sync;
12use rustc_errors::LintBuffer;
13use rustc_metadata::{DylibError, load_symbol_from_dylib};
14use rustc_middle::ty::CurrentGcx;
15use rustc_session::config::{Cfg, OutFileName, OutputFilenames, OutputTypes, Sysroot, host_tuple};
16use rustc_session::lint::{self, BuiltinLintDiag};
17use rustc_session::output::{CRATE_TYPES, categorize_crate_type};
18use rustc_session::{EarlyDiagCtxt, Session, filesearch};
19use rustc_span::edit_distance::find_best_match_for_name;
20use rustc_span::edition::Edition;
21use rustc_span::source_map::SourceMapInputs;
22use rustc_span::{SessionGlobals, Symbol, sym};
23use rustc_target::spec::Target;
24use tracing::info;
25
26use crate::errors;
27use crate::passes::parse_crate_name;
28
29type MakeBackendFn = fn() -> Box<dyn CodegenBackend>;
31
32pub(crate) fn add_configuration(
38 cfg: &mut Cfg,
39 sess: &mut Session,
40 codegen_backend: &dyn CodegenBackend,
41) {
42 let tf = sym::target_feature;
43 let tf_cfg = codegen_backend.target_config(sess);
44
45 sess.unstable_target_features.extend(tf_cfg.unstable_target_features.iter().copied());
46 sess.target_features.extend(tf_cfg.target_features.iter().copied());
47
48 cfg.extend(tf_cfg.target_features.into_iter().map(|feat| (tf, Some(feat))));
49
50 if tf_cfg.has_reliable_f16 {
51 cfg.insert((sym::target_has_reliable_f16, None));
52 }
53 if tf_cfg.has_reliable_f16_math {
54 cfg.insert((sym::target_has_reliable_f16_math, None));
55 }
56 if tf_cfg.has_reliable_f128 {
57 cfg.insert((sym::target_has_reliable_f128, None));
58 }
59 if tf_cfg.has_reliable_f128_math {
60 cfg.insert((sym::target_has_reliable_f128_math, None));
61 }
62
63 if sess.crt_static(None) {
64 cfg.insert((tf, Some(sym::crt_dash_static)));
65 }
66}
67
68pub(crate) fn check_abi_required_features(sess: &Session) {
71 let abi_feature_constraints = sess.target.abi_required_features();
72 for feature in
76 abi_feature_constraints.required.iter().chain(abi_feature_constraints.incompatible.iter())
77 {
78 assert!(
79 sess.target.rust_target_features().iter().any(|(name, ..)| feature == name),
80 "target feature {feature} is required/incompatible for the current ABI but not a recognized feature for this target"
81 );
82 }
83
84 for feature in abi_feature_constraints.required {
85 if !sess.unstable_target_features.contains(&Symbol::intern(feature)) {
86 sess.dcx().emit_warn(errors::AbiRequiredTargetFeature { feature, enabled: "enabled" });
87 }
88 }
89 for feature in abi_feature_constraints.incompatible {
90 if sess.unstable_target_features.contains(&Symbol::intern(feature)) {
91 sess.dcx().emit_warn(errors::AbiRequiredTargetFeature { feature, enabled: "disabled" });
92 }
93 }
94}
95
96pub static STACK_SIZE: OnceLock<usize> = OnceLock::new();
97pub const DEFAULT_STACK_SIZE: usize = 8 * 1024 * 1024;
98
99fn init_stack_size(early_dcx: &EarlyDiagCtxt) -> usize {
100 *STACK_SIZE.get_or_init(|| {
102 env::var_os("RUST_MIN_STACK")
103 .as_ref()
104 .map(|os_str| os_str.to_string_lossy())
105 .filter(|s| !s.trim().is_empty())
109 .map(|s| {
113 let s = s.trim();
114 #[allow(rustc::untranslatable_diagnostic, rustc::diagnostic_outside_of_impl)]
116 s.parse::<usize>().unwrap_or_else(|_| {
117 let mut err = early_dcx.early_struct_fatal(format!(
118 r#"`RUST_MIN_STACK` should be a number of bytes, but was "{s}""#,
119 ));
120 err.note("you can also unset `RUST_MIN_STACK` to use the default stack size");
121 err.emit()
122 })
123 })
124 .unwrap_or(DEFAULT_STACK_SIZE)
126 })
127}
128
129fn run_in_thread_with_globals<F: FnOnce(CurrentGcx, Arc<Proxy>) -> R + Send, R: Send>(
130 thread_stack_size: usize,
131 edition: Edition,
132 sm_inputs: SourceMapInputs,
133 extra_symbols: &[&'static str],
134 f: F,
135) -> R {
136 let builder = thread::Builder::new().name("rustc".to_string()).stack_size(thread_stack_size);
143
144 thread::scope(|s| {
147 let r = builder
150 .spawn_scoped(s, move || {
151 rustc_span::create_session_globals_then(
152 edition,
153 extra_symbols,
154 Some(sm_inputs),
155 || f(CurrentGcx::new(), Proxy::new()),
156 )
157 })
158 .unwrap()
159 .join();
160
161 match r {
162 Ok(v) => v,
163 Err(e) => std::panic::resume_unwind(e),
164 }
165 })
166}
167
168pub(crate) fn run_in_thread_pool_with_globals<
169 F: FnOnce(CurrentGcx, Arc<Proxy>) -> R + Send,
170 R: Send,
171>(
172 thread_builder_diag: &EarlyDiagCtxt,
173 edition: Edition,
174 threads: usize,
175 extra_symbols: &[&'static str],
176 sm_inputs: SourceMapInputs,
177 f: F,
178) -> R {
179 use std::process;
180
181 use rustc_data_structures::defer;
182 use rustc_data_structures::sync::FromDyn;
183 use rustc_middle::ty::tls;
184 use rustc_query_impl::QueryCtxt;
185 use rustc_query_system::query::{QueryContext, break_query_cycles};
186
187 let thread_stack_size = init_stack_size(thread_builder_diag);
188
189 let registry = sync::Registry::new(std::num::NonZero::new(threads).unwrap());
190
191 if !sync::is_dyn_thread_safe() {
192 return run_in_thread_with_globals(
193 thread_stack_size,
194 edition,
195 sm_inputs,
196 extra_symbols,
197 |current_gcx, jobserver_proxy| {
198 registry.register();
200
201 f(current_gcx, jobserver_proxy)
202 },
203 );
204 }
205
206 let current_gcx = FromDyn::from(CurrentGcx::new());
207 let current_gcx2 = current_gcx.clone();
208
209 let proxy = Proxy::new();
210
211 let proxy_ = Arc::clone(&proxy);
212 let proxy__ = Arc::clone(&proxy);
213 let builder = rustc_thread_pool::ThreadPoolBuilder::new()
214 .thread_name(|_| "rustc".to_string())
215 .acquire_thread_handler(move || proxy_.acquire_thread())
216 .release_thread_handler(move || proxy__.release_thread())
217 .num_threads(threads)
218 .deadlock_handler(move || {
219 let current_gcx2 = current_gcx2.clone();
223 let registry = rustc_thread_pool::Registry::current();
224 let session_globals = rustc_span::with_session_globals(|session_globals| {
225 session_globals as *const SessionGlobals as usize
226 });
227 thread::Builder::new()
228 .name("rustc query cycle handler".to_string())
229 .spawn(move || {
230 let on_panic = defer(|| {
231 eprintln!("internal compiler error: query cycle handler thread panicked, aborting process");
232 process::abort();
235 });
236
237 current_gcx2.access(|gcx| {
240 tls::enter_context(&tls::ImplicitCtxt::new(gcx), || {
241 tls::with(|tcx| {
242 let query_map = rustc_span::set_session_globals_then(unsafe { &*(session_globals as *const SessionGlobals) }, || {
245 QueryCtxt::new(tcx).collect_active_jobs().ok().expect("failed to collect active queries in deadlock handler")
248 });
249 break_query_cycles(query_map, ®istry);
250 })
251 })
252 });
253
254 on_panic.disable();
255 })
256 .unwrap();
257 })
258 .stack_size(thread_stack_size);
259
260 rustc_span::create_session_globals_then(edition, extra_symbols, Some(sm_inputs), || {
265 rustc_span::with_session_globals(|session_globals| {
266 let session_globals = FromDyn::from(session_globals);
267 builder
268 .build_scoped(
269 move |thread: rustc_thread_pool::ThreadBuilder| {
271 registry.register();
273
274 rustc_span::set_session_globals_then(session_globals.into_inner(), || {
275 thread.run()
276 })
277 },
278 move |pool: &rustc_thread_pool::ThreadPool| {
280 pool.install(|| f(current_gcx.into_inner(), proxy))
281 },
282 )
283 .unwrap()
284 })
285 })
286}
287
288#[allow(rustc::untranslatable_diagnostic)] fn load_backend_from_dylib(early_dcx: &EarlyDiagCtxt, path: &Path) -> MakeBackendFn {
290 match unsafe { load_symbol_from_dylib::<MakeBackendFn>(path, "__rustc_codegen_backend") } {
291 Ok(backend_sym) => backend_sym,
292 Err(DylibError::DlOpen(path, err)) => {
293 let err = format!("couldn't load codegen backend {path}{err}");
294 early_dcx.early_fatal(err);
295 }
296 Err(DylibError::DlSym(_path, err)) => {
297 let e = format!(
298 "`__rustc_codegen_backend` symbol lookup in the codegen backend failed{err}",
299 );
300 early_dcx.early_fatal(e);
301 }
302 }
303}
304
305pub fn get_codegen_backend(
309 early_dcx: &EarlyDiagCtxt,
310 sysroot: &Sysroot,
311 backend_name: Option<&str>,
312 target: &Target,
313) -> Box<dyn CodegenBackend> {
314 static LOAD: OnceLock<unsafe fn() -> Box<dyn CodegenBackend>> = OnceLock::new();
315
316 let load = LOAD.get_or_init(|| {
317 let backend = backend_name
318 .or(target.default_codegen_backend.as_deref())
319 .or(option_env!("CFG_DEFAULT_CODEGEN_BACKEND"))
320 .unwrap_or("llvm");
321
322 match backend {
323 filename if filename.contains('.') => {
324 load_backend_from_dylib(early_dcx, filename.as_ref())
325 }
326 #[cfg(feature = "llvm")]
327 "llvm" => rustc_codegen_llvm::LlvmCodegenBackend::new,
328 backend_name => get_codegen_sysroot(early_dcx, sysroot, backend_name),
329 }
330 });
331
332 unsafe { load() }
336}
337
338pub fn rustc_path<'a>(sysroot: &Sysroot) -> Option<&'a Path> {
342 static RUSTC_PATH: OnceLock<Option<PathBuf>> = OnceLock::new();
343
344 RUSTC_PATH
345 .get_or_init(|| {
346 let candidate = sysroot
347 .default
348 .join(env!("RUSTC_INSTALL_BINDIR"))
349 .join(if cfg!(target_os = "windows") { "rustc.exe" } else { "rustc" });
350 candidate.exists().then_some(candidate)
351 })
352 .as_deref()
353}
354
355#[allow(rustc::untranslatable_diagnostic)] fn get_codegen_sysroot(
357 early_dcx: &EarlyDiagCtxt,
358 sysroot: &Sysroot,
359 backend_name: &str,
360) -> MakeBackendFn {
361 static LOADED: AtomicBool = AtomicBool::new(false);
367 assert!(
368 !LOADED.fetch_or(true, Ordering::SeqCst),
369 "cannot load the default codegen backend twice"
370 );
371
372 let target = host_tuple();
373
374 let sysroot = sysroot
375 .all_paths()
376 .map(|sysroot| {
377 filesearch::make_target_lib_path(sysroot, target).with_file_name("codegen-backends")
378 })
379 .find(|f| {
380 info!("codegen backend candidate: {}", f.display());
381 f.exists()
382 })
383 .unwrap_or_else(|| {
384 let candidates = sysroot
385 .all_paths()
386 .map(|p| p.display().to_string())
387 .collect::<Vec<_>>()
388 .join("\n* ");
389 let err = format!(
390 "failed to find a `codegen-backends` folder \
391 in the sysroot candidates:\n* {candidates}"
392 );
393 early_dcx.early_fatal(err);
394 });
395
396 info!("probing {} for a codegen backend", sysroot.display());
397
398 let d = sysroot.read_dir().unwrap_or_else(|e| {
399 let err = format!(
400 "failed to load default codegen backend, couldn't \
401 read `{}`: {}",
402 sysroot.display(),
403 e
404 );
405 early_dcx.early_fatal(err);
406 });
407
408 let mut file: Option<PathBuf> = None;
409
410 let expected_names = &[
411 format!("rustc_codegen_{}-{}", backend_name, env!("CFG_RELEASE")),
412 format!("rustc_codegen_{backend_name}"),
413 ];
414 for entry in d.filter_map(|e| e.ok()) {
415 let path = entry.path();
416 let Some(filename) = path.file_name().and_then(|s| s.to_str()) else { continue };
417 if !(filename.starts_with(DLL_PREFIX) && filename.ends_with(DLL_SUFFIX)) {
418 continue;
419 }
420 let name = &filename[DLL_PREFIX.len()..filename.len() - DLL_SUFFIX.len()];
421 if !expected_names.iter().any(|expected| expected == name) {
422 continue;
423 }
424 if let Some(ref prev) = file {
425 let err = format!(
426 "duplicate codegen backends found\n\
427 first: {}\n\
428 second: {}\n\
429 ",
430 prev.display(),
431 path.display()
432 );
433 early_dcx.early_fatal(err);
434 }
435 file = Some(path.clone());
436 }
437
438 match file {
439 Some(ref s) => load_backend_from_dylib(early_dcx, s),
440 None => {
441 let err = format!("unsupported builtin codegen backend `{backend_name}`");
442 early_dcx.early_fatal(err);
443 }
444 }
445}
446
447pub(crate) fn check_attr_crate_type(
448 sess: &Session,
449 attrs: &[ast::Attribute],
450 lint_buffer: &mut LintBuffer,
451) {
452 for a in attrs.iter() {
454 if a.has_name(sym::crate_type) {
455 if let Some(n) = a.value_str() {
456 if categorize_crate_type(n).is_some() {
457 return;
458 }
459
460 if let ast::MetaItemKind::NameValue(spanned) = a.meta_kind().unwrap() {
461 let span = spanned.span;
462 let candidate = find_best_match_for_name(
463 &CRATE_TYPES.iter().map(|(k, _)| *k).collect::<Vec<_>>(),
464 n,
465 None,
466 );
467 lint_buffer.buffer_lint(
468 lint::builtin::UNKNOWN_CRATE_TYPES,
469 ast::CRATE_NODE_ID,
470 span,
471 BuiltinLintDiag::UnknownCrateTypes { span, candidate },
472 );
473 }
474 } else {
475 validate_attr::emit_fatal_malformed_builtin_attribute(
483 &sess.psess,
484 a,
485 sym::crate_type,
486 );
487 }
488 }
489 }
490}
491
492fn multiple_output_types_to_stdout(
493 output_types: &OutputTypes,
494 single_output_file_is_stdout: bool,
495) -> bool {
496 use std::io::IsTerminal;
497 if std::io::stdout().is_terminal() {
498 let named_text_types = output_types
501 .iter()
502 .filter(|(f, o)| f.is_text_output() && *o == &Some(OutFileName::Stdout))
503 .count();
504 let unnamed_text_types =
505 output_types.iter().filter(|(f, o)| f.is_text_output() && o.is_none()).count();
506 named_text_types > 1 || unnamed_text_types > 1 && single_output_file_is_stdout
507 } else {
508 let named_types =
510 output_types.values().filter(|o| *o == &Some(OutFileName::Stdout)).count();
511 let unnamed_types = output_types.values().filter(|o| o.is_none()).count();
512 named_types > 1 || unnamed_types > 1 && single_output_file_is_stdout
513 }
514}
515
516pub fn build_output_filenames(attrs: &[ast::Attribute], sess: &Session) -> OutputFilenames {
517 if multiple_output_types_to_stdout(
518 &sess.opts.output_types,
519 sess.io.output_file == Some(OutFileName::Stdout),
520 ) {
521 sess.dcx().emit_fatal(errors::MultipleOutputTypesToStdout);
522 }
523
524 let crate_name =
525 sess.opts.crate_name.clone().or_else(|| {
526 parse_crate_name(sess, attrs, ShouldEmit::Nothing).map(|i| i.0.to_string())
527 });
528
529 match sess.io.output_file {
530 None => {
531 let dirpath = sess.io.output_dir.clone().unwrap_or_default();
535
536 let stem = crate_name.clone().unwrap_or_else(|| sess.io.input.filestem().to_owned());
538
539 OutputFilenames::new(
540 dirpath,
541 crate_name.unwrap_or_else(|| stem.replace('-', "_")),
542 stem,
543 None,
544 sess.io.temps_dir.clone(),
545 sess.opts.cg.extra_filename.clone(),
546 sess.opts.output_types.clone(),
547 )
548 }
549
550 Some(ref out_file) => {
551 let unnamed_output_types =
552 sess.opts.output_types.values().filter(|a| a.is_none()).count();
553 let ofile = if unnamed_output_types > 1 {
554 sess.dcx().emit_warn(errors::MultipleOutputTypesAdaption);
555 None
556 } else {
557 if !sess.opts.cg.extra_filename.is_empty() {
558 sess.dcx().emit_warn(errors::IgnoringExtraFilename);
559 }
560 Some(out_file.clone())
561 };
562 if sess.io.output_dir != None {
563 sess.dcx().emit_warn(errors::IgnoringOutDir);
564 }
565
566 let out_filestem =
567 out_file.filestem().unwrap_or_default().to_str().unwrap().to_string();
568 OutputFilenames::new(
569 out_file.parent().unwrap_or_else(|| Path::new("")).to_path_buf(),
570 crate_name.unwrap_or_else(|| out_filestem.replace('-', "_")),
571 out_filestem,
572 ofile,
573 sess.io.temps_dir.clone(),
574 sess.opts.cg.extra_filename.clone(),
575 sess.opts.output_types.clone(),
576 )
577 }
578 }
579}
580
581pub macro version_str() {
583 option_env!("CFG_VERSION")
584}
585
586pub fn rustc_version_str() -> Option<&'static str> {
588 version_str!()
589}