Skip to main content

rustc_session/
session.rs

1use std::any::Any;
2use std::path::PathBuf;
3use std::str::FromStr;
4use std::sync::Arc;
5use std::sync::atomic::{AtomicBool, AtomicUsize};
6use std::{env, io};
7
8use rand::{RngCore, rng};
9use rustc_data_structures::base_n::{CASE_INSENSITIVE, ToBaseN};
10use rustc_data_structures::flock;
11use rustc_data_structures::fx::{FxHashMap, FxHashSet, FxIndexSet};
12use rustc_data_structures::profiling::{SelfProfiler, SelfProfilerRef};
13use rustc_data_structures::sync::{DynSend, DynSync, Lock, MappedReadGuard, ReadGuard, RwLock};
14use rustc_errors::annotate_snippet_emitter_writer::AnnotateSnippetEmitter;
15use rustc_errors::codes::*;
16use rustc_errors::emitter::{DynEmitter, HumanReadableErrorType, OutputTheme, stderr_destination};
17use rustc_errors::json::JsonEmitter;
18use rustc_errors::timings::TimingSectionHandler;
19use rustc_errors::{
20    Diag, DiagCtxt, DiagCtxtHandle, DiagMessage, Diagnostic, ErrorGuaranteed, FatalAbort,
21    TerminalUrl,
22};
23use rustc_hir::limit::Limit;
24use rustc_macros::HashStable_Generic;
25pub use rustc_span::def_id::StableCrateId;
26use rustc_span::edition::Edition;
27use rustc_span::source_map::{FilePathMapping, SourceMap};
28use rustc_span::{RealFileName, Span, Symbol};
29use rustc_target::asm::InlineAsmArch;
30use rustc_target::spec::{
31    Arch, CodeModel, DebuginfoKind, Os, PanicStrategy, RelocModel, RelroLevel, SanitizerSet,
32    SmallDataThresholdSupport, SplitDebuginfo, StackProtector, SymbolVisibility, Target,
33    TargetTuple, TlsModel, apple,
34};
35
36use crate::code_stats::CodeStats;
37pub use crate::code_stats::{DataTypeKind, FieldInfo, FieldKind, SizeKind, VariantInfo};
38use crate::config::{
39    self, CoverageLevel, CoverageOptions, CrateType, DebugInfo, ErrorOutputType, FunctionReturn,
40    Input, InstrumentCoverage, OptLevel, OutFileName, OutputType, SwitchWithOptPath,
41};
42use crate::filesearch::FileSearch;
43use crate::lint::{CheckLintNameResult, LintId, RegisteredTools};
44use crate::parse::{ParseSess, add_feature_diagnostics};
45use crate::search_paths::SearchPath;
46use crate::{errors, filesearch, lint};
47
48/// The behavior of the CTFE engine when an error occurs with regards to backtraces.
49#[derive(#[automatically_derived]
impl ::core::clone::Clone for CtfeBacktrace {
    #[inline]
    fn clone(&self) -> CtfeBacktrace { *self }
}Clone, #[automatically_derived]
impl ::core::marker::Copy for CtfeBacktrace { }Copy)]
50pub enum CtfeBacktrace {
51    /// Do nothing special, return the error as usual without a backtrace.
52    Disabled,
53    /// Capture a backtrace at the point the error is created and return it in the error
54    /// (to be printed later if/when the error ever actually gets shown to the user).
55    Capture,
56    /// Capture a backtrace at the point the error is created and immediately print it out.
57    Immediate,
58}
59
60#[derive(#[automatically_derived]
impl ::core::clone::Clone for Limits {
    #[inline]
    fn clone(&self) -> Limits {
        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]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        ::core::fmt::Formatter::debug_struct_field4_finish(f, "Limits",
            "recursion_limit", &self.recursion_limit, "move_size_limit",
            &self.move_size_limit, "type_length_limit",
            &self.type_length_limit, "pattern_complexity_limit",
            &&self.pattern_complexity_limit)
    }
}Debug, const _: () =
    {
        impl<__CTX> ::rustc_data_structures::stable_hasher::HashStable<__CTX>
            for Limits where __CTX: ::rustc_span::HashStableContext {
            #[inline]
            fn hash_stable(&self, __hcx: &mut __CTX,
                __hasher:
                    &mut ::rustc_data_structures::stable_hasher::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.hash_stable(__hcx, __hasher); }
                        { __binding_1.hash_stable(__hcx, __hasher); }
                        { __binding_2.hash_stable(__hcx, __hasher); }
                        { __binding_3.hash_stable(__hcx, __hasher); }
                    }
                }
            }
        }
    };HashStable_Generic)]
