Skip to main content

rustc_interface/
util.rs

1use std::any::Any;
2use std::collections::BTreeMap;
3use std::env::consts::{DLL_PREFIX, DLL_SUFFIX};
4use std::path::{Path, PathBuf};
5use std::sync::atomic::{AtomicBool, Ordering};
6use std::sync::{Arc, OnceLock};
7use std::{env, thread};
8
9use rand::{RngCore, rng};
10use rustc_ast as ast;
11use rustc_attr_parsing::ShouldEmit;
12use rustc_codegen_ssa::back::archive::{ArArchiveBuilderBuilder, ArchiveBuilderBuilder};
13use rustc_codegen_ssa::back::link::link_binary;
14use rustc_codegen_ssa::target_features::internal_target_features;
15use rustc_codegen_ssa::traits::CodegenBackend;
16use rustc_codegen_ssa::{CompiledModules, CrateInfo, TargetConfig};
17use rustc_data_structures::base_n::{CASE_INSENSITIVE, ToBaseN};
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::IncrCompSession;
22use rustc_middle::ty::{CurrentGcx, TyCtxt};
23use rustc_query_impl::{CollectActiveJobsKind, collect_active_query_jobs};
24pub use rustc_session::config::DEFAULT_STACK_SIZE;
25use rustc_session::config::{
26    Cfg, Jobs, OptionsTargetModifiers, OutFileName, OutputFilenames, Sysroot, host_tuple,
27};
28use rustc_session::output::OutputTypes;
29use rustc_session::{CodegenBackendInit, EarlyDiagCtxt, EarlySession, Session, filesearch};
30use rustc_span::edition::Edition;
31use rustc_span::source_map::SourceMapInputs;
32use rustc_span::{SessionGlobals, Symbol, sym};
33use rustc_structures::CrateType;
34use rustc_target::spec::{Arch, Target};
35use tracing::info;
36
37use crate::diagnostics;
38use crate::passes::parse_crate_name;
39
40/// Function pointer type that constructs a new CodegenBackend.
41type MakeBackendFn = fn() -> Box<dyn CodegenBackend>;
42
43/// Adds `cfg` values based on the current target configuration (in particular for target features).
44///
45/// This is performed by checking whether a set of permitted features
46/// is available on the target machine, by querying the `TargetConfig` from the codegen backend.
47pub(crate) fn add_configuration(
48    cfg: &mut Cfg,
49    target_config: &TargetConfig,
50    target: &Target,
51    is_nightly_build: bool,
52    is_crt_static: bool,
53) {
54    // Add some of the target features to `cfg`.
55    cfg.extend(
56        target
57            .rust_target_features()
58            .iter()
59            .filter_map(|(feature, stab, _)| {
60                if stab.in_cfg()
61                    && (is_nightly_build || stab.requires_nightly(/* in_cfg */ true).is_none())
62                {
63                    Some(Symbol::intern(feature))
64                } else {
65                    None
66                }
67            })
68            .filter(|feature| target_config.internal_target_features.contains(&feature))
69            .map(|feature| (sym::target_feature, Some(feature))),
70    );
71
72    if target_config.has_reliable_f16 {
73        cfg.insert((sym::target_has_reliable_f16, None));
74    }
75    if target_config.has_reliable_f16_math {
76        cfg.insert((sym::target_has_reliable_f16_math, None));
77    }
78    if target_config.has_reliable_f16b {
79        cfg.insert((sym::target_has_reliable_f16b, None));
80    }
81    if target_config.has_reliable_f128 {
82        cfg.insert((sym::target_has_reliable_f128, None));
83    }
84    if target_config.has_reliable_f128_math {
85        cfg.insert((sym::target_has_reliable_f128_math, None));
86    }
87
88    if is_crt_static {
89        cfg.insert((sym::target_feature, Some(sym::crt_dash_static)));
90    }
91}
92
93/// Populates the target modifier database based on the current target.
94pub(crate) fn add_target_modifiers(
95    tmod: &mut BTreeMap<OptionsTargetModifiers, String>,
96    target_config: &TargetConfig,
97    target: &Target,
98    cg_backend: &dyn CodegenBackend,
99) {
100    // Record relevant target features as target modifier.
101    // Join all target-modifier target features into a single comma-separated string,
102    // sorted by the order they appear in in `rust_target_features`.
103    let target_feature_modifier = target
104        .rust_target_features()
105        .iter()
106        .filter(|(_, stab, _)| stab.is_target_modifier())
107        .map(|(feature, ..)| *feature)
108        .filter(|feature| target_config.internal_target_features.contains(&Symbol::intern(feature)))
109        .collect::<Vec<_>>()
110        .join(",");
111    tmod.insert(OptionsTargetModifiers::TargetFeatures, target_feature_modifier);
112
113    // Record the codegen backend name as target modifier.
114    tmod.insert(OptionsTargetModifiers::CodegenBackendName, cg_backend.name().to_string());
115}
116
117/// Ensures that all target features required by the ABI are present.
118/// Must be called after `internal_target_features` has been populated!
119pub(crate) fn check_abi_required_features(sess: &Session) {
120    let abi_feature_constraints = sess.target.abi_required_features();
121    // We check this against `internal_target_features` as that is conveniently already
122    // back-translated to rustc feature names, taking into account `-Ctarget-cpu` and `-Ctarget-feature`.
123    // Just double-check that the features we care about are actually on our list.
124    for feature in
125        abi_feature_constraints.required.iter().chain(abi_feature_constraints.incompatible.iter())
126    {
127        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!(
128            sess.target.rust_target_features().iter().any(|(name, ..)| feature == name),
129            "target feature {feature} is required/incompatible for the current ABI but not a recognized feature for this target"
130        );
131    }
132
133    // Make this a hard error on ARM since starting with LLVM24, the backend will otherwise
134    // emit a (less friendly) hard error.
135    // Also make it a hard error on x86, where we use SSE registers for the "Rust" ABI. The
136    // post-mono ABI check only systematically checks "C" calls, so we better reject this here.
137    let hard_error = #[allow(non_exhaustive_omitted_patterns)] match sess.target.arch {
    Arch::AArch64 | Arch::Arm | Arch::X86 => true,
    _ => false,
}matches!(sess.target.arch, Arch::AArch64 | Arch::Arm | Arch::X86);
138
139    for feature in abi_feature_constraints.required {
140        if !sess.internal_target_features.contains(&Symbol::intern(feature)) {
141            let diag = diagnostics::AbiRequiredTargetFeature {
142                feature,
143                enabled: "enabled",
144                fcw: !hard_error,
145            };
146            if hard_error {
147                sess.dcx().emit_err(diag);
148            } else {
149                sess.dcx().emit_warn(diag);
150            }
151        }
152    }
153    for feature in abi_feature_constraints.incompatible {
154        if sess.internal_target_features.contains(&Symbol::intern(feature)) {
155            let diag = diagnostics::AbiRequiredTargetFeature {
156                feature,
157                enabled: "disabled",
158                fcw: !hard_error,
159            };
160            if hard_error {
161                sess.dcx().emit_err(diag);
162            } else {
163                sess.dcx().emit_warn(diag);
164            }
165        }
166    }
167}
168
169pub static STACK_SIZE: OnceLock<usize> = OnceLock::new();
170
171fn init_stack_size(early_dcx: &EarlyDiagCtxt) -> usize {
172    // Obey the environment setting or default
173    *STACK_SIZE.get_or_init(|| {
174        env::var_os("RUST_MIN_STACK")
175            .as_ref()
176            .map(|os_str| os_str.to_string_lossy())
177            // if someone finds out `export RUST_MIN_STACK=640000` isn't enough stack
178            // they might try to "unset" it by running `RUST_MIN_STACK=  rustc code.rs`
179            // this is wrong, but std would nonetheless "do what they mean", so let's do likewise
180            .filter(|s| !s.trim().is_empty())
181            // rustc is a batch program, so error early on inputs which are unlikely to be intended
182            // so no one thinks we parsed them setting `RUST_MIN_STACK="64 megabytes"`
183            // FIXME: we could accept `RUST_MIN_STACK=64MB`, perhaps?
184            .map(|s| {
185                let s = s.trim();
186                s.parse::<usize>().unwrap_or_else(|_| {
187                    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!(
188                        r#"`RUST_MIN_STACK` should be a number of bytes, but was "{s}""#,
189                    ));
190                    err.note("you can also unset `RUST_MIN_STACK` to use the default stack size");
191                    err.emit_fatal()
192                })
193            })
194            // otherwise pick a consistent default
195            .unwrap_or(DEFAULT_STACK_SIZE)
196    })
197}
198
199fn run_in_thread_with_globals<F: FnOnce(CurrentGcx) -> R + Send, R: Send>(
200    thread_stack_size: usize,
201    edition: Edition,
202    sm_inputs: SourceMapInputs,
203    extra_symbols: &[&'static str],
204    f: F,
205) -> R {
206    // The "thread pool" is a single spawned thread in the non-parallel
207    // compiler. We run on a spawned thread instead of the main thread (a) to
208    // provide control over the stack size, and (b) to increase similarity with
209    // the parallel compiler, in particular to ensure there is no accidental
210    // sharing of data between the main thread and the compilation thread
211    // (which might cause problems for the parallel compiler).
212    let builder = thread::Builder::new().name("rustc".to_string()).stack_size(thread_stack_size);
213
214    // We build the session globals and run `f` on the spawned thread, because
215    // `SessionGlobals` does not impl `Send` in the non-parallel compiler.
216    thread::scope(|s| {
217        // `unwrap` is ok here because `spawn_scoped` only panics if the thread
218        // name contains null bytes.
219        let r = builder
220            .spawn_scoped(s, move || {
221                rustc_span::create_session_globals_then(
222                    edition,
223                    extra_symbols,
224                    Some(sm_inputs),
225                    || f(CurrentGcx::new()),
226                )
227            })
228            .unwrap()
229            .join();
230
231        match r {
232            Ok(v) => v,
233            Err(e) => std::panic::resume_unwind(e),
234        }
235    })
236}
237
238pub(crate) fn run_in_thread_pool_with_globals<F: FnOnce(CurrentGcx) -> R + Send, R: Send>(
239    thread_builder_diag: &EarlyDiagCtxt,
240    edition: Edition,
241    jobs: Jobs,
242    extra_symbols: &[&'static str],
243    sm_inputs: SourceMapInputs,
244    f: F,
245) -> R {
246    use std::process;
247
248    use rustc_data_structures::defer;
249    use rustc_middle::ty::tls;
250    use rustc_query_impl::break_query_cycle;
251
252    let thread_stack_size = init_stack_size(thread_builder_diag);
253
254    let jobs_frontend = jobs.frontend.limit();
255    let registry = sync::Registry::new(jobs_frontend);
256
257    let Some(proof) = sync::check_dyn_thread_safe() else {
258        {
    match (&jobs_frontend.get(), &1) {
        (left_val, right_val) => {
            if !(*left_val == *right_val) {
                let kind = ::core::panicking::AssertKind::Eq;
                ::core::panicking::assert_failed(kind, &*left_val,
                    &*right_val, ::core::option::Option::None);
            }
        }
    }
};assert_eq!(jobs_frontend.get(), 1);
259        return run_in_thread_with_globals(
260            thread_stack_size,
261            edition,
262            sm_inputs,
263            extra_symbols,
264            |current_gcx| {
265                // Register the thread for use with the `WorkerLocal` type.
266                registry.register();
267
268                f(current_gcx)
269            },
270        );
271    };
272
273    let current_gcx = proof.derive(CurrentGcx::new());
274    let current_gcx2 = current_gcx.clone();
275
276    let proxy = Proxy::new();
277
278    // Explicitly drop and join helper thread before rustc exits,
279    // so all job server tokens are returned.
280    let _drop_helper_thread = defer({
281        let proxy = Arc::clone(&proxy);
282        move || proxy.drop_helper_thread()
283    });
284
285    let proxy_ = Arc::clone(&proxy);
286
287    let builder = rustc_thread_pool::ThreadPoolBuilder::new()
288        .thread_name(|_| "rustc".to_string())
289        .acquire_thread_handler(move || proxy.acquire_thread())
290        .release_thread_handler(move || proxy_.release_thread())
291        .num_threads(jobs_frontend.get())
292        .deadlock_handler(move || {
293            // On deadlock, creates a new thread and forwards information in thread
294            // locals to it. The new thread runs the deadlock handler.
295
296            let current_gcx2 = current_gcx2.clone();
297            let registry = rustc_thread_pool::Registry::current();
298            let session_globals = rustc_span::with_session_globals(|session_globals| {
299                session_globals as *const SessionGlobals as usize
300            });
301            thread::Builder::new()
302                .name("rustc query cycle handler".to_string())
303                .spawn(move || {
304                    let on_panic = defer(|| {
305                        // Split this long string so that it doesn't cause rustfmt to
306                        // give up on the entire builder expression.
307                        // <https://github.com/rust-lang/rustfmt/issues/3863>
308                        const MESSAGE: &str = "\
309internal compiler error: query cycle handler thread panicked, aborting process";
310                        { ::std::io::_eprint(format_args!("{0}\n", MESSAGE)); };eprintln!("{MESSAGE}");
311                        // We need to abort here as we failed to resolve the deadlock,
312                        // otherwise the compiler could just hang,
313                        process::abort();
314                    });
315
316                    // Get a `GlobalCtxt` reference from `CurrentGcx` as we cannot rely on having a
317                    // `TyCtxt` TLS reference here.
318                    current_gcx2.access(|gcx| {
319                        tls::enter_context(&tls::ImplicitCtxt::new(gcx), || {
320                            tls::with(|tcx| {
321                                // Accessing session globals is sound as they outlive `GlobalCtxt`.
322                                // They are needed to hash query keys containing spans or symbols.
323                                let job_map = rustc_span::set_session_globals_then(
324                                    unsafe { &*(session_globals as *const SessionGlobals) },
325                                    || {
326                                        // Ensure there were no errors collecting all active jobs.
327                                        // We need the complete map to ensure we find a cycle to
328                                        // break.
329                                        collect_active_query_jobs(
330                                            tcx,
331                                            CollectActiveJobsKind::FullNoContention,
332                                        )
333                                    },
334                                );
335                                break_query_cycle(job_map, &registry);
336                            })
337                        })
338                    });
339
340                    on_panic.disable();
341                })
342                .unwrap();
343        })
344        .stack_size(thread_stack_size);
345
346    // We create the session globals on the main thread, then create the thread
347    // pool. Upon creation, each worker thread created gets a copy of the
348    // session globals in TLS. This is possible because `SessionGlobals` impls
349    // `Send` in the parallel compiler.
350    rustc_span::create_session_globals_then(edition, extra_symbols, Some(sm_inputs), || {
351        rustc_span::with_session_globals(|session_globals| {
352            let session_globals = proof.derive(session_globals);
353            builder
354                .build_scoped(
355                    // Initialize each new worker thread when created.
356                    move |thread: rustc_thread_pool::ThreadBuilder| {
357                        // Register the thread for use with the `WorkerLocal` type.
358                        registry.register();
359
360                        rustc_span::set_session_globals_then(session_globals.into_inner(), || {
361                            thread.run()
362                        })
363                    },
364                    // Run `f` on the first thread in the thread pool.
365                    move |pool: &rustc_thread_pool::ThreadPool| {
366                        pool.install(|| f(current_gcx.into_inner()))
367                    },
368                )
369                .unwrap_or_else(|err| {
370                    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})",
                jobs_frontend, err))
    })format!(
371                        "failed to spawn compiler thread pool: could not create {jobs_frontend} threads ({err})",
372                    ));
373                    diag.help(
374                        "try lowering `-Z threads` or checking the operating system's resource limits",
375                    );
376                    diag.emit_fatal()
377                })
378        })
379    })
380}
381
382fn load_backend_from_dylib(early_dcx: &EarlyDiagCtxt, path: &Path) -> MakeBackendFn {
383    match unsafe { load_symbol_from_dylib::<MakeBackendFn>(path, "__rustc_codegen_backend") } {
384        Ok(backend_sym) => backend_sym,
385        Err(DylibError::DlOpen(path, err)) => {
386            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}");
387            early_dcx.early_fatal(err);
388        }
389        Err(DylibError::DlSym(_path, err)) => {
390            let e = ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("`__rustc_codegen_backend` symbol lookup in the codegen backend failed{0}",
                err))
    })format!(
391                "`__rustc_codegen_backend` symbol lookup in the codegen backend failed{err}",
392            );
393            early_dcx.early_fatal(e);
394        }
395    }
396}
397
398/// Get the codegen backend based on the name and specified sysroot.
399///
400/// A name of `None` indicates that the default backend should be used.
401pub fn get_codegen_backend(
402    early_dcx: &EarlyDiagCtxt,
403    sysroot: &Sysroot,
404    backend_name: Option<&str>,
405    target: &Target,
406) -> Box<dyn CodegenBackend> {
407    static LOAD: OnceLock<unsafe fn() -> Box<dyn CodegenBackend>> = OnceLock::new();
408
409    let load = LOAD.get_or_init(|| {
410        let backend = backend_name
411            .or(target.default_codegen_backend.as_deref())
412            .or(::core::option::Option::Some("llvm")option_env!("CFG_DEFAULT_CODEGEN_BACKEND"))
413            .unwrap_or("dummy");
414
415        match backend {
416            filename if filename.contains('.') => {
417                load_backend_from_dylib(early_dcx, filename.as_ref())
418            }
419            "dummy" => || Box::new(DummyCodegenBackend),
420            #[cfg(feature = "llvm")]
421            "llvm" => rustc_codegen_llvm::LlvmCodegenBackend::new,
422            backend_name => get_codegen_sysroot(early_dcx, sysroot, backend_name),
423        }
424    });
425
426    // SAFETY: In case of a builtin codegen backend this is safe. In case of an external codegen
427    // backend we hope that the backend links against the same rustc_driver version. If this is not
428    // the case, we get UB.
429    unsafe { load() }
430}
431
432pub struct DummyCodegenBackend;
433
434impl CodegenBackend for DummyCodegenBackend {
435    fn name(&self) -> &'static str {
436        "dummy"
437    }
438
439    fn init(&mut self, sess: &EarlySession) -> (CodegenBackendInit, TargetConfig) {
440        let init = CodegenBackendInit::default();
441
442        let abi_required_features = sess.target.abi_required_features();
443        let internal_target_features = internal_target_features::<0>(
444            sess,
445            |_feature| Default::default(),
446            |feature| {
447                // This is a standin for the list of features a backend is expected to enable.
448                // It would be better to parse target.features instead and handle implied features,
449                // but target.features doesn't contain features that are enabled by default for an
450                // architecture or target cpu.
451                abi_required_features.required.contains(&feature)
452            },
453        );
454
455        let config = TargetConfig {
456            internal_target_features,
457            has_reliable_f16: true,
458            has_reliable_f16_math: true,
459            has_reliable_f16b: true,
460            has_reliable_f128: true,
461            has_reliable_f128_math: true,
462        };
463
464        (init, config)
465    }
466
467    fn supported_crate_types(&self, _sess: &Session) -> Vec<CrateType> {
468        // This includes bin despite failing on the link step to ensure that you
469        // can still get the frontend handling for binaries. For all library
470        // like crate types cargo will fallback to rlib unless you specifically
471        // say that only a different crate type must be used.
472        ::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]
473    }
474
475    fn target_cpu(&self, _sess: &Session) -> String {
476        String::new()
477    }
478
479    fn codegen_crate<'tcx>(&self, _tcx: TyCtxt<'tcx>) -> Box<dyn Any> {
480        Box::new(CompiledModules { modules: ::alloc::vec::Vec::new()vec![], allocator_module: None })
481    }
482
483    fn join_codegen(
484        &self,
485        ongoing_codegen: Box<dyn Any>,
486        _sess: &Session,
487        _incr_comp_session: Option<&mut IncrCompSession>,
488        _outputs: &OutputFilenames,
489        _crate_info: &CrateInfo,
490    ) -> CompiledModules {
491        *ongoing_codegen.downcast().unwrap()
492    }
493
494    fn link(
495        &self,
496        sess: &Session,
497        compiled_modules: CompiledModules,
498        crate_info: CrateInfo,
499        metadata: EncodedMetadata,
500        outputs: &OutputFilenames,
501    ) {
502        // JUSTIFICATION: TyCtxt no longer available here
503        #[allow(rustc::bad_opt_access)]
504        if let Some(&crate_type) =
505            crate_info.crate_types.iter().find(|&&crate_type| crate_type != CrateType::Rlib)
506            && outputs.outputs.should_link()
507        {
508            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!(
509                "crate type {crate_type} not supported by the dummy codegen backend"
510            ));
511        }
512
513        link_binary(
514            sess,
515            &DummyArchiveBuilderBuilder,
516            compiled_modules,
517            crate_info,
518            metadata,
519            outputs,
520            self.name(),
521        );
522    }
523}
524
525struct DummyArchiveBuilderBuilder;
526
527impl ArchiveBuilderBuilder for DummyArchiveBuilderBuilder {
528    fn new_archive_builder<'a>(
529        &self,
530        sess: &'a Session,
531    ) -> Box<dyn rustc_codegen_ssa::back::archive::ArchiveBuilder + 'a> {
532        ArArchiveBuilderBuilder.new_archive_builder(sess)
533    }
534
535    fn create_dll_import_lib(
536        &self,
537        sess: &Session,
538        _lib_name: &str,
539        _items: Vec<rustc_codegen_ssa::back::archive::ImportLibraryItem>,
540        output_path: &Path,
541    ) {
542        // Build an empty static library to avoid calling an external dlltool on mingw
543        ArArchiveBuilderBuilder.new_archive_builder(sess).build(output_path, None);
544    }
545}
546
547// This is used for rustdoc, but it uses similar machinery to codegen backend
548// loading, so we leave the code here. It is potentially useful for other tools
549// that want to invoke the rustc binary while linking to rustc as well.
550pub fn rustc_path<'a>(sysroot: &Sysroot) -> Option<&'a Path> {
551    static RUSTC_PATH: OnceLock<Option<PathBuf>> = OnceLock::new();
552
553    RUSTC_PATH
554        .get_or_init(|| {
555            let candidate = sysroot
556                .default
557                .join("bin"env!("RUSTC_INSTALL_BINDIR"))
558                .join(if falsecfg!(target_os = "windows") { "rustc.exe" } else { "rustc" });
559            candidate.exists().then_some(candidate)
560        })
561        .as_deref()
562}
563
564fn get_codegen_sysroot(
565    early_dcx: &EarlyDiagCtxt,
566    sysroot: &Sysroot,
567    backend_name: &str,
568) -> MakeBackendFn {
569    // For now we only allow this function to be called once as it'll dlopen a
570    // few things, which seems to work best if we only do that once. In
571    // general this assertion never trips due to the once guard in `get_codegen_backend`,
572    // but there's a few manual calls to this function in this file we protect
573    // against.
574    static LOADED: AtomicBool = AtomicBool::new(false);
575    if !!LOADED.fetch_or(true, Ordering::SeqCst) {
    {
        ::core::panicking::panic_fmt(format_args!("cannot load the default codegen backend twice"));
    }
};assert!(
576        !LOADED.fetch_or(true, Ordering::SeqCst),
577        "cannot load the default codegen backend twice"
578    );
579
580    let target = host_tuple();
581
582    let sysroot = sysroot
583        .all_paths()
584        .map(|sysroot| {
585            filesearch::make_target_lib_path(sysroot, target).with_file_name("codegen-backends")
586        })
587        .find(|f| {
588            {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/75a3786afbc93bbddf2c0259033b63957b45ace1/compiler/rustc_interface/src/util.rs:588",
                        "rustc_interface::util", ::tracing::Level::INFO,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/75a3786afbc93bbddf2c0259033b63957b45ace1/compiler/rustc_interface/src/util.rs"),
                        ::tracing_core::__macro_support::Option::Some(588u32),
                        ::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};
                __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("codegen backend candidate: {0}",
                                                    f.display()) as &dyn ::tracing::field::Value))])
            });
    } else { ; }
};info!("codegen backend candidate: {}", f.display());
589            f.exists()
590        })
591        .unwrap_or_else(|| {
592            let candidates = sysroot
593                .all_paths()
594                .map(|p| p.display().to_string())
595                .collect::<Vec<_>>()
596                .join("\n* ");
597            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!(
598                "failed to find a `codegen-backends` folder in the sysroot candidates:\n\
599                 * {candidates}"
600            );
601            early_dcx.early_fatal(err);
602        });
603
604    {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/75a3786afbc93bbddf2c0259033b63957b45ace1/compiler/rustc_interface/src/util.rs:604",
                        "rustc_interface::util", ::tracing::Level::INFO,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/75a3786afbc93bbddf2c0259033b63957b45ace1/compiler/rustc_interface/src/util.rs"),
                        ::tracing_core::__macro_support::Option::Some(604u32),
                        ::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};
                __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("probing {0} for a codegen backend",
                                                    sysroot.display()) as &dyn ::tracing::field::Value))])
            });
    } else { ; }
};info!("probing {} for a codegen backend", sysroot.display());
605
606    let d = sysroot.read_dir().unwrap_or_else(|e| {
607        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!(
608            "failed to load default codegen backend, couldn't read `{}`: {e}",
609            sysroot.display(),
610        );
611        early_dcx.early_fatal(err);
612    });
613
614    let mut file: Option<PathBuf> = None;
615
616    let expected_names = &[
617        ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("rustc_codegen_{0}-{1}",
                backend_name, "1.102.0-nightly"))
    })format!("rustc_codegen_{}-{}", backend_name, env!("CFG_RELEASE")),
