Skip to main content

rustc_interface/
util.rs

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 rand::{RngCore, rng};
9use rustc_ast as ast;
10use rustc_attr_parsing::ShouldEmit;
11use rustc_codegen_ssa::back::archive::{ArArchiveBuilderBuilder, ArchiveBuilderBuilder};
12use rustc_codegen_ssa::back::link::link_binary;
13use rustc_codegen_ssa::target_features::cfg_target_feature;
14use rustc_codegen_ssa::traits::CodegenBackend;
15use rustc_codegen_ssa::{CompiledModules, CrateInfo, TargetConfig};
16use rustc_data_structures::base_n::{CASE_INSENSITIVE, ToBaseN};
17use rustc_data_structures::fx::FxIndexMap;
18use rustc_data_structures::jobserver::Proxy;
19use rustc_data_structures::sync;
20use rustc_metadata::{DylibError, EncodedMetadata, load_symbol_from_dylib};
21use rustc_middle::dep_graph::{WorkProduct, WorkProductId};
22use rustc_middle::ty::{CurrentGcx, TyCtxt};
23use rustc_query_impl::{CollectActiveJobsKind, collect_active_query_jobs};
24use rustc_session::config::{
25    Cfg, CrateType, OutFileName, OutputFilenames, OutputTypes, Sysroot, host_tuple,
26};
27use rustc_session::{EarlyDiagCtxt, Session, filesearch};
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
37/// Function pointer type that constructs a new CodegenBackend.
38type MakeBackendFn = fn() -> Box<dyn CodegenBackend>;
39
40/// Adds `target_feature = "..."` cfgs for a variety of platform
41/// specific features (SSE, NEON etc.).
42///
43/// This is performed by checking whether a set of permitted features
44/// is available on the target machine, by querying the codegen backend.
45pub(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
76/// Ensures that all target features required by the ABI are present.
77/// Must be called after `unstable_target_features` has been populated!
78pub(crate) fn check_abi_required_features(sess: &Session) {
79    let abi_feature_constraints = sess.target.abi_required_features();
80    // We check this against `unstable_target_features` as that is conveniently already
81    // back-translated to rustc feature names, taking into account `-Ctarget-cpu` and `-Ctarget-feature`.
82    // Just double-check that the features we care about are actually on our list.
83    for feature in
84        abi_feature_constraints.required.iter().chain(abi_feature_constraints.incompatible.iter())
85    {
86        if !sess.target.rust_target_features().iter().any(|(name, ..)|
                feature == name) {
    {
        ::core::panicking::panic_fmt(format_args!("target feature {0} is required/incompatible for the current ABI but not a recognized feature for this target",
                feature));
    }
};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    // Obey the environment setting or default
109    *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            // if someone finds out `export RUST_MIN_STACK=640000` isn't enough stack
114            // they might try to "unset" it by running `RUST_MIN_STACK=  rustc code.rs`
115            // this is wrong, but std would nonetheless "do what they mean", so let's do likewise
116            .filter(|s| !s.trim().is_empty())
117            // rustc is a batch program, so error early on inputs which are unlikely to be intended
118            // so no one thinks we parsed them setting `RUST_MIN_STACK="64 megabytes"`
119            // FIXME: we could accept `RUST_MIN_STACK=64MB`, perhaps?
120            .map(|s| {
121                let s = s.trim();
122                s.parse::<usize>().unwrap_or_else(|_| {
123                    let mut err = early_dcx.early_struct_fatal(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("`RUST_MIN_STACK` should be a number of bytes, but was \"{0}\"",
                s))
    })format!(
124                        r#"`RUST_MIN_STACK` should be a number of bytes, but was "{s}""#,
125                    ));
126                    err.note("you can also unset `RUST_MIN_STACK` to use the default stack size");
127                    err.emit()
128                })
129            })
130            // otherwise pick a consistent default
131            .unwrap_or(DEFAULT_STACK_SIZE)
132    })
133}
134
135fn run_in_thread_with_globals<F: FnOnce(CurrentGcx, Arc<Proxy>) -> R + Send, R: Send>(
136    thread_stack_size: usize,
137    edition: Edition,
138    sm_inputs: SourceMapInputs,
139    extra_symbols: &[&'static str],
140    f: F,
141) -> R {
142    // The "thread pool" is a single spawned thread in the non-parallel
143    // compiler. We run on a spawned thread instead of the main thread (a) to
144    // provide control over the stack size, and (b) to increase similarity with
145    // the parallel compiler, in particular to ensure there is no accidental
146    // sharing of data between the main thread and the compilation thread
147    // (which might cause problems for the parallel compiler).
148    let builder = thread::Builder::new().name("rustc".to_string()).stack_size(thread_stack_size);
149
150    // We build the session globals and run `f` on the spawned thread, because
151    // `SessionGlobals` does not impl `Send` in the non-parallel compiler.
152    thread::scope(|s| {
153        // `unwrap` is ok here because `spawn_scoped` only panics if the thread
154        // name contains null bytes.
155        let r = builder
156            .spawn_scoped(s, move || {
157                rustc_span::create_session_globals_then(
158                    edition,
159                    extra_symbols,
160                    Some(sm_inputs),
161                    || f(CurrentGcx::new(), Proxy::new()),
162                )
163            })
164            .unwrap()
165            .join();
166
167        match r {
168            Ok(v) => v,
169            Err(e) => std::panic::resume_unwind(e),
170        }
171    })
172}
173
174pub(crate) fn run_in_thread_pool_with_globals<
175    F: FnOnce(CurrentGcx, Arc<Proxy>) -> R + Send,
176    R: Send,
177>(
178    thread_builder_diag: &EarlyDiagCtxt,
179    edition: Edition,
180    threads: usize,
181    extra_symbols: &[&'static str],
182    sm_inputs: SourceMapInputs,
183    f: F,
184) -> R {
185    use std::process;
186
187    use rustc_data_structures::defer;
188    use rustc_middle::ty::tls;
189    use rustc_query_impl::break_query_cycle;
190
191    let thread_stack_size = init_stack_size(thread_builder_diag);
192
193    let registry = sync::Registry::new(std::num::NonZero::new(threads).unwrap());
194
195    let Some(proof) = sync::check_dyn_thread_safe() else {
196        return run_in_thread_with_globals(
197            thread_stack_size,
198            edition,
199            sm_inputs,
200            extra_symbols,
201            |current_gcx, jobserver_proxy| {
202                // Register the thread for use with the `WorkerLocal` type.
203                registry.register();
204
205                f(current_gcx, jobserver_proxy)
206            },
207        );
208    };
209
210    let current_gcx = proof.derive(CurrentGcx::new());
211    let current_gcx2 = current_gcx.clone();
212
213    let proxy = Proxy::new();
214
215    let proxy_ = Arc::clone(&proxy);
216    let proxy__ = Arc::clone(&proxy);
217    let builder = rustc_thread_pool::ThreadPoolBuilder::new()
218        .thread_name(|_| "rustc".to_string())
219        .acquire_thread_handler(move || proxy_.acquire_thread())
220        .release_thread_handler(move || proxy__.release_thread())
221        .num_threads(threads)
222        .deadlock_handler(move || {
223            // On deadlock, creates a new thread and forwards information in thread
224            // locals to it. The new thread runs the deadlock handler.
225
226            let current_gcx2 = current_gcx2.clone();
227            let registry = rustc_thread_pool::Registry::current();
228            let session_globals = rustc_span::with_session_globals(|session_globals| {
229                session_globals as *const SessionGlobals as usize
230            });
231            thread::Builder::new()
232                .name("rustc query cycle handler".to_string())
233                .spawn(move || {
234                    let on_panic = defer(|| {
235                        // Split this long string so that it doesn't cause rustfmt to
236                        // give up on the entire builder expression.
237                        // <https://github.com/rust-lang/rustfmt/issues/3863>
238                        const MESSAGE: &str = "\
239internal compiler error: query cycle handler thread panicked, aborting process";
240                        { ::std::io::_eprint(format_args!("{0}\n", MESSAGE)); };eprintln!("{MESSAGE}");
241                        // We need to abort here as we failed to resolve the deadlock,
242                        // otherwise the compiler could just hang,
243                        process::abort();
244                    });
245
246                    // Get a `GlobalCtxt` reference from `CurrentGcx` as we cannot rely on having a
247                    // `TyCtxt` TLS reference here.
248                    current_gcx2.access(|gcx| {
249                        tls::enter_context(&tls::ImplicitCtxt::new(gcx), || {
250                            tls::with(|tcx| {
251                                // Accessing session globals is sound as they outlive `GlobalCtxt`.
252                                // They are needed to hash query keys containing spans or symbols.
253                                let job_map = rustc_span::set_session_globals_then(
254                                    unsafe { &*(session_globals as *const SessionGlobals) },
255                                    || {
256                                        // Ensure there were no errors collecting all active jobs.
257                                        // We need the complete map to ensure we find a cycle to
258                                        // break.
259                                        collect_active_query_jobs(
260                                            tcx,
261                                            CollectActiveJobsKind::FullNoContention,
262                                        )
263                                    },
264                                );
265                                break_query_cycle(job_map, &registry);
266                            })
267                        })
268                    });
269
270                    on_panic.disable();
271                })
272                .unwrap();
273        })
274        .stack_size(thread_stack_size);
275
276    // We create the session globals on the main thread, then create the thread
277    // pool. Upon creation, each worker thread created gets a copy of the
278    // session globals in TLS. This is possible because `SessionGlobals` impls
279    // `Send` in the parallel compiler.
280    rustc_span::create_session_globals_then(edition, extra_symbols, Some(sm_inputs), || {
281        rustc_span::with_session_globals(|session_globals| {
282            let session_globals = proof.derive(session_globals);
283            builder
284                .build_scoped(
285                    // Initialize each new worker thread when created.
286                    move |thread: rustc_thread_pool::ThreadBuilder| {
287                        // Register the thread for use with the `WorkerLocal` type.
288                        registry.register();
289
290                        rustc_span::set_session_globals_then(session_globals.into_inner(), || {
291                            thread.run()
292                        })
293                    },
294                    // Run `f` on the first thread in the thread pool.
295                    move |pool: &rustc_thread_pool::ThreadPool| {
296                        pool.install(|| f(current_gcx.into_inner(), proxy))
297                    },
298                )
299                .unwrap_or_else(|err| {
300                    let mut diag = thread_builder_diag.early_struct_fatal(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("failed to spawn compiler thread pool: could not create {0} threads ({1})",
                threads, err))
    })format!(
301                        "failed to spawn compiler thread pool: could not create {threads} threads ({err})",
302                    ));
303                    diag.help(
304                        "try lowering `-Z threads` or checking the operating system's resource limits",
305                    );
306                    diag.emit()
307                })
308        })
309    })
310}
311
312fn load_backend_from_dylib(early_dcx: &EarlyDiagCtxt, path: &Path) -> MakeBackendFn {
313    match unsafe { load_symbol_from_dylib::<MakeBackendFn>(path, "__rustc_codegen_backend") } {
314        Ok(backend_sym) => backend_sym,
315        Err(DylibError::DlOpen(path, err)) => {
316            let err = ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("couldn\'t load codegen backend {0}{1}",
                path, err))
    })format!("couldn't load codegen backend {path}{err}");
