Skip to main content

rustc_session/
session.rs

1use std::any::Any;
2use std::ops::{Deref, DerefMut};
3use std::path::Component::Prefix;
4use std::path::PathBuf;
5use std::str::FromStr;
6use std::sync::Arc;
7use std::sync::atomic::{AtomicBool, AtomicUsize};
8use std::{env, io};
9
10use rustc_abi::PackCoroutineLayout;
11use rustc_data_structures::flock;
12use rustc_data_structures::fx::{FxHashMap, FxHashSet, FxIndexSet};
13use rustc_data_structures::profiling::{SelfProfiler, SelfProfilerRef};
14use rustc_data_structures::sync::{AppendOnlyVec, DynSend, DynSync, Lock};
15use rustc_errors::annotate_snippet_emitter_writer::AnnotateSnippetEmitter;
16use rustc_errors::codes::*;
17use rustc_errors::emitter::{DynEmitter, HumanReadableErrorType, OutputTheme, stderr_destination};
18use rustc_errors::json::JsonEmitter;
19use rustc_errors::timings::TimingSectionHandler;
20use rustc_errors::{
21    Diag, DiagCtxt, DiagCtxtHandle, DiagMessage, Diagnostic, ErrorGuaranteed, PResult, TerminalUrl,
22};
23use rustc_feature::UnstableFeatures;
24use rustc_lint_defs::{CheckLintNameResult, LintName, RegisteredTools};
25use rustc_macros::StableHash;
26pub use rustc_span::def_id::StableCrateId;
27use rustc_span::edition::Edition;
28use rustc_span::source_map::{FilePathMapping, SourceMap};
29use rustc_span::{RealFileName, Span, Symbol};
30use rustc_structures::{CrateType, Limit};
31use rustc_target::asm::InlineAsmArch;
32use rustc_target::spec::{
33    Arch, CfgAbi, CodeModel, DebuginfoKind, MergeFunctions, Os, PanicStrategy, RelocModel,
34    RelroLevel, SanitizerSet, SmallDataThresholdSupport, SplitDebuginfo, StackProtector,
35    SymbolVisibility, Target, TargetTuple, TlsModel, apple,
36};
37
38use crate::code_stats::CodeStats;
39pub use crate::code_stats::{DataTypeKind, FieldInfo, FieldKind, SizeKind, VariantInfo};
40use crate::config::{
41    self, BranchProtection, Cfg, CheckCfg, CoverageLevel, CoverageOptions, DebugInfo,
42    FunctionReturn, Input, InstrumentCoverage, InstrumentMcount, LtoCli, NATIVE_CPU, OutFileName,
43    PAuthKey, PointerAuthOption, SwitchWithOptPath,
44};
45use crate::filesearch::FileSearch;
46use crate::lint::LintId;
47use crate::output::{ErrorOutputType, OutputType};
48use crate::parse::ParseSess;
49use crate::search_paths::SearchPath;
50use crate::{diagnostics, filesearch, lint};
51
52/// The behavior of the CTFE engine when an error occurs with regards to backtraces.
53#[derive(#[automatically_derived]#[doc(hidden)]unsafe impl ::core::clone::TrivialClone
    for CtfeBacktrace {
}
#[automatically_derived]impl ::core::clone::Clone for CtfeBacktrace {
    #[inline]
    #[rustc_trivial_field_reads]
    fn clone(&self) -> Self { *self }
}Clone, #[automatically_derived]impl ::core::marker::Copy for CtfeBacktrace { }Copy)]
54pub enum CtfeBacktrace {
55    /// Do nothing special, return the error as usual without a backtrace.
56    Disabled,
57    /// Capture a backtrace at the point the error is created and return it in the error
58    /// (to be printed later if/when the error ever actually gets shown to the user).
59    Capture,
60    /// Capture a backtrace at the point the error is created and immediately print it out.
61    Immediate,
62}
63
64#[derive(#[automatically_derived]#[doc(hidden)]unsafe impl ::core::clone::TrivialClone
    for Limits {
}
#[automatically_derived]impl ::core::clone::Clone for Limits {
    #[inline]
    #[rustc_trivial_field_reads]
    fn clone(&self) -> Self {
        let _: ::core::clone::AssertParamIsClone<Limit>;
        *self
    }
}Clone, #[automatically_derived]impl ::core::marker::Copy for Limits { }Copy, #[automatically_derived]impl ::core::fmt::Debug for Limits {
    #[inline]
    #[rustc_trivial_field_reads]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        ::core::fmt::Formatter::debug_struct_field4_finish(f,
            "Limits recursion_limit move_size_limit type_length_limit pattern_complexity_limit",
            &self.recursion_limit, &self.move_size_limit,
            &self.type_length_limit, &&self.pattern_complexity_limit)
    }
}Debug, const _: () =
    {
        impl ::rustc_data_structures::stable_hash::StableHash for Limits {
            #[inline]
            fn stable_hash<__Hcx: ::rustc_data_structures::stable_hash::StableHashCtxt>(&self,
                __hcx: &mut __Hcx,
                __hasher:
                    &mut ::rustc_data_structures::stable_hash::StableHasher) {
                match *self {
                    Limits {
                        recursion_limit: ref __binding_0,
                        move_size_limit: ref __binding_1,
                        type_length_limit: ref __binding_2,
                        pattern_complexity_limit: ref __binding_3 } => {
                        { __binding_0.stable_hash(__hcx, __hasher); }
                        { __binding_1.stable_hash(__hcx, __hasher); }
                        { __binding_2.stable_hash(__hcx, __hasher); }
                        { __binding_3.stable_hash(__hcx, __hasher); }
                    }
                }
            }
        }
    };StableHash)]