61pub struct Limits {
62    /// The maximum recursion limit for potentially infinitely recursive
63    /// operations such as auto-dereference and monomorphization.
64    pub recursion_limit: Limit,
65    /// The size at which the `large_assignments` lint starts
66    /// being emitted.
67    pub move_size_limit: Limit,
68    /// The maximum length of types during monomorphization.
69    pub type_length_limit: Limit,
70    /// The maximum pattern complexity allowed (internal only).
71    pub pattern_complexity_limit: Limit,
72}
73
74pub struct CompilerIO {
75    pub input: Input,
76    pub output_dir: Option<PathBuf>,
77    pub output_file: Option<OutFileName>,
78    pub temps_dir: Option<PathBuf>,
79}
80
81pub trait DynLintStore: Any + DynSync + DynSend {
82    /// Provides a way to access lint groups without depending on `rustc_lint`
83    fn lint_groups_iter(&self) -> Box<dyn Iterator<Item = LintGroup> + '_>;
84
85    fn check_lint_name(
86        &self,
87        lint_name: &str,
88        tool_name: Option<Symbol>,
89        registered_tools: &RegisteredTools,
90    ) -> CheckLintNameResult<'_>;
91
92    fn find_lints(&self, lint_name: &str) -> Option<&[LintId]>;
93}
94
95/// Represents the data associated with a compilation
96/// session for a single crate.
97pub struct Session {
98    pub target: Target,
99    pub host: Target,
100    pub opts: config::Options,
101    pub target_tlib_path: Arc<SearchPath>,
102    pub psess: ParseSess,
103    /// Input, input file path and output file path to this compilation process.
104    pub io: CompilerIO,
105
106    incr_comp_session: RwLock<IncrCompSession>,
107
108    /// Used by `-Z self-profile`.
109    pub prof: SelfProfilerRef,
110
111    /// Used to emit section timings events (enabled by `--json=timings`).
112    pub timings: TimingSectionHandler,
113
114    /// Data about code being compiled, gathered during compilation.
115    pub code_stats: CodeStats,
116
117    /// This only ever stores a `LintStore` but we don't want a dependency on that type here.
118    pub lint_store: Option<Arc<dyn DynLintStore>>,
119
120    /// Cap lint level specified by a driver specifically.
121    pub driver_lint_caps: FxHashMap<lint::LintId, lint::Level>,
122
123    /// Tracks the current behavior of the CTFE engine when an error occurs.
124    /// Options range from returning the error without a backtrace to returning an error
125    /// and immediately printing the backtrace to stderr.
126    /// The `Lock` is only used by miri to allow setting `ctfe_backtrace` after analysis when
127    /// `MIRI_BACKTRACE` is set. This makes it only apply to miri's errors and not to all CTFE
128    /// errors.
129    pub ctfe_backtrace: Lock<CtfeBacktrace>,
130
131    /// This tracks where `-Zunleash-the-miri-inside-of-you` was used to get around a
132    /// const check, optionally with the relevant feature gate. We use this to
133    /// warn about unleashing, but with a single diagnostic instead of dozens that
134    /// drown everything else in noise.
135    miri_unleashed_features: Lock<Vec<(Span, Option<Symbol>)>>,
136
137    /// Architecture to use for interpreting asm!.
138    pub asm_arch: Option<InlineAsmArch>,
139
140    /// Set of enabled features for the current target.
141    pub target_features: FxIndexSet<Symbol>,
142
143    /// Set of enabled features for the current target, including unstable ones.
144    pub unstable_target_features: FxIndexSet<Symbol>,
145
146    /// The version of the rustc process, possibly including a commit hash and description.
147    pub cfg_version: &'static str,
148
149    /// The inner atomic value is set to true when a feature marked as `internal` is
150    /// enabled. Makes it so that "please report a bug" is hidden, as ICEs with
151    /// internal features are wontfix, and they are usually the cause of the ICEs.
152    /// None signifies that this is not tracked.
153    pub using_internal_features: &'static AtomicBool,
154
155    /// Environment variables accessed during the build and their values when they exist.
156    pub env_depinfo: Lock<FxIndexSet<(Symbol, Option<Symbol>)>>,
157
158    /// File paths accessed during the build.
159    pub file_depinfo: Lock<FxIndexSet<Symbol>>,
160
161    target_filesearch: FileSearch,
162    host_filesearch: FileSearch,
163
164    /// A random string generated per invocation of rustc.
165    ///
166    /// This is prepended to all temporary files so that they do not collide
167    /// during concurrent invocations of rustc, or past invocations that were
168    /// preserved with a flag like `-C save-temps`, since these files may be
169    /// hard linked.
170    pub invocation_temp: Option<String>,
171
172    /// The names of intrinsics that the current codegen backend replaces
173    /// with its own implementations.
174    pub replaced_intrinsics: FxHashSet<Symbol>,
175
176    /// Does the codegen backend support ThinLTO?
177    pub thin_lto_supported: bool,
178
179    /// Global per-session counter for MIR optimization pass applications.
180    ///
181    /// Used by `-Zmir-opt-bisect-limit` to assign an index to each
182    /// optimization-pass execution candidate during this compilation.
183    pub mir_opt_bisect_eval_count: AtomicUsize,
184
185    /// Enabled features that are used in the current compilation.
186    ///
187    /// The value is the `DepNodeIndex` of the node encodes the used feature.
188    pub used_features: Lock<FxHashMap<Symbol, u32>>,
189}
190
191#[derive(#[automatically_derived]
impl ::core::clone::Clone for CodegenUnits {
    #[inline]
    fn clone(&self) -> CodegenUnits {
        let _: ::core::clone::AssertParamIsClone<usize>;
        *self
    }
}Clone, #[automatically_derived]
impl ::core::marker::Copy for CodegenUnits { }Copy)]
192pub enum CodegenUnits {
193    /// Specified by the user. In this case we try fairly hard to produce the
194    /// number of CGUs requested.
195    User(usize),
196
197    /// A default value, i.e. not specified by the user. In this case we take
198    /// more liberties about CGU formation, e.g. avoid producing very small
199    /// CGUs.
200    Default(usize),
201}
202
203impl CodegenUnits {
204    pub fn as_usize(self) -> usize {
205        match self {
206            CodegenUnits::User(n) => n,
207            CodegenUnits::Default(n) => n,
208        }
209    }
210}
211
212pub struct LintGroup {
213    pub name: &'static str,
214    pub lints: Vec<LintId>,
215    pub is_externally_loaded: bool,
216}
217
218impl Session {
219    pub fn miri_unleashed_feature(&self, span: Span, feature_gate: Option<Symbol>) {
220        self.miri_unleashed_features.lock().push((span, feature_gate));
221    }
222
223    pub fn local_crate_source_file(&self) -> Option<RealFileName> {
224        Some(
225            self.source_map()
226                .path_mapping()
227                .to_real_filename(self.source_map().working_dir(), self.io.input.opt_path()?),
228        )
229    }
230
231    fn check_miri_unleashed_features(&self) -> Option<ErrorGuaranteed> {
232        let mut guar = None;
233        let unleashed_features = self.miri_unleashed_features.lock();
234        if !unleashed_features.is_empty() {
235            let mut must_err = false;
236            // Create a diagnostic pointing at where things got unleashed.
237            self.dcx().emit_warn(errors::SkippingConstChecks {
238                unleashed_features: unleashed_features
239                    .iter()
240                    .map(|(span, gate)| {
241                        gate.map(|gate| {
242                            must_err = true;
243                            errors::UnleashedFeatureHelp::Named { span: *span, gate }
244                        })
245                        .unwrap_or(errors::UnleashedFeatureHelp::Unnamed { span: *span })
246                    })
247                    .collect(),
248            });
249
250            // If we should err, make sure we did.
251            if must_err && self.dcx().has_errors().is_none() {
252                // We have skipped a feature gate, and not run into other errors... reject.
253                guar = Some(self.dcx().emit_err(errors::NotCircumventFeature));
254            }
255        }
256        guar
257    }
258
259    /// Invoked all the way at the end to finish off diagnostics printing.
260    pub fn finish_diagnostics(&self) -> Option<ErrorGuaranteed> {
261        let mut guar = None;
262        guar = guar.or(self.check_miri_unleashed_features());
263        guar = guar.or(self.dcx().emit_stashed_diagnostics());
264        self.dcx().print_error_count();
265        if self.opts.json_future_incompat {
266            self.dcx().emit_future_breakage_report();
267        }
268        guar
269    }
270
271    /// Returns true if the crate is a testing one.
272    pub fn is_test_crate(&self) -> bool {
273        self.opts.test
274    }
275
276    /// `feature` must be a language feature.
277    #[track_caller]
278    pub fn create_feature_err<'a>(&'a self, err: impl Diagnostic<'a>, feature: Symbol) -> Diag<'a> {
279        let mut err = self.dcx().create_err(err);
280        if err.code.is_none() {
281            err.code(E0658);
282        }
283        add_feature_diagnostics(&mut err, self, feature);
284        err
285    }
286
287    /// Record the fact that we called `trimmed_def_paths`, and do some
288    /// checking about whether its cost was justified.
289    pub fn record_trimmed_def_paths(&self) {
290        if self.opts.unstable_opts.print_type_sizes
291            || self.opts.unstable_opts.query_dep_graph
292            || self.opts.unstable_opts.dump_mir.is_some()
293            || self.opts.unstable_opts.unpretty.is_some()
294            || self.prof.is_args_recording_enabled()
295            || self.opts.output_types.contains_key(&OutputType::Mir)
296            || std::env::var_os("RUSTC_LOG").is_some()
297        {
298            return;
299        }
300
301        self.dcx().set_must_produce_diag()
302    }
303
304    #[inline]
305    pub fn dcx(&self) -> DiagCtxtHandle<'_> {
306        self.psess.dcx()
307    }
308
309    #[inline]
310    pub fn source_map(&self) -> &SourceMap {
311        self.psess.source_map()
312    }
313
314    /// Returns `true` if internal lints should be added to the lint store - i.e. if
315    /// `-Zunstable-options` is provided and this isn't rustdoc (internal lints can trigger errors
316    /// to be emitted under rustdoc).
317    pub fn enable_internal_lints(&self) -> bool {
318        self.unstable_options() && !self.opts.actually_rustdoc
319    }
320
321    pub fn instrument_coverage(&self) -> bool {
322        self.opts.cg.instrument_coverage() != InstrumentCoverage::No
323    }
324
325    pub fn instrument_coverage_branch(&self) -> bool {
326        self.instrument_coverage()
327            && self.opts.unstable_opts.coverage_options.level >= CoverageLevel::Branch
328    }
329
330    pub fn instrument_coverage_condition(&self) -> bool {
331        self.instrument_coverage()
332            && self.opts.unstable_opts.coverage_options.level >= CoverageLevel::Condition
333    }
334
335    /// Provides direct access to the `CoverageOptions` struct, so that
336    /// individual flags for debugging/testing coverage instrumetation don't
337    /// need separate accessors.
338    pub fn coverage_options(&self) -> &CoverageOptions {
339        &self.opts.unstable_opts.coverage_options
340    }
341
342    pub fn is_sanitizer_cfi_enabled(&self) -> bool {
343        self.sanitizers().contains(SanitizerSet::CFI)
344    }
345
346    pub fn is_sanitizer_cfi_canonical_jump_tables_disabled(&self) -> bool {
347        self.opts.unstable_opts.sanitizer_cfi_canonical_jump_tables == Some(false)
348    }
349
350    pub fn is_sanitizer_cfi_canonical_jump_tables_enabled(&self) -> bool {
351        self.opts.unstable_opts.sanitizer_cfi_canonical_jump_tables == Some(true)
352    }
353
354    pub fn is_sanitizer_cfi_generalize_pointers_enabled(&self) -> bool {
355        self.opts.unstable_opts.sanitizer_cfi_generalize_pointers == Some(true)
356    }
357
358    pub fn is_sanitizer_cfi_normalize_integers_enabled(&self) -> bool {
359        self.opts.unstable_opts.sanitizer_cfi_normalize_integers == Some(true)
360    }
361
362    pub fn is_sanitizer_kcfi_arity_enabled(&self) -> bool {
363        self.opts.unstable_opts.sanitizer_kcfi_arity == Some(true)
364    }
365
366    pub fn is_sanitizer_kcfi_enabled(&self) -> bool {
367        self.sanitizers().contains(SanitizerSet::KCFI)
368    }
369
370    pub fn is_split_lto_unit_enabled(&self) -> bool {
371        self.opts.unstable_opts.split_lto_unit == Some(true)
372    }
373
374    /// Check whether this compile session and crate type use static crt.
375    pub fn crt_static(&self, crate_type: Option<CrateType>) -> bool {
376        if !self.target.crt_static_respected {
377            // If the target does not opt in to crt-static support, use its default.
378            return self.target.crt_static_default;
379        }
380
381        let requested_features = self.opts.cg.target_feature.split(',');
382        let found_negative = requested_features.clone().any(|r| r == "-crt-static");
383        let found_positive = requested_features.clone().any(|r| r == "+crt-static");
384
385        // JUSTIFICATION: necessary use of crate_types directly (see FIXME below)
386        #[allow(rustc::bad_opt_access)]
387        if found_positive || found_negative {
388            found_positive
389        } else if crate_type == Some(CrateType::ProcMacro)
390            || crate_type == None && self.opts.crate_types.contains(&CrateType::ProcMacro)
391        {
392            // FIXME: When crate_type is not available,
393            // we use compiler options to determine the crate_type.
394            // We can't check `#![crate_type = "proc-macro"]` here.
395            false
396        } else {
397            self.target.crt_static_default
398        }
399    }
400
401    pub fn is_wasi_reactor(&self) -> bool {
402        self.target.options.os == Os::Wasi
403            && #[allow(non_exhaustive_omitted_patterns)] match self.opts.unstable_opts.wasi_exec_model
    {
    Some(config::WasiExecModel::Reactor) => true,
    _ => false,
}matches!(
404                self.opts.unstable_opts.wasi_exec_model,
405                Some(config::WasiExecModel::Reactor)
406            )
407    }
408
409    /// Returns `true` if the target can use the current split debuginfo configuration.
410    pub fn target_can_use_split_dwarf(&self) -> bool {
411        self.target.debuginfo_kind == DebuginfoKind::Dwarf
412    }
413
414    pub fn generate_proc_macro_decls_symbol(&self, stable_crate_id: StableCrateId) -> String {
415        ::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())
416    }
417
418    pub fn target_filesearch(&self) -> &filesearch::FileSearch {
419        &self.target_filesearch
420    }
421    pub fn host_filesearch(&self) -> &filesearch::FileSearch {
422        &self.host_filesearch
423    }
424
425    /// Returns a list of directories where target-specific tool binaries are located. Some fallback
426    /// directories are also returned, for example if `--sysroot` is used but tools are missing
427    /// (#125246): we also add the bin directories to the sysroot where rustc is located.
428    pub fn get_tools_search_paths(&self, self_contained: bool) -> Vec<PathBuf> {
429        let search_paths = self
430            .opts
431            .sysroot
432            .all_paths()
433            .map(|sysroot| filesearch::make_target_bin_path(&sysroot, config::host_tuple()));
434
435        if self_contained {
436            // The self-contained tools are expected to be e.g. in `bin/self-contained` in the
437            // sysroot's `rustlib` path, so we add such a subfolder to the bin path, and the
438            // fallback paths.
439            search_paths.flat_map(|path| [path.clone(), path.join("self-contained")]).collect()
440        } else {
441            search_paths.collect()
442        }
443    }
444
445    pub fn init_incr_comp_session(&self, session_dir: PathBuf, lock_file: flock::Lock) {
446        let mut incr_comp_session = self.incr_comp_session.borrow_mut();
447
448        if let IncrCompSession::NotInitialized = *incr_comp_session {
449        } else {
450            {
    ::core::panicking::panic_fmt(format_args!("Trying to initialize IncrCompSession `{0:?}`",
            *incr_comp_session));
}panic!("Trying to initialize IncrCompSession `{:?}`", *incr_comp_session)
451        }
452
453        *incr_comp_session =
454            IncrCompSession::Active { session_directory: session_dir, _lock_file: lock_file };
455    }
456
457    pub fn finalize_incr_comp_session(&self, new_directory_path: PathBuf) {
458        let mut incr_comp_session = self.incr_comp_session.borrow_mut();
459
460        if let IncrCompSession::Active { .. } = *incr_comp_session {
461        } else {
462            {
    ::core::panicking::panic_fmt(format_args!("trying to finalize `IncrCompSession` `{0:?}`",
            *incr_comp_session));
};panic!("trying to finalize `IncrCompSession` `{:?}`", *incr_comp_session);
463        }
464
465        // Note: this will also drop the lock file, thus unlocking the directory.
466        *incr_comp_session = IncrCompSession::Finalized { session_directory: new_directory_path };
467    }
468
469    pub fn mark_incr_comp_session_as_invalid(&self) {
470        let mut incr_comp_session = self.incr_comp_session.borrow_mut();
471
472        let session_directory = match *incr_comp_session {
473            IncrCompSession::Active { ref session_directory, .. } => session_directory.clone(),
474            IncrCompSession::InvalidBecauseOfErrors { .. } => return,
475            _ => {
    ::core::panicking::panic_fmt(format_args!("trying to invalidate `IncrCompSession` `{0:?}`",
            *incr_comp_session));
}panic!("trying to invalidate `IncrCompSession` `{:?}`", *incr_comp_session),
476        };
477
478        // Note: this will also drop the lock file, thus unlocking the directory.
479        *incr_comp_session = IncrCompSession::InvalidBecauseOfErrors { session_directory };
480    }
481
482    pub fn incr_comp_session_dir(&self) -> MappedReadGuard<'_, PathBuf> {
483        let incr_comp_session = self.incr_comp_session.borrow();
484        ReadGuard::map(incr_comp_session, |incr_comp_session| match *incr_comp_session {
485            IncrCompSession::NotInitialized => {
    ::core::panicking::panic_fmt(format_args!("trying to get session directory from `IncrCompSession`: {0:?}",
            *incr_comp_session));
}panic!(
486                "trying to get session directory from `IncrCompSession`: {:?}",
487                *incr_comp_session,
488            ),
489            IncrCompSession::Active { ref session_directory, .. }
490            | IncrCompSession::Finalized { ref session_directory }
491            | IncrCompSession::InvalidBecauseOfErrors { ref session_directory } => {
492                session_directory
493            }
494        })
495    }
496
497    pub fn incr_comp_session_dir_opt(&self) -> Option<MappedReadGuard<'_, PathBuf>> {
498        self.opts.incremental.as_ref().map(|_| self.incr_comp_session_dir())
499    }
500
501    /// Is this edition 2015?
502    pub fn is_rust_2015(&self) -> bool {
503        self.edition().is_rust_2015()
504    }
505
506    /// Are we allowed to use features from the Rust 2018 edition?
507    pub fn at_least_rust_2018(&self) -> bool {
508        self.edition().at_least_rust_2018()
509    }
510
511    /// Are we allowed to use features from the Rust 2021 edition?
512    pub fn at_least_rust_2021(&self) -> bool {
513        self.edition().at_least_rust_2021()
514    }
515
516    /// Are we allowed to use features from the Rust 2024 edition?
517    pub fn at_least_rust_2024(&self) -> bool {
518        self.edition().at_least_rust_2024()
519    }
520
521    /// Returns `true` if we should use the PLT for shared library calls.
522    pub fn needs_plt(&self) -> bool {
523        // Check if the current target usually wants PLT to be enabled.
524        // The user can use the command line flag to override it.
525        let want_plt = self.target.plt_by_default;
526
527        let dbg_opts = &self.opts.unstable_opts;
528
529        let relro_level = self.opts.cg.relro_level.unwrap_or(self.target.relro_level);
530
531        // Only enable this optimization by default if full relro is also enabled.
532        // In this case, lazy binding was already unavailable, so nothing is lost.
533        // This also ensures `-Wl,-z,now` is supported by the linker.
534        let full_relro = RelroLevel::Full == relro_level;
535
536        // If user didn't explicitly forced us to use / skip the PLT,
537        // then use it unless the target doesn't want it by default or the full relro forces it on.
538        dbg_opts.plt.unwrap_or(want_plt || !full_relro)
539    }
540
541    /// Checks if LLVM lifetime markers should be emitted.
542    pub fn emit_lifetime_markers(&self) -> bool {
543        self.opts.optimize != config::OptLevel::No
544        // AddressSanitizer and KernelAddressSanitizer uses lifetimes to detect use after scope bugs.
545        //
546        // MemorySanitizer uses lifetimes to detect use of uninitialized stack variables.
547        //
548        // HWAddressSanitizer and KernelHWAddressSanitizer will use lifetimes to detect use after
549        // scope bugs in the future.
550        || self.sanitizers().intersects(SanitizerSet::ADDRESS | SanitizerSet::KERNELADDRESS | SanitizerSet::MEMORY | SanitizerSet::HWADDRESS | SanitizerSet::KERNELHWADDRESS)
551    }
552
553    pub fn diagnostic_width(&self) -> usize {
554        let default_column_width = 140;
555        if let Some(width) = self.opts.diagnostic_width {
556            width
557        } else if self.opts.unstable_opts.ui_testing {
558            default_column_width
559        } else {
560            termize::dimensions().map_or(default_column_width, |(w, _)| w)
561        }
562    }
563
564    /// Returns the default symbol visibility.
565    pub fn default_visibility(&self) -> SymbolVisibility {
566        self.opts
567            .unstable_opts
568            .default_visibility
569            .or(self.target.options.default_visibility)
570            .unwrap_or(SymbolVisibility::Interposable)
571    }
572
573    pub fn staticlib_components(&self, verbatim: bool) -> (&str, &str) {
574        if verbatim {
575            ("", "")
576        } else {
577            (&*self.target.staticlib_prefix, &*self.target.staticlib_suffix)
578        }
579    }
580
581    pub fn lint_groups_iter(&self) -> Box<dyn Iterator<Item = LintGroup> + '_> {
582        match self.lint_store {
583            Some(ref lint_store) => lint_store.lint_groups_iter(),
584            None => Box::new(std::iter::empty()),
585        }
586    }
587}
588
589// JUSTIFICATION: defn of the suggested wrapper fns
590#[allow(rustc::bad_opt_access)]
591impl Session {
592    pub fn verbose_internals(&self) -> bool {
593        self.opts.unstable_opts.verbose_internals
594    }
595
596    pub fn print_llvm_stats(&self) -> bool {
597        self.opts.unstable_opts.print_codegen_stats
598    }
599
600    pub fn verify_llvm_ir(&self) -> bool {
601        self.opts.unstable_opts.verify_llvm_ir || ::core::option::Option::None::<&'static str>option_env!("RUSTC_VERIFY_LLVM_IR").is_some()
602    }
603
604    pub fn binary_dep_depinfo(&self) -> bool {
605        self.opts.unstable_opts.binary_dep_depinfo
606    }
607
608    pub fn mir_opt_level(&self) -> usize {
609        self.opts
610            .unstable_opts
611            .mir_opt_level
612            .unwrap_or_else(|| if self.opts.optimize != OptLevel::No { 2 } else { 1 })
613    }
614
615    /// Calculates the flavor of LTO to use for this compilation.
616    pub fn lto(&self) -> config::Lto {
617        // If our target has codegen requirements ignore the command line
618        if self.target.requires_lto {
619            return config::Lto::Fat;
620        }
621
622        // If the user specified something, return that. If they only said `-C
623        // lto` and we've for whatever reason forced off ThinLTO via the CLI,
624        // then ensure we can't use a ThinLTO.
625        match self.opts.cg.lto {
626            config::LtoCli::Unspecified => {
627                // The compiler was invoked without the `-Clto` flag. Fall
628                // through to the default handling
629            }
630            config::LtoCli::No => {
631                // The user explicitly opted out of any kind of LTO
632                return config::Lto::No;
633            }
634            config::LtoCli::Yes | config::LtoCli::Fat | config::LtoCli::NoParam => {
635                // All of these mean fat LTO
636                return config::Lto::Fat;
637            }
638            config::LtoCli::Thin => {
639                // The user explicitly asked for ThinLTO
640                if !self.thin_lto_supported {
641                    // Backend doesn't support ThinLTO, fallback to fat LTO.
642                    self.dcx().emit_warn(errors::ThinLtoNotSupportedByBackend);
643                    return config::Lto::Fat;
644                }
645                return config::Lto::Thin;
646            }
647        }
648
649        if !self.thin_lto_supported {
650            return config::Lto::No;
651        }
652
653        // Ok at this point the target doesn't require anything and the user
654        // hasn't asked for anything. Our next decision is whether or not
655        // we enable "auto" ThinLTO where we use multiple codegen units and
656        // then do ThinLTO over those codegen units. The logic below will
657        // either return `No` or `ThinLocal`.
658
659        // If processing command line options determined that we're incompatible
660        // with ThinLTO (e.g., `-C lto --emit llvm-ir`) then return that option.
661        if self.opts.cli_forced_local_thinlto_off {
662            return config::Lto::No;
663        }
664
665        // If `-Z thinlto` specified process that, but note that this is mostly
666        // a deprecated option now that `-C lto=thin` exists.
667        if let Some(enabled) = self.opts.unstable_opts.thinlto {
668            if enabled {
669                return config::Lto::ThinLocal;
670            } else {
671                return config::Lto::No;
672            }
673        }
674
675        // If there's only one codegen unit and LTO isn't enabled then there's
676        // no need for ThinLTO so just return false.
677        if self.codegen_units().as_usize() == 1 {
678            return config::Lto::No;
679        }
680
681        // Now we're in "defaults" territory. By default we enable ThinLTO for
682        // optimized compiles (anything greater than O0).
683        match self.opts.optimize {
684            config::OptLevel::No => config::Lto::No,
685            _ => config::Lto::ThinLocal,
686        }
687    }
688
689    /// Returns the panic strategy for this compile session. If the user explicitly selected one
690    /// using '-C panic', use that, otherwise use the panic strategy defined by the target.
691    pub fn panic_strategy(&self) -> PanicStrategy {
692        self.opts.cg.panic.unwrap_or(self.target.panic_strategy)
693    }
694
695    pub fn fewer_names(&self) -> bool {
696        if let Some(fewer_names) = self.opts.unstable_opts.fewer_names {
697            fewer_names
698        } else {
699            let more_names = self.opts.output_types.contains_key(&OutputType::LlvmAssembly)
700                || self.opts.output_types.contains_key(&OutputType::Bitcode)
701                // AddressSanitizer and MemorySanitizer use alloca name when reporting an issue.
702                || self.opts.unstable_opts.sanitizer.intersects(SanitizerSet::ADDRESS | SanitizerSet::MEMORY);
703            !more_names
704        }
705    }
706
707    pub fn unstable_options(&self) -> bool {
708        self.opts.unstable_opts.unstable_options
709    }
710
711    pub fn is_nightly_build(&self) -> bool {
712        self.opts.unstable_features.is_nightly_build()
713    }
714
715    pub fn overflow_checks(&self) -> bool {
716        self.opts.cg.overflow_checks.unwrap_or(self.opts.debug_assertions)
717    }
718
719    pub fn ub_checks(&self) -> bool {
720        self.opts.unstable_opts.ub_checks.unwrap_or(self.opts.debug_assertions)
721    }
722
723    pub fn contract_checks(&self) -> bool {
724        self.opts.unstable_opts.contract_checks.unwrap_or(false)
725    }
726
727    pub fn relocation_model(&self) -> RelocModel {
728        self.opts.cg.relocation_model.unwrap_or(self.target.relocation_model)
729    }
730
731    pub fn code_model(&self) -> Option<CodeModel> {
732        self.opts.cg.code_model.or(self.target.code_model)
733    }
734
735    pub fn tls_model(&self) -> TlsModel {
736        self.opts.unstable_opts.tls_model.unwrap_or(self.target.tls_model)
737    }
738
739    pub fn direct_access_external_data(&self) -> Option<bool> {
740        self.opts
741            .unstable_opts
742            .direct_access_external_data
743            .or(self.target.direct_access_external_data)
744    }
745
746    pub fn split_debuginfo(&self) -> SplitDebuginfo {
747        self.opts.cg.split_debuginfo.unwrap_or(self.target.split_debuginfo)
748    }
749
750    /// Returns the DWARF version passed on the CLI or the default for the target.
751    pub fn dwarf_version(&self) -> u32 {
752        self.opts
753            .cg
754            .dwarf_version
755            .or(self.opts.unstable_opts.dwarf_version)
756            .unwrap_or(self.target.default_dwarf_version)
757    }
758
759    pub fn stack_protector(&self) -> StackProtector {
760        if self.target.options.supports_stack_protector {
761            self.opts.unstable_opts.stack_protector
762        } else {
763            StackProtector::None
764        }
765    }
766
767    pub fn must_emit_unwind_tables(&self) -> bool {
768        // This is used to control the emission of the `uwtable` attribute on
769        // LLVM functions. The `uwtable` attribute according to LLVM is:
770        //
771        //     This attribute indicates that the ABI being targeted requires that an
772        //     unwind table entry be produced for this function even if we can show
773        //     that no exceptions passes by it. This is normally the case for the
774        //     ELF x86-64 abi, but it can be disabled for some compilation units.
775        //
776        // Typically when we're compiling with `-C panic=abort` we don't need
777        // `uwtable` because we can't generate any exceptions! But note that
778        // some targets require unwind tables to generate backtraces.
779        // Unwind tables are needed when compiling with `-C panic=unwind`, but
780        // LLVM won't omit unwind tables unless the function is also marked as
781        // `nounwind`, so users are allowed to disable `uwtable` emission.
782        // Historically rustc always emits `uwtable` attributes by default, so
783        // even they can be disabled, they're still emitted by default.
784        //
785        // On some targets (including windows), however, exceptions include
786        // other events such as illegal instructions, segfaults, etc. This means
787        // that on Windows we end up still needing unwind tables even if the `-C
788        // panic=abort` flag is passed.
789        //
790        // You can also find more info on why Windows needs unwind tables in:
791        //      https://bugzilla.mozilla.org/show_bug.cgi?id=1302078
792        //
793        // If a target requires unwind tables, then they must be emitted.
794        // Otherwise, we can defer to the `-C force-unwind-tables=<yes/no>`
795        // value, if it is provided, or disable them, if not.
796        self.target.requires_uwtable
797            || self
798                .opts
799                .cg
800                .force_unwind_tables
801                .unwrap_or(self.panic_strategy().unwinds() || self.target.default_uwtable)
802    }
803
804    /// Returns the number of query threads that should be used for this
805    /// compilation
806    #[inline]
807    pub fn threads(&self) -> usize {
808        self.opts.unstable_opts.threads
809    }
810
811    /// Returns the number of codegen units that should be used for this
812    /// compilation
813    pub fn codegen_units(&self) -> CodegenUnits {
814        if let Some(n) = self.opts.cli_forced_codegen_units {
815            return CodegenUnits::User(n);
816        }
817        if let Some(n) = self.target.default_codegen_units {
818            return CodegenUnits::Default(n as usize);
819        }
820
821        // If incremental compilation is turned on, we default to a high number
822        // codegen units in order to reduce the "collateral damage" small
823        // changes cause.
824        if self.opts.incremental.is_some() {
825            return CodegenUnits::Default(256);
826        }
827
828        // Why is 16 codegen units the default all the time?
829        //
830        // The main reason for enabling multiple codegen units by default is to
831        // leverage the ability for the codegen backend to do codegen and
832        // optimization in parallel. This allows us, especially for large crates, to
833        // make good use of all available resources on the machine once we've
834        // hit that stage of compilation. Large crates especially then often
835        // take a long time in codegen/optimization and this helps us amortize that
836        // cost.
837        //
838        // Note that a high number here doesn't mean that we'll be spawning a
839        // large number of threads in parallel. The backend of rustc contains
840        // global rate limiting through the `jobserver` crate so we'll never
841        // overload the system with too much work, but rather we'll only be
842        // optimizing when we're otherwise cooperating with other instances of
843        // rustc.
844        //
845        // Rather a high number here means that we should be able to keep a lot
846        // of idle cpus busy. By ensuring that no codegen unit takes *too* long
847        // to build we'll be guaranteed that all cpus will finish pretty closely
848        // to one another and we should make relatively optimal use of system
849        // resources
850        //
851        // Note that the main cost of codegen units is that it prevents LLVM
852        // from inlining across codegen units. Users in general don't have a lot
853        // of control over how codegen units are split up so it's our job in the
854        // compiler to ensure that undue performance isn't lost when using
855        // codegen units (aka we can't require everyone to slap `#[inline]` on
856        // everything).
857        //
858        // If we're compiling at `-O0` then the number doesn't really matter too
859        // much because performance doesn't matter and inlining is ok to lose.
860        // In debug mode we just want to try to guarantee that no cpu is stuck
861        // doing work that could otherwise be farmed to others.
862        //
863        // In release mode, however (O1 and above) performance does indeed
864        // matter! To recover the loss in performance due to inlining we'll be
865        // enabling ThinLTO by default (the function for which is just below).
866        // This will ensure that we recover any inlining wins we otherwise lost
867        // through codegen unit partitioning.
868        //
869        // ---
870        //
871        // Ok that's a lot of words but the basic tl;dr; is that we want a high
872        // number here -- but not too high. Additionally we're "safe" to have it
873        // always at the same number at all optimization levels.
874        //
875        // As a result 16 was chosen here! Mostly because it was a power of 2
876        // and most benchmarks agreed it was roughly a local optimum. Not very
877        // scientific.
878        CodegenUnits::Default(16)
879    }
880
881    pub fn teach(&self, code: ErrCode) -> bool {
882        self.opts.unstable_opts.teach && self.dcx().must_teach(code)
883    }
884
885    pub fn edition(&self) -> Edition {
886        self.opts.edition
887    }
888
889    pub fn link_dead_code(&self) -> bool {
890        self.opts.cg.link_dead_code.unwrap_or(false)
891    }
892
893    /// Get the deployment target on Apple platforms based on the standard environment variables,
894    /// or fall back to the minimum version supported by `rustc`.
895    ///
896    /// This should be guarded behind `if sess.target.is_like_darwin`.
897    pub fn apple_deployment_target(&self) -> apple::OSVersion {
898        let min = apple::OSVersion::minimum_deployment_target(&self.target);
899        let env_var = apple::deployment_target_env_var(&self.target.os);
900
901        // FIXME(madsmtm): Track changes to this.
902        if let Ok(deployment_target) = env::var(env_var) {
903            match apple::OSVersion::from_str(&deployment_target) {
904                Ok(version) => {
905                    let os_min = apple::OSVersion::os_minimum_deployment_target(&self.target.os);
906                    // It is common that the deployment target is set a bit too low, for example on
907                    // macOS Aarch64 to also target older x86_64. So we only want to warn when variable
908                    // is lower than the minimum OS supported by rustc, not when the variable is lower
909                    // than the minimum for a specific target.
910                    if version < os_min {
911                        self.dcx().emit_warn(errors::AppleDeploymentTarget::TooLow {
912                            env_var,
913                            version: version.fmt_pretty().to_string(),
914                            os_min: os_min.fmt_pretty().to_string(),
915                        });
916                    }
917
918                    // Raise the deployment target to the minimum supported.
919                    version.max(min)
920                }
921                Err(error) => {
922                    self.dcx().emit_err(errors::AppleDeploymentTarget::Invalid { env_var, error });
923                    min
924                }
925            }
926        } else {
927            // If no deployment target variable is set, default to the minimum found above.
928            min
929        }
930    }
931
932    pub fn sanitizers(&self) -> SanitizerSet {
933        return self.opts.unstable_opts.sanitizer | self.target.options.default_sanitizers;
934    }
935}
936
937// JUSTIFICATION: part of session construction
938#[allow(rustc::bad_opt_access)]
939fn default_emitter(sopts: &config::Options, source_map: Arc<SourceMap>) -> Box<DynEmitter> {
940    let macro_backtrace = sopts.unstable_opts.macro_backtrace;
941    let track_diagnostics = sopts.unstable_opts.track_diagnostics;
942    let terminal_url = match sopts.unstable_opts.terminal_urls {
943        TerminalUrl::Auto => {
944            match (std::env::var("COLORTERM").as_deref(), std::env::var("TERM").as_deref()) {
945                (Ok("truecolor"), Ok("xterm-256color"))
946                    if sopts.unstable_features.is_nightly_build() =>
947                {
948                    TerminalUrl::Yes
949                }
950                _ => TerminalUrl::No,
951            }
952        }
953        t => t,
954    };
955
956    let source_map = if sopts.unstable_opts.link_only { None } else { Some(source_map) };
957
958    match sopts.error_format {
959        config::ErrorOutputType::HumanReadable { kind, color_config } => match kind {
960            HumanReadableErrorType { short, unicode } => {
961                let emitter = AnnotateSnippetEmitter::new(stderr_destination(color_config))
962                    .sm(source_map)
963                    .short_message(short)
964                    .diagnostic_width(sopts.diagnostic_width)
965                    .macro_backtrace(macro_backtrace)
966                    .track_diagnostics(track_diagnostics)
967                    .terminal_url(terminal_url)
968                    .theme(if unicode { OutputTheme::Unicode } else { OutputTheme::Ascii })
969                    .ignored_directories_in_source_blocks(
970                        sopts.unstable_opts.ignore_directory_in_diagnostics_source_blocks.clone(),
971                    );
972                Box::new(emitter.ui_testing(sopts.unstable_opts.ui_testing))
973            }
974        },
975        config::ErrorOutputType::Json { pretty, json_rendered, color_config } => Box::new(
976            JsonEmitter::new(
977                Box::new(io::BufWriter::new(io::stderr())),
978                source_map,
979                pretty,
980                json_rendered,
981                color_config,
982            )
983            .ui_testing(sopts.unstable_opts.ui_testing)
984            .ignored_directories_in_source_blocks(
985                sopts.unstable_opts.ignore_directory_in_diagnostics_source_blocks.clone(),
986            )
987            .diagnostic_width(sopts.diagnostic_width)
988            .macro_backtrace(macro_backtrace)
989            .track_diagnostics(track_diagnostics)
990            .terminal_url(terminal_url),
991        ),
992    }
993}
994
995// JUSTIFICATION: literally session construction
996#[allow(rustc::bad_opt_access)]
997pub fn build_session(
998    sopts: config::Options,
999    io: CompilerIO,
1000    driver_lint_caps: FxHashMap<lint::LintId, lint::Level>,
1001    target: Target,
1002    cfg_version: &'static str,
1003    ice_file: Option<PathBuf>,
1004    using_internal_features: &'static AtomicBool,
1005) -> Session {
1006    // FIXME: This is not general enough to make the warning lint completely override
1007    // normal diagnostic warnings, since the warning lint can also be denied and changed
1008    // later via the source code.
1009    let warnings_allow = sopts
1010        .lint_opts
1011        .iter()
1012        .rfind(|&(key, _)| *key == "warnings")
1013        .is_some_and(|&(_, level)| level == lint::Allow);
1014    let cap_lints_allow = sopts.lint_cap.is_some_and(|cap| cap == lint::Allow);
1015    let can_emit_warnings = !(warnings_allow || cap_lints_allow);
1016
1017    let source_map = rustc_span::source_map::get_source_map().unwrap();
1018    let emitter = default_emitter(&sopts, Arc::clone(&source_map));
1019
1020    let mut dcx =
1021        DiagCtxt::new(emitter).with_flags(sopts.unstable_opts.dcx_flags(can_emit_warnings));
1022    if let Some(ice_file) = ice_file {
1023        dcx = dcx.with_ice_file(ice_file);
1024    }
1025
1026    let host_triple = TargetTuple::from_tuple(config::host_tuple());
1027    let (host, target_warnings) =
1028        Target::search(&host_triple, sopts.sysroot.path(), sopts.unstable_opts.unstable_options)
1029            .unwrap_or_else(|e| {
1030                dcx.handle().fatal(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("Error loading host specification: {0}",
                e))
    })format!("Error loading host specification: {e}"))