618        ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("rustc_codegen_{0}", backend_name))
    })format!("rustc_codegen_{backend_name}"),
619    ];
620    for entry in d.filter_map(|e| e.ok()) {
621        let path = entry.path();
622        let Some(filename) = path.file_name().and_then(|s| s.to_str()) else { continue };
623        if !(filename.starts_with(DLL_PREFIX) && filename.ends_with(DLL_SUFFIX)) {
624            continue;
625        }
626        let name = &filename[DLL_PREFIX.len()..filename.len() - DLL_SUFFIX.len()];
627        if !expected_names.iter().any(|expected| expected == name) {
628            continue;
629        }
630        if let Some(ref prev) = file {
631            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!(
632                "duplicate codegen backends found\n\
633                               first:  {}\n\
634                               second: {}\n\
635            ",
636                prev.display(),
637                path.display()
638            );
639            early_dcx.early_fatal(err);
640        }
641        file = Some(path.clone());
642    }
643
644    match file {
645        Some(ref s) => load_backend_from_dylib(early_dcx, s),
646        None => {
647            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}`");
648            early_dcx.early_fatal(err);
649        }
650    }
651}
652
653fn multiple_output_types_to_stdout(
654    output_types: &OutputTypes,
655    single_output_file_is_stdout: bool,
656) -> bool {
657    use std::io::IsTerminal;
658    if std::io::stdout().is_terminal() {
659        // If stdout is a tty, check if multiple text output types are
660        // specified by `--emit foo=- --emit bar=-` or `-o - --emit foo,bar`
661        let named_text_types = output_types
662            .iter()
663            .filter(|(f, o)| f.is_text_output() && *o == &Some(OutFileName::Stdout))
664            .count();
665        let unnamed_text_types =
666            output_types.iter().filter(|(f, o)| f.is_text_output() && o.is_none()).count();
667        named_text_types > 1 || unnamed_text_types > 1 && single_output_file_is_stdout
668    } else {
669        // Otherwise, all the output types should be checked
670        let named_types =
671            output_types.values().filter(|o| *o == &Some(OutFileName::Stdout)).count();
672        let unnamed_types = output_types.values().filter(|o| o.is_none()).count();
673        named_types > 1 || unnamed_types > 1 && single_output_file_is_stdout
674    }
675}
676
677pub fn build_output_filenames(attrs: &[ast::Attribute], sess: &Session) -> OutputFilenames {
678    if multiple_output_types_to_stdout(
679        &sess.opts.output_types,
680        sess.io.output_file == Some(OutFileName::Stdout),
681    ) {
682        sess.dcx().emit_fatal(diagnostics::MultipleOutputTypesToStdout);
683    }
684
685    let crate_name =
686        sess.opts.crate_name.clone().or_else(|| {
687            parse_crate_name(sess, attrs, ShouldEmit::Nothing).map(|i| i.0.to_string())
688        });
689
690    let invocation_temp = sess
691        .opts
692        .incremental
693        .as_ref()
694        .map(|_| rng().next_u32().to_base_fixed_len(CASE_INSENSITIVE).to_string());
695
696    match sess.io.output_file {
697        None => {
698            // "-" as input file will cause the parser to read from stdin so we
699            // have to make up a name
700            // We want to toss everything after the final '.'
701            let dirpath = sess.io.output_dir.clone().unwrap_or_default();
702
703            // If a crate name is present, we use it as the link name
704            let stem = crate_name.clone().unwrap_or_else(|| sess.io.input.filestem().to_owned());
705
706            OutputFilenames::new(
707                dirpath,
708                crate_name.unwrap_or_else(|| stem.replace('-', "_")),
709                stem,
710                None,
711                sess.io.temps_dir.clone(),
712                invocation_temp,
713                sess.opts.unstable_opts.split_dwarf_out_dir.clone(),
714                sess.opts.cg.extra_filename.clone(),
715                sess.opts.output_types.clone(),
716            )
717        }
718
719        Some(ref out_file) => {
720            let unnamed_output_types =
721                sess.opts.output_types.values().filter(|a| a.is_none()).count();
722            let ofile = if unnamed_output_types > 1 {
723                sess.dcx().emit_warn(diagnostics::MultipleOutputTypesAdaption);
724                None
725            } else {
726                if !sess.opts.cg.extra_filename.is_empty() {
727                    sess.dcx().emit_warn(diagnostics::IgnoringExtraFilename);
728                }
729                Some(out_file.clone())
730            };
731            if sess.io.output_dir.is_some() {
732                sess.dcx().emit_warn(diagnostics::IgnoringOutDir);
733            }
734
735            let out_filestem =
736                out_file.filestem().unwrap_or_default().to_str().unwrap().to_string();
737            OutputFilenames::new(
738                out_file.parent().unwrap_or_else(|| Path::new("")).to_path_buf(),
739                crate_name.unwrap_or_else(|| out_filestem.replace('-', "_")),
740                out_filestem,
741                ofile,
742                sess.io.temps_dir.clone(),
743                invocation_temp,
744                sess.opts.unstable_opts.split_dwarf_out_dir.clone(),
745                sess.opts.cg.extra_filename.clone(),
746                sess.opts.output_types.clone(),
747            )
748        }
749    }
750}
751
752/// Returns a version string such as "1.46.0 (04488afe3 2020-08-24)" when invoked by an in-tree tool.
753pub macro version_str() {
754    option_env!("CFG_VERSION")
755}
756
757/// Returns the version string for `rustc` itself (which may be different from a tool version).
758pub fn rustc_version_str() -> Option<&'static str> {
759    ::core::option::Option::Some("1.102.0-nightly (75a3786af 2026-11-30)")version_str!()
760}