65pub struct Limits {
66    /// The maximum recursion limit for potentially infinitely recursive
67    /// operations such as auto-dereference and monomorphization.
68    pub recursion_limit: Limit,
69    /// The size at which the `large_assignments` lint starts
70    /// being emitted.
71    pub move_size_limit: Limit,
72    /// The maximum length of types during monomorphization.
73    pub type_length_limit: Limit,
74    /// The maximum pattern complexity allowed (internal only).
75    pub pattern_complexity_limit: Limit,
76}
77
78pub struct CompilerIO {
79    pub input: Input,
80    pub output_dir: Option<PathBuf>,
81    pub output_file: Option<OutFileName>,
82    pub temps_dir: Option<PathBuf>,
83}
84
85pub trait DynLintStore: Any + DynSync + DynSend {
86    /// Provides a way to access lint groups without depending on `rustc_lint`
87    fn lint_groups_iter(&self) -> Box<dyn Iterator<Item = LintGroup> + '_>;
88
89    fn check_attribute_lint_name(
90        &self,
91        lint_name: LintName,
92        lint_tools: &RegisteredTools,
93    ) -> CheckLintNameResult<'_>;
94}
95
96/// Hardware pointer-signing keys in ARM8.3.
97/// These values are the same as used in ptrauth.h.
98#[derive(#[automatically_derived]#[doc(hidden)]unsafe impl ::core::clone::TrivialClone
    for PointerAuthARM8_3Key {
}
#[automatically_derived]impl ::core::clone::Clone for PointerAuthARM8_3Key {
    #[inline]
    #[rustc_trivial_field_reads]
    fn clone(&self) -> Self { *self }
}Clone, #[automatically_derived]impl ::core::marker::Copy for PointerAuthARM8_3Key { }Copy, #[automatically_derived]impl ::core::fmt::Debug for PointerAuthARM8_3Key {
    #[inline]
    #[rustc_trivial_field_reads]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        ::core::fmt::Formatter::write_str(f,
            match self {
                PointerAuthARM8_3Key::ASIA => "ASIA",
                PointerAuthARM8_3Key::ASIB => "ASIB",
                PointerAuthARM8_3Key::ASDA => "ASDA",
                PointerAuthARM8_3Key::ASDB => "ASDB",
            })
    }
}Debug, #[automatically_derived]impl ::core::marker::StructuralPartialEq for
    PointerAuthARM8_3Key {
}
#[automatically_derived]impl ::core::cmp::PartialEq for PointerAuthARM8_3Key {
    #[inline]
    fn eq(&self, other: &Self) -> bool {
        ::core::intrinsics::discriminant_value(self) ==
            ::core::intrinsics::discriminant_value(other)
    }
}PartialEq, #[automatically_derived]impl ::core::cmp::Eq for PointerAuthARM8_3Key { }Eq)]
99pub enum PointerAuthARM8_3Key {
100    ASIA = 0,
101    ASIB = 1,
102    ASDA = 2,
103    ASDB = 3,
104}
105
106/// Forms of extra discrimination.
107pub enum PointerAuthDiscrimination {
108    /// No additional discrimination.
109    None,
110    /// Include a hash of the entity's type.
111    Type,
112    /// Include a hash of the entity's identity.
113    Decl,
114    /// Discriminate using a constant value.
115    Constant,
116}
117
118/// Types of address discrimination.
119pub enum PointerAuthAddressDiscriminator {
120    /// Enable/disable hardware address discrimination.
121    HardwareAddress(bool),
122    /// Use a synthetic value. For instance init/fini entries can not the address of the arrays,
123    /// they must use a synthetic value of `1`.
124    Synthetic(u64),
125}
126
127pub struct PointerAuthSchema {
128    pub is_address_discriminated: PointerAuthAddressDiscriminator,
129    pub discrimination_kind: PointerAuthDiscrimination,
130    pub key: PointerAuthARM8_3Key,
131    pub constant_discriminator: u16,
132}
133impl PointerAuthSchema {
134    pub fn function_pointers_default(target: &Target) -> Self {
135        if !(target.cfg_abi == CfgAbi::Pauthtest) {
    ::core::panicking::panic("assertion failed: target.cfg_abi == CfgAbi::Pauthtest")
};assert!(target.cfg_abi == CfgAbi::Pauthtest);
136        return Self {
137            is_address_discriminated: PointerAuthAddressDiscriminator::HardwareAddress(false),
138            discrimination_kind: PointerAuthDiscrimination::None,
139            key: PointerAuthARM8_3Key::ASIA,
140            constant_discriminator: 0,
141        };
142    }
143    pub fn init_fini_default(target: &Target) -> Self {
144        if !(target.cfg_abi == CfgAbi::Pauthtest) {
    ::core::panicking::panic("assertion failed: target.cfg_abi == CfgAbi::Pauthtest")
};assert!(target.cfg_abi == CfgAbi::Pauthtest);
145        return Self {
146            is_address_discriminated: PointerAuthAddressDiscriminator::Synthetic(1),
147            discrimination_kind: PointerAuthDiscrimination::None,
148            key: PointerAuthARM8_3Key::ASIA,
149            // ptrauth_string_discriminator("init_fini")
150            constant_discriminator: 0xd9d4,
151        };
152    }
153}
154
155pub struct PointerAuthConfig {
156    /// Should return addresses be authenticated?
157    pub return_addresses: bool,
158    /// Do authentication failures cause a trap?
159    pub auth_traps: bool,
160    /// Do indirect goto label addresses need to be authenticated?
161    pub indirect_gotos: bool,
162    /// Should ELF GOT entries be signed?
163    pub elf_got: bool,
164    /// Use hardened lowering for jump-table dispatch?
165    pub aarch64_jump_table_hardening: bool,
166    /// The ABI for C function pointers.
167    pub function_pointers: Option<PointerAuthSchema>,
168    /// The ABI for function addresses in .init_array and .fini_array
169    pub init_fini: Option<PointerAuthSchema>,
170    /// Use of pointer authentication intrinsics.
171    pub intrinsics: bool,
172    /// The following are used only for compatibility with C++ and control over generated abi
173    /// version. They do not control Rust code generation.
174    pub typeinfo_vt_ptr_discrimination: bool,
175    pub vt_ptr_addr_discrimination: bool,
176    pub vt_ptr_type_discrimination: bool,
177}
178impl PointerAuthConfig {
179    fn default(target: &Target) -> Self {
180        if !(target.cfg_abi == CfgAbi::Pauthtest) {
    ::core::panicking::panic("assertion failed: target.cfg_abi == CfgAbi::Pauthtest")
};assert!(target.cfg_abi == CfgAbi::Pauthtest);
181        return Self {
182            return_addresses: true,
183            auth_traps: true,
184            indirect_gotos: true,
185            elf_got: false,
186            aarch64_jump_table_hardening: true,
187            function_pointers: Some(PointerAuthSchema::function_pointers_default(target)),
188            init_fini: Some(PointerAuthSchema::init_fini_default(target)),
189            intrinsics: true,
190            typeinfo_vt_ptr_discrimination: true,
191            vt_ptr_addr_discrimination: true,
192            vt_ptr_type_discrimination: true,
193        };
194    }
195    pub fn calculate_pauth_abi_version(&self, target: &Target) -> u32 {
196        if !(target.cfg_abi == CfgAbi::Pauthtest) {
    ::core::panicking::panic("assertion failed: target.cfg_abi == CfgAbi::Pauthtest")
};assert!(target.cfg_abi == CfgAbi::Pauthtest);
197        // Bit positions of version flags for AARCH64_PAUTH_PLATFORM_LLVM_LINUX.
198        // NOTE: The enum values must stay in sync with clang, see:
199        // <llvm_root>/llvm/include/llvm/BinaryFormat/ELF.h
200        //
201        // We do not expect to use C++ virtual dispatch, but enable these flags
202        // for compatibility with C++ code. Intrinsics are also always enabled.
203        //
204        // Link to PAuth core info documentation:
205        // <https://github.com/ARM-software/abi-aa/blob/2025Q4/pauthabielf64/pauthabielf64.rst#core-information>
206        const INTRINSICS: u32 = 0;
207        const CALLS: u32 = 1;
208        const RETURNS: u32 = 2;
209        const AUTHTRAPS: u32 = 3;
210        const VT_PTR_ADDR_DISCR: u32 = 4;
211        const VT_PTR_TYPE_DISCR: u32 = 5;
212        const INIT_FINI: u32 = 6;
213        const INIT_FINI_ADDR_DISC: u32 = 7;
214        const GOT: u32 = 8;
215        const GOTOS: u32 = 9;
216        const TYPEINFO_VT_PTR_DISCR: u32 = 10;
217        // FIXME(jchlanda) We don't yet support function pointer type discrimination.
218        // const FPTR_TYPE_DISCR: u32 = 11;
219
220        let pauth_abi_version: u32 = (u32::from(self.intrinsics) << INTRINSICS)
221            | (u32::from(self.function_pointers.is_some()) << CALLS)
222            | (u32::from(self.return_addresses) << RETURNS)
223            | (u32::from(self.auth_traps) << AUTHTRAPS)
224            | (u32::from(self.vt_ptr_addr_discrimination) << VT_PTR_ADDR_DISCR)
225            | (u32::from(self.vt_ptr_type_discrimination) << VT_PTR_TYPE_DISCR)
226            | (u32::from(self.init_fini.is_some()) << INIT_FINI)
227            | (u32::from(self.init_fini.as_ref().is_some_and(|schema| {
228                #[allow(non_exhaustive_omitted_patterns)] match schema.is_address_discriminated
    {
    PointerAuthAddressDiscriminator::HardwareAddress(true) |
        PointerAuthAddressDiscriminator::Synthetic(_) => true,
    _ => false,
}matches!(
229                    schema.is_address_discriminated,
230                    PointerAuthAddressDiscriminator::HardwareAddress(true)
231                        | PointerAuthAddressDiscriminator::Synthetic(_)
232                )
233            })) << INIT_FINI_ADDR_DISC)
234            | (u32::from(self.elf_got) << GOT)
235            | (u32::from(self.indirect_gotos) << GOTOS)
236            | (u32::from(self.typeinfo_vt_ptr_discrimination) << TYPEINFO_VT_PTR_DISCR);
237
238        pauth_abi_version
239    }
240    pub fn from_raw(raw: &[(PointerAuthOption, bool)], target: &Target) -> Option<Self> {
241        if target.cfg_abi != CfgAbi::Pauthtest {
242            return None;
243        }
244
245        let mut cfg = Self::default(target);
246        if raw.is_empty() {
247            return Some(cfg);
248        }
249
250        for (opt, enabled) in raw {
251            match opt {
252                PointerAuthOption::Calls => {
253                    if *enabled {
254                        cfg.function_pointers.get_or_insert_with(|| {
255                            PointerAuthSchema::function_pointers_default(target)
256                        });
257                    } else {
258                        cfg.function_pointers = None;
259                    }
260                }
261                PointerAuthOption::FunctionPointerTypeDiscrimination => {
262                    if *enabled {
263                        let schema = cfg.function_pointers.get_or_insert_with(|| {
264                            PointerAuthSchema::function_pointers_default(target)
265                        });
266                        schema.discrimination_kind = PointerAuthDiscrimination::Type;
267                    } else if let Some(schema) = &mut cfg.function_pointers {
268                        schema.discrimination_kind = PointerAuthDiscrimination::None;
269                    }
270                }
271                PointerAuthOption::ReturnAddresses => cfg.return_addresses = *enabled,
272                PointerAuthOption::AuthTraps => cfg.auth_traps = *enabled,
273                PointerAuthOption::IndirectGotos => cfg.indirect_gotos = *enabled,
274                PointerAuthOption::ElfGot => cfg.elf_got = *enabled,
275                PointerAuthOption::Aarch64JumpTableHardening => {
276                    cfg.aarch64_jump_table_hardening = *enabled
277                }
278                PointerAuthOption::InitFini => {
279                    if *enabled {
280                        cfg.init_fini
281                            .get_or_insert_with(|| PointerAuthSchema::init_fini_default(target));
282                    } else {
283                        cfg.init_fini = None;
284                    }
285                }
286                PointerAuthOption::InitFiniAddressDiscrimination => {
287                    if *enabled {
288                        let schema = cfg
289                            .init_fini
290                            .get_or_insert_with(|| PointerAuthSchema::init_fini_default(target));
291                        schema.is_address_discriminated =
292                            PointerAuthAddressDiscriminator::HardwareAddress(true);
293                    } else if let Some(schema) = &mut cfg.init_fini {
294                        schema.is_address_discriminated =
295                            PointerAuthAddressDiscriminator::Synthetic(1);
296                    }
297                }
298
299                PointerAuthOption::Intrinsics => cfg.intrinsics = *enabled,
300                PointerAuthOption::TypeInfoVTPtrDisc => {
301                    cfg.typeinfo_vt_ptr_discrimination = *enabled
302                }
303                PointerAuthOption::VTPtrAddrDisc => cfg.vt_ptr_addr_discrimination = *enabled,
304                PointerAuthOption::VTPtrTypeDisc => cfg.vt_ptr_type_discrimination = *enabled,
305            }
306        }
307
308        Some(cfg)
309    }
310    pub fn fn_attrs(&self) -> Vec<&'static str> {
311        // FIXME(jchlanda) This is not an exhaustive list of all `ptrauth`-related attributes, but only
312        // those currently supported. The list is expected to grow as additional functionality is
313        // implemented, particularly for C++ interoperability.
314        let mut attrs = ::alloc::vec::Vec::new()vec![];
315        if self.aarch64_jump_table_hardening {
316            attrs.push("aarch64-jump-table-hardening");
317        }
318        if self.auth_traps {
319            attrs.push("ptrauth-auth-traps");
320        }
321        if self.function_pointers.is_some() {
322            attrs.push("ptrauth-calls");
323        }
324        if self.indirect_gotos {
325            attrs.push("ptrauth-indirect-gotos");
326        }
327        if self.return_addresses {
328            attrs.push("ptrauth-returns");
329        }
330
331        attrs
332    }
333}
334
335/// Partial session built before the full session. More specifically, `EarlySession` is used to
336/// init the codegen backend, and then both pieces are used to build the full `Session`.
337pub struct EarlySession {
338    pub target: Target,
339    pub host: Target,
340    pub opts: config::Options,
341    pub psess: ParseSess,
342}
343
344// JUSTIFICATION: defn of the suggested wrapper fns
345#[allow(rustc::bad_opt_access)]
346impl EarlySession {
347    #[inline]
348    pub fn dcx(&self) -> DiagCtxtHandle<'_> {
349        self.psess.dcx()
350    }
351
352    #[inline]
353    pub fn source_map(&self) -> &SourceMap {
354        self.psess.source_map()
355    }
356
357    /// Note: this is simpler than `Session::lto`, hence the `early_` prefix (to more clearly
358    /// distinguish it).
359    pub fn early_lto(&self) -> LtoCli {
360        self.opts.cg.lto
361    }
362
363    pub fn print_llvm_stats(&self) -> bool {
364        self.opts.unstable_opts.print_codegen_stats
365    }
366
367    pub fn print_llvm_stats_json(&self) -> Option<&String> {
368        self.opts.unstable_opts.print_codegen_stats_json.as_ref()
369    }
370
371    pub fn relocation_model(&self) -> RelocModel {
372        self.opts.cg.relocation_model.unwrap_or(self.target.relocation_model)
373    }
374
375    pub fn code_model(&self) -> Option<CodeModel> {
376        self.opts.cg.code_model.or(self.target.code_model)
377    }
378
379    pub fn tls_model(&self) -> TlsModel {
380        self.opts.unstable_opts.tls_model.unwrap_or(self.target.tls_model)
381    }
382
383    /// Returns the panic strategy for this compile session. If the user explicitly selected one
384    /// using '-C panic', use that, otherwise use the panic strategy defined by the target.
385    pub fn panic_strategy(&self) -> PanicStrategy {
386        self.opts.cg.panic.unwrap_or(self.target.panic_strategy)
387    }
388
389    /// Get the deployment target on Apple platforms based on the standard environment variables,
390    /// or fall back to the minimum version supported by `rustc`.
391    ///
392    /// This should be guarded behind `if sess.target.is_like_darwin`.
393    pub fn apple_deployment_target(&self) -> apple::OSVersion {
394        let min = apple::OSVersion::minimum_deployment_target(&self.target);
395        let env_var = apple::deployment_target_env_var(&self.target.os);
396
397        // FIXME(madsmtm): Track changes to this.
398        if let Ok(deployment_target) = env::var(env_var) {
399            match apple::OSVersion::from_str(&deployment_target) {
400                Ok(version) => {
401                    let os_min = apple::OSVersion::os_minimum_deployment_target(&self.target.os);
402                    // It is common that the deployment target is set a bit too low, for example on
403                    // macOS Aarch64 to also target older x86_64. So we only want to warn when
404                    // variable is lower than the minimum OS supported by rustc, not when the
405                    // variable is lower than the minimum for a specific target.
406                    if version < os_min {
407                        self.dcx().emit_warn(diagnostics::AppleDeploymentTarget::TooLow {
408                            env_var,
409                            version: version.fmt_pretty().to_string(),
410                            os_min: os_min.fmt_pretty().to_string(),
411                        });
412                    }
413
414                    // Raise the deployment target to the minimum supported.
415                    version.max(min)
416                }
417                Err(error) => {
418                    self.dcx()
419                        .emit_err(diagnostics::AppleDeploymentTarget::Invalid { env_var, error });
420                    min
421                }
422            }
423        } else {
424            // If no deployment target variable is set, default to the minimum found above.
425            min
426        }
427    }
428
429    pub fn sanitizers(&self) -> SanitizerSet {
430        self.opts
431            .unstable_opts
432            .sanitizer
433            .combine_with_defaults(self.target.options.default_sanitizers)
434    }
435
436    pub fn merge_functions(&self) -> MergeFunctions {
437        self.opts.unstable_opts.merge_functions.unwrap_or(self.target.merge_functions)
438    }
439
440    pub fn is_nightly_build(&self) -> bool {
441        self.opts.unstable_features.is_nightly_build()
442    }
443}
444
445/// Some info about the backend, returned by `CodegenBackend::init` and put into the `Session`.
446#[derive(#[automatically_derived]impl ::core::default::Default for CodegenBackendInit {
    #[inline]
    fn default() -> Self {
        CodegenBackendInit {
            global_backend_features: ::core::default::Default::default(),
            replaced_rustc_intrinsics: ::core::default::Default::default(),
            fallback_rustc_intrinsics: ::core::default::Default::default(),
            thin_lto_supported: const true,
        }
    }
}Default)]
447pub struct CodegenBackendInit {
448    /// See `Session::global_backend_features`.
449    pub global_backend_features: Vec<String>,
450
451    /// See `Session::replaced_intrinsics`.
452    pub replaced_rustc_intrinsics: Vec<Symbol>,
453
454    /// See `Session::fallback_intrinsics`.
455    pub fallback_rustc_intrinsics: Vec<Symbol>,
456
457    /// See `Session::thin_lto_supported`.
458    pub thin_lto_supported: bool = true,
459}
460
461/// Represents the data associated with a compilation
462/// session for a single crate.
463pub struct Session {
464    /// The `EarlySession` is embedded so it can be passed to functions that need it.
465    /// `Session::deref{_,mut}` exist so the fields within can be accessed as if they were direct
466    /// fields of `Session`.
467    pub early_sess: EarlySession,
468    pub wasm_proc_macro_tuple: TargetTuple,
469    pub wasm_proc_macro_target: Target,
470    pub target_tlib_path: SearchPath,
471    pub unstable_features: UnstableFeatures,
472    pub config: Cfg,
473    pub check_config: CheckCfg,
474    /// Spans passed to `proc_macro::quote_span`. Each span has a numerical
475    /// identifier represented by its position in the vector.
476    proc_macro_quoted_spans: AppendOnlyVec<Span>,
477
478    /// Input, input file path and output file path to this compilation process.
479    pub io: CompilerIO,
480
481    /// Used by `-Z self-profile`.
482    pub prof: SelfProfilerRef,
483
484    /// Used to emit section timings events (enabled by `--json=timings`).
485    pub timings: TimingSectionHandler,
486
487    /// Data about code being compiled, gathered during compilation.
488    pub code_stats: CodeStats,
489
490    /// This only ever stores a `LintStore` but we don't want a dependency on that type here.
491    pub lint_store: Option<Arc<dyn DynLintStore>>,
492
493    /// Cap lint level specified by a driver specifically.
494    pub driver_lint_caps: FxHashMap<lint::LintId, lint::Level>,
495
496    /// Tracks the current behavior of the CTFE engine when an error occurs.
497    /// Options range from returning the error without a backtrace to returning an error
498    /// and immediately printing the backtrace to stderr.
499    /// The `Lock` is only used by miri to allow setting `ctfe_backtrace` after analysis when
500    /// `MIRI_BACKTRACE` is set. This makes it only apply to miri's errors and not to all CTFE
501    /// errors.
502    pub ctfe_backtrace: Lock<CtfeBacktrace>,
503
504    /// This tracks where `-Zunleash-the-miri-inside-of-you` was used to get around a
505    /// const check, optionally with the relevant feature gate. We use this to
506    /// warn about unleashing, but with a single diagnostic instead of dozens that
507    /// drown everything else in noise.
508    miri_unleashed_features: Lock<Vec<(Span, Option<Symbol>)>>,
509
510    /// Architecture to use for interpreting asm!.
511    pub asm_arch: Option<InlineAsmArch>,
512
513    /// Set of actually enabled features for the current target, including ones that are not
514    /// in `cfg(target_feature)` because they are unstable or internal-only.
515    /// This is used by the compiler itself when it needs to know which target features are actually
516    /// going to be enabled in the backend (e.g. for knowing which registers inline asm can use).
517    pub internal_target_features: FxIndexSet<Symbol>,
518
519    /// The list of backend target features for this session. Not used by Rust itself because the
520    /// concrete feature names can be backend-specific. This is computed from the target's base
521    /// features, `-Ctarget-cpu`, `-Ctarget-feature`, and other flags that the current backend
522    /// models as target features (but that are not considered target features in Rust).
523    pub global_backend_features: Vec<String>,
524
525    /// The version of the rustc process, possibly including a commit hash and description.
526    pub cfg_version: &'static str,
527
528    /// The inner atomic value is set to true when a feature marked as `internal` is
529    /// enabled. Makes it so that "please report a bug" is hidden, as ICEs with
530    /// internal features are wontfix, and they are usually the cause of the ICEs.
531    /// None signifies that this is not tracked.
532    pub using_internal_features: &'static AtomicBool,
533
534    /// Environment variables accessed during the build and their values when they exist.
535    pub env_depinfo: Lock<FxIndexSet<(Symbol, Option<Symbol>)>>,
536
537    /// File paths accessed during the build.
538    pub file_depinfo: Lock<FxIndexSet<Symbol>>,
539
540    target_filesearch: Arc<FileSearch>,
541    host_filesearch: Arc<FileSearch>,
542    wasm_proc_macro_filesearch: Option<Arc<FileSearch>>,
543
544    /// A list of all intrinsics that the current codegen backend definitely replaces with its own
545    /// implementations, which means their fallback bodies do not need to be monomorphized.
546    pub replaced_rustc_intrinsics: FxHashSet<Symbol>,
547
548    /// A list of all intrinsics that the current codegen backend definitely does *not* replace
549    /// with its own implementations, which means their fallback bodies can be MIR-inlined.
550    pub fallback_rustc_intrinsics: FxHashSet<Symbol>,
551
552    /// Does the codegen backend support ThinLTO?
553    pub thin_lto_supported: bool,
554
555    /// Global per-session counter for MIR optimization pass applications.
556    ///
557    /// Used by `-Zmir-opt-bisect-limit` to assign an index to each
558    /// optimization-pass execution candidate during this compilation.
559    pub mir_opt_bisect_eval_count: AtomicUsize,
560
561    /// Whether the test harness removed a user-written `#[rustc_main]` attribute
562    /// while generating the synthetic test entry point.
563    pub removed_rustc_main_attr: AtomicBool,
564
565    /// Config specifying targets' pointer authentication preference.
566    pub pointer_auth_config: Option<PointerAuthConfig>,
567
568    /// Cached sanitizer set. Cached because it is accessed frequently.
569    sanitizers: SanitizerSet,
570}
571
572impl Deref for Session {
573    type Target = EarlySession;
574
575    fn deref(&self) -> &EarlySession {
576        &self.early_sess
577    }
578}
579
580impl DerefMut for Session {
581    fn deref_mut(&mut self) -> &mut EarlySession {
582        &mut self.early_sess
583    }
584}
585
586#[derive(#[automatically_derived]#[doc(hidden)]unsafe impl ::core::clone::TrivialClone
    for CodegenUnits {
}
#[automatically_derived]impl ::core::clone::Clone for CodegenUnits {
    #[inline]
    #[rustc_trivial_field_reads]
    fn clone(&self) -> Self {
        let _: ::core::clone::AssertParamIsClone<usize>;
        *self
    }
}Clone, #[automatically_derived]impl ::core::marker::Copy for CodegenUnits { }Copy)]
587pub enum CodegenUnits {
588    /// Specified by the user. In this case we try fairly hard to produce the
589    /// number of CGUs requested.
590    User(usize),
591
592    /// A default value, i.e. not specified by the user. In this case we take
593    /// more liberties about CGU formation, e.g. avoid producing very small
594    /// CGUs.
595    Default(usize),
596}
597
598impl CodegenUnits {
599    pub fn as_usize(self) -> usize {
600        match self {
601            CodegenUnits::User(n) => n,
602            CodegenUnits::Default(n) => n,
603        }
604    }
605}
606
607pub struct LintGroup {
608    pub name: LintName,
609    pub lints: Vec<LintId>,
610    pub is_externally_loaded: bool,
611}
612
613impl Session {
614    pub fn miri_unleashed_feature(&self, span: Span, feature_gate: Option<Symbol>) {
615        self.miri_unleashed_features.lock().push((span, feature_gate));
616    }
617
618    pub fn local_crate_source_file(&self) -> Option<RealFileName> {
619        Some(
620            self.source_map()
621                .path_mapping()
622                .to_real_filename(self.source_map().working_dir(), self.io.input.opt_path()?),
623        )
624    }
625
626    fn check_miri_unleashed_features(&self) -> Option<ErrorGuaranteed> {
627        let mut guar = None;
628        let unleashed_features = self.miri_unleashed_features.lock();
629        if !unleashed_features.is_empty() {
630            let mut must_err = false;
631            // Create a diagnostic pointing at where things got unleashed.
632            self.dcx().emit_warn(diagnostics::SkippingConstChecks {
633                unleashed_features: unleashed_features
634                    .iter()
635                    .map(|(span, gate)| {
636                        gate.map(|gate| {
637                            must_err = true;
638                            diagnostics::UnleashedFeatureHelp::Named { span: *span, gate }
639                        })
640                        .unwrap_or(diagnostics::UnleashedFeatureHelp::Unnamed { span: *span })
641                    })
642                    .collect(),
643            });
644
645            // If we should err, make sure we did.
646            if must_err && self.dcx().has_errors().is_none() {
647                // We have skipped a feature gate, and not run into other errors... reject.
648                guar = Some(self.dcx().emit_err(diagnostics::NotCircumventFeature));
649            }
650        }
651        guar
652    }
653
654    /// Invoked all the way at the end to finish off diagnostics printing.
655    pub fn finish_diagnostics(&self) -> Option<ErrorGuaranteed> {
656        let mut guar = None;
657        guar = guar.or(self.check_miri_unleashed_features());
658        guar = guar.or(self.dcx().emit_stashed_diagnostics());
659        self.dcx().print_error_count();
660        if self.opts.json_future_incompat {
661            self.dcx().emit_future_breakage_report();
662        }
663        guar
664    }
665
666    /// Returns true if the crate is a testing one.
667    pub fn is_test_crate(&self) -> bool {
668        self.opts.test
669    }
670
671    /// `feature` must be a language feature.
672    #[track_caller]
673    pub fn create_feature_err<'a>(&'a self, err: impl Diagnostic<'a>, feature: Symbol) -> Diag<'a> {
674        let mut err = self.dcx().create_err(err);
675        if err.code.is_none() {
676            err.code(E0658);
677        }
678        diagnostics::add_feature_diagnostics(&mut err, self, feature);
679        err
680    }
681
682    /// Record the fact that we called `trimmed_def_paths`, and do some
683    /// checking about whether its cost was justified.
684    pub fn record_trimmed_def_paths(&self) {
685        if self.opts.unstable_opts.print_type_sizes
686            || self.opts.unstable_opts.query_dep_graph
687            || self.opts.unstable_opts.dump_mir.is_some()
688            || self.opts.unstable_opts.unpretty.is_some()
689            || self.prof.is_args_recording_enabled()
690            || self.opts.output_types.contains_key(&OutputType::Mir)
691            || std::env::var_os("RUSTC_LOG").is_some()
692        {
693            return;
694        }
695
696        self.dcx().set_must_produce_diag()
697    }
698
699    pub fn proc_macro_quoted_spans(&self) -> impl Iterator<Item = (usize, Span)> {
700        // This is equivalent to `.iter().copied().enumerate()`, but that isn't possible for
701        // AppendOnlyVec, so we resort to this scheme.
702        self.proc_macro_quoted_spans.iter_enumerated()
703    }
704
705    pub fn save_proc_macro_span(&self, span: Span) -> usize {
706        self.proc_macro_quoted_spans.push(span)
707    }
708
709    /// Returns `true` if internal lints should be added to the lint store - i.e. if
710    /// `-Zunstable-options` is provided and this isn't rustdoc (internal lints can trigger errors
711    /// to be emitted under rustdoc).
712    pub fn enable_internal_lints(&self) -> bool {
713        self.unstable_options() && !self.opts.actually_rustdoc
714    }
715
716    pub fn instrument_coverage(&self) -> bool {
717        self.opts.cg.instrument_coverage() != InstrumentCoverage::No
718    }
719
720    pub fn instrument_coverage_branch(&self) -> bool {
721        self.instrument_coverage()
722            && self.opts.unstable_opts.coverage_options.level >= CoverageLevel::Branch
723    }
724
725    pub fn instrument_coverage_condition(&self) -> bool {
726        self.instrument_coverage()
727            && self.opts.unstable_opts.coverage_options.level >= CoverageLevel::Condition
728    }
729
730    /// Provides direct access to the `CoverageOptions` struct, so that
731    /// individual flags for debugging/testing coverage instrumetation don't
732    /// need separate accessors.
733    pub fn coverage_options(&self) -> &CoverageOptions {
734        &self.opts.unstable_opts.coverage_options
735    }
736
737    pub fn is_sanitizer_cfi_enabled(&self) -> bool {
738        self.sanitizers().contains(SanitizerSet::CFI)
739    }
740
741    pub fn is_sanitizer_cfi_canonical_jump_tables_disabled(&self) -> bool {
742        self.opts.unstable_opts.sanitizer_cfi_canonical_jump_tables == Some(false)
743    }
744
745    pub fn is_sanitizer_cfi_canonical_jump_tables_enabled(&self) -> bool {
746        self.opts.unstable_opts.sanitizer_cfi_canonical_jump_tables == Some(true)
747    }
748
749    pub fn is_sanitizer_cfi_generalize_pointers_enabled(&self) -> bool {
750        self.opts.unstable_opts.sanitizer_cfi_generalize_pointers == Some(true)
751    }
752
753    pub fn is_sanitizer_cfi_normalize_integers_enabled(&self) -> bool {
754        self.opts.unstable_opts.sanitizer_cfi_normalize_integers == Some(true)
755    }
756
757    pub fn is_sanitizer_cfi_recover_enabled(&self) -> bool {
758        self.opts.unstable_opts.sanitizer_cfi_recover == Some(true)
759    }
760
761    pub fn is_sanitizer_cfi_diag_enabled(&self) -> bool {
762        self.opts.unstable_opts.sanitizer_cfi_diag == Some(true)
763    }
764
765    pub fn is_sanitizer_cfi_minimal_runtime_enabled(&self) -> bool {
766        self.opts.unstable_opts.sanitizer_cfi_minimal_runtime == Some(true)
767    }
768
769    pub fn is_sanitizer_kcfi_arity_enabled(&self) -> bool {
770        self.opts.unstable_opts.sanitizer_kcfi_arity == Some(true)
771    }
772
773    pub fn is_sanitizer_kcfi_enabled(&self) -> bool {
774        self.sanitizers().contains(SanitizerSet::KCFI)
775    }
776
777    pub fn is_split_lto_unit_enabled(&self) -> bool {
778        self.opts.unstable_opts.split_lto_unit == Some(true)
779    }
780
781    /// Check whether this compile session and crate type use static crt.
782    pub fn crt_static(&self, crate_type: Option<CrateType>) -> bool {
783        if !self.target.crt_static_respected {
784            // If the target does not opt in to crt-static support, use its default.
785            return self.target.crt_static_default;
786        }
787
788        let requested_features = self.opts.cg.target_feature.split(',');
789        let found_negative = requested_features.clone().any(|r| r == "-crt-static");
790        let found_positive = requested_features.clone().any(|r| r == "+crt-static");
791
792        // JUSTIFICATION: necessary use of crate_types directly (see FIXME below)
793        #[allow(rustc::bad_opt_access)]
794        if found_positive || found_negative {
795            found_positive
796        } else if crate_type == Some(CrateType::ProcMacro)
797            || crate_type == None && self.opts.crate_types.contains(&CrateType::ProcMacro)
798        {
799            // FIXME: When crate_type is not available,
800            // we use compiler options to determine the crate_type.
801            // We can't check `#![crate_type = "proc-macro"]` here.
802            false
803        } else {
804            self.target.crt_static_default
805        }
806    }
807
808    pub fn is_wasi_reactor(&self) -> bool {
809        self.target.options.os == Os::Wasi
810            && #[allow(non_exhaustive_omitted_patterns)] match self.opts.unstable_opts.wasi_exec_model
    {
    Some(config::WasiExecModel::Reactor) => true,
    _ => false,
}matches!(
811                self.opts.unstable_opts.wasi_exec_model,
812                Some(config::WasiExecModel::Reactor)
813            )
814    }
815
816    /// Returns `true` if the target can use the current split debuginfo configuration.
817    pub fn target_can_use_split_dwarf(&self) -> bool {
818        self.target.debuginfo_kind == DebuginfoKind::Dwarf
819    }
820
821    pub fn target_filesearch(&self) -> &filesearch::FileSearch {
822        &self.target_filesearch
823    }
824    pub fn host_filesearch(&self) -> &filesearch::FileSearch {
825        &self.host_filesearch
826    }
827    pub fn wasm_proc_macro_filesearch(&self) -> &filesearch::FileSearch {
828        self.wasm_proc_macro_filesearch.as_ref().expect("wasm_filesearch not set")
829    }
830
831    /// Returns a list of directories where target-specific tool binaries are located. Some fallback
832    /// directories are also returned, for example if `--sysroot` is used but tools are missing
833    /// (#125246): we also add the bin directories to the sysroot where rustc is located.
834    pub fn get_tools_search_paths(&self, self_contained: bool) -> Vec<PathBuf> {
835        let search_paths = self
836            .opts
837            .sysroot
838            .all_paths()
839            .map(|sysroot| filesearch::make_target_bin_path(&sysroot, config::host_tuple()));
840
841        if self_contained {
842            // The self-contained tools are expected to be e.g. in `bin/self-contained` in the
843            // sysroot's `rustlib` path, so we add such a subfolder to the bin path, and the
844            // fallback paths.
845            search_paths.flat_map(|path| [path.clone(), path.join("self-contained")]).collect()
846        } else {
847            search_paths.collect()
848        }
849    }
850
851    /// Is this edition 2015?
852    pub fn is_rust_2015(&self) -> bool {
853        self.edition().is_rust_2015()
854    }
855
856    /// Are we allowed to use features from the Rust 2018 edition?
857    pub fn at_least_rust_2018(&self) -> bool {
858        self.edition().at_least_rust_2018()
859    }
860
861    /// Are we allowed to use features from the Rust 2021 edition?
862    pub fn at_least_rust_2021(&self) -> bool {
863        self.edition().at_least_rust_2021()
864    }
865
866    /// Are we allowed to use features from the Rust 2024 edition?
867    pub fn at_least_rust_2024(&self) -> bool {
868        self.edition().at_least_rust_2024()
869    }
870
871    /// Returns `true` if we should use the PLT for shared library calls.
872    pub fn needs_plt(&self) -> bool {
873        // Check if the current target usually wants PLT to be enabled.
874        // The user can use the command line flag to override it.
875        let want_plt = self.target.plt_by_default;
876
877        let dbg_opts = &self.opts.unstable_opts;
878
879        let relro_level = self.opts.cg.relro_level.unwrap_or(self.target.relro_level);
880
881        // Only enable this optimization by default if full relro is also enabled.
882        // In this case, lazy binding was already unavailable, so nothing is lost.
883        // This also ensures `-Wl,-z,now` is supported by the linker.
884        let full_relro = RelroLevel::Full == relro_level;
885
886        // If user didn't explicitly forced us to use / skip the PLT,
887        // then use it unless the target doesn't want it by default or the full relro forces it on.
888        dbg_opts.plt.unwrap_or(want_plt || !full_relro)
889    }
890
891    /// Checks if LLVM lifetime markers should be emitted.
892    pub fn emit_lifetime_markers(&self) -> bool {
893        self.opts.optimize != config::OptLevel::No
894        // AddressSanitizer and KernelAddressSanitizer uses lifetimes to detect use after scope bugs.
895        //
896        // MemorySanitizer uses lifetimes to detect use of uninitialized stack variables.
897        //
898        // HWAddressSanitizer and KernelHWAddressSanitizer will use lifetimes to detect use after
899        // scope bugs in the future.
900        || self.sanitizers().intersects(SanitizerSet::ADDRESS | SanitizerSet::KERNELADDRESS | SanitizerSet::MEMORY | SanitizerSet::HWADDRESS | SanitizerSet::KERNELHWADDRESS)
901        // Lifetimes are necessary for retagging semantics.
902        || self.opts.unstable_opts.codegen_emit_retag.is_some()
903    }
904
905    pub fn diagnostic_width(&self) -> usize {
906        let default_column_width = 140;
907        if let Some(width) = self.opts.diagnostic_width {
908            width
909        } else if self.opts.unstable_opts.ui_testing {
910            default_column_width
911        } else {
912            termize::dimensions().map_or(default_column_width, |(w, _)| w)
913        }
914    }
915
916    /// Returns the default symbol visibility.
917    pub fn default_visibility(&self) -> SymbolVisibility {
918        self.opts
919            .unstable_opts
920            .default_visibility
921            .or(self.target.options.default_visibility)
922            .unwrap_or(SymbolVisibility::Interposable)
923    }
924
925    pub fn staticlib_components(&self, verbatim: bool) -> (&str, &str) {
926        if verbatim {
927            ("", "")
928        } else {
929            (&*self.target.staticlib_prefix, &*self.target.staticlib_suffix)
930        }
931    }
932
933    pub fn lint_groups_iter(&self) -> Box<dyn Iterator<Item = LintGroup> + '_> {
934        match self.lint_store {
935            Some(ref lint_store) => lint_store.lint_groups_iter(),
936            None => Box::new(std::iter::empty()),
937        }
938    }
939
940    /// Resolves a `path` mentioned inside Rust code, returning an absolute path.
941    ///
942    /// This unifies the logic used for resolving `include_*!` and debugger visualizers.
943    pub fn resolve_path(&self, path: impl Into<PathBuf>, span: Span) -> PResult<'_, PathBuf> {
944        let path = path.into();
945
946        // Relative paths are resolved relative to the file in which they are found
947        // after macro expansion (that is, they are unhygienic).
948        if !path.is_absolute() {
949            let callsite = span.source_callsite();
950            let source_map = self.source_map();
951            let Some(mut base_path) = source_map.span_to_filename(callsite).into_local_path()
952            else {
953                return Err(self.dcx().create_err(diagnostics::ResolveRelativePath {
954                    span,
955                    path: source_map
956                        .filename_for_diagnostics(&source_map.span_to_filename(callsite))
957                        .to_string(),
958                }));
959            };
960            base_path.pop();
961            base_path.push(path);
962            Ok(base_path)
963        } else {
964            // This ensures that Windows verbatim paths are fixed if mixed path separators are used,
965            // which can happen when `concat!` is used to join paths.
966            match path.components().next() {
967                Some(Prefix(prefix)) if prefix.kind().is_verbatim() => {
968                    Ok(path.components().collect())
969                }
970                _ => Ok(path),
971            }
972        }
973    }
974
975    /// Should metadata be embedded within .rlib and .dylib files?
976    pub fn embed_metadata(&self) -> bool {
977        self.opts.cg.embed_metadata.or(self.opts.unstable_opts.embed_metadata).unwrap_or(true)
978    }
979}
980
981// JUSTIFICATION: defn of the suggested wrapper fns
982#[allow(rustc::bad_opt_access)]
983impl Session {
984    pub fn verbose_internals(&self) -> bool {
985        self.opts.unstable_opts.verbose_internals
986    }
987
988    pub fn verify_llvm_ir(&self) -> bool {
989        self.opts.unstable_opts.verify_llvm_ir || ::core::option::Option::None::<&'static str>option_env!("RUSTC_VERIFY_LLVM_IR").is_some()
990    }
991
992    pub fn binary_dep_depinfo(&self) -> bool {
993        self.opts.unstable_opts.binary_dep_depinfo
994    }
995
996    pub fn mir_opt_level(&self) -> usize {
997        self.opts.unstable_opts.mir_opt_level.unwrap_or_else(|| self.opts.optimize.mir_opt_level())
998    }
999
1000    /// What this compilation optimizes for; see [`config::OptimizationObjective`].
1001    pub fn optimization_objective(&self) -> config::OptimizationObjective {
1002        self.opts.optimize.objective()
1003    }
1004
1005    /// Calculates the flavor of LTO to use for this compilation.
1006    pub fn lto(&self) -> config::Lto {
1007        // If our target has codegen requirements ignore the command line
1008        if self.target.requires_lto {
1009            return config::Lto::Fat;
1010        }
1011
1012        // If the user specified something, return that. If they only said `-C
1013        // lto` and we've for whatever reason forced off ThinLTO via the CLI,
1014        // then ensure we can't use a ThinLTO.
1015        match self.opts.cg.lto {
1016            config::LtoCli::Unspecified => {
1017                // The compiler was invoked without the `-Clto` flag. Fall
1018                // through to the default handling
1019            }
1020            config::LtoCli::No => {
1021                // The user explicitly opted out of any kind of LTO
1022                return config::Lto::No;
1023            }
1024            config::LtoCli::Yes | config::LtoCli::Fat | config::LtoCli::NoParam => {
1025                // All of these mean fat LTO
1026                return config::Lto::Fat;
1027            }
1028            config::LtoCli::Thin => {
1029                // The user explicitly asked for ThinLTO
1030                if !self.thin_lto_supported {
1031                    // Backend doesn't support ThinLTO, fallback to fat LTO.
1032                    self.dcx().emit_warn(diagnostics::ThinLtoNotSupportedByBackend);
1033                    return config::Lto::Fat;
1034                }
1035                return config::Lto::Thin;
1036            }
1037        }
1038
1039        if !self.thin_lto_supported {
1040            return config::Lto::No;
1041        }
1042
1043        // Ok at this point the target doesn't require anything and the user
1044        // hasn't asked for anything. Our next decision is whether or not
1045        // we enable "auto" ThinLTO where we use multiple codegen units and
1046        // then do ThinLTO over those codegen units. The logic below will
1047        // either return `No` or `ThinLocal`.
1048
1049        // If processing command line options determined that we're incompatible
1050        // with ThinLTO (e.g., `-C lto --emit llvm-ir`) then return that option.
1051        if self.opts.cli_forced_local_thinlto_off {
1052            return config::Lto::No;
1053        }
1054
1055        // If `-Z thinlto` specified process that, but note that this is mostly
1056        // a deprecated option now that `-C lto=thin` exists.
1057        if let Some(enabled) = self.opts.unstable_opts.thinlto {
1058            if enabled {
1059                return config::Lto::ThinLocal;
1060            } else {
1061                return config::Lto::No;
1062            }
1063        }
1064
1065        // If there's only one codegen unit and LTO isn't enabled then there's
1066        // no need for ThinLTO so just return false.
1067        if self.codegen_units().as_usize() == 1 {
1068            return config::Lto::No;
1069        }
1070
1071        // Now we're in "defaults" territory. By default we enable ThinLTO for
1072        // optimized compiles (anything greater than O0).
1073        match self.opts.optimize {
1074            config::OptLevel::No => config::Lto::No,
1075            _ => config::Lto::ThinLocal,
1076        }
1077    }
1078
1079    pub fn fewer_names(&self) -> bool {
1080        if let Some(fewer_names) = self.opts.unstable_opts.fewer_names {
1081            fewer_names
1082        } else {
1083            let more_names = self.opts.output_types.contains_key(&OutputType::LlvmAssembly)
1084                || self.opts.output_types.contains_key(&OutputType::Bitcode)
1085                // AddressSanitizer and MemorySanitizer use alloca name when reporting an issue.
1086                || self.sanitizers().intersects(SanitizerSet::ADDRESS | SanitizerSet::MEMORY);
1087            !more_names
1088        }
1089    }
1090
1091    pub fn unstable_options(&self) -> bool {
1092        self.opts.unstable_opts.unstable_options
1093    }
1094
1095    pub fn is_nightly_build(&self) -> bool {
1096        self.opts.unstable_features.is_nightly_build()
1097    }
1098
1099    pub fn overflow_checks(&self) -> bool {
1100        self.opts.cg.overflow_checks.unwrap_or(self.opts.debug_assertions)
1101    }
1102
1103    pub fn ub_checks(&self) -> bool {
1104        self.opts.unstable_opts.ub_checks.unwrap_or(self.opts.debug_assertions)
1105    }
1106
1107    pub fn contract_checks(&self) -> bool {
1108        self.opts.unstable_opts.contract_checks.unwrap_or(false)
1109    }
1110
1111    pub fn direct_access_external_data(&self) -> Option<bool> {
1112        self.opts
1113            .unstable_opts
1114            .direct_access_external_data
1115            .or(self.target.direct_access_external_data)
1116    }
1117
1118    pub fn split_debuginfo(&self) -> SplitDebuginfo {
1119        self.opts.cg.split_debuginfo.unwrap_or(self.target.split_debuginfo)
1120    }
1121
1122    /// Returns the DWARF version passed on the CLI or the default for the target.
1123    pub fn dwarf_version(&self) -> u32 {
1124        self.opts
1125            .cg
1126            .dwarf_version
1127            .or(self.opts.unstable_opts.dwarf_version)
1128            .unwrap_or(self.target.default_dwarf_version)
1129    }
1130
1131    pub fn stack_protector(&self) -> StackProtector {
1132        if self.target.options.supports_stack_protector {
1133            self.opts.unstable_opts.stack_protector
1134        } else {
1135            StackProtector::None
1136        }
1137    }
1138
1139    /// Returns the `-Zbranch-protection` info. Note that it is adjusted to the current target, e.g.
1140    /// some targets only support certain Pointer Authentication Code keys.
1141    ///
1142    /// Accessing the session's unstable `branch_protection` option fields directly is linted
1143    /// against.
1144    pub fn branch_protection(&self) -> Option<BranchProtection> {
1145        let mut bp = self.opts.unstable_opts.branch_protection;
1146
1147        if let Some(bp) = bp.as_mut() {
1148            // Windows on Arm only supports PAC Key B for return address signing, as shown in
1149            // https://github.com/llvm/llvm-project/pull/203989. We parse the CLI flags for branch
1150            // protection and target separately though, so we adjust this possible discrepancy here.
1151            if self.target.os == Os::Windows && self.target.arch == Arch::AArch64 {
1152                if let Some(pac_ret) = bp.pac_ret.as_mut()
1153                    && pac_ret.key == PAuthKey::A
1154                {
1155                    pac_ret.key = PAuthKey::B;
1156                }
1157            }
1158        }
1159
1160        bp
1161    }
1162
1163    pub fn must_emit_unwind_tables(&self) -> bool {
1164        // This is used to control the emission of the `uwtable` attribute on
1165        // LLVM functions. The `uwtable` attribute according to LLVM is:
1166        //
1167        //     This attribute indicates that the ABI being targeted requires that an
1168        //     unwind table entry be produced for this function even if we can show
1169        //     that no exceptions passes by it. This is normally the case for the
1170        //     ELF x86-64 abi, but it can be disabled for some compilation units.
1171        //
1172        // Typically when we're compiling with `-C panic=abort` we don't need
1173        // `uwtable` because we can't generate any exceptions! But note that
1174        // some targets require unwind tables to generate backtraces.
1175        // Unwind tables are needed when compiling with `-C panic=unwind`, but
1176        // LLVM won't omit unwind tables unless the function is also marked as
1177        // `nounwind`, so users are allowed to disable `uwtable` emission.
1178        // Historically rustc always emits `uwtable` attributes by default, so
1179        // even they can be disabled, they're still emitted by default.
1180        //
1181        // On some targets (including windows), however, exceptions include
1182        // other events such as illegal instructions, segfaults, etc. This means
1183        // that on Windows we end up still needing unwind tables even if the `-C
1184        // panic=abort` flag is passed.
1185        //
1186        // You can also find more info on why Windows needs unwind tables in:
1187        //      https://bugzilla.mozilla.org/show_bug.cgi?id=1302078
1188        //
1189        // If a target requires unwind tables, then they must be emitted.
1190        // Otherwise, we can defer to the `-C force-unwind-tables=<yes/no>`
1191        // value, if it is provided, or disable them, if not.
1192        self.target.requires_uwtable
1193            || self
1194                .opts
1195                .cg
1196                .force_unwind_tables
1197                .unwrap_or(self.panic_strategy().unwinds() || self.target.default_uwtable)
1198    }
1199
1200    /// Returns the number of codegen units that should be used for this
1201    /// compilation
1202    pub fn codegen_units(&self) -> CodegenUnits {
1203        if let Some(n) = self.opts.cli_forced_codegen_units {
1204            return CodegenUnits::User(n);
1205        }
1206        if let Some(n) = self.target.default_codegen_units {
1207            return CodegenUnits::Default(n as usize);
1208        }
1209
1210        // If incremental compilation is turned on, we default to a high number
1211        // codegen units in order to reduce the "collateral damage" small
1212        // changes cause.
1213        if self.opts.incremental.is_some() {
1214            return CodegenUnits::Default(256);
1215        }
1216
1217        // Why is 16 codegen units the default all the time?
1218        //
1219        // The main reason for enabling multiple codegen units by default is to
1220        // leverage the ability for the codegen backend to do codegen and
1221        // optimization in parallel. This allows us, especially for large crates, to
1222        // make good use of all available resources on the machine once we've
1223        // hit that stage of compilation. Large crates especially then often
1224        // take a long time in codegen/optimization and this helps us amortize that
1225        // cost.
1226        //
1227        // Note that a high number here doesn't mean that we'll be spawning a
1228        // large number of threads in parallel. The backend of rustc contains
1229        // global rate limiting through the `jobserver` crate so we'll never
1230        // overload the system with too much work, but rather we'll only be
1231        // optimizing when we're otherwise cooperating with other instances of
1232        // rustc.
1233        //
1234        // Rather a high number here means that we should be able to keep a lot
1235        // of idle cpus busy. By ensuring that no codegen unit takes *too* long
1236        // to build we'll be guaranteed that all cpus will finish pretty closely
1237        // to one another and we should make relatively optimal use of system
1238        // resources
1239        //
1240        // Note that the main cost of codegen units is that it prevents LLVM
1241        // from inlining across codegen units. Users in general don't have a lot
1242        // of control over how codegen units are split up so it's our job in the
1243        // compiler to ensure that undue performance isn't lost when using
1244        // codegen units (aka we can't require everyone to slap `#[inline]` on
1245        // everything).
1246        //
1247        // If we're compiling at `-O0` then the number doesn't really matter too
1248        // much because performance doesn't matter and inlining is ok to lose.
1249        // In debug mode we just want to try to guarantee that no cpu is stuck
1250        // doing work that could otherwise be farmed to others.
1251        //
1252        // In release mode, however (O1 and above) performance does indeed
1253        // matter! To recover the loss in performance due to inlining we'll be
1254        // enabling ThinLTO by default (the function for which is just below).
1255        // This will ensure that we recover any inlining wins we otherwise lost
1256        // through codegen unit partitioning.
1257        //
1258        // ---
1259        //
1260        // Ok that's a lot of words but the basic tl;dr; is that we want a high
1261        // number here -- but not too high. Additionally we're "safe" to have it
1262        // always at the same number at all optimization levels.
1263        //
1264        // As a result 16 was chosen here! Mostly because it was a power of 2
1265        // and most benchmarks agreed it was roughly a local optimum. Not very
1266        // scientific.
1267        CodegenUnits::Default(16)
1268    }
1269
1270    pub fn teach(&self, code: ErrCode) -> bool {
1271        self.opts.unstable_opts.teach && self.dcx().must_teach(code)
1272    }
1273
1274    pub fn edition(&self) -> Edition {
1275        self.opts.edition
1276    }
1277
1278    pub fn link_dead_code(&self) -> bool {
1279        self.opts.cg.link_dead_code.unwrap_or(false)
1280    }
1281
1282    pub fn sanitizers(&self) -> SanitizerSet {
1283        self.sanitizers
1284    }
1285
1286    pub fn pointer_authentication(&self) -> bool {
1287        self.pointer_auth_config.is_some()
1288    }
1289
1290    pub fn pointer_authentication_functions(&self) -> Option<&PointerAuthSchema> {
1291        self.pointer_auth_config.as_ref().and_then(|cfg| cfg.function_pointers.as_ref())
1292    }
1293
1294    pub fn pointer_authentication_init_fini(&self) -> Option<&PointerAuthSchema> {
1295        self.pointer_auth_config.as_ref().and_then(|cfg| cfg.init_fini.as_ref())
1296    }
1297}
1298
1299// JUSTIFICATION: part of session construction
1300#[allow(rustc::bad_opt_access)]
1301fn default_emitter(sopts: &config::Options, source_map: Arc<SourceMap>) -> Box<DynEmitter> {
1302    let macro_backtrace = sopts.unstable_opts.macro_backtrace;
1303    let track_diagnostics = sopts.unstable_opts.track_diagnostics;
1304    let terminal_url = match sopts.unstable_opts.terminal_urls {
1305        TerminalUrl::Auto => {
1306            match (std::env::var("COLORTERM").as_deref(), std::env::var("TERM").as_deref()) {
1307                (Ok("truecolor"), Ok("xterm-256color"))
1308                    if sopts.unstable_features.is_nightly_build() =>
1309                {
1310                    TerminalUrl::Yes
1311                }
1312                _ => TerminalUrl::No,
1313            }
1314        }
1315        t => t,
1316    };
1317
1318    let source_map = if sopts.unstable_opts.link_only { None } else { Some(source_map) };
1319
1320    match sopts.error_format {
1321        ErrorOutputType::HumanReadable { kind, color_config } => match kind {
1322            HumanReadableErrorType { no_graphics, short, unicode } => {
1323                let emitter = AnnotateSnippetEmitter::new(stderr_destination(color_config))
1324                    .sm(source_map)
1325                    .short_message(short)
1326                    .diagnostic_width(sopts.diagnostic_width)
1327                    .macro_backtrace(macro_backtrace)
1328                    .track_diagnostics(track_diagnostics)
1329                    .terminal_url(terminal_url)
1330                    .theme(if unicode { OutputTheme::Unicode } else { OutputTheme::Ascii })
1331                    .ignored_directories_in_source_blocks(
1332                        sopts.unstable_opts.ignore_directory_in_diagnostics_source_blocks.clone(),
1333                    )
1334                    .no_graphics(no_graphics);
1335                Box::new(emitter.ui_testing(sopts.unstable_opts.ui_testing))
1336            }
1337        },
1338        ErrorOutputType::Json { pretty, json_rendered, color_config } => Box::new(
1339            JsonEmitter::new(
1340                Box::new(io::BufWriter::new(io::stderr())),
1341                source_map,
1342                pretty,
1343                json_rendered,
1344                color_config,
1345            )
1346            .ui_testing(sopts.unstable_opts.ui_testing)
1347            .ignored_directories_in_source_blocks(
1348                sopts.unstable_opts.ignore_directory_in_diagnostics_source_blocks.clone(),
1349            )
1350            .diagnostic_width(sopts.diagnostic_width)
1351            .macro_backtrace(macro_backtrace)
1352            .track_diagnostics(track_diagnostics)
1353            .terminal_url(terminal_url),
1354        ),
1355    }
1356}
1357
1358// JUSTIFICATION: literally session construction
1359#[allow(rustc::bad_opt_access)]
1360pub fn build_early_session(
1361    sopts: config::Options,
1362    target: Target,
1363    ice_file: Option<PathBuf>,
1364) -> EarlySession {
1365    // FIXME: This is not general enough to make the warning lint completely override
1366    // normal diagnostic warnings, since the warning lint can also be denied and changed
1367    // later via the source code.
1368    let warnings_allow = sopts
1369        .lint_opts
1370        .iter()
1371        .rfind(|&(key, _)| *key == "warnings")
1372        .is_some_and(|&(_, level)| level == lint::Allow);
1373    let cap_lints_allow = sopts.lint_cap.is_some_and(|cap| cap == lint::Allow);
1374    let can_emit_warnings = !(warnings_allow || cap_lints_allow);
1375
1376    let source_map = rustc_span::source_map::get_source_map().unwrap();
1377    let emitter = default_emitter(&sopts, Arc::clone(&source_map));
1378
1379    let mut dcx =
1380        DiagCtxt::new(emitter).with_flags(sopts.unstable_opts.dcx_flags(can_emit_warnings));
1381    if let Some(ice_file) = ice_file {
1382        dcx = dcx.with_ice_file(ice_file);
1383    }
1384
1385    if let Some(msrv) = sopts.unstable_opts.hint_msrv {
1386        dcx = dcx.with_msrv(msrv);
1387    }
1388
1389    let host_triple = TargetTuple::from_tuple(config::host_tuple());
1390    let (host, target_warnings) =
1391        Target::search(&host_triple, sopts.sysroot.path(), sopts.unstable_opts.unstable_options)
1392            .unwrap_or_else(|e| {
1393                dcx.handle().fatal(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("Error loading host specification: {0}",
                e))
    })format!("Error loading host specification: {e}"))
