rustc_interface/
util.rs

1use std::env::consts::{DLL_PREFIX, DLL_SUFFIX};
2use std::path::{Path, PathBuf};
3use std::sync::OnceLock;
4use std::sync::atomic::{AtomicBool, Ordering};
5use std::{env, iter, thread};
6
7use rustc_ast as ast;
8use rustc_codegen_ssa::traits::CodegenBackend;
9use rustc_data_structures::sync;
10use rustc_metadata::{DylibError, load_symbol_from_dylib};
11use rustc_middle::ty::CurrentGcx;
12use rustc_parse::validate_attr;
13use rustc_session::config::{Cfg, OutFileName, OutputFilenames, OutputTypes, host_tuple};
14use rustc_session::filesearch::sysroot_candidates;
15use rustc_session::lint::{self, BuiltinLintDiag, LintBuffer};
16use rustc_session::output::{CRATE_TYPES, categorize_crate_type};
17use rustc_session::{EarlyDiagCtxt, Session, filesearch};
18use rustc_span::edit_distance::find_best_match_for_name;
19use rustc_span::edition::Edition;
20use rustc_span::source_map::SourceMapInputs;
21use rustc_span::{Symbol, sym};
22use rustc_target::spec::Target;
23use tracing::info;
24
25use crate::errors;
26
27/// Function pointer type that constructs a new CodegenBackend.
28type MakeBackendFn = fn() -> Box<dyn CodegenBackend>;
29
30/// Adds `target_feature = "..."` cfgs for a variety of platform
31/// specific features (SSE, NEON etc.).
32///
33/// This is performed by checking whether a set of permitted features
34/// is available on the target machine, by querying the codegen backend.
35pub(crate) fn add_configuration(
36    cfg: &mut Cfg,
37    sess: &mut Session,
38    codegen_backend: &dyn CodegenBackend,
39) {
40    let tf = sym::target_feature;
41
42    let (target_features, unstable_target_features) = codegen_backend.target_features_cfg(sess);
43
44    sess.unstable_target_features.extend(unstable_target_features.iter().copied());
45
46    sess.target_features.extend(target_features.iter().copied());
47
48    cfg.extend(target_features.into_iter().map(|feat| (tf, Some(feat))));
49
50    if sess.crt_static(None) {
51        cfg.insert((tf, Some(sym::crt_dash_static)));
52    }
53}
54
55/// Ensures that all target features required by the ABI are present.
56/// Must be called after `unstable_target_features` has been populated!
57pub(crate) fn check_abi_required_features(sess: &Session) {
58    let abi_feature_constraints = sess.target.abi_required_features();
59    // We check this against `unstable_target_features` as that is conveniently already
60    // back-translated to rustc feature names, taking into account `-Ctarget-cpu` and `-Ctarget-feature`.
61    // Just double-check that the features we care about are actually on our list.
62    for feature in
63        abi_feature_constraints.required.iter().chain(abi_feature_constraints.incompatible.iter())
64    {
65        assert!(
66            sess.target.rust_target_features().iter().any(|(name, ..)| feature == name),
67            "target feature {feature} is required/incompatible for the current ABI but not a recognized feature for this target"
68        );
69    }
70
71    for feature in abi_feature_constraints.required {
72        if !sess.unstable_target_features.contains(&Symbol::intern(feature)) {
73            sess.dcx().emit_warn(errors::AbiRequiredTargetFeature { feature, enabled: "enabled" });
74        }
75    }
76    for feature in abi_feature_constraints.incompatible {
77        if sess.unstable_target_features.contains(&Symbol::intern(feature)) {
78            sess.dcx().emit_warn(errors::AbiRequiredTargetFeature { feature, enabled: "disabled" });
79        }
80    }
81}
82
83pub static STACK_SIZE: OnceLock<usize> = OnceLock::new();
84pub const DEFAULT_STACK_SIZE: usize = 8 * 1024 * 1024;
85
86fn init_stack_size(early_dcx: &EarlyDiagCtxt) -> usize {
87    // Obey the environment setting or default
88    *STACK_SIZE.get_or_init(|| {
89        env::var_os("RUST_MIN_STACK")
90            .as_ref()
91            .map(|os_str| os_str.to_string_lossy())
92            // if someone finds out `export RUST_MIN_STACK=640000` isn't enough stack
93            // they might try to "unset" it by running `RUST_MIN_STACK=  rustc code.rs`
94            // this is wrong, but std would nonetheless "do what they mean", so let's do likewise
95            .filter(|s| !s.trim().is_empty())
96            // rustc is a batch program, so error early on inputs which are unlikely to be intended
97            // so no one thinks we parsed them setting `RUST_MIN_STACK="64 megabytes"`
98            // FIXME: we could accept `RUST_MIN_STACK=64MB`, perhaps?
99            .map(|s| {
100                let s = s.trim();
101                // FIXME(workingjubilee): add proper diagnostics when we factor out "pre-run" setup
102                #[allow(rustc::untranslatable_diagnostic, rustc::diagnostic_outside_of_impl)]
103                s.parse::<usize>().unwrap_or_else(|_| {
104                    let mut err = early_dcx.early_struct_fatal(format!(
105                        r#"`RUST_MIN_STACK` should be a number of bytes, but was "{s}""#,
106                    ));
107                    err.note("you can also unset `RUST_MIN_STACK` to use the default stack size");
108                    err.emit()
109                })
110            })
111            // otherwise pick a consistent default
112            .unwrap_or(DEFAULT_STACK_SIZE)
113    })
114}
115
116fn run_in_thread_with_globals<F: FnOnce(CurrentGcx) -> R + Send, R: Send>(
117    thread_stack_size: usize,
118    edition: Edition,
119    sm_inputs: SourceMapInputs,
120    f: F,
121) -> R {
122    // The "thread pool" is a single spawned thread in the non-parallel
123    // compiler. We run on a spawned thread instead of the main thread (a) to
124    // provide control over the stack size, and (b) to increase similarity with
125    // the parallel compiler, in particular to ensure there is no accidental
126    // sharing of data between the main thread and the compilation thread
127    // (which might cause problems for the parallel compiler).
128    let builder = thread::Builder::new().name("rustc".to_string()).stack_size(thread_stack_size);
129
130    // We build the session globals and run `f` on the spawned thread, because
131    // `SessionGlobals` does not impl `Send` in the non-parallel compiler.
132    thread::scope(|s| {
133        // `unwrap` is ok here because `spawn_scoped` only panics if the thread
134        // name contains null bytes.
135        let r = builder
136            .spawn_scoped(s, move || {
137                rustc_span::create_session_globals_then(edition, Some(sm_inputs), || {
138                    f(CurrentGcx::new())
139                })
140            })
141            .unwrap()
142            .join();
143
144        match r {
145            Ok(v) => v,
146            Err(e) => std::panic::resume_unwind(e),
147        }
148    })
149}
150
151pub(crate) fn run_in_thread_pool_with_globals<F: FnOnce(CurrentGcx) -> R + Send, R: Send>(
152    thread_builder_diag: &EarlyDiagCtxt,
153    edition: Edition,
154    threads: usize,
155    sm_inputs: SourceMapInputs,
156    f: F,
157) -> R {
158    use std::process;
159
160    use rustc_data_structures::sync::FromDyn;
161    use rustc_data_structures::{defer, jobserver};
162    use rustc_middle::ty::tls;
163    use rustc_query_impl::QueryCtxt;
164    use rustc_query_system::query::{QueryContext, break_query_cycles};
165
166    let thread_stack_size = init_stack_size(thread_builder_diag);
167
168    let registry = sync::Registry::new(std::num::NonZero::new(threads).unwrap());
169
170    if !sync::is_dyn_thread_safe() {
171        return run_in_thread_with_globals(thread_stack_size, edition, sm_inputs, |current_gcx| {
172            // Register the thread for use with the `WorkerLocal` type.
173            registry.register();
174
175            f(current_gcx)
176        });
177    }
178
179    let current_gcx = FromDyn::from(CurrentGcx::new());
180    let current_gcx2 = current_gcx.clone();
181
182    let builder = rayon::ThreadPoolBuilder::new()
183        .thread_name(|_| "rustc".to_string())
184        .acquire_thread_handler(jobserver::acquire_thread)
185        .release_thread_handler(jobserver::release_thread)
186        .num_threads(threads)
187        .deadlock_handler(move || {
188            // On deadlock, creates a new thread and forwards information in thread
189            // locals to it. The new thread runs the deadlock handler.
190
191            // Get a `GlobalCtxt` reference from `CurrentGcx` as we cannot rely on having a
192            // `TyCtxt` TLS reference here.
193            let query_map = current_gcx2.access(|gcx| {
194                tls::enter_context(&tls::ImplicitCtxt::new(gcx), || {
195                    tls::with(|tcx| {
196                        match QueryCtxt::new(tcx).collect_active_jobs() {
197                            Ok(query_map) => query_map,
198                            Err(_) => {
199                                // There was an unexpected error collecting all active jobs, which we need
200                                // to find cycles to break.
201                                // We want to avoid panicking in the deadlock handler, so we abort instead.
202                                eprintln!("internal compiler error: failed to get query map in deadlock handler, aborting process");
203                                process::abort();
204                            }
205                        }
206                    })
207                })
208            });
209            let query_map = FromDyn::from(query_map);
210            let registry = rayon_core::Registry::current();
211            thread::Builder::new()
212                .name("rustc query cycle handler".to_string())
213                .spawn(move || {
214                    let on_panic = defer(|| {
215                        eprintln!("internal compiler error: query cycle handler thread panicked, aborting process");
216                        // We need to abort here as we failed to resolve the deadlock,
217                        // otherwise the compiler could just hang,
218                        process::abort();
219                    });
220                    break_query_cycles(query_map.into_inner(), &registry);
221                    on_panic.disable();
222                })
223                .unwrap();
224        })
225        .stack_size(thread_stack_size);
226
227    // We create the session globals on the main thread, then create the thread
228    // pool. Upon creation, each worker thread created gets a copy of the
229    // session globals in TLS. This is possible because `SessionGlobals` impls
230    // `Send` in the parallel compiler.
231    rustc_span::create_session_globals_then(edition, Some(sm_inputs), || {
232        rustc_span::with_session_globals(|session_globals| {
233            let session_globals = FromDyn::from(session_globals);
234            builder
235                .build_scoped(
236                    // Initialize each new worker thread when created.
237                    move |thread: rayon::ThreadBuilder| {
238                        // Register the thread for use with the `WorkerLocal` type.
239                        registry.register();
240
241                        rustc_span::set_session_globals_then(session_globals.into_inner(), || {
242                            thread.run()
243                        })
244                    },
245                    // Run `f` on the first thread in the thread pool.
246                    move |pool: &rayon::ThreadPool| pool.install(|| f(current_gcx.into_inner())),
247                )
248                .unwrap()
249        })
250    })
251}
252
253#[allow(rustc::untranslatable_diagnostic)] // FIXME: make this translatable
254fn load_backend_from_dylib(early_dcx: &EarlyDiagCtxt, path: &Path) -> MakeBackendFn {
255    match unsafe { load_symbol_from_dylib::<MakeBackendFn>(path, "__rustc_codegen_backend") } {
256        Ok(backend_sym) => backend_sym,
257        Err(DylibError::DlOpen(path, err)) => {
258            let err = format!("couldn't load codegen backend {path}{err}");
259            early_dcx.early_fatal(err);
260        }
261        Err(DylibError::DlSym(_path, err)) => {
262            let e = format!(
263                "`__rustc_codegen_backend` symbol lookup in the codegen backend failed{err}",
264            );
265            early_dcx.early_fatal(e);
266        }
267    }
268}
269
270/// Get the codegen backend based on the name and specified sysroot.
271///
272/// A name of `None` indicates that the default backend should be used.
273pub fn get_codegen_backend(
274    early_dcx: &EarlyDiagCtxt,
275    sysroot: &Path,
276    backend_name: Option<&str>,
277    target: &Target,
278) -> Box<dyn CodegenBackend> {
279    static LOAD: OnceLock<unsafe fn() -> Box<dyn CodegenBackend>> = OnceLock::new();
280
281    let load = LOAD.get_or_init(|| {
282        let backend = backend_name
283            .or(target.default_codegen_backend.as_deref())
284            .or(option_env!("CFG_DEFAULT_CODEGEN_BACKEND"))
285            .unwrap_or("llvm");
286
287        match backend {
288            filename if filename.contains('.') => {
289                load_backend_from_dylib(early_dcx, filename.as_ref())
290            }
291            #[cfg(feature = "llvm")]
292            "llvm" => rustc_codegen_llvm::LlvmCodegenBackend::new,
293            backend_name => get_codegen_sysroot(early_dcx, sysroot, backend_name),
294        }
295    });
296
297    // SAFETY: In case of a builtin codegen backend this is safe. In case of an external codegen
298    // backend we hope that the backend links against the same rustc_driver version. If this is not
299    // the case, we get UB.
300    unsafe { load() }
301}
302
303// This is used for rustdoc, but it uses similar machinery to codegen backend
304// loading, so we leave the code here. It is potentially useful for other tools
305// that want to invoke the rustc binary while linking to rustc as well.
306pub fn rustc_path<'a>() -> Option<&'a Path> {
307    static RUSTC_PATH: OnceLock<Option<PathBuf>> = OnceLock::new();
308
309    const BIN_PATH: &str = env!("RUSTC_INSTALL_BINDIR");
310
311    RUSTC_PATH.get_or_init(|| get_rustc_path_inner(BIN_PATH)).as_deref()
312}
313
314fn get_rustc_path_inner(bin_path: &str) -> Option<PathBuf> {
315    sysroot_candidates().iter().find_map(|sysroot| {
316        let candidate = sysroot.join(bin_path).join(if cfg!(target_os = "windows") {
317            "rustc.exe"
318        } else {
319            "rustc"
320        });
321        candidate.exists().then_some(candidate)
322    })
323}
324
325#[allow(rustc::untranslatable_diagnostic)] // FIXME: make this translatable
326fn get_codegen_sysroot(
327    early_dcx: &EarlyDiagCtxt,
328    sysroot: &Path,
329    backend_name: &str,
330) -> MakeBackendFn {
331    // For now we only allow this function to be called once as it'll dlopen a
332    // few things, which seems to work best if we only do that once. In
333    // general this assertion never trips due to the once guard in `get_codegen_backend`,
334    // but there's a few manual calls to this function in this file we protect
335    // against.
336    static LOADED: AtomicBool = AtomicBool::new(false);
337    assert!(
338        !LOADED.fetch_or(true, Ordering::SeqCst),
339        "cannot load the default codegen backend twice"
340    );
341
342    let target = host_tuple();
343    let sysroot_candidates = sysroot_candidates();
344
345    let sysroot = iter::once(sysroot)
346        .chain(sysroot_candidates.iter().map(<_>::as_ref))
347        .map(|sysroot| {
348            filesearch::make_target_lib_path(sysroot, target).with_file_name("codegen-backends")
349        })
350        .find(|f| {
351            info!("codegen backend candidate: {}", f.display());
352            f.exists()
353        })
354        .unwrap_or_else(|| {
355            let candidates = sysroot_candidates
356                .iter()
357                .map(|p| p.display().to_string())
358                .collect::<Vec<_>>()
359                .join("\n* ");
360            let err = format!(
361                "failed to find a `codegen-backends` folder \
362                           in the sysroot candidates:\n* {candidates}"
363            );
364            early_dcx.early_fatal(err);
365        });
366
367    info!("probing {} for a codegen backend", sysroot.display());
368
369    let d = sysroot.read_dir().unwrap_or_else(|e| {
370        let err = format!(
371            "failed to load default codegen backend, couldn't \
372                           read `{}`: {}",
373            sysroot.display(),
374            e
375        );
376        early_dcx.early_fatal(err);
377    });
378
379    let mut file: Option<PathBuf> = None;
380
381    let expected_names = &[
382        format!("rustc_codegen_{}-{}", backend_name, env!("CFG_RELEASE")),
383        format!("rustc_codegen_{backend_name}"),
384    ];
385    for entry in d.filter_map(|e| e.ok()) {
386        let path = entry.path();
387        let Some(filename) = path.file_name().and_then(|s| s.to_str()) else { continue };
388        if !(filename.starts_with(DLL_PREFIX) && filename.ends_with(DLL_SUFFIX)) {
389            continue;
390        }
391        let name = &filename[DLL_PREFIX.len()..filename.len() - DLL_SUFFIX.len()];
392        if !expected_names.iter().any(|expected| expected == name) {
393            continue;
394        }
395        if let Some(ref prev) = file {
396            let err = format!(
397                "duplicate codegen backends found\n\
398                               first:  {}\n\
399                               second: {}\n\
400            ",
401                prev.display(),
402                path.display()
403            );
404            early_dcx.early_fatal(err);
405        }
406        file = Some(path.clone());
407    }
408
409    match file {
410        Some(ref s) => load_backend_from_dylib(early_dcx, s),
411        None => {
412            let err = format!("unsupported builtin codegen backend `{backend_name}`");
413            early_dcx.early_fatal(err);
414        }
415    }
416}
417
418pub(crate) fn check_attr_crate_type(
419    sess: &Session,
420    attrs: &[ast::Attribute],
421    lint_buffer: &mut LintBuffer,
422) {
423    // Unconditionally collect crate types from attributes to make them used
424    for a in attrs.iter() {
425        if a.has_name(sym::crate_type) {
426            if let Some(n) = a.value_str() {
427                if categorize_crate_type(n).is_some() {
428                    return;
429                }
430
431                if let ast::MetaItemKind::NameValue(spanned) = a.meta_kind().unwrap() {
432                    let span = spanned.span;
433                    let candidate = find_best_match_for_name(
434                        &CRATE_TYPES.iter().map(|(k, _)| *k).collect::<Vec<_>>(),
435                        n,
436                        None,
437                    );
438                    lint_buffer.buffer_lint(
439                        lint::builtin::UNKNOWN_CRATE_TYPES,
440                        ast::CRATE_NODE_ID,
441                        span,
442                        BuiltinLintDiag::UnknownCrateTypes { span, candidate },
443                    );
444                }
445            } else {
446                // This is here mainly to check for using a macro, such as
447                // `#![crate_type = foo!()]`. That is not supported since the
448                // crate type needs to be known very early in compilation long
449                // before expansion. Otherwise, validation would normally be
450                // caught during semantic analysis via `TyCtxt::check_mod_attrs`,
451                // but by the time that runs the macro is expanded, and it doesn't
452                // give an error.
453                validate_attr::emit_fatal_malformed_builtin_attribute(
454                    &sess.psess,
455                    a,
456                    sym::crate_type,
457                );
458            }
459        }
460    }
461}
462
463fn multiple_output_types_to_stdout(
464    output_types: &OutputTypes,
465    single_output_file_is_stdout: bool,
466) -> bool {
467    use std::io::IsTerminal;
468    if std::io::stdout().is_terminal() {
469        // If stdout is a tty, check if multiple text output types are
470        // specified by `--emit foo=- --emit bar=-` or `-o - --emit foo,bar`
471        let named_text_types = output_types
472            .iter()
473            .filter(|(f, o)| f.is_text_output() && *o == &Some(OutFileName::Stdout))
474            .count();
475        let unnamed_text_types =
476            output_types.iter().filter(|(f, o)| f.is_text_output() && o.is_none()).count();
477        named_text_types > 1 || unnamed_text_types > 1 && single_output_file_is_stdout
478    } else {
479        // Otherwise, all the output types should be checked
480        let named_types =
481            output_types.values().filter(|o| *o == &Some(OutFileName::Stdout)).count();
482        let unnamed_types = output_types.values().filter(|o| o.is_none()).count();
483        named_types > 1 || unnamed_types > 1 && single_output_file_is_stdout
484    }
485}
486
487pub fn build_output_filenames(attrs: &[ast::Attribute], sess: &Session) -> OutputFilenames {
488    if multiple_output_types_to_stdout(
489        &sess.opts.output_types,
490        sess.io.output_file == Some(OutFileName::Stdout),
491    ) {
492        sess.dcx().emit_fatal(errors::MultipleOutputTypesToStdout);
493    }
494
495    let crate_name = sess
496        .opts
497        .crate_name
498        .clone()
499        .or_else(|| rustc_attr_parsing::find_crate_name(attrs).map(|n| n.to_string()));
500
501    match sess.io.output_file {
502        None => {
503            // "-" as input file will cause the parser to read from stdin so we
504            // have to make up a name
505            // We want to toss everything after the final '.'
506            let dirpath = sess.io.output_dir.clone().unwrap_or_default();
507
508            // If a crate name is present, we use it as the link name
509            let stem = crate_name.clone().unwrap_or_else(|| sess.io.input.filestem().to_owned());
510
511            OutputFilenames::new(
512                dirpath,
513                crate_name.unwrap_or_else(|| stem.replace('-', "_")),
514                stem,
515                None,
516                sess.io.temps_dir.clone(),
517                sess.opts.cg.extra_filename.clone(),
518                sess.opts.output_types.clone(),
519            )
520        }
521
522        Some(ref out_file) => {
523            let unnamed_output_types =
524                sess.opts.output_types.values().filter(|a| a.is_none()).count();
525            let ofile = if unnamed_output_types > 1 {
526                sess.dcx().emit_warn(errors::MultipleOutputTypesAdaption);
527                None
528            } else {
529                if !sess.opts.cg.extra_filename.is_empty() {
530                    sess.dcx().emit_warn(errors::IgnoringExtraFilename);
531                }
532                Some(out_file.clone())
533            };
534            if sess.io.output_dir != None {
535                sess.dcx().emit_warn(errors::IgnoringOutDir);
536            }
537
538            let out_filestem =
539                out_file.filestem().unwrap_or_default().to_str().unwrap().to_string();
540            OutputFilenames::new(
541                out_file.parent().unwrap_or_else(|| Path::new("")).to_path_buf(),
542                crate_name.unwrap_or_else(|| out_filestem.replace('-', "_")),
543                out_filestem,
544                ofile,
545                sess.io.temps_dir.clone(),
546                sess.opts.cg.extra_filename.clone(),
547                sess.opts.output_types.clone(),
548            )
549        }
550    }
551}
552
553/// Returns a version string such as "1.46.0 (04488afe3 2020-08-24)" when invoked by an in-tree tool.
554pub macro version_str() {
555    option_env!("CFG_VERSION")
556}
557
558/// Returns the version string for `rustc` itself (which may be different from a tool version).
559pub fn rustc_version_str() -> Option<&'static str> {
560    version_str!()
561}