317            early_dcx.early_fatal(err);
318        }
319        Err(DylibError::DlSym(_path, err)) => {
320            let e = ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("`__rustc_codegen_backend` symbol lookup in the codegen backend failed{0}",
                err))
    })format!(
321                "`__rustc_codegen_backend` symbol lookup in the codegen backend failed{err}",
322            );
323            early_dcx.early_fatal(e);
324        }
325    }
326}
327
328/// Get the codegen backend based on the name and specified sysroot.
329///
330/// A name of `None` indicates that the default backend should be used.
331pub fn get_codegen_backend(
332    early_dcx: &EarlyDiagCtxt,
333    sysroot: &Sysroot,
334    backend_name: Option<&str>,
335    target: &Target,
336) -> Box<dyn CodegenBackend> {
337    static LOAD: OnceLock<unsafe fn() -> Box<dyn CodegenBackend>> = OnceLock::new();
338
339    let load = LOAD.get_or_init(|| {
340        let backend = backend_name
341            .or(target.default_codegen_backend.as_deref())
342            .or(::core::option::Option::Some("llvm")option_env!("CFG_DEFAULT_CODEGEN_BACKEND"))
343            .unwrap_or("dummy");
344
345        match backend {
346            filename if filename.contains('.') => {
347                load_backend_from_dylib(early_dcx, filename.as_ref())
348            }
349            "dummy" => || Box::new(DummyCodegenBackend { target_config_override: None }),
350            #[cfg(feature = "llvm")]
351            "llvm" => rustc_codegen_llvm::LlvmCodegenBackend::new,
352            backend_name => get_codegen_sysroot(early_dcx, sysroot, backend_name),
353        }
354    });
355
356    // SAFETY: In case of a builtin codegen backend this is safe. In case of an external codegen
357    // backend we hope that the backend links against the same rustc_driver version. If this is not
358    // the case, we get UB.
359    unsafe { load() }
360}
361
362pub struct DummyCodegenBackend {
363    pub target_config_override: Option<Box<dyn Fn(&Session) -> TargetConfig>>,
364}
365
366impl CodegenBackend for DummyCodegenBackend {
367    fn name(&self) -> &'static str {
368        "dummy"
369    }
370
371    fn target_config(&self, sess: &Session) -> TargetConfig {
372        if let Some(target_config_override) = &self.target_config_override {
373            return target_config_override(sess);
374        }
375
376        let abi_required_features = sess.target.abi_required_features();
377        let (target_features, unstable_target_features) = cfg_target_feature::<0>(
378            sess,
379            |_feature| Default::default(),
380            |feature| {
381                // This is a standin for the list of features a backend is expected to enable.
382                // It would be better to parse target.features instead and handle implied features,
383                // but target.features doesn't contain features that are enabled by default for an
384                // architecture or target cpu.
385                abi_required_features.required.contains(&feature)
386            },
387        );
388
389        TargetConfig {
390            target_features,
391            unstable_target_features,
392            has_reliable_f16: true,
393            has_reliable_f16_math: true,
394            has_reliable_f128: true,
395            has_reliable_f128_math: true,
396        }
397    }
398
399    fn supported_crate_types(&self, _sess: &Session) -> Vec<CrateType> {
400        // This includes bin despite failing on the link step to ensure that you
401        // can still get the frontend handling for binaries. For all library
402        // like crate types cargo will fallback to rlib unless you specifically
403        // say that only a different crate type must be used.
404        ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
        [CrateType::Rlib, CrateType::Executable]))vec![CrateType::Rlib, CrateType::Executable]