1394            });
1395    for warning in target_warnings.warning_messages() {
1396        dcx.handle().warn(warning)
1397    }
1398
1399    let psess = ParseSess::with_dcx(dcx, source_map);
1400
1401    EarlySession { target, host, opts: sopts, psess }
1402}
1403
1404// JUSTIFICATION: literally session construction
1405#[allow(rustc::bad_opt_access)]
1406pub fn build_session(
1407    early_sess: EarlySession,
1408    codegen_backend_init: CodegenBackendInit,
1409    io: CompilerIO,
1410    driver_lint_caps: FxHashMap<lint::LintId, lint::Level>,
1411    cfg_version: &'static str,
1412    using_internal_features: &'static AtomicBool,
1413) -> Session {
1414    let EarlySession { target, host, opts: sopts, psess } = &early_sess;
1415    let dcx = psess.dcx();
1416
1417    let wasm_proc_macro_tuple = TargetTuple::from_tuple("wasm32-wasip2");
1418    let (wasm_proc_macro_target, target_warnings) = Target::search(
1419        &wasm_proc_macro_tuple,
1420        sopts.sysroot.path(),
1421        sopts.unstable_opts.unstable_options,
1422    )
1423    .unwrap_or_else(|e| {
1424        dcx.fatal(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("Error loading wasm proc-macro target specification: {0}",
                e))
    })format!("Error loading wasm proc-macro target specification: {e}"))