1031            });
1032    for warning in target_warnings.warning_messages() {
1033        dcx.handle().warn(warning)
1034    }
1035
1036    let self_profiler = if let SwitchWithOptPath::Enabled(ref d) = sopts.unstable_opts.self_profile
1037    {
1038        let directory = if let Some(directory) = d { directory } else { std::path::Path::new(".") };
1039
1040        let profiler = SelfProfiler::new(
1041            directory,
1042            sopts.crate_name.as_deref(),
1043            sopts.unstable_opts.self_profile_events.as_deref(),
1044            &sopts.unstable_opts.self_profile_counter,
1045        );
1046        match profiler {
1047            Ok(profiler) => Some(Arc::new(profiler)),
1048            Err(e) => {
1049                dcx.handle().emit_warn(errors::FailedToCreateProfiler { err: e.to_string() });
1050                None
1051            }
1052        }
1053    } else {
1054        None
1055    };
1056
1057    let mut psess = ParseSess::with_dcx(dcx, source_map);
1058    psess.assume_incomplete_release = sopts.unstable_opts.assume_incomplete_release;
1059
1060    let host_triple = config::host_tuple();
1061    let target_triple = sopts.target_triple.tuple();
1062    // FIXME use host sysroot?
1063    let host_tlib_path =
1064        Arc::new(SearchPath::from_sysroot_and_triple(sopts.sysroot.path(), host_triple));
1065    let target_tlib_path = if host_triple == target_triple {
1066        // Use the same `SearchPath` if host and target triple are identical to avoid unnecessary
1067        // rescanning of the target lib path and an unnecessary allocation.
1068        Arc::clone(&host_tlib_path)
1069    } else {
1070        Arc::new(SearchPath::from_sysroot_and_triple(sopts.sysroot.path(), target_triple))
1071    };
1072
1073    let prof = SelfProfilerRef::new(
1074        self_profiler,
1075        sopts.unstable_opts.time_passes.then(|| sopts.unstable_opts.time_passes_format),
1076    );
1077
1078    let ctfe_backtrace = Lock::new(match env::var("RUSTC_CTFE_BACKTRACE") {
1079        Ok(ref val) if val == "immediate" => CtfeBacktrace::Immediate,
1080        Ok(ref val) if val != "0" => CtfeBacktrace::Capture,
1081        _ => CtfeBacktrace::Disabled,
1082    });
1083
1084    let asm_arch = if target.allow_asm { InlineAsmArch::from_arch(&target.arch) } else { None };
1085    let target_filesearch =
1086        filesearch::FileSearch::new(&sopts.search_paths, &target_tlib_path, &target);
1087    let host_filesearch = filesearch::FileSearch::new(&sopts.search_paths, &host_tlib_path, &host);
1088
1089    let invocation_temp = sopts
1090        .incremental
1091        .as_ref()
1092        .map(|_| rng().next_u32().to_base_fixed_len(CASE_INSENSITIVE).to_string());
1093
1094    let timings = TimingSectionHandler::new(sopts.json_timings);
1095
1096    let sess = Session {
1097        target,
1098        host,
1099        opts: sopts,
1100        target_tlib_path,
1101        psess,
1102        io,
1103        incr_comp_session: RwLock::new(IncrCompSession::NotInitialized),
1104        prof,
1105        timings,
1106        code_stats: Default::default(),
1107        lint_store: None,
1108        driver_lint_caps,
1109        ctfe_backtrace,
1110        miri_unleashed_features: Lock::new(Default::default()),
1111        asm_arch,
1112        target_features: Default::default(),
1113        unstable_target_features: Default::default(),
1114        cfg_version,
1115        using_internal_features,
1116        env_depinfo: Default::default(),
1117        file_depinfo: Default::default(),
1118        target_filesearch,
1119        host_filesearch,
1120        invocation_temp,
1121        replaced_intrinsics: FxHashSet::default(), // filled by `run_compiler`
1122        thin_lto_supported: true,                  // filled by `run_compiler`
1123        mir_opt_bisect_eval_count: AtomicUsize::new(0),
1124        used_features: Lock::default(),
1125    };
1126
1127    validate_commandline_args_with_session_available(&sess);
1128
1129    sess
1130}
1131
1132/// Validate command line arguments with a `Session`.
1133///
1134/// If it is useful to have a Session available already for validating a commandline argument, you
1135/// can do so here.
1136// JUSTIFICATION: needs to access args to validate them
1137#[allow(rustc::bad_opt_access)]
1138fn validate_commandline_args_with_session_available(sess: &Session) {
1139    // Since we don't know if code in an rlib will be linked to statically or
1140    // dynamically downstream, rustc generates `__imp_` symbols that help linkers
1141    // on Windows deal with this lack of knowledge (#27438). Unfortunately,
1142    // these manually generated symbols confuse LLD when it tries to merge
1143    // bitcode during ThinLTO. Therefore we disallow dynamic linking on Windows
1144    // when compiling for LLD ThinLTO. This way we can validly just not generate
1145    // the `dllimport` attributes and `__imp_` symbols in that case.
1146    if sess.opts.cg.linker_plugin_lto.enabled()
1147        && sess.opts.cg.prefer_dynamic
1148        && sess.target.is_like_windows
1149    {
1150        sess.dcx().emit_err(errors::LinkerPluginToWindowsNotSupported);
1151    }
1152
1153    // Make sure that any given profiling data actually exists so LLVM can't
1154    // decide to silently skip PGO.
1155    if let Some(ref path) = sess.opts.cg.profile_use {
1156        if !path.exists() {
1157            sess.dcx().emit_err(errors::ProfileUseFileDoesNotExist { path });
1158        }
1159    }
1160
1161    // Do the same for sample profile data.
1162    if let Some(ref path) = sess.opts.unstable_opts.profile_sample_use {
1163        if !path.exists() {
1164            sess.dcx().emit_err(errors::ProfileSampleUseFileDoesNotExist { path });
1165        }
1166    }
1167
1168    // Unwind tables cannot be disabled if the target requires them.
1169    if let Some(include_uwtables) = sess.opts.cg.force_unwind_tables {
1170        if sess.target.requires_uwtable && !include_uwtables {
1171            sess.dcx().emit_err(errors::TargetRequiresUnwindTables);
1172        }
1173    }
1174
1175    // Sanitizers can only be used on platforms that we know have working sanitizer codegen.
1176    let supported_sanitizers = sess.target.options.supported_sanitizers;
1177    let mut unsupported_sanitizers = sess.opts.unstable_opts.sanitizer - supported_sanitizers;
1178    // Niche: if `fixed-x18`, or effectively switching on `reserved-x18` flag, is enabled
1179    // we should allow Shadow Call Stack sanitizer.
1180    if sess.opts.unstable_opts.fixed_x18 && sess.target.arch == Arch::AArch64 {
1181        unsupported_sanitizers -= SanitizerSet::SHADOWCALLSTACK;
1182    }
1183    match unsupported_sanitizers.into_iter().count() {
1184        0 => {}
1185        1 => {
1186            sess.dcx()
1187                .emit_err(errors::SanitizerNotSupported { us: unsupported_sanitizers.to_string() });
1188        }
1189        _ => {
1190            sess.dcx().emit_err(errors::SanitizersNotSupported {
1191                us: unsupported_sanitizers.to_string(),
1192            });
1193        }
1194    }
1195
1196    // Cannot mix and match mutually-exclusive sanitizers.
1197    if let Some((first, second)) = sess.opts.unstable_opts.sanitizer.mutually_exclusive() {
1198        sess.dcx().emit_err(errors::CannotMixAndMatchSanitizers {
1199            first: first.to_string(),
1200            second: second.to_string(),
1201        });
1202    }
1203
1204    // Cannot enable crt-static with sanitizers on Linux
1205    if sess.crt_static(None)
1206        && !sess.opts.unstable_opts.sanitizer.is_empty()
1207        && !sess.target.is_like_msvc
1208    {
1209        sess.dcx().emit_err(errors::CannotEnableCrtStaticLinux);
1210    }
1211
1212    // LLVM CFI requires LTO.
1213    if sess.is_sanitizer_cfi_enabled()
1214        && !(sess.lto() == config::Lto::Fat || sess.opts.cg.linker_plugin_lto.enabled())
1215    {
1216        sess.dcx().emit_err(errors::SanitizerCfiRequiresLto);
1217    }
1218
1219    // KCFI requires panic=abort
1220    if sess.is_sanitizer_kcfi_enabled() && sess.panic_strategy().unwinds() {
1221        sess.dcx().emit_err(errors::SanitizerKcfiRequiresPanicAbort);
1222    }
1223
1224    // LLVM CFI using rustc LTO requires a single codegen unit.
1225    if sess.is_sanitizer_cfi_enabled()
1226        && sess.lto() == config::Lto::Fat
1227        && (sess.codegen_units().as_usize() != 1)
1228    {
1229        sess.dcx().emit_err(errors::SanitizerCfiRequiresSingleCodegenUnit);
1230    }
1231
1232    // Canonical jump tables requires CFI.
1233    if sess.is_sanitizer_cfi_canonical_jump_tables_disabled() {
1234        if !sess.is_sanitizer_cfi_enabled() {
1235            sess.dcx().emit_err(errors::SanitizerCfiCanonicalJumpTablesRequiresCfi);
1236        }
1237    }
1238
1239    // KCFI arity indicator requires KCFI.
1240    if sess.is_sanitizer_kcfi_arity_enabled() && !sess.is_sanitizer_kcfi_enabled() {
1241        sess.dcx().emit_err(errors::SanitizerKcfiArityRequiresKcfi);
1242    }
1243
1244    // LLVM CFI pointer generalization requires CFI or KCFI.
1245    if sess.is_sanitizer_cfi_generalize_pointers_enabled() {
1246        if !(sess.is_sanitizer_cfi_enabled() || sess.is_sanitizer_kcfi_enabled()) {
1247            sess.dcx().emit_err(errors::SanitizerCfiGeneralizePointersRequiresCfi);
1248        }
1249    }
1250
1251    // LLVM CFI integer normalization requires CFI or KCFI.
1252    if sess.is_sanitizer_cfi_normalize_integers_enabled() {
1253        if !(sess.is_sanitizer_cfi_enabled() || sess.is_sanitizer_kcfi_enabled()) {
1254            sess.dcx().emit_err(errors::SanitizerCfiNormalizeIntegersRequiresCfi);
1255        }
1256    }
1257
1258    // LTO unit splitting requires LTO.
1259    if sess.is_split_lto_unit_enabled()
1260        && !(sess.lto() == config::Lto::Fat
1261            || sess.lto() == config::Lto::Thin
1262            || sess.opts.cg.linker_plugin_lto.enabled())
1263    {
1264        sess.dcx().emit_err(errors::SplitLtoUnitRequiresLto);
1265    }
1266
1267    // VFE requires LTO.
1268    if sess.lto() != config::Lto::Fat {
1269        if sess.opts.unstable_opts.virtual_function_elimination {
1270            sess.dcx().emit_err(errors::UnstableVirtualFunctionElimination);
1271        }
1272    }
1273
1274    if sess.opts.unstable_opts.stack_protector != StackProtector::None {
1275        if !sess.target.options.supports_stack_protector {
1276            sess.dcx().emit_warn(errors::StackProtectorNotSupportedForTarget {
1277                stack_protector: sess.opts.unstable_opts.stack_protector,
1278                target_triple: &sess.opts.target_triple,
1279            });
1280        }
1281    }
1282
1283    if sess.opts.unstable_opts.small_data_threshold.is_some() {
1284        if sess.target.small_data_threshold_support() == SmallDataThresholdSupport::None {
1285            sess.dcx().emit_warn(errors::SmallDataThresholdNotSupportedForTarget {
1286                target_triple: &sess.opts.target_triple,
1287            })
1288        }
1289    }
1290
1291    if sess.opts.unstable_opts.branch_protection.is_some() && sess.target.arch != Arch::AArch64 {
1292        sess.dcx().emit_err(errors::BranchProtectionRequiresAArch64);
1293    }
1294
1295    if let Some(dwarf_version) =
1296        sess.opts.cg.dwarf_version.or(sess.opts.unstable_opts.dwarf_version)
1297    {
1298        // DWARF 1 is not supported by LLVM and DWARF 6 is not yet finalized.
1299        if dwarf_version < 2 || dwarf_version > 5 {
1300            sess.dcx().emit_err(errors::UnsupportedDwarfVersion { dwarf_version });
1301        }
1302    }
1303
1304    if !sess.target.options.supported_split_debuginfo.contains(&sess.split_debuginfo())
1305        && !sess.opts.unstable_opts.unstable_options
1306    {
1307        sess.dcx()
1308            .emit_err(errors::SplitDebugInfoUnstablePlatform { debuginfo: sess.split_debuginfo() });
1309    }
1310
1311    if sess.opts.unstable_opts.embed_source {
1312        let dwarf_version = sess.dwarf_version();
1313
1314        if dwarf_version < 5 {
1315            sess.dcx().emit_warn(errors::EmbedSourceInsufficientDwarfVersion { dwarf_version });
1316        }
1317
1318        if sess.opts.debuginfo == DebugInfo::None {
1319            sess.dcx().emit_warn(errors::EmbedSourceRequiresDebugInfo);
1320        }
1321    }
1322
1323    if sess.opts.unstable_opts.instrument_xray.is_some() && !sess.target.options.supports_xray {
1324        sess.dcx().emit_err(errors::InstrumentationNotSupported { us: "XRay".to_string() });
1325    }
1326
1327    if let Some(flavor) = sess.opts.cg.linker_flavor
1328        && let Some(compatible_list) = sess.target.linker_flavor.check_compatibility(flavor)
1329    {
1330        let flavor = flavor.desc();
1331        sess.dcx().emit_err(errors::IncompatibleLinkerFlavor { flavor, compatible_list });
1332    }
1333
1334    if sess.opts.unstable_opts.function_return != FunctionReturn::default() {
1335        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) {
1336            sess.dcx().emit_err(errors::FunctionReturnRequiresX86OrX8664);
1337        }
1338    }
1339
1340    if sess.opts.unstable_opts.indirect_branch_cs_prefix {
1341        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) {
1342            sess.dcx().emit_err(errors::IndirectBranchCsPrefixRequiresX86OrX8664);
1343        }
1344    }
1345
1346    if let Some(regparm) = sess.opts.unstable_opts.regparm {
1347        if regparm > 3 {
1348            sess.dcx().emit_err(errors::UnsupportedRegparm { regparm });
1349        }
1350        if sess.target.arch != Arch::X86 {
1351            sess.dcx().emit_err(errors::UnsupportedRegparmArch);
1352        }
1353    }
1354    if sess.opts.unstable_opts.reg_struct_return {
1355        if sess.target.arch != Arch::X86 {
1356            sess.dcx().emit_err(errors::UnsupportedRegStructReturnArch);
1357        }
1358    }
1359
1360    // The code model check applies to `thunk` and `thunk-extern`, but not `thunk-inline`, so it is
1361    // kept as a `match` to force a change if new ones are added, even if we currently only support
1362    // `thunk-extern` like Clang.
1363    match sess.opts.unstable_opts.function_return {
1364        FunctionReturn::Keep => (),
1365        FunctionReturn::ThunkExtern => {
1366            // FIXME: In principle, the inherited base LLVM target code model could be large,
1367            // but this only checks whether we were passed one explicitly (like Clang does).
1368            if let Some(code_model) = sess.code_model()
1369                && code_model == CodeModel::Large
1370            {
1371                sess.dcx().emit_err(errors::FunctionReturnThunkExternRequiresNonLargeCodeModel);
1372            }
1373        }
1374    }
1375
1376    if sess.opts.unstable_opts.packed_stack {
1377        if sess.target.arch != Arch::S390x {
1378            sess.dcx().emit_err(errors::UnsupportedPackedStack);
1379        }
1380    }
1381}
1382
1383/// Holds data on the current incremental compilation session, if there is one.
1384#[derive(#[automatically_derived]
impl ::core::fmt::Debug for IncrCompSession {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        match self {
            IncrCompSession::NotInitialized =>
                ::core::fmt::Formatter::write_str(f, "NotInitialized"),
            IncrCompSession::Active {
                session_directory: __self_0, _lock_file: __self_1 } =>
                ::core::fmt::Formatter::debug_struct_field2_finish(f,
                    "Active", "session_directory", __self_0, "_lock_file",
                    &__self_1),
            IncrCompSession::Finalized { session_directory: __self_0 } =>
                ::core::fmt::Formatter::debug_struct_field1_finish(f,
                    "Finalized", "session_directory", &__self_0),
            IncrCompSession::InvalidBecauseOfErrors {
                session_directory: __self_0 } =>
                ::core::fmt::Formatter::debug_struct_field1_finish(f,
                    "InvalidBecauseOfErrors", "session_directory", &__self_0),
        }
    }
}Debug)]
1385enum IncrCompSession {
1386    /// This is the state the session will be in until the incr. comp. dir is
1387    /// needed.
1388    NotInitialized,
1389    /// This is the state during which the session directory is private and can
1390    /// be modified. `_lock_file` is never directly used, but its presence
1391    /// alone has an effect, because the file will unlock when the session is
1392    /// dropped.
1393    Active { session_directory: PathBuf, _lock_file: flock::Lock },
1394    /// This is the state after the session directory has been finalized. In this
1395    /// state, the contents of the directory must not be modified any more.
1396    Finalized { session_directory: PathBuf },
1397    /// This is an error state that is reached when some compilation error has
1398    /// occurred. It indicates that the contents of the session directory must
1399    /// not be used, since they might be invalid.
1400    InvalidBecauseOfErrors { session_directory: PathBuf },
1401}
1402
1403/// A wrapper around an [`DiagCtxt`] that is used for early error emissions.
1404pub struct EarlyDiagCtxt {
1405    dcx: DiagCtxt,
1406}
1407
1408impl EarlyDiagCtxt {
1409    pub fn new(output: ErrorOutputType) -> Self {
1410        let emitter = mk_emitter(output);
1411        Self { dcx: DiagCtxt::new(emitter) }
1412    }
1413
1414    /// Swap out the underlying dcx once we acquire the user's preference on error emission
1415    /// format. If `early_err` was previously called this will panic.
1416    pub fn set_error_format(&mut self, output: ErrorOutputType) {
1417        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());
1418
1419        let emitter = mk_emitter(output);
1420        self.dcx = DiagCtxt::new(emitter);
1421    }
1422
1423    pub fn early_note(&self, msg: impl Into<DiagMessage>) {
1424        self.dcx.handle().note(msg)
1425    }
1426
1427    pub fn early_help(&self, msg: impl Into<DiagMessage>) {
1428        self.dcx.handle().struct_help(msg).emit()
1429    }
1430
1431    #[must_use = "raise_fatal must be called on the returned ErrorGuaranteed in order to exit with a non-zero status code"]
1432    pub fn early_err(&self, msg: impl Into<DiagMessage>) -> ErrorGuaranteed {
1433        self.dcx.handle().err(msg)
1434    }
1435
1436    pub fn early_fatal(&self, msg: impl Into<DiagMessage>) -> ! {
1437        self.dcx.handle().fatal(msg)
1438    }
1439
1440    pub fn early_struct_fatal(&self, msg: impl Into<DiagMessage>) -> Diag<'_, FatalAbort> {
1441        self.dcx.handle().struct_fatal(msg)
1442    }
1443
1444    pub fn early_warn(&self, msg: impl Into<DiagMessage>) {
1445        self.dcx.handle().warn(msg)
1446    }
1447
1448    pub fn early_struct_warn(&self, msg: impl Into<DiagMessage>) -> Diag<'_, ()> {
1449        self.dcx.handle().struct_warn(msg)
1450    }
1451}
1452
1453fn mk_emitter(output: ErrorOutputType) -> Box<DynEmitter> {
1454    let emitter: Box<DynEmitter> = match output {
1455        config::ErrorOutputType::HumanReadable { kind, color_config } => match kind {
1456            HumanReadableErrorType { short, unicode } => Box::new(
1457                AnnotateSnippetEmitter::new(stderr_destination(color_config))
1458                    .theme(if unicode { OutputTheme::Unicode } else { OutputTheme::Ascii })
1459                    .short_message(short),
1460            ),
1461        },
1462        config::ErrorOutputType::Json { pretty, json_rendered, color_config } => {
1463            Box::new(JsonEmitter::new(
1464                Box::new(io::BufWriter::new(io::stderr())),
1465                Some(Arc::new(SourceMap::new(FilePathMapping::empty()))),
1466                pretty,
1467                json_rendered,
1468                color_config,
1469            ))
1470        }
1471    };
1472    emitter
1473}