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 unstable_target_features = codegen_backend.target_features_cfg(sess, true);
43    sess.unstable_target_features.extend(unstable_target_features.iter().cloned());
44
45    let target_features = codegen_backend.target_features_cfg(sess, false);
46    sess.target_features.extend(target_features.iter().cloned());
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| QueryCtxt::new(tcx).collect_active_jobs())
196                })
197            });
198            let query_map = FromDyn::from(query_map);
199            let registry = rayon_core::Registry::current();
200            thread::Builder::new()
201                .name("rustc query cycle handler".to_string())
202                .spawn(move || {
203                    let on_panic = defer(|| {
204                        eprintln!("query cycle handler thread panicked, aborting process");
205                        // We need to abort here as we failed to resolve the deadlock,
206                        // otherwise the compiler could just hang,
207                        process::abort();
208                    });
209                    break_query_cycles(query_map.into_inner(), &registry);
210                    on_panic.disable();
211                })
212                .unwrap();
213        })
214        .stack_size(thread_stack_size);
215
216    // We create the session globals on the main thread, then create the thread
217    // pool. Upon creation, each worker thread created gets a copy of the
218    // session globals in TLS. This is possible because `SessionGlobals` impls
219    // `Send` in the parallel compiler.
220    rustc_span::create_session_globals_then(edition, Some(sm_inputs), || {
221        rustc_span::with_session_globals(|session_globals| {
222            let session_globals = FromDyn::from(session_globals);
223            builder
224                .build_scoped(
225                    // Initialize each new worker thread when created.
226                    move |thread: rayon::ThreadBuilder| {
227                        // Register the thread for use with the `WorkerLocal` type.
228                        registry.register();
229
230                        rustc_span::set_session_globals_then(session_globals.into_inner(), || {
231                            thread.run()
232                        })
233                    },
234                    // Run `f` on the first thread in the thread pool.
235                    move |pool: &rayon::ThreadPool| pool.install(|| f(current_gcx.into_inner())),
236                )
237                .unwrap()
238        })
239    })
240}
241
242#[allow(rustc::untranslatable_diagnostic)] // FIXME: make this translatable
243fn load_backend_from_dylib(early_dcx: &EarlyDiagCtxt, path: &Path) -> MakeBackendFn {
244    match unsafe { load_symbol_from_dylib::<MakeBackendFn>(path, "__rustc_codegen_backend") } {
245        Ok(backend_sym) => backend_sym,
246        Err(DylibError::DlOpen(path, err)) => {
247            let err = format!("couldn't load codegen backend {path}{err}");
248            early_dcx.early_fatal(err);
249        }
250        Err(DylibError::DlSym(_path, err)) => {
251            let e = format!(
252                "`__rustc_codegen_backend` symbol lookup in the codegen backend failed{err}",
253            );
254            early_dcx.early_fatal(e);
255        }
256    }
257}
258
259/// Get the codegen backend based on the name and specified sysroot.
260///
261/// A name of `None` indicates that the default backend should be used.
262pub fn get_codegen_backend(
263    early_dcx: &EarlyDiagCtxt,
264    sysroot: &Path,
265    backend_name: Option<&str>,
266    target: &Target,
267) -> Box<dyn CodegenBackend> {
268    static LOAD: OnceLock<unsafe fn() -> Box<dyn CodegenBackend>> = OnceLock::new();
269
270    let load = LOAD.get_or_init(|| {
271        let backend = backend_name
272            .or(target.default_codegen_backend.as_deref())
273            .or(option_env!("CFG_DEFAULT_CODEGEN_BACKEND"))
274            .unwrap_or("llvm");
275
276        match backend {
277            filename if filename.contains('.') => {
278                load_backend_from_dylib(early_dcx, filename.as_ref())
279            }
280            #[cfg(feature = "llvm")]
281            "llvm" => rustc_codegen_llvm::LlvmCodegenBackend::new,
282            backend_name => get_codegen_sysroot(early_dcx, sysroot, backend_name),
283        }
284    });
285
286    // SAFETY: In case of a builtin codegen backend this is safe. In case of an external codegen
287    // backend we hope that the backend links against the same rustc_driver version. If this is not
288    // the case, we get UB.
289    unsafe { load() }
290}
291
292// This is used for rustdoc, but it uses similar machinery to codegen backend
293// loading, so we leave the code here. It is potentially useful for other tools
294// that want to invoke the rustc binary while linking to rustc as well.
295pub fn rustc_path<'a>() -> Option<&'a Path> {
296    static RUSTC_PATH: OnceLock<Option<PathBuf>> = OnceLock::new();
297
298    const BIN_PATH: &str = env!("RUSTC_INSTALL_BINDIR");
299
300    RUSTC_PATH.get_or_init(|| get_rustc_path_inner(BIN_PATH)).as_deref()
301}
302
303fn get_rustc_path_inner(bin_path: &str) -> Option<PathBuf> {
304    sysroot_candidates().iter().find_map(|sysroot| {
305        let candidate = sysroot.join(bin_path).join(if cfg!(target_os = "windows") {
306            "rustc.exe"
307        } else {
308            "rustc"
309        });
310        candidate.exists().then_some(candidate)
311    })
312}
313
314#[allow(rustc::untranslatable_diagnostic)] // FIXME: make this translatable
315fn get_codegen_sysroot(
316    early_dcx: &EarlyDiagCtxt,
317    sysroot: &Path,
318    backend_name: &str,
319) -> MakeBackendFn {
320    // For now we only allow this function to be called once as it'll dlopen a
321    // few things, which seems to work best if we only do that once. In
322    // general this assertion never trips due to the once guard in `get_codegen_backend`,
323    // but there's a few manual calls to this function in this file we protect
324    // against.
325    static LOADED: AtomicBool = AtomicBool::new(false);
326    assert!(
327        !LOADED.fetch_or(true, Ordering::SeqCst),
328        "cannot load the default codegen backend twice"
329    );
330
331    let target = host_tuple();
332    let sysroot_candidates = sysroot_candidates();
333
334    let sysroot = iter::once(sysroot)
335        .chain(sysroot_candidates.iter().map(<_>::as_ref))
336        .map(|sysroot| {
337            filesearch::make_target_lib_path(sysroot, target).with_file_name("codegen-backends")
338        })
339        .find(|f| {
340            info!("codegen backend candidate: {}", f.display());
341            f.exists()
342        })
343        .unwrap_or_else(|| {
344            let candidates = sysroot_candidates
345                .iter()
346                .map(|p| p.display().to_string())
347                .collect::<Vec<_>>()
348                .join("\n* ");
349            let err = format!(
350                "failed to find a `codegen-backends` folder \
351                           in the sysroot candidates:\n* {candidates}"
352            );
353            early_dcx.early_fatal(err);
354        });
355
356    info!("probing {} for a codegen backend", sysroot.display());
357
358    let d = sysroot.read_dir().unwrap_or_else(|e| {
359        let err = format!(
360            "failed to load default codegen backend, couldn't \
361                           read `{}`: {}",
362            sysroot.display(),
363            e
364        );
365        early_dcx.early_fatal(err);
366    });
367
368    let mut file: Option<PathBuf> = None;
369
370    let expected_names = &[
371        format!("rustc_codegen_{}-{}", backend_name, env!("CFG_RELEASE")),
372        format!("rustc_codegen_{backend_name}"),
373    ];
374    for entry in d.filter_map(|e| e.ok()) {
375        let path = entry.path();
376        let Some(filename) = path.file_name().and_then(|s| s.to_str()) else { continue };
377        if !(filename.starts_with(DLL_PREFIX) && filename.ends_with(DLL_SUFFIX)) {
378            continue;
379        }
380        let name = &filename[DLL_PREFIX.len()..filename.len() - DLL_SUFFIX.len()];
381        if !expected_names.iter().any(|expected| expected == name) {
382            continue;
383        }
384        if let Some(ref prev) = file {
385            let err = format!(
386                "duplicate codegen backends found\n\
387                               first:  {}\n\
388                               second: {}\n\
389            ",
390                prev.display(),
391                path.display()
392            );
393            early_dcx.early_fatal(err);
394        }
395        file = Some(path.clone());
396    }
397
398    match file {
399        Some(ref s) => load_backend_from_dylib(early_dcx, s),
400        None => {
401            let err = format!("unsupported builtin codegen backend `{backend_name}`");
402            early_dcx.early_fatal(err);
403        }
404    }
405}
406
407pub(crate) fn check_attr_crate_type(
408    sess: &Session,
409    attrs: &[ast::Attribute],
410    lint_buffer: &mut LintBuffer,
411) {
412    // Unconditionally collect crate types from attributes to make them used
413    for a in attrs.iter() {
414        if a.has_name(sym::crate_type) {
415            if let Some(n) = a.value_str() {
416                if categorize_crate_type(n).is_some() {
417                    return;
418                }
419
420                if let ast::MetaItemKind::NameValue(spanned) = a.meta_kind().unwrap() {
421                    let span = spanned.span;
422                    let candidate = find_best_match_for_name(
423                        &CRATE_TYPES.iter().map(|(k, _)| *k).collect::<Vec<_>>(),
424                        n,
425                        None,
426                    );
427                    lint_buffer.buffer_lint(
428                        lint::builtin::UNKNOWN_CRATE_TYPES,
429                        ast::CRATE_NODE_ID,
430                        span,
431                        BuiltinLintDiag::UnknownCrateTypes { span, candidate },
432                    );
433                }
434            } else {
435                // This is here mainly to check for using a macro, such as
436                // #![crate_type = foo!()]. That is not supported since the
437                // crate type needs to be known very early in compilation long
438                // before expansion. Otherwise, validation would normally be
439                // caught in AstValidator (via `check_builtin_attribute`), but
440                // by the time that runs the macro is expanded, and it doesn't
441                // give an error.
442                validate_attr::emit_fatal_malformed_builtin_attribute(
443                    &sess.psess,
444                    a,
445                    sym::crate_type,
446                );
447            }
448        }
449    }
450}
451
452fn multiple_output_types_to_stdout(
453    output_types: &OutputTypes,
454    single_output_file_is_stdout: bool,
455) -> bool {
456    use std::io::IsTerminal;
457    if std::io::stdout().is_terminal() {
458        // If stdout is a tty, check if multiple text output types are
459        // specified by `--emit foo=- --emit bar=-` or `-o - --emit foo,bar`
460        let named_text_types = output_types
461            .iter()
462            .filter(|(f, o)| f.is_text_output() && *o == &Some(OutFileName::Stdout))
463            .count();
464        let unnamed_text_types =
465            output_types.iter().filter(|(f, o)| f.is_text_output() && o.is_none()).count();
466        named_text_types > 1 || unnamed_text_types > 1 && single_output_file_is_stdout
467    } else {
468        // Otherwise, all the output types should be checked
469        let named_types =
470            output_types.values().filter(|o| *o == &Some(OutFileName::Stdout)).count();
471        let unnamed_types = output_types.values().filter(|o| o.is_none()).count();
472        named_types > 1 || unnamed_types > 1 && single_output_file_is_stdout
473    }
474}
475
476pub fn build_output_filenames(attrs: &[ast::Attribute], sess: &Session) -> OutputFilenames {
477    if multiple_output_types_to_stdout(
478        &sess.opts.output_types,
479        sess.io.output_file == Some(OutFileName::Stdout),
480    ) {
481        sess.dcx().emit_fatal(errors::MultipleOutputTypesToStdout);
482    }
483
484    let crate_name = sess
485        .opts
486        .crate_name
487        .clone()
488        .or_else(|| rustc_attr_parsing::find_crate_name(attrs).map(|n| n.to_string()));
489
490    match sess.io.output_file {
491        None => {
492            // "-" as input file will cause the parser to read from stdin so we
493            // have to make up a name
494            // We want to toss everything after the final '.'
495            let dirpath = sess.io.output_dir.clone().unwrap_or_default();
496
497            // If a crate name is present, we use it as the link name
498            let stem = crate_name.clone().unwrap_or_else(|| sess.io.input.filestem().to_owned());
499
500            OutputFilenames::new(
501                dirpath,
502                crate_name.unwrap_or_else(|| stem.replace('-', "_")),
503                stem,
504                None,
505                sess.io.temps_dir.clone(),
506                sess.opts.cg.extra_filename.clone(),
507                sess.opts.output_types.clone(),
508            )
509        }
510
511        Some(ref out_file) => {
512            let unnamed_output_types =
513                sess.opts.output_types.values().filter(|a| a.is_none()).count();
514            let ofile = if unnamed_output_types > 1 {
515                sess.dcx().emit_warn(errors::MultipleOutputTypesAdaption);
516                None
517            } else {
518                if !sess.opts.cg.extra_filename.is_empty() {
519                    sess.dcx().emit_warn(errors::IgnoringExtraFilename);
520                }
521                Some(out_file.clone())
522            };
523            if sess.io.output_dir != None {
524                sess.dcx().emit_warn(errors::IgnoringOutDir);
525            }
526
527            let out_filestem =
528                out_file.filestem().unwrap_or_default().to_str().unwrap().to_string();
529            OutputFilenames::new(
530                out_file.parent().unwrap_or_else(|| Path::new("")).to_path_buf(),
531                crate_name.unwrap_or_else(|| out_filestem.replace('-', "_")),
532                out_filestem,
533                ofile,
534                sess.io.temps_dir.clone(),
535                sess.opts.cg.extra_filename.clone(),
536                sess.opts.output_types.clone(),
537            )
538        }
539    }
540}
541
542/// Returns a version string such as "1.46.0 (04488afe3 2020-08-24)" when invoked by an in-tree tool.
543pub macro version_str() {
544    option_env!("CFG_VERSION")
545}
546
547/// Returns the version string for `rustc` itself (which may be different from a tool version).
548pub fn rustc_version_str() -> Option<&'static str> {
549    version_str!()
550}