405    }
406
407    fn target_cpu(&self, _sess: &Session) -> String {
408        String::new()
409    }
410
411    fn codegen_crate<'tcx>(&self, _tcx: TyCtxt<'tcx>) -> Box<dyn Any> {
412        Box::new(CompiledModules { modules: ::alloc::vec::Vec::new()vec![], allocator_module: None })
413    }
414
415    fn join_codegen(
416        &self,
417        ongoing_codegen: Box<dyn Any>,
418        _sess: &Session,
419        _outputs: &OutputFilenames,
420        _crate_info: &CrateInfo,
421    ) -> (CompiledModules, FxIndexMap<WorkProductId, WorkProduct>) {
422        (*ongoing_codegen.downcast().unwrap(), FxIndexMap::default())
423    }
424
425    fn link(
426        &self,
427        sess: &Session,
428        compiled_modules: CompiledModules,
429        crate_info: CrateInfo,
430        metadata: EncodedMetadata,
431        outputs: &OutputFilenames,
432    ) {
433        // JUSTIFICATION: TyCtxt no longer available here
434        #[allow(rustc::bad_opt_access)]
435        if let Some(&crate_type) =
436            crate_info.crate_types.iter().find(|&&crate_type| crate_type != CrateType::Rlib)
437            && outputs.outputs.should_link()
438        {
439            sess.dcx().fatal(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("crate type {0} not supported by the dummy codegen backend",
                crate_type))
    })format!(
440                "crate type {crate_type} not supported by the dummy codegen backend"
441            ));
442        }
443
444        link_binary(
445            sess,
446            &DummyArchiveBuilderBuilder,
447            compiled_modules,
448            crate_info,
449            metadata,
450            outputs,
451            self.name(),
452        );
453    }
454}
455
456struct DummyArchiveBuilderBuilder;
457
458impl ArchiveBuilderBuilder for DummyArchiveBuilderBuilder {
459    fn new_archive_builder<'a>(
460        &self,
461        sess: &'a Session,
462    ) -> Box<dyn rustc_codegen_ssa::back::archive::ArchiveBuilder + 'a> {
463        ArArchiveBuilderBuilder.new_archive_builder(sess)
464    }
465
466    fn create_dll_import_lib(
467        &self,
468        sess: &Session,
469        _lib_name: &str,
470        _items: Vec<rustc_codegen_ssa::back::archive::ImportLibraryItem>,
471        output_path: &Path,
472    ) {
473        // Build an empty static library to avoid calling an external dlltool on mingw
474        ArArchiveBuilderBuilder.new_archive_builder(sess).build(output_path);
475    }
476}
477
478// This is used for rustdoc, but it uses similar machinery to codegen backend
479// loading, so we leave the code here. It is potentially useful for other tools
480// that want to invoke the rustc binary while linking to rustc as well.
481pub fn rustc_path<'a>(sysroot: &Sysroot) -> Option<&'a Path> {
482    static RUSTC_PATH: OnceLock<Option<PathBuf>> = OnceLock::new();
483
484    RUSTC_PATH
485        .get_or_init(|| {
486            let candidate = sysroot
487                .default
488                .join("bin"env!("RUSTC_INSTALL_BINDIR"))
489                .join(if falsecfg!(target_os = "windows") { "rustc.exe" } else { "rustc" });
490            candidate.exists().then_some(candidate)
491        })
492        .as_deref()
493}
494
495fn get_codegen_sysroot(
496    early_dcx: &EarlyDiagCtxt,
497    sysroot: &Sysroot,
498    backend_name: &str,
499) -> MakeBackendFn {
500    // For now we only allow this function to be called once as it'll dlopen a
501    // few things, which seems to work best if we only do that once. In
502    // general this assertion never trips due to the once guard in `get_codegen_backend`,
503    // but there's a few manual calls to this function in this file we protect
504    // against.
505    static LOADED: AtomicBool = AtomicBool::new(false);
506    if !!LOADED.fetch_or(true, Ordering::SeqCst) {
    {
        ::core::panicking::panic_fmt(format_args!("cannot load the default codegen backend twice"));
    }
};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            {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_interface/src/util.rs:519",
                        "rustc_interface::util", ::tracing::Level::INFO,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_interface/src/util.rs"),
                        ::tracing_core::__macro_support::Option::Some(519u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_interface::util"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::INFO <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::INFO <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                let mut iter = __CALLSITE.metadata().fields().iter();
                __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                    ::tracing::__macro_support::Option::Some(&format_args!("codegen backend candidate: {0}",
                                                    f.display()) as &dyn Value))])
            });
    } else { ; }
};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 = ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("failed to find a `codegen-backends` folder in the sysroot candidates:\n* {0}",
                candidates))
    })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    {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_interface/src/util.rs:535",
                        "rustc_interface::util", ::tracing::Level::INFO,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_interface/src/util.rs"),
                        ::tracing_core::__macro_support::Option::Some(535u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_interface::util"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::INFO <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::INFO <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                let mut iter = __CALLSITE.metadata().fields().iter();
                __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                    ::tracing::__macro_support::Option::Some(&format_args!("probing {0} for a codegen backend",
                                                    sysroot.display()) as &dyn Value))])
            });
    } else { ; }
};info!("probing {} for a codegen backend", sysroot.display());
536
537    let d = sysroot.read_dir().unwrap_or_else(|e| {
538        let err = ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("failed to load default codegen backend, couldn\'t read `{0}`: {1}",
                sysroot.display(), e))
    })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        ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("rustc_codegen_{0}-{1}",
                backend_name, "1.97.0-nightly"))
    })format!("rustc_codegen_{}-{}", backend_name, env!("CFG_RELEASE")),