1425    });
1426    for warning in target_warnings.warning_messages() {
1427        dcx.warn(warning)
1428    }
1429
1430    let self_profiler = if let SwitchWithOptPath::Enabled(ref d) = sopts.unstable_opts.self_profile
1431    {
1432        let directory = if let Some(directory) = d { directory } else { std::path::Path::new(".") };
1433
1434        let profiler = SelfProfiler::new(
1435            directory,
1436            sopts.crate_name.as_deref(),
1437            sopts.unstable_opts.self_profile_events.as_deref(),
1438            &sopts.unstable_opts.self_profile_counter,
1439        );
1440        match profiler {
1441            Ok(profiler) => Some(Arc::new(profiler)),
1442            Err(e) => {
1443                dcx.emit_warn(diagnostics::FailedToCreateProfiler { err: e.to_string() });
1444                None
1445            }
1446        }
1447    } else {
1448        None
1449    };
1450
1451    let host_triple = config::host_tuple();
1452    let target_triple = sopts.target_triple.tuple();
1453    // FIXME use host sysroot?
1454    let host_tlib_path = SearchPath::from_sysroot_and_triple(sopts.sysroot.path(), host_triple);
1455    let target_tlib_path = SearchPath::from_sysroot_and_triple(sopts.sysroot.path(), target_triple);
1456    let wasm_proc_macro_tlib_path =
1457        SearchPath::from_sysroot_and_triple(sopts.sysroot.path(), wasm_proc_macro_tuple.tuple());
1458
1459    let prof = SelfProfilerRef::new(
1460        self_profiler,
1461        sopts.unstable_opts.time_passes.then(|| sopts.unstable_opts.time_passes_format),
1462    );
1463
1464    let ctfe_backtrace = Lock::new(match env::var("RUSTC_CTFE_BACKTRACE") {
1465        Ok(ref val) if val == "immediate" => CtfeBacktrace::Immediate,
1466        Ok(ref val) if val != "0" => CtfeBacktrace::Capture,
1467        _ => CtfeBacktrace::Disabled,
1468    });
1469
1470    let asm_arch = if target.allow_asm { InlineAsmArch::from_arch(&target.arch) } else { None };
1471    let target_filesearch = Arc::new(filesearch::FileSearch::new(
1472        &sopts.search_paths,
1473        &target_tlib_path,
1474        &target,
1475        sopts.unstable_opts.implicit_sysroot_deps,
1476    ));
1477    let host_filesearch = if target == host {
1478        Arc::clone(&target_filesearch)
1479    } else {
1480        Arc::new(filesearch::FileSearch::new(
1481            &sopts.search_paths,
1482            &host_tlib_path,
1483            &host,
1484            sopts.unstable_opts.implicit_sysroot_deps,
1485        ))
1486    };
1487    let wasm_proc_macro_filesearch = if sopts.unstable_opts.wasm_proc_macros {
1488        Some(Arc::new(FileSearch::new(
1489            &sopts.search_paths,
1490            &wasm_proc_macro_tlib_path,
1491            &wasm_proc_macro_target,
1492            sopts.unstable_opts.implicit_sysroot_deps,
1493        )))
1494    } else {
1495        None
1496    };
1497
1498    let timings = TimingSectionHandler::new(sopts.json_timings);
1499
1500    let pointer_auth_config: Option<PointerAuthConfig> =
1501        PointerAuthConfig::from_raw(&sopts.unstable_opts.pointer_authentication, &target);
1502
1503    // `EarlySess::sanitizers` does some computation but is called infrequently. `Sess::sanitizers`
1504    // is called much more often so we cache the value.
1505    let sanitizers = early_sess.sanitizers();
1506
1507    let CodegenBackendInit {
1508        global_backend_features,
1509        replaced_rustc_intrinsics: replaced_intrinsics,
1510        fallback_rustc_intrinsics: fallback_intrinsics,
1511        thin_lto_supported,
1512    } = codegen_backend_init;
1513
1514    let sess = Session {
1515        early_sess,
1516        wasm_proc_macro_tuple,
1517        wasm_proc_macro_target,
1518        target_tlib_path,
1519        unstable_features: UnstableFeatures::from_environment(None),
1520        config: Cfg::default(),
1521        check_config: CheckCfg::default(),
1522        proc_macro_quoted_spans: Default::default(),
1523        io,
1524        prof,
1525        timings,
1526        code_stats: Default::default(),
1527        lint_store: None,
1528        driver_lint_caps,
1529        ctfe_backtrace,
1530        miri_unleashed_features: Lock::new(Default::default()),
1531        asm_arch,
1532        internal_target_features: Default::default(),
1533        global_backend_features,
1534        cfg_version,
1535        using_internal_features,
1536        env_depinfo: Default::default(),
1537        file_depinfo: Default::default(),
1538        target_filesearch,
1539        host_filesearch,
1540        wasm_proc_macro_filesearch,
1541        replaced_rustc_intrinsics: FxHashSet::from_iter(replaced_intrinsics),
1542        fallback_rustc_intrinsics: FxHashSet::from_iter(fallback_intrinsics),
1543        thin_lto_supported,
1544        mir_opt_bisect_eval_count: AtomicUsize::new(0),
1545        removed_rustc_main_attr: AtomicBool::new(false),
1546        pointer_auth_config,
1547        sanitizers,
1548    };
1549
1550    validate_commandline_args_with_session_available(&sess);
1551
1552    sess
1553}
1554
1555pub fn generate_proc_macro_decls_symbol(stable_crate_id: StableCrateId) -> String {
1556    ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("__rustc_proc_macro_decls_{0:08x}__",
                stable_crate_id.as_u64()))
    })format!("__rustc_proc_macro_decls_{:08x}__", stable_crate_id.as_u64())