549        ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("rustc_codegen_{0}", backend_name))
    })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 = ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("duplicate codegen backends found\nfirst:  {0}\nsecond: {1}\n",
                prev.display(), path.display()))
    })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 = ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("unsupported builtin codegen backend `{0}`",
                backend_name))
    })format!("unsupported builtin codegen backend `{backend_name}`");
579            early_dcx.early_fatal(err);
580        }
581    }
582}
583
584fn multiple_output_types_to_stdout(
585    output_types: &OutputTypes,
586    single_output_file_is_stdout: bool,
587) -> bool {
588    use std::io::IsTerminal;
589    if std::io::stdout().is_terminal() {
590        // If stdout is a tty, check if multiple text output types are
591        // specified by `--emit foo=- --emit bar=-` or `-o - --emit foo,bar`
592        let named_text_types = output_types
593            .iter()
594            .filter(|(f, o)| f.is_text_output() && *o == &Some(OutFileName::Stdout))
595            .count();
596        let unnamed_text_types =
597            output_types.iter().filter(|(f, o)| f.is_text_output() && o.is_none()).count();
598        named_text_types > 1 || unnamed_text_types > 1 && single_output_file_is_stdout
599    } else {
600        // Otherwise, all the output types should be checked
601        let named_types =
602            output_types.values().filter(|o| *o == &Some(OutFileName::Stdout)).count();
603        let unnamed_types = output_types.values().filter(|o| o.is_none()).count();
604        named_types > 1 || unnamed_types > 1 && single_output_file_is_stdout
605    }
606}
607
608pub fn build_output_filenames(attrs: &[ast::Attribute], sess: &Session) -> OutputFilenames {
609    if multiple_output_types_to_stdout(
610        &sess.opts.output_types,
611        sess.io.output_file == Some(OutFileName::Stdout),
612    ) {
613        sess.dcx().emit_fatal(errors::MultipleOutputTypesToStdout);
614    }
615
616    let crate_name =
617        sess.opts.crate_name.clone().or_else(|| {
618            parse_crate_name(sess, attrs, ShouldEmit::Nothing).map(|i| i.0.to_string())
619        });
620
621    let invocation_temp = sess
622        .opts
623        .incremental
624        .as_ref()
625        .map(|_| rng().next_u32().to_base_fixed_len(CASE_INSENSITIVE).to_string());
626
627    match sess.io.output_file {
628        None => {
629            // "-" as input file will cause the parser to read from stdin so we
630            // have to make up a name
631            // We want to toss everything after the final '.'
632            let dirpath = sess.io.output_dir.clone().unwrap_or_default();
633
634            // If a crate name is present, we use it as the link name
635            let stem = crate_name.clone().unwrap_or_else(|| sess.io.input.filestem().to_owned());
636
637            OutputFilenames::new(
638                dirpath,
639                crate_name.unwrap_or_else(|| stem.replace('-', "_")),
640                stem,
641                None,
642                sess.io.temps_dir.clone(),
643                invocation_temp,
644                sess.opts.unstable_opts.split_dwarf_out_dir.clone(),
645                sess.opts.cg.extra_filename.clone(),
646                sess.opts.output_types.clone(),
647            )
648        }
649
650        Some(ref out_file) => {
651            let unnamed_output_types =
652                sess.opts.output_types.values().filter(|a| a.is_none()).count();
653            let ofile = if unnamed_output_types > 1 {
654                sess.dcx().emit_warn(errors::MultipleOutputTypesAdaption);
655                None
656            } else {
657                if !sess.opts.cg.extra_filename.is_empty() {
658                    sess.dcx().emit_warn(errors::IgnoringExtraFilename);
659                }
660                Some(out_file.clone())
661            };
662            if sess.io.output_dir.is_some() {
663                sess.dcx().emit_warn(errors::IgnoringOutDir);
664            }
665
666            let out_filestem =
667                out_file.filestem().unwrap_or_default().to_str().unwrap().to_string();
668            OutputFilenames::new(
669                out_file.parent().unwrap_or_else(|| Path::new("")).to_path_buf(),
670                crate_name.unwrap_or_else(|| out_filestem.replace('-', "_")),
671                out_filestem,
672                ofile,
673                sess.io.temps_dir.clone(),
674                invocation_temp,
675                sess.opts.unstable_opts.split_dwarf_out_dir.clone(),
676                sess.opts.cg.extra_filename.clone(),
677                sess.opts.output_types.clone(),
678            )
679        }
680    }
681}
682
683/// Returns a version string such as "1.46.0 (04488afe3 2020-08-24)" when invoked by an in-tree tool.
684pub macro version_str() {
685    option_env!("CFG_VERSION")
686}
687
688/// Returns the version string for `rustc` itself (which may be different from a tool version).
689pub fn rustc_version_str() -> Option<&'static str> {
690    ::core::option::Option::Some("1.97.0-nightly (f964de49b 2026-05-07)")version_str!()
691}