1557}
1558
1559/// Validate command line arguments with a `Session`.
1560///
1561/// If it is useful to have a Session available already for validating a commandline argument, you
1562/// can do so here.
1563// JUSTIFICATION: needs to access args to validate them
1564#[allow(rustc::bad_opt_access)]
1565fn validate_commandline_args_with_session_available(sess: &Session) {
1566    // Since we don't know if code in an rlib will be linked to statically or
1567    // dynamically downstream, rustc generates `__imp_` symbols that help linkers
1568    // on Windows deal with this lack of knowledge (#27438). Unfortunately,
1569    // these manually generated symbols confuse LLD when it tries to merge
1570    // bitcode during ThinLTO. Therefore we disallow dynamic linking on Windows
1571    // when compiling for LLD ThinLTO. This way we can validly just not generate
1572    // the `dllimport` attributes and `__imp_` symbols in that case.
1573    if sess.opts.cg.linker_plugin_lto.enabled()
1574        && sess.opts.cg.prefer_dynamic
1575        && sess.target.is_like_windows
1576    {
1577        sess.dcx().emit_err(diagnostics::LinkerPluginToWindowsNotSupported);
1578    }
1579
1580    if sess
1581        .pointer_auth_config
1582        .as_ref()
1583        .and_then(|cfg| cfg.function_pointers.as_ref())
1584        .is_some_and(|schema| #[allow(non_exhaustive_omitted_patterns)] match schema.discrimination_kind {
    PointerAuthDiscrimination::Type => true,
    _ => false,
}matches!(schema.discrimination_kind, PointerAuthDiscrimination::Type))
1585    {
1586        sess.dcx().emit_err(
1587            diagnostics::PointerAuthenticationTypeDiscriminationNotSupportedForTarget {
1588                target_triple: &sess.opts.target_triple,
1589            },
1590        );
1591    }
1592
1593    if sess.target.cfg_abi != CfgAbi::Pauthtest
1594        && !sess.opts.unstable_opts.pointer_authentication.is_empty()
1595    {
1596        sess.dcx().emit_warn(diagnostics::PointerAuthenticationNotSupportedForTarget {
1597            target_triple: &sess.opts.target_triple,
1598        });
1599    }
1600
1601    // Make sure that any given profiling data actually exists so LLVM can't
1602    // decide to silently skip PGO.
1603    if let Some(ref path) = sess.opts.cg.profile_use {
1604        if !path.exists() {
1605            sess.dcx().emit_err(diagnostics::ProfileUseFileDoesNotExist { path });
1606        }
1607    }
1608
1609    // Do the same for sample profile data.
1610    if let Some(ref path) = sess.opts.cg.profile_sample_use {
1611        if !path.exists() {
1612            sess.dcx().emit_err(diagnostics::ProfileSampleUseFileDoesNotExist { path });
1613        }
1614    }
1615
1616    // Unwind tables cannot be disabled if the target requires them.
1617    if let Some(include_uwtables) = sess.opts.cg.force_unwind_tables {
1618        if sess.target.requires_uwtable && !include_uwtables {
1619            sess.dcx().emit_err(diagnostics::TargetRequiresUnwindTables);
1620        }
1621    }
1622
1623    // Sanitizers can only be used on platforms that we know have working sanitizer codegen.
1624    let supported_sanitizers = sess.target.options.supported_sanitizers;
1625    let mut unsupported_sanitizers = sess.sanitizers() - supported_sanitizers;
1626    // Niche: if `fixed-x18`, or effectively switching on `reserved-x18` flag, is enabled
1627    // we should allow Shadow Call Stack sanitizer.
1628    if sess.opts.unstable_opts.fixed_x18 && sess.target.arch == Arch::AArch64 {
1629        unsupported_sanitizers -= SanitizerSet::SHADOWCALLSTACK;
1630    }
1631    match unsupported_sanitizers.into_iter().count() {
1632        0 => {}
1633        1 => {
1634            sess.dcx().emit_err(diagnostics::SanitizerNotSupported {
1635                us: unsupported_sanitizers.to_string(),
1636            });
1637        }
1638        _ => {
1639            sess.dcx().emit_err(diagnostics::SanitizersNotSupported {
1640                us: unsupported_sanitizers.to_string(),
1641            });
1642        }
1643    }
1644
1645    // Cannot mix and match mutually-exclusive sanitizers.
1646    if let Some((first, second)) = sess.sanitizers().mutually_exclusive() {
1647        sess.dcx().emit_err(diagnostics::CannotMixAndMatchSanitizers {
1648            first: first.to_string(),
1649            second: second.to_string(),
1650        });
1651    }
1652
1653    // Cannot enable crt-static with sanitizers on Linux
1654    if sess.crt_static(None) && !sess.sanitizers().is_empty() && !sess.target.is_like_msvc {
1655        sess.dcx().emit_err(diagnostics::CannotEnableCrtStaticLinux);
1656    }
1657
1658    // FIXME(jchlanda) Pauthtest does not support static linking. It must be dynamically linked,
1659    // with a dynamic linker acting as the ELF interpreter that can resolve pauth relocations and
1660    // enforce pointer authentication constraints.
1661    if sess.crt_static(None) && sess.target.cfg_abi == CfgAbi::Pauthtest {
1662        sess.dcx().emit_err(diagnostics::CannotEnableCrtStaticPointerAuth);
1663    }
1664
1665    // LLVM CFI requires LTO.
1666    if sess.is_sanitizer_cfi_enabled()
1667        && !(sess.lto() == config::Lto::Fat || sess.opts.cg.linker_plugin_lto.enabled())
1668    {
1669        sess.dcx().emit_err(diagnostics::SanitizerCfiRequiresLto);
1670    }
1671
1672    // KCFI requires panic=abort
1673    if sess.is_sanitizer_kcfi_enabled() && sess.panic_strategy().unwinds() {
1674        sess.dcx().emit_err(diagnostics::SanitizerKcfiRequiresPanicAbort);
1675    }
1676
1677    // LLVM CFI using rustc LTO requires a single codegen unit.
1678    if sess.is_sanitizer_cfi_enabled()
1679        && sess.lto() == config::Lto::Fat
1680        && (sess.codegen_units().as_usize() != 1)
1681    {
1682        sess.dcx().emit_err(diagnostics::SanitizerCfiRequiresSingleCodegenUnit);
1683    }
1684
1685    // Canonical jump tables requires CFI.
1686    if sess.is_sanitizer_cfi_canonical_jump_tables_disabled() {
1687        if !sess.is_sanitizer_cfi_enabled() {
1688            sess.dcx().emit_err(diagnostics::SanitizerCfiCanonicalJumpTablesRequiresCfi);
1689        }
1690    }
1691
1692    // KCFI arity indicator requires KCFI.
1693    if sess.is_sanitizer_kcfi_arity_enabled() && !sess.is_sanitizer_kcfi_enabled() {
1694        sess.dcx().emit_err(diagnostics::SanitizerKcfiArityRequiresKcfi);
1695    }
1696
1697    // LLVM CFI pointer generalization requires CFI or KCFI.
1698    if sess.is_sanitizer_cfi_generalize_pointers_enabled() {
1699        if !(sess.is_sanitizer_cfi_enabled() || sess.is_sanitizer_kcfi_enabled()) {
1700            sess.dcx().emit_err(diagnostics::SanitizerCfiGeneralizePointersRequiresCfi);
1701        }
1702    }
1703
1704    // LLVM CFI recovery requires CFI.
1705    if sess.is_sanitizer_cfi_recover_enabled() {
1706        if !sess.is_sanitizer_cfi_enabled() {
1707            sess.dcx().emit_err(diagnostics::SanitizerCfiRecoverRequiresCfi);
1708        }
1709    }
1710
1711    // LLVM CFI diagnostics requires CFI.
1712    if sess.is_sanitizer_cfi_diag_enabled() {
1713        if !sess.is_sanitizer_cfi_enabled() {
1714            sess.dcx().emit_err(diagnostics::SanitizerCfiDiagRequiresCfi);
1715        }
1716    }
1717
1718    // LLVM CFI minimal runtime requires CFI recovery or CFI diagnostics.
1719    if sess.is_sanitizer_cfi_minimal_runtime_enabled() {
1720        if !sess.is_sanitizer_cfi_enabled() {
1721            sess.dcx().emit_err(diagnostics::SanitizerCfiMinimalRuntimeRequiresCfi);
1722        } else if !(sess.is_sanitizer_cfi_recover_enabled() || sess.is_sanitizer_cfi_diag_enabled())
1723        {
1724            sess.dcx().emit_err(diagnostics::SanitizerCfiMinimalRuntimeRequiresCfiRecoverOrDiag);
1725        }
1726    }
1727
1728    // LLVM CFI integer normalization requires CFI or KCFI.
1729    if sess.is_sanitizer_cfi_normalize_integers_enabled() {
1730        if !(sess.is_sanitizer_cfi_enabled() || sess.is_sanitizer_kcfi_enabled()) {
1731            sess.dcx().emit_err(diagnostics::SanitizerCfiNormalizeIntegersRequiresCfi);
1732        }
1733    }
1734
1735    // LTO unit splitting requires LTO.
1736    if sess.is_split_lto_unit_enabled()
1737        && !(sess.lto() == config::Lto::Fat
1738            || sess.lto() == config::Lto::Thin
1739            || sess.opts.cg.linker_plugin_lto.enabled())
1740    {
1741        sess.dcx().emit_err(diagnostics::SplitLtoUnitRequiresLto);
1742    }
1743
1744    // VFE requires LTO.
1745    if sess.lto() != config::Lto::Fat {
1746        if sess.opts.unstable_opts.virtual_function_elimination {
1747            sess.dcx().emit_err(diagnostics::UnstableVirtualFunctionElimination);
1748        }
1749    }
1750
1751    if sess.opts.unstable_opts.stack_protector != StackProtector::None {
1752        if !sess.target.options.supports_stack_protector {
1753            sess.dcx().emit_warn(diagnostics::StackProtectorNotSupportedForTarget {
1754                stack_protector: sess.opts.unstable_opts.stack_protector,
1755                target_triple: &sess.opts.target_triple,
1756            });
1757        }
1758    }
1759
1760    if sess.opts.unstable_opts.small_data_threshold.is_some() {
1761        if sess.target.small_data_threshold_support() == SmallDataThresholdSupport::None {
1762            sess.dcx().emit_warn(diagnostics::SmallDataThresholdNotSupportedForTarget {
1763                target_triple: &sess.opts.target_triple,
1764            })
1765        }
1766    }
1767
1768    if sess.opts.unstable_opts.branch_protection.is_some() && sess.target.arch != Arch::AArch64 {
1769        sess.dcx().emit_err(diagnostics::BranchProtectionRequiresAArch64);
1770    }
1771
1772    if let Some(dwarf_version) =
1773        sess.opts.cg.dwarf_version.or(sess.opts.unstable_opts.dwarf_version)
1774    {
1775        // DWARF 1 is not supported by LLVM and DWARF 6 is not yet finalized.
1776        if dwarf_version < 2 || dwarf_version > 5 {
1777            sess.dcx().emit_err(diagnostics::UnsupportedDwarfVersion { dwarf_version });
1778        }
1779    }
1780
1781    if !sess.target.options.supported_split_debuginfo.contains(&sess.split_debuginfo())
1782        && !sess.opts.unstable_opts.unstable_options
1783    {
1784        sess.dcx().emit_err(diagnostics::SplitDebugInfoUnstablePlatform {
1785            debuginfo: sess.split_debuginfo(),
1786        });
1787    }
1788
1789    if sess.opts.unstable_opts.embed_source {
1790        let dwarf_version = sess.dwarf_version();
1791
1792        if dwarf_version < 5 {
1793            sess.dcx()
1794                .emit_warn(diagnostics::EmbedSourceInsufficientDwarfVersion { dwarf_version });
1795        }
1796
1797        if sess.opts.debuginfo == DebugInfo::None {
1798            sess.dcx().emit_warn(diagnostics::EmbedSourceRequiresDebugInfo);
1799        }
1800    }
1801
1802    if let InstrumentMcount::Fentry(opts) = sess.opts.unstable_opts.instrument_mcount {
1803        if !sess.target.options.supports_fentry {
1804            sess.dcx()
1805                .emit_err(diagnostics::InstrumentationNotSupported { us: "fentry".to_string() });
1806        }
1807        if (opts.no_call || opts.record) && sess.target.arch != Arch::S390x {
1808            sess.dcx()
1809                .emit_err(diagnostics::InstrumentationNotSupported { us: "fentry-*".to_string() });
1810        }
1811    }
1812
1813    if sess.opts.unstable_opts.instrument_xray.is_some() && !sess.target.options.supports_xray {
1814        sess.dcx().emit_err(diagnostics::InstrumentationNotSupported { us: "XRay".to_string() });
1815    }
1816
1817    if let Some(flavor) = sess.opts.cg.linker_flavor
1818        && let Some(compatible_list) = sess.target.linker_flavor.check_compatibility(flavor)
1819    {
1820        let flavor = flavor.desc();
1821        sess.dcx().emit_err(diagnostics::IncompatibleLinkerFlavor { flavor, compatible_list });
1822    }
1823
1824    if sess.opts.unstable_opts.function_return != FunctionReturn::default() {
1825        if !#[allow(non_exhaustive_omitted_patterns)] match sess.target.arch {
    Arch::X86 | Arch::X86_64 => true,
    _ => false,
}matches!(sess.target.arch, Arch::X86 | Arch::X86_64) {
1826            sess.dcx().emit_err(diagnostics::FunctionReturnRequiresX86OrX8664);
1827        }
1828    }
1829
1830    if sess.opts.unstable_opts.indirect_branch_cs_prefix {
1831        if !#[allow(non_exhaustive_omitted_patterns)] match sess.target.arch {
    Arch::X86 | Arch::X86_64 => true,
    _ => false,
}matches!(sess.target.arch, Arch::X86 | Arch::X86_64) {
1832            sess.dcx().emit_err(diagnostics::IndirectBranchCsPrefixRequiresX86OrX8664);
1833        }
1834    }
1835
1836    if let Some(regparm) = sess.opts.unstable_opts.regparm {
1837        if regparm > 3 {
1838            sess.dcx().emit_err(diagnostics::UnsupportedRegparm { regparm });
1839        }
1840        if sess.target.arch != Arch::X86 {
1841            sess.dcx().emit_err(diagnostics::UnsupportedRegparmArch);
1842        }
1843    }
1844    if sess.opts.unstable_opts.reg_struct_return {
1845        if sess.target.arch != Arch::X86 {
1846            sess.dcx().emit_err(diagnostics::UnsupportedRegStructReturnArch);
1847        }
1848    }
1849
1850    // The code model check applies to `thunk` and `thunk-extern`, but not `thunk-inline`, so it is
1851    // kept as a `match` to force a change if new ones are added, even if we currently only support
1852    // `thunk-extern` like Clang.
1853    match sess.opts.unstable_opts.function_return {
1854        FunctionReturn::Keep => (),
1855        FunctionReturn::ThunkExtern => {
1856            // FIXME: In principle, the inherited base LLVM target code model could be large,
1857            // but this only checks whether we were passed one explicitly (like Clang does).
1858            if let Some(code_model) = sess.code_model()
1859                && code_model == CodeModel::Large
1860            {
1861                sess.dcx()
1862                    .emit_err(diagnostics::FunctionReturnThunkExternRequiresNonLargeCodeModel);
1863            }
1864        }
1865    }
1866
1867    if sess.opts.unstable_opts.packed_stack {
1868        if sess.target.arch != Arch::S390x {
1869            sess.dcx().emit_err(diagnostics::UnsupportedPackedStack);
1870        }
1871    }
1872
1873    match sess.opts.unstable_opts.pack_coroutine_layout {
1874        PackCoroutineLayout::Classic => {}
1875        PackCoroutineLayout::CapturesOnly => {
1876            sess.dcx().emit_warn(diagnostics::PackCoroutineLayoutNotImplemented);
1877        }
1878    }
1879
1880    if let Some(ref cpu_name) = sess.opts.cg.target_cpu {
1881        if cpu_name == NATIVE_CPU && sess.target.requires_consistent_cpu {
1882            sess.dcx().emit_fatal(diagnostics::NativeTargetCpuNotAllowed {
1883                target_triple: &sess.opts.target_triple,
1884                need_explicit_cpu: sess.target.need_explicit_cpu,
1885            });
1886        }
1887    }
1888}
1889
1890/// Holds data on the current incremental compilation session, if there is one.
1891pub struct IncrCompSession {
1892    /// The directory from which cached data of a previous session can be read.
1893    pub old_session_directory: Option<flock::LockedDir>,
1894    /// The directory to which cached data for the current session can be
1895    /// written to.
1896    pub new_session_directory: flock::LockedDir,
1897    borrows: Arc<()>,
1898}
1899
1900impl IncrCompSession {
1901    pub fn new(
1902        old_session_directory: Option<flock::LockedDir>,
1903        new_session_directory: flock::LockedDir,
1904    ) -> Self {
1905        IncrCompSession { old_session_directory, new_session_directory, borrows: Arc::new(()) }
1906    }
1907
1908    pub fn borrow(&self) -> BorrowedIncrCompSession {
1909        BorrowedIncrCompSession {
1910            old_session_directory: self.old_session_directory.as_deref().map(ToOwned::to_owned),
1911            new_session_directory: (&*self.new_session_directory).to_owned(),
1912            _borrows: Arc::clone(&self.borrows),
1913        }
1914    }
1915}
1916
1917impl Drop for IncrCompSession {
1918    fn drop(&mut self) {
1919        // Check that there are no worker threads remaining that use the incr
1920        // comp session before we unlock the old and new session dir. If there
1921        // does exist a worker thread, there is not much we can do, but at
1922        // least we will unconditionally complain rather than the worker thread
1923        // sometimes crashing depending on what other rustc instances run.
1924        if !(Arc::strong_count(&self.borrows) == 1) {
    {
        ::core::panicking::panic_fmt(format_args!("Incr comp session dropped while there are still references"));
    }
};assert!(
1925            Arc::strong_count(&self.borrows) == 1,
1926            "Incr comp session dropped while there are still references",
1927        );
1928    }
1929}
1930
1931/// A runtime tracked borrow of the incr comp session. Can be sent to worker threads.
1932pub struct BorrowedIncrCompSession {
1933    pub old_session_directory: Option<PathBuf>,
1934    pub new_session_directory: PathBuf,
1935    _borrows: Arc<()>,
1936}
1937
1938/// A wrapper around an [`DiagCtxt`] that is used for early error emissions.
1939pub struct EarlyDiagCtxt {
1940    dcx: DiagCtxt,
1941}
1942
1943impl EarlyDiagCtxt {
1944    pub fn new(output: ErrorOutputType) -> Self {
1945        let emitter = mk_emitter(output);
1946        Self { dcx: DiagCtxt::new(emitter) }
1947    }
1948
1949    /// Swap out the underlying dcx once we acquire the user's preference on error emission
1950    /// format. If `early_err` was previously called this will panic.
1951    pub fn set_error_format(&mut self, output: ErrorOutputType) {
1952        if !self.dcx.handle().has_errors().is_none() {
    ::core::panicking::panic("assertion failed: self.dcx.handle().has_errors().is_none()")
};assert!(self.dcx.handle().has_errors().is_none());
1953
1954        let emitter = mk_emitter(output);
1955        self.dcx = DiagCtxt::new(emitter);
1956    }
1957
1958    #[must_use = "raise_fatal must be called on the returned ErrorGuaranteed in order to exit with a non-zero status code"]
1959    pub fn early_err(&self, msg: impl Into<DiagMessage>) -> ErrorGuaranteed {
1960        self.dcx.handle().err(msg)
1961    }
1962
1963    pub fn early_fatal(&self, msg: impl Into<DiagMessage>) -> ! {
1964        self.dcx.handle().fatal(msg)
1965    }
1966
1967    pub fn early_struct_fatal(&self, msg: impl Into<DiagMessage>) -> Diag<'_> {
1968        self.dcx.handle().struct_fatal(msg)
1969    }
1970
1971    pub fn early_warn(&self, msg: impl Into<DiagMessage>) {
1972        self.dcx.handle().warn(msg)
1973    }
1974
1975    pub fn early_struct_warn(&self, msg: impl Into<DiagMessage>) -> Diag<'_> {
1976        self.dcx.handle().struct_warn(msg)
1977    }
1978}
1979
1980fn mk_emitter(output: ErrorOutputType) -> Box<DynEmitter> {
1981    let emitter: Box<DynEmitter> = match output {
1982        ErrorOutputType::HumanReadable { kind, color_config } => match kind {
1983            HumanReadableErrorType { no_graphics, short, unicode } => Box::new(
1984                AnnotateSnippetEmitter::new(stderr_destination(color_config))
1985                    .theme(if unicode { OutputTheme::Unicode } else { OutputTheme::Ascii })
1986                    .short_message(short)
1987                    .no_graphics(no_graphics),
1988            ),
1989        },
1990        ErrorOutputType::Json { pretty, json_rendered, color_config } => {
1991            Box::new(JsonEmitter::new(
1992                Box::new(io::BufWriter::new(io::stderr())),
1993                Some(Arc::new(SourceMap::new(FilePathMapping::empty()))),
1994                pretty,
1995                json_rendered,
1996                color_config,
1997            ))
1998        }
1999    };
2000    emitter
2001}