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 rustc_data_structures::fx::{FxHashMap, FxHashSet, FxIndexSet};
9use rustc_data_structures::profiling::{SelfProfiler, SelfProfilerRef};
10use rustc_data_structures::sync::{
11 AppendOnlyVec, DynSend, DynSync, Lock, MappedReadGuard, ReadGuard, RwLock,
12};
13use rustc_data_structures::{Limit, flock};
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_feature::UnstableFeatures;
24use rustc_macros::StableHash;
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, CfgAbi, CodeModel, DebuginfoKind, Os, PanicStrategy, RelocModel, RelroLevel,
32 SanitizerSet, SmallDataThresholdSupport, SplitDebuginfo, StackProtector, SymbolVisibility,
33 Target, 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, Cfg, CheckCfg, CoverageLevel, CoverageOptions, CrateType, DebugInfo, ErrorOutputType,
40 FunctionReturn, Input, InstrumentCoverage, InstrumentMcount, NATIVE_CPU, OptLevel, OutFileName,
41 OutputType, PointerAuthOption, SwitchWithOptPath,
42};
43use crate::filesearch::FileSearch;
44use crate::lint::LintId;
45use crate::parse::ParseSess;
46use crate::search_paths::SearchPath;
47use crate::{diagnostics, filesearch, lint};
48
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)]
51pub enum CtfeBacktrace {
52 Disabled,
54 Capture,
57 Immediate,
59}
60
61#[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 ::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)]
62pub struct Limits {
63 pub recursion_limit: Limit,
66 pub move_size_limit: Limit,
69 pub type_length_limit: Limit,
71 pub pattern_complexity_limit: Limit,
73}
74
75pub struct CompilerIO {
76 pub input: Input,
77 pub output_dir: Option<PathBuf>,
78 pub output_file: Option<OutFileName>,
79 pub temps_dir: Option<PathBuf>,
80}
81
82pub trait DynLintStore: Any + DynSync + DynSend {
83 fn lint_groups_iter(&self) -> Box<dyn Iterator<Item = LintGroup> + '_>;
85}
86
87#[derive(#[automatically_derived]
impl ::core::clone::Clone for PointerAuthARM8_3Key {
#[inline]
fn clone(&self) -> PointerAuthARM8_3Key { *self }
}Clone, #[automatically_derived]
impl ::core::marker::Copy for PointerAuthARM8_3Key { }Copy, #[automatically_derived]
impl ::core::fmt::Debug for PointerAuthARM8_3Key {
#[inline]
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::cmp::PartialEq for PointerAuthARM8_3Key {
#[inline]
fn eq(&self, other: &PointerAuthARM8_3Key) -> bool {
let __self_discr = ::core::intrinsics::discriminant_value(self);
let __arg1_discr = ::core::intrinsics::discriminant_value(other);
__self_discr == __arg1_discr
}
}PartialEq, #[automatically_derived]
impl ::core::cmp::Eq for PointerAuthARM8_3Key {
#[inline]
#[doc(hidden)]
#[coverage(off)]
fn assert_fields_are_eq(&self) {}
}Eq)]
90pub enum PointerAuthARM8_3Key {
91 ASIA = 0,
92 ASIB = 1,
93 ASDA = 2,
94 ASDB = 3,
95}
96
97pub enum PointerAuthDiscrimination {
99 None,
101 Type,
103 Decl,
105 Constant,
107}
108
109pub enum PointerAuthAddressDiscriminator {
111 HardwareAddress(bool),
113 Synthetic(u64),
116}
117
118pub struct PointerAuthSchema {
119 pub is_address_discriminated: PointerAuthAddressDiscriminator,
120 pub discrimination_kind: PointerAuthDiscrimination,
121 pub key: PointerAuthARM8_3Key,
122 pub constant_discriminator: u16,
123}
124impl PointerAuthSchema {
125 pub fn function_pointers_default(target: &Target) -> Self {
126 if !(target.cfg_abi == CfgAbi::Pauthtest) {
::core::panicking::panic("assertion failed: target.cfg_abi == CfgAbi::Pauthtest")
};assert!(target.cfg_abi == CfgAbi::Pauthtest);
127 return Self {
128 is_address_discriminated: PointerAuthAddressDiscriminator::HardwareAddress(false),
129 discrimination_kind: PointerAuthDiscrimination::None,
130 key: PointerAuthARM8_3Key::ASIA,
131 constant_discriminator: 0,
132 };
133 }
134 pub fn init_fini_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::Synthetic(1),
138 discrimination_kind: PointerAuthDiscrimination::None,
139 key: PointerAuthARM8_3Key::ASIA,
140 constant_discriminator: 0xd9d4,
142 };
143 }
144}
145
146pub struct PointerAuthConfig {
147 pub return_addresses: bool,
149 pub auth_traps: bool,
151 pub indirect_gotos: bool,
153 pub elf_got: bool,
155 pub aarch64_jump_table_hardening: bool,
157 pub function_pointers: Option<PointerAuthSchema>,
159 pub init_fini: Option<PointerAuthSchema>,
161 pub intrinsics: bool,
163 pub typeinfo_vt_ptr_discrimination: bool,
166 pub vt_ptr_addr_discrimination: bool,
167 pub vt_ptr_type_discrimination: bool,
168}
169impl PointerAuthConfig {
170 fn default(target: &Target) -> Self {
171 if !(target.cfg_abi == CfgAbi::Pauthtest) {
::core::panicking::panic("assertion failed: target.cfg_abi == CfgAbi::Pauthtest")
};assert!(target.cfg_abi == CfgAbi::Pauthtest);
172 return Self {
173 return_addresses: true,
174 auth_traps: true,
175 indirect_gotos: true,
176 elf_got: false,
177 aarch64_jump_table_hardening: true,
178 function_pointers: Some(PointerAuthSchema::function_pointers_default(target)),
179 init_fini: Some(PointerAuthSchema::init_fini_default(target)),
180 intrinsics: true,
181 typeinfo_vt_ptr_discrimination: true,
182 vt_ptr_addr_discrimination: true,
183 vt_ptr_type_discrimination: true,
184 };
185 }
186 pub fn calculate_pauth_abi_version(&self, target: &Target) -> u32 {
187 if !(target.cfg_abi == CfgAbi::Pauthtest) {
::core::panicking::panic("assertion failed: target.cfg_abi == CfgAbi::Pauthtest")
};assert!(target.cfg_abi == CfgAbi::Pauthtest);
188 const INTRINSICS: u32 = 0;
198 const CALLS: u32 = 1;
199 const RETURNS: u32 = 2;
200 const AUTHTRAPS: u32 = 3;
201 const VT_PTR_ADDR_DISCR: u32 = 4;
202 const VT_PTR_TYPE_DISCR: u32 = 5;
203 const INIT_FINI: u32 = 6;
204 const INIT_FINI_ADDR_DISC: u32 = 7;
205 const GOT: u32 = 8;
206 const GOTOS: u32 = 9;
207 const TYPEINFO_VT_PTR_DISCR: u32 = 10;
208 let pauth_abi_version: u32 = (u32::from(self.intrinsics) << INTRINSICS)
212 | (u32::from(self.function_pointers.is_some()) << CALLS)
213 | (u32::from(self.return_addresses) << RETURNS)
214 | (u32::from(self.auth_traps) << AUTHTRAPS)
215 | (u32::from(self.vt_ptr_addr_discrimination) << VT_PTR_ADDR_DISCR)
216 | (u32::from(self.vt_ptr_type_discrimination) << VT_PTR_TYPE_DISCR)
217 | (u32::from(self.init_fini.is_some()) << INIT_FINI)
218 | (u32::from(self.init_fini.as_ref().is_some_and(|schema| {
219 #[allow(non_exhaustive_omitted_patterns)] match schema.is_address_discriminated
{
PointerAuthAddressDiscriminator::HardwareAddress(true) |
PointerAuthAddressDiscriminator::Synthetic(_) => true,
_ => false,
}matches!(
220 schema.is_address_discriminated,
221 PointerAuthAddressDiscriminator::HardwareAddress(true)
222 | PointerAuthAddressDiscriminator::Synthetic(_)
223 )
224 })) << INIT_FINI_ADDR_DISC)
225 | (u32::from(self.elf_got) << GOT)
226 | (u32::from(self.indirect_gotos) << GOTOS)
227 | (u32::from(self.typeinfo_vt_ptr_discrimination) << TYPEINFO_VT_PTR_DISCR);
228
229 pauth_abi_version
230 }
231 pub fn from_raw(raw: &[(PointerAuthOption, bool)], target: &Target) -> Option<Self> {
232 if target.cfg_abi != CfgAbi::Pauthtest {
233 return None;
234 }
235
236 let mut cfg = Self::default(target);
237 if raw.is_empty() {
238 return Some(cfg);
239 }
240
241 for (opt, enabled) in raw {
242 match opt {
243 PointerAuthOption::Calls => {
244 if *enabled {
245 cfg.function_pointers.get_or_insert_with(|| {
246 PointerAuthSchema::function_pointers_default(target)
247 });
248 } else {
249 cfg.function_pointers = None;
250 }
251 }
252 PointerAuthOption::FunctionPointerTypeDiscrimination => {
253 if *enabled {
254 let schema = cfg.function_pointers.get_or_insert_with(|| {
255 PointerAuthSchema::function_pointers_default(target)
256 });
257 schema.discrimination_kind = PointerAuthDiscrimination::Type;
258 } else if let Some(schema) = &mut cfg.function_pointers {
259 schema.discrimination_kind = PointerAuthDiscrimination::None;
260 }
261 }
262 PointerAuthOption::ReturnAddresses => cfg.return_addresses = *enabled,
263 PointerAuthOption::AuthTraps => cfg.auth_traps = *enabled,
264 PointerAuthOption::IndirectGotos => cfg.indirect_gotos = *enabled,
265 PointerAuthOption::ElfGot => cfg.elf_got = *enabled,
266 PointerAuthOption::Aarch64JumpTableHardening => {
267 cfg.aarch64_jump_table_hardening = *enabled
268 }
269 PointerAuthOption::InitFini => {
270 if *enabled {
271 cfg.init_fini
272 .get_or_insert_with(|| PointerAuthSchema::init_fini_default(target));
273 } else {
274 cfg.init_fini = None;
275 }
276 }
277 PointerAuthOption::InitFiniAddressDiscrimination => {
278 if *enabled {
279 let schema = cfg
280 .init_fini
281 .get_or_insert_with(|| PointerAuthSchema::init_fini_default(target));
282 schema.is_address_discriminated =
283 PointerAuthAddressDiscriminator::HardwareAddress(true);
284 } else if let Some(schema) = &mut cfg.init_fini {
285 schema.is_address_discriminated =
286 PointerAuthAddressDiscriminator::Synthetic(1);
287 }
288 }
289
290 PointerAuthOption::Intrinsics => cfg.intrinsics = *enabled,
291 PointerAuthOption::TypeInfoVTPtrDisc => {
292 cfg.typeinfo_vt_ptr_discrimination = *enabled
293 }
294 PointerAuthOption::VTPtrAddrDisc => cfg.vt_ptr_addr_discrimination = *enabled,
295 PointerAuthOption::VTPtrTypeDisc => cfg.vt_ptr_type_discrimination = *enabled,
296 }
297 }
298
299 Some(cfg)
300 }
301 pub fn fn_attrs(&self) -> Vec<&'static str> {
302 let mut attrs = ::alloc::vec::Vec::new()vec![];
306 if self.aarch64_jump_table_hardening {
307 attrs.push("aarch64-jump-table-hardening");
308 }
309 if self.auth_traps {
310 attrs.push("ptrauth-auth-traps");
311 }
312 if self.function_pointers.is_some() {
313 attrs.push("ptrauth-calls");
314 }
315 if self.indirect_gotos {
316 attrs.push("ptrauth-indirect-gotos");
317 }
318 if self.return_addresses {
319 attrs.push("ptrauth-returns");
320 }
321
322 attrs
323 }
324}
325
326pub struct Session {
329 pub target: Target,
330 pub host: Target,
331 pub opts: config::Options,
332 pub target_tlib_path: Arc<SearchPath>,
333 pub psess: ParseSess,
334 pub unstable_features: UnstableFeatures,
335 pub config: Cfg,
336 pub check_config: CheckCfg,
337 proc_macro_quoted_spans: AppendOnlyVec<Span>,
340
341 pub io: CompilerIO,
343
344 incr_comp_session: RwLock<IncrCompSession>,
345
346 pub prof: SelfProfilerRef,
348
349 pub timings: TimingSectionHandler,
351
352 pub code_stats: CodeStats,
354
355 pub lint_store: Option<Arc<dyn DynLintStore>>,
357
358 pub driver_lint_caps: FxHashMap<lint::LintId, lint::Level>,
360
361 pub ctfe_backtrace: Lock<CtfeBacktrace>,
368
369 miri_unleashed_features: Lock<Vec<(Span, Option<Symbol>)>>,
374
375 pub asm_arch: Option<InlineAsmArch>,
377
378 pub target_features: FxIndexSet<Symbol>,
380
381 pub unstable_target_features: FxIndexSet<Symbol>,
383
384 pub cfg_version: &'static str,
386
387 pub using_internal_features: &'static AtomicBool,
392
393 pub env_depinfo: Lock<FxIndexSet<(Symbol, Option<Symbol>)>>,
395
396 pub file_depinfo: Lock<FxIndexSet<Symbol>>,
398
399 target_filesearch: FileSearch,
400 host_filesearch: FileSearch,
401
402 pub replaced_intrinsics: FxHashSet<Symbol>,
405 pub fallback_intrinsics: FxHashSet<Symbol>,
408
409 pub thin_lto_supported: bool,
411
412 pub mir_opt_bisect_eval_count: AtomicUsize,
417
418 pub used_features: Lock<FxHashMap<Symbol, u32>>,
422
423 pub removed_rustc_main_attr: AtomicBool,
426
427 pub pointer_auth_config: Option<PointerAuthConfig>,
429}
430
431#[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)]
432pub enum CodegenUnits {
433 User(usize),
436
437 Default(usize),
441}
442
443impl CodegenUnits {
444 pub fn as_usize(self) -> usize {
445 match self {
446 CodegenUnits::User(n) => n,
447 CodegenUnits::Default(n) => n,
448 }
449 }
450}
451
452pub struct LintGroup {
453 pub name: &'static str,
454 pub lints: Vec<LintId>,
455 pub is_externally_loaded: bool,
456}
457
458impl Session {
459 pub fn miri_unleashed_feature(&self, span: Span, feature_gate: Option<Symbol>) {
460 self.miri_unleashed_features.lock().push((span, feature_gate));
461 }
462
463 pub fn local_crate_source_file(&self) -> Option<RealFileName> {
464 Some(
465 self.source_map()
466 .path_mapping()
467 .to_real_filename(self.source_map().working_dir(), self.io.input.opt_path()?),
468 )
469 }
470
471 fn check_miri_unleashed_features(&self) -> Option<ErrorGuaranteed> {
472 let mut guar = None;
473 let unleashed_features = self.miri_unleashed_features.lock();
474 if !unleashed_features.is_empty() {
475 let mut must_err = false;
476 self.dcx().emit_warn(diagnostics::SkippingConstChecks {
478 unleashed_features: unleashed_features
479 .iter()
480 .map(|(span, gate)| {
481 gate.map(|gate| {
482 must_err = true;
483 diagnostics::UnleashedFeatureHelp::Named { span: *span, gate }
484 })
485 .unwrap_or(diagnostics::UnleashedFeatureHelp::Unnamed { span: *span })
486 })
487 .collect(),
488 });
489
490 if must_err && self.dcx().has_errors().is_none() {
492 guar = Some(self.dcx().emit_err(diagnostics::NotCircumventFeature));
494 }
495 }
496 guar
497 }
498
499 pub fn finish_diagnostics(&self) -> Option<ErrorGuaranteed> {
501 let mut guar = None;
502 guar = guar.or(self.check_miri_unleashed_features());
503 guar = guar.or(self.dcx().emit_stashed_diagnostics());
504 self.dcx().print_error_count();
505 if self.opts.json_future_incompat {
506 self.dcx().emit_future_breakage_report();
507 }
508 guar
509 }
510
511 pub fn is_test_crate(&self) -> bool {
513 self.opts.test
514 }
515
516 #[track_caller]
518 pub fn create_feature_err<'a>(&'a self, err: impl Diagnostic<'a>, feature: Symbol) -> Diag<'a> {
519 let mut err = self.dcx().create_err(err);
520 if err.code.is_none() {
521 err.code(E0658);
522 }
523 diagnostics::add_feature_diagnostics(&mut err, self, feature);
524 err
525 }
526
527 pub fn record_trimmed_def_paths(&self) {
530 if self.opts.unstable_opts.print_type_sizes
531 || self.opts.unstable_opts.query_dep_graph
532 || self.opts.unstable_opts.dump_mir.is_some()
533 || self.opts.unstable_opts.unpretty.is_some()
534 || self.prof.is_args_recording_enabled()
535 || self.opts.output_types.contains_key(&OutputType::Mir)
536 || std::env::var_os("RUSTC_LOG").is_some()
537 {
538 return;
539 }
540
541 self.dcx().set_must_produce_diag()
542 }
543
544 #[inline]
545 pub fn dcx(&self) -> DiagCtxtHandle<'_> {
546 self.psess.dcx()
547 }
548
549 #[inline]
550 pub fn source_map(&self) -> &SourceMap {
551 self.psess.source_map()
552 }
553
554 pub fn proc_macro_quoted_spans(&self) -> impl Iterator<Item = (usize, Span)> {
555 self.proc_macro_quoted_spans.iter_enumerated()
558 }
559
560 pub fn save_proc_macro_span(&self, span: Span) -> usize {
561 self.proc_macro_quoted_spans.push(span)
562 }
563
564 pub fn enable_internal_lints(&self) -> bool {
568 self.unstable_options() && !self.opts.actually_rustdoc
569 }
570
571 pub fn instrument_coverage(&self) -> bool {
572 self.opts.cg.instrument_coverage() != InstrumentCoverage::No
573 }
574
575 pub fn instrument_coverage_branch(&self) -> bool {
576 self.instrument_coverage()
577 && self.opts.unstable_opts.coverage_options.level >= CoverageLevel::Branch
578 }
579
580 pub fn instrument_coverage_condition(&self) -> bool {
581 self.instrument_coverage()
582 && self.opts.unstable_opts.coverage_options.level >= CoverageLevel::Condition
583 }
584
585 pub fn coverage_options(&self) -> &CoverageOptions {
589 &self.opts.unstable_opts.coverage_options
590 }
591
592 pub fn is_sanitizer_cfi_enabled(&self) -> bool {
593 self.sanitizers().contains(SanitizerSet::CFI)
594 }
595
596 pub fn is_sanitizer_cfi_canonical_jump_tables_disabled(&self) -> bool {
597 self.opts.unstable_opts.sanitizer_cfi_canonical_jump_tables == Some(false)
598 }
599
600 pub fn is_sanitizer_cfi_canonical_jump_tables_enabled(&self) -> bool {
601 self.opts.unstable_opts.sanitizer_cfi_canonical_jump_tables == Some(true)
602 }
603
604 pub fn is_sanitizer_cfi_generalize_pointers_enabled(&self) -> bool {
605 self.opts.unstable_opts.sanitizer_cfi_generalize_pointers == Some(true)
606 }
607
608 pub fn is_sanitizer_cfi_normalize_integers_enabled(&self) -> bool {
609 self.opts.unstable_opts.sanitizer_cfi_normalize_integers == Some(true)
610 }
611
612 pub fn is_sanitizer_kcfi_arity_enabled(&self) -> bool {
613 self.opts.unstable_opts.sanitizer_kcfi_arity == Some(true)
614 }
615
616 pub fn is_sanitizer_kcfi_enabled(&self) -> bool {
617 self.sanitizers().contains(SanitizerSet::KCFI)
618 }
619
620 pub fn is_split_lto_unit_enabled(&self) -> bool {
621 self.opts.unstable_opts.split_lto_unit == Some(true)
622 }
623
624 pub fn crt_static(&self, crate_type: Option<CrateType>) -> bool {
626 if !self.target.crt_static_respected {
627 return self.target.crt_static_default;
629 }
630
631 let requested_features = self.opts.cg.target_feature.split(',');
632 let found_negative = requested_features.clone().any(|r| r == "-crt-static");
633 let found_positive = requested_features.clone().any(|r| r == "+crt-static");
634
635 #[allow(rustc::bad_opt_access)]
637 if found_positive || found_negative {
638 found_positive
639 } else if crate_type == Some(CrateType::ProcMacro)
640 || crate_type == None && self.opts.crate_types.contains(&CrateType::ProcMacro)
641 {
642 false
646 } else {
647 self.target.crt_static_default
648 }
649 }
650
651 pub fn is_wasi_reactor(&self) -> bool {
652 self.target.options.os == Os::Wasi
653 && #[allow(non_exhaustive_omitted_patterns)] match self.opts.unstable_opts.wasi_exec_model
{
Some(config::WasiExecModel::Reactor) => true,
_ => false,
}matches!(
654 self.opts.unstable_opts.wasi_exec_model,
655 Some(config::WasiExecModel::Reactor)
656 )
657 }
658
659 pub fn target_can_use_split_dwarf(&self) -> bool {
661 self.target.debuginfo_kind == DebuginfoKind::Dwarf
662 }
663
664 pub fn target_filesearch(&self) -> &filesearch::FileSearch {
665 &self.target_filesearch
666 }
667 pub fn host_filesearch(&self) -> &filesearch::FileSearch {
668 &self.host_filesearch
669 }
670
671 pub fn get_tools_search_paths(&self, self_contained: bool) -> Vec<PathBuf> {
675 let search_paths = self
676 .opts
677 .sysroot
678 .all_paths()
679 .map(|sysroot| filesearch::make_target_bin_path(&sysroot, config::host_tuple()));
680
681 if self_contained {
682 search_paths.flat_map(|path| [path.clone(), path.join("self-contained")]).collect()
686 } else {
687 search_paths.collect()
688 }
689 }
690
691 pub fn init_incr_comp_session(&self, session_dir: PathBuf, lock_file: flock::Lock) {
692 let mut incr_comp_session = self.incr_comp_session.borrow_mut();
693
694 if let IncrCompSession::NotInitialized = *incr_comp_session {
695 } else {
696 {
::core::panicking::panic_fmt(format_args!("Trying to initialize IncrCompSession `{0:?}`",
*incr_comp_session));
}panic!("Trying to initialize IncrCompSession `{:?}`", *incr_comp_session)
697 }
698
699 *incr_comp_session =
700 IncrCompSession::Active { session_directory: session_dir, _lock_file: lock_file };
701 }
702
703 pub fn finalize_incr_comp_session(&self) {
704 let mut incr_comp_session = self.incr_comp_session.borrow_mut();
705
706 if let IncrCompSession::Active { .. } = *incr_comp_session {
707 } else {
708 {
::core::panicking::panic_fmt(format_args!("trying to finalize `IncrCompSession` `{0:?}`",
*incr_comp_session));
};panic!("trying to finalize `IncrCompSession` `{:?}`", *incr_comp_session);
709 }
710
711 *incr_comp_session = IncrCompSession::FinalizedOrRemoved;
713 }
714
715 pub fn incr_comp_session_dir(&self) -> MappedReadGuard<'_, PathBuf> {
716 let incr_comp_session = self.incr_comp_session.borrow();
717 ReadGuard::map(incr_comp_session, |incr_comp_session| match incr_comp_session {
718 IncrCompSession::NotInitialized | IncrCompSession::FinalizedOrRemoved => {
::core::panicking::panic_fmt(format_args!("trying to get session directory from `IncrCompSession`: {0:?}",
incr_comp_session));
}panic!(
719 "trying to get session directory from `IncrCompSession`: {:?}",
720 incr_comp_session,
721 ),
722 IncrCompSession::Active { session_directory, .. } => session_directory,
723 })
724 }
725
726 pub fn incr_comp_session_dir_opt(&self) -> Option<MappedReadGuard<'_, PathBuf>> {
727 self.opts.incremental.as_ref().map(|_| self.incr_comp_session_dir())
728 }
729
730 pub fn is_rust_2015(&self) -> bool {
732 self.edition().is_rust_2015()
733 }
734
735 pub fn at_least_rust_2018(&self) -> bool {
737 self.edition().at_least_rust_2018()
738 }
739
740 pub fn at_least_rust_2021(&self) -> bool {
742 self.edition().at_least_rust_2021()
743 }
744
745 pub fn at_least_rust_2024(&self) -> bool {
747 self.edition().at_least_rust_2024()
748 }
749
750 pub fn needs_plt(&self) -> bool {
752 let want_plt = self.target.plt_by_default;
755
756 let dbg_opts = &self.opts.unstable_opts;
757
758 let relro_level = self.opts.cg.relro_level.unwrap_or(self.target.relro_level);
759
760 let full_relro = RelroLevel::Full == relro_level;
764
765 dbg_opts.plt.unwrap_or(want_plt || !full_relro)
768 }
769
770 pub fn emit_lifetime_markers(&self) -> bool {
772 self.opts.optimize != config::OptLevel::No
773 || self.sanitizers().intersects(SanitizerSet::ADDRESS | SanitizerSet::KERNELADDRESS | SanitizerSet::MEMORY | SanitizerSet::HWADDRESS | SanitizerSet::KERNELHWADDRESS)
780 || self.opts.unstable_opts.codegen_emit_retag.is_some()
782 }
783
784 pub fn diagnostic_width(&self) -> usize {
785 let default_column_width = 140;
786 if let Some(width) = self.opts.diagnostic_width {
787 width
788 } else if self.opts.unstable_opts.ui_testing {
789 default_column_width
790 } else {
791 termize::dimensions().map_or(default_column_width, |(w, _)| w)
792 }
793 }
794
795 pub fn default_visibility(&self) -> SymbolVisibility {
797 self.opts
798 .unstable_opts
799 .default_visibility
800 .or(self.target.options.default_visibility)
801 .unwrap_or(SymbolVisibility::Interposable)
802 }
803
804 pub fn staticlib_components(&self, verbatim: bool) -> (&str, &str) {
805 if verbatim {
806 ("", "")
807 } else {
808 (&*self.target.staticlib_prefix, &*self.target.staticlib_suffix)
809 }
810 }
811
812 pub fn lint_groups_iter(&self) -> Box<dyn Iterator<Item = LintGroup> + '_> {
813 match self.lint_store {
814 Some(ref lint_store) => lint_store.lint_groups_iter(),
815 None => Box::new(std::iter::empty()),
816 }
817 }
818}
819
820#[allow(rustc::bad_opt_access)]
822impl Session {
823 pub fn verbose_internals(&self) -> bool {
824 self.opts.unstable_opts.verbose_internals
825 }
826
827 pub fn print_llvm_stats(&self) -> bool {
828 self.opts.unstable_opts.print_codegen_stats
829 }
830
831 pub fn print_llvm_stats_json(&self) -> Option<&String> {
832 self.opts.unstable_opts.print_codegen_stats_json.as_ref()
833 }
834
835 pub fn verify_llvm_ir(&self) -> bool {
836 self.opts.unstable_opts.verify_llvm_ir || ::core::option::Option::None::<&'static str>option_env!("RUSTC_VERIFY_LLVM_IR").is_some()
837 }
838
839 pub fn binary_dep_depinfo(&self) -> bool {
840 self.opts.unstable_opts.binary_dep_depinfo
841 }
842
843 pub fn mir_opt_level(&self) -> usize {
844 self.opts
845 .unstable_opts
846 .mir_opt_level
847 .unwrap_or_else(|| if self.opts.optimize != OptLevel::No { 2 } else { 1 })
848 }
849
850 pub fn lto(&self) -> config::Lto {
852 if self.target.requires_lto {
854 return config::Lto::Fat;
855 }
856
857 match self.opts.cg.lto {
861 config::LtoCli::Unspecified => {
862 }
865 config::LtoCli::No => {
866 return config::Lto::No;
868 }
869 config::LtoCli::Yes | config::LtoCli::Fat | config::LtoCli::NoParam => {
870 return config::Lto::Fat;
872 }
873 config::LtoCli::Thin => {
874 if !self.thin_lto_supported {
876 self.dcx().emit_warn(diagnostics::ThinLtoNotSupportedByBackend);
878 return config::Lto::Fat;
879 }
880 return config::Lto::Thin;
881 }
882 }
883
884 if !self.thin_lto_supported {
885 return config::Lto::No;
886 }
887
888 if self.opts.cli_forced_local_thinlto_off {
897 return config::Lto::No;
898 }
899
900 if let Some(enabled) = self.opts.unstable_opts.thinlto {
903 if enabled {
904 return config::Lto::ThinLocal;
905 } else {
906 return config::Lto::No;
907 }
908 }
909
910 if self.codegen_units().as_usize() == 1 {
913 return config::Lto::No;
914 }
915
916 match self.opts.optimize {
919 config::OptLevel::No => config::Lto::No,
920 _ => config::Lto::ThinLocal,
921 }
922 }
923
924 pub fn panic_strategy(&self) -> PanicStrategy {
927 self.opts.cg.panic.unwrap_or(self.target.panic_strategy)
928 }
929
930 pub fn fewer_names(&self) -> bool {
931 if let Some(fewer_names) = self.opts.unstable_opts.fewer_names {
932 fewer_names
933 } else {
934 let more_names = self.opts.output_types.contains_key(&OutputType::LlvmAssembly)
935 || self.opts.output_types.contains_key(&OutputType::Bitcode)
936 || self.opts.unstable_opts.sanitizer.intersects(SanitizerSet::ADDRESS | SanitizerSet::MEMORY);
938 !more_names
939 }
940 }
941
942 pub fn unstable_options(&self) -> bool {
943 self.opts.unstable_opts.unstable_options
944 }
945
946 pub fn is_nightly_build(&self) -> bool {
947 self.opts.unstable_features.is_nightly_build()
948 }
949
950 pub fn overflow_checks(&self) -> bool {
951 self.opts.cg.overflow_checks.unwrap_or(self.opts.debug_assertions)
952 }
953
954 pub fn ub_checks(&self) -> bool {
955 self.opts.unstable_opts.ub_checks.unwrap_or(self.opts.debug_assertions)
956 }
957
958 pub fn contract_checks(&self) -> bool {
959 self.opts.unstable_opts.contract_checks.unwrap_or(false)
960 }
961
962 pub fn relocation_model(&self) -> RelocModel {
963 self.opts.cg.relocation_model.unwrap_or(self.target.relocation_model)
964 }
965
966 pub fn code_model(&self) -> Option<CodeModel> {
967 self.opts.cg.code_model.or(self.target.code_model)
968 }
969
970 pub fn tls_model(&self) -> TlsModel {
971 self.opts.unstable_opts.tls_model.unwrap_or(self.target.tls_model)
972 }
973
974 pub fn direct_access_external_data(&self) -> Option<bool> {
975 self.opts
976 .unstable_opts
977 .direct_access_external_data
978 .or(self.target.direct_access_external_data)
979 }
980
981 pub fn split_debuginfo(&self) -> SplitDebuginfo {
982 self.opts.cg.split_debuginfo.unwrap_or(self.target.split_debuginfo)
983 }
984
985 pub fn dwarf_version(&self) -> u32 {
987 self.opts
988 .cg
989 .dwarf_version
990 .or(self.opts.unstable_opts.dwarf_version)
991 .unwrap_or(self.target.default_dwarf_version)
992 }
993
994 pub fn stack_protector(&self) -> StackProtector {
995 if self.target.options.supports_stack_protector {
996 self.opts.unstable_opts.stack_protector
997 } else {
998 StackProtector::None
999 }
1000 }
1001
1002 pub fn must_emit_unwind_tables(&self) -> bool {
1003 self.target.requires_uwtable
1032 || self
1033 .opts
1034 .cg
1035 .force_unwind_tables
1036 .unwrap_or(self.panic_strategy().unwinds() || self.target.default_uwtable)
1037 }
1038
1039 #[inline]
1044 pub fn threads(&self) -> Option<usize> {
1045 self.opts.unstable_opts.threads
1046 }
1047
1048 pub fn codegen_units(&self) -> CodegenUnits {
1051 if let Some(n) = self.opts.cli_forced_codegen_units {
1052 return CodegenUnits::User(n);
1053 }
1054 if let Some(n) = self.target.default_codegen_units {
1055 return CodegenUnits::Default(n as usize);
1056 }
1057
1058 if self.opts.incremental.is_some() {
1062 return CodegenUnits::Default(256);
1063 }
1064
1065 CodegenUnits::Default(16)
1116 }
1117
1118 pub fn teach(&self, code: ErrCode) -> bool {
1119 self.opts.unstable_opts.teach && self.dcx().must_teach(code)
1120 }
1121
1122 pub fn edition(&self) -> Edition {
1123 self.opts.edition
1124 }
1125
1126 pub fn link_dead_code(&self) -> bool {
1127 self.opts.cg.link_dead_code.unwrap_or(false)
1128 }
1129
1130 pub fn apple_deployment_target(&self) -> apple::OSVersion {
1135 let min = apple::OSVersion::minimum_deployment_target(&self.target);
1136 let env_var = apple::deployment_target_env_var(&self.target.os);
1137
1138 if let Ok(deployment_target) = env::var(env_var) {
1140 match apple::OSVersion::from_str(&deployment_target) {
1141 Ok(version) => {
1142 let os_min = apple::OSVersion::os_minimum_deployment_target(&self.target.os);
1143 if version < os_min {
1148 self.dcx().emit_warn(diagnostics::AppleDeploymentTarget::TooLow {
1149 env_var,
1150 version: version.fmt_pretty().to_string(),
1151 os_min: os_min.fmt_pretty().to_string(),
1152 });
1153 }
1154
1155 version.max(min)
1157 }
1158 Err(error) => {
1159 self.dcx()
1160 .emit_err(diagnostics::AppleDeploymentTarget::Invalid { env_var, error });
1161 min
1162 }
1163 }
1164 } else {
1165 min
1167 }
1168 }
1169
1170 pub fn sanitizers(&self) -> SanitizerSet {
1171 return self.opts.unstable_opts.sanitizer | self.target.options.default_sanitizers;
1172 }
1173
1174 pub fn pointer_authentication(&self) -> bool {
1175 self.pointer_auth_config.is_some()
1176 }
1177
1178 pub fn pointer_authentication_functions(&self) -> Option<&PointerAuthSchema> {
1179 self.pointer_auth_config.as_ref().and_then(|cfg| cfg.function_pointers.as_ref())
1180 }
1181
1182 pub fn pointer_authentication_init_fini(&self) -> Option<&PointerAuthSchema> {
1183 self.pointer_auth_config.as_ref().and_then(|cfg| cfg.init_fini.as_ref())
1184 }
1185}
1186
1187#[allow(rustc::bad_opt_access)]
1189fn default_emitter(sopts: &config::Options, source_map: Arc<SourceMap>) -> Box<DynEmitter> {
1190 let macro_backtrace = sopts.unstable_opts.macro_backtrace;
1191 let track_diagnostics = sopts.unstable_opts.track_diagnostics;
1192 let terminal_url = match sopts.unstable_opts.terminal_urls {
1193 TerminalUrl::Auto => {
1194 match (std::env::var("COLORTERM").as_deref(), std::env::var("TERM").as_deref()) {
1195 (Ok("truecolor"), Ok("xterm-256color"))
1196 if sopts.unstable_features.is_nightly_build() =>
1197 {
1198 TerminalUrl::Yes
1199 }
1200 _ => TerminalUrl::No,
1201 }
1202 }
1203 t => t,
1204 };
1205
1206 let source_map = if sopts.unstable_opts.link_only { None } else { Some(source_map) };
1207
1208 match sopts.error_format {
1209 config::ErrorOutputType::HumanReadable { kind, color_config } => match kind {
1210 HumanReadableErrorType { short, unicode } => {
1211 let emitter = AnnotateSnippetEmitter::new(stderr_destination(color_config))
1212 .sm(source_map)
1213 .short_message(short)
1214 .diagnostic_width(sopts.diagnostic_width)
1215 .macro_backtrace(macro_backtrace)
1216 .track_diagnostics(track_diagnostics)
1217 .terminal_url(terminal_url)
1218 .theme(if unicode { OutputTheme::Unicode } else { OutputTheme::Ascii })
1219 .ignored_directories_in_source_blocks(
1220 sopts.unstable_opts.ignore_directory_in_diagnostics_source_blocks.clone(),
1221 );
1222 Box::new(emitter.ui_testing(sopts.unstable_opts.ui_testing))
1223 }
1224 },
1225 config::ErrorOutputType::Json { pretty, json_rendered, color_config } => Box::new(
1226 JsonEmitter::new(
1227 Box::new(io::BufWriter::new(io::stderr())),
1228 source_map,
1229 pretty,
1230 json_rendered,
1231 color_config,
1232 )
1233 .ui_testing(sopts.unstable_opts.ui_testing)
1234 .ignored_directories_in_source_blocks(
1235 sopts.unstable_opts.ignore_directory_in_diagnostics_source_blocks.clone(),
1236 )
1237 .diagnostic_width(sopts.diagnostic_width)
1238 .macro_backtrace(macro_backtrace)
1239 .track_diagnostics(track_diagnostics)
1240 .terminal_url(terminal_url),
1241 ),
1242 }
1243}
1244
1245#[allow(rustc::bad_opt_access)]
1247pub fn build_session(
1248 sopts: config::Options,
1249 io: CompilerIO,
1250 driver_lint_caps: FxHashMap<lint::LintId, lint::Level>,
1251 target: Target,
1252 cfg_version: &'static str,
1253 ice_file: Option<PathBuf>,
1254 using_internal_features: &'static AtomicBool,
1255) -> Session {
1256 let warnings_allow = sopts
1260 .lint_opts
1261 .iter()
1262 .rfind(|&(key, _)| *key == "warnings")
1263 .is_some_and(|&(_, level)| level == lint::Allow);
1264 let cap_lints_allow = sopts.lint_cap.is_some_and(|cap| cap == lint::Allow);
1265 let can_emit_warnings = !(warnings_allow || cap_lints_allow);
1266
1267 let source_map = rustc_span::source_map::get_source_map().unwrap();
1268 let emitter = default_emitter(&sopts, Arc::clone(&source_map));
1269
1270 let mut dcx =
1271 DiagCtxt::new(emitter).with_flags(sopts.unstable_opts.dcx_flags(can_emit_warnings));
1272 if let Some(ice_file) = ice_file {
1273 dcx = dcx.with_ice_file(ice_file);
1274 }
1275
1276 if let Some(msrv) = sopts.unstable_opts.hint_msrv {
1277 dcx = dcx.with_msrv(msrv);
1278 }
1279
1280 let host_triple = TargetTuple::from_tuple(config::host_tuple());
1281 let (host, target_warnings) =
1282 Target::search(&host_triple, sopts.sysroot.path(), sopts.unstable_opts.unstable_options)
1283 .unwrap_or_else(|e| {
1284 dcx.handle().fatal(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("Error loading host specification: {0}",
e))
})format!("Error loading host specification: {e}"))
1285 });
1286 for warning in target_warnings.warning_messages() {
1287 dcx.handle().warn(warning)
1288 }
1289
1290 let self_profiler = if let SwitchWithOptPath::Enabled(ref d) = sopts.unstable_opts.self_profile
1291 {
1292 let directory = if let Some(directory) = d { directory } else { std::path::Path::new(".") };
1293
1294 let profiler = SelfProfiler::new(
1295 directory,
1296 sopts.crate_name.as_deref(),
1297 sopts.unstable_opts.self_profile_events.as_deref(),
1298 &sopts.unstable_opts.self_profile_counter,
1299 );
1300 match profiler {
1301 Ok(profiler) => Some(Arc::new(profiler)),
1302 Err(e) => {
1303 dcx.handle().emit_warn(diagnostics::FailedToCreateProfiler { err: e.to_string() });
1304 None
1305 }
1306 }
1307 } else {
1308 None
1309 };
1310
1311 let psess = ParseSess::with_dcx(dcx, source_map);
1312
1313 let host_triple = config::host_tuple();
1314 let target_triple = sopts.target_triple.tuple();
1315 let host_tlib_path =
1317 Arc::new(SearchPath::from_sysroot_and_triple(sopts.sysroot.path(), host_triple));
1318 let target_tlib_path = if host_triple == target_triple {
1319 Arc::clone(&host_tlib_path)
1322 } else {
1323 Arc::new(SearchPath::from_sysroot_and_triple(sopts.sysroot.path(), target_triple))
1324 };
1325
1326 let prof = SelfProfilerRef::new(
1327 self_profiler,
1328 sopts.unstable_opts.time_passes.then(|| sopts.unstable_opts.time_passes_format),
1329 );
1330
1331 let ctfe_backtrace = Lock::new(match env::var("RUSTC_CTFE_BACKTRACE") {
1332 Ok(ref val) if val == "immediate" => CtfeBacktrace::Immediate,
1333 Ok(ref val) if val != "0" => CtfeBacktrace::Capture,
1334 _ => CtfeBacktrace::Disabled,
1335 });
1336
1337 let asm_arch = if target.allow_asm { InlineAsmArch::from_arch(&target.arch) } else { None };
1338 let target_filesearch = filesearch::FileSearch::new(
1339 &sopts.search_paths,
1340 &target_tlib_path,
1341 &target,
1342 sopts.unstable_opts.implicit_sysroot_deps,
1343 );
1344 let host_filesearch = filesearch::FileSearch::new(
1345 &sopts.search_paths,
1346 &host_tlib_path,
1347 &host,
1348 sopts.unstable_opts.implicit_sysroot_deps,
1349 );
1350
1351 let timings = TimingSectionHandler::new(sopts.json_timings);
1352
1353 let pointer_auth_config: Option<PointerAuthConfig> =
1354 PointerAuthConfig::from_raw(&sopts.unstable_opts.pointer_authentication, &target);
1355
1356 let sess = Session {
1357 target,
1358 host,
1359 opts: sopts,
1360 target_tlib_path,
1361 psess,
1362 unstable_features: UnstableFeatures::from_environment(None),
1363 config: Cfg::default(),
1364 check_config: CheckCfg::default(),
1365 proc_macro_quoted_spans: Default::default(),
1366 io,
1367 incr_comp_session: RwLock::new(IncrCompSession::NotInitialized),
1368 prof,
1369 timings,
1370 code_stats: Default::default(),
1371 lint_store: None,
1372 driver_lint_caps,
1373 ctfe_backtrace,
1374 miri_unleashed_features: Lock::new(Default::default()),
1375 asm_arch,
1376 target_features: Default::default(),
1377 unstable_target_features: Default::default(),
1378 cfg_version,
1379 using_internal_features,
1380 env_depinfo: Default::default(),
1381 file_depinfo: Default::default(),
1382 target_filesearch,
1383 host_filesearch,
1384 replaced_intrinsics: FxHashSet::default(), fallback_intrinsics: FxHashSet::default(), thin_lto_supported: true, mir_opt_bisect_eval_count: AtomicUsize::new(0),
1388 used_features: Lock::default(),
1389 removed_rustc_main_attr: AtomicBool::new(false),
1390 pointer_auth_config,
1391 };
1392
1393 validate_commandline_args_with_session_available(&sess);
1394
1395 sess
1396}
1397
1398pub fn generate_proc_macro_decls_symbol(stable_crate_id: StableCrateId) -> String {
1399 ::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())
1400}
1401
1402#[allow(rustc::bad_opt_access)]
1408fn validate_commandline_args_with_session_available(sess: &Session) {
1409 if sess.opts.cg.linker_plugin_lto.enabled()
1417 && sess.opts.cg.prefer_dynamic
1418 && sess.target.is_like_windows
1419 {
1420 sess.dcx().emit_err(diagnostics::LinkerPluginToWindowsNotSupported);
1421 }
1422
1423 if sess
1424 .pointer_auth_config
1425 .as_ref()
1426 .and_then(|cfg| cfg.function_pointers.as_ref())
1427 .is_some_and(|schema| #[allow(non_exhaustive_omitted_patterns)] match schema.discrimination_kind {
PointerAuthDiscrimination::Type => true,
_ => false,
}matches!(schema.discrimination_kind, PointerAuthDiscrimination::Type))
1428 {
1429 sess.dcx().emit_err(
1430 diagnostics::PointerAuthenticationTypeDiscriminationNotSupportedForTarget {
1431 target_triple: &sess.opts.target_triple,
1432 },
1433 );
1434 }
1435
1436 if sess.target.cfg_abi != CfgAbi::Pauthtest
1437 && !sess.opts.unstable_opts.pointer_authentication.is_empty()
1438 {
1439 sess.dcx().emit_warn(diagnostics::PointerAuthenticationNotSupportedForTarget {
1440 target_triple: &sess.opts.target_triple,
1441 });
1442 }
1443
1444 if let Some(ref path) = sess.opts.cg.profile_use {
1447 if !path.exists() {
1448 sess.dcx().emit_err(diagnostics::ProfileUseFileDoesNotExist { path });
1449 }
1450 }
1451
1452 if let Some(ref path) = sess.opts.unstable_opts.profile_sample_use {
1454 if !path.exists() {
1455 sess.dcx().emit_err(diagnostics::ProfileSampleUseFileDoesNotExist { path });
1456 }
1457 }
1458
1459 if let Some(include_uwtables) = sess.opts.cg.force_unwind_tables {
1461 if sess.target.requires_uwtable && !include_uwtables {
1462 sess.dcx().emit_err(diagnostics::TargetRequiresUnwindTables);
1463 }
1464 }
1465
1466 let supported_sanitizers = sess.target.options.supported_sanitizers;
1468 let mut unsupported_sanitizers = sess.opts.unstable_opts.sanitizer - supported_sanitizers;
1469 if sess.opts.unstable_opts.fixed_x18 && sess.target.arch == Arch::AArch64 {
1472 unsupported_sanitizers -= SanitizerSet::SHADOWCALLSTACK;
1473 }
1474 match unsupported_sanitizers.into_iter().count() {
1475 0 => {}
1476 1 => {
1477 sess.dcx().emit_err(diagnostics::SanitizerNotSupported {
1478 us: unsupported_sanitizers.to_string(),
1479 });
1480 }
1481 _ => {
1482 sess.dcx().emit_err(diagnostics::SanitizersNotSupported {
1483 us: unsupported_sanitizers.to_string(),
1484 });
1485 }
1486 }
1487
1488 if let Some((first, second)) = sess.opts.unstable_opts.sanitizer.mutually_exclusive() {
1490 sess.dcx().emit_err(diagnostics::CannotMixAndMatchSanitizers {
1491 first: first.to_string(),
1492 second: second.to_string(),
1493 });
1494 }
1495
1496 if sess.crt_static(None)
1498 && !sess.opts.unstable_opts.sanitizer.is_empty()
1499 && !sess.target.is_like_msvc
1500 {
1501 sess.dcx().emit_err(diagnostics::CannotEnableCrtStaticLinux);
1502 }
1503
1504 if sess.crt_static(None) && sess.target.cfg_abi == CfgAbi::Pauthtest {
1508 sess.dcx().emit_err(diagnostics::CannotEnableCrtStaticPointerAuth);
1509 }
1510
1511 if sess.is_sanitizer_cfi_enabled()
1513 && !(sess.lto() == config::Lto::Fat || sess.opts.cg.linker_plugin_lto.enabled())
1514 {
1515 sess.dcx().emit_err(diagnostics::SanitizerCfiRequiresLto);
1516 }
1517
1518 if sess.is_sanitizer_kcfi_enabled() && sess.panic_strategy().unwinds() {
1520 sess.dcx().emit_err(diagnostics::SanitizerKcfiRequiresPanicAbort);
1521 }
1522
1523 if sess.is_sanitizer_cfi_enabled()
1525 && sess.lto() == config::Lto::Fat
1526 && (sess.codegen_units().as_usize() != 1)
1527 {
1528 sess.dcx().emit_err(diagnostics::SanitizerCfiRequiresSingleCodegenUnit);
1529 }
1530
1531 if sess.is_sanitizer_cfi_canonical_jump_tables_disabled() {
1533 if !sess.is_sanitizer_cfi_enabled() {
1534 sess.dcx().emit_err(diagnostics::SanitizerCfiCanonicalJumpTablesRequiresCfi);
1535 }
1536 }
1537
1538 if sess.is_sanitizer_kcfi_arity_enabled() && !sess.is_sanitizer_kcfi_enabled() {
1540 sess.dcx().emit_err(diagnostics::SanitizerKcfiArityRequiresKcfi);
1541 }
1542
1543 if sess.is_sanitizer_cfi_generalize_pointers_enabled() {
1545 if !(sess.is_sanitizer_cfi_enabled() || sess.is_sanitizer_kcfi_enabled()) {
1546 sess.dcx().emit_err(diagnostics::SanitizerCfiGeneralizePointersRequiresCfi);
1547 }
1548 }
1549
1550 if sess.is_sanitizer_cfi_normalize_integers_enabled() {
1552 if !(sess.is_sanitizer_cfi_enabled() || sess.is_sanitizer_kcfi_enabled()) {
1553 sess.dcx().emit_err(diagnostics::SanitizerCfiNormalizeIntegersRequiresCfi);
1554 }
1555 }
1556
1557 if sess.is_split_lto_unit_enabled()
1559 && !(sess.lto() == config::Lto::Fat
1560 || sess.lto() == config::Lto::Thin
1561 || sess.opts.cg.linker_plugin_lto.enabled())
1562 {
1563 sess.dcx().emit_err(diagnostics::SplitLtoUnitRequiresLto);
1564 }
1565
1566 if sess.lto() != config::Lto::Fat {
1568 if sess.opts.unstable_opts.virtual_function_elimination {
1569 sess.dcx().emit_err(diagnostics::UnstableVirtualFunctionElimination);
1570 }
1571 }
1572
1573 if sess.opts.unstable_opts.stack_protector != StackProtector::None {
1574 if !sess.target.options.supports_stack_protector {
1575 sess.dcx().emit_warn(diagnostics::StackProtectorNotSupportedForTarget {
1576 stack_protector: sess.opts.unstable_opts.stack_protector,
1577 target_triple: &sess.opts.target_triple,
1578 });
1579 }
1580 }
1581
1582 if sess.opts.unstable_opts.small_data_threshold.is_some() {
1583 if sess.target.small_data_threshold_support() == SmallDataThresholdSupport::None {
1584 sess.dcx().emit_warn(diagnostics::SmallDataThresholdNotSupportedForTarget {
1585 target_triple: &sess.opts.target_triple,
1586 })
1587 }
1588 }
1589
1590 if sess.opts.unstable_opts.branch_protection.is_some() && sess.target.arch != Arch::AArch64 {
1591 sess.dcx().emit_err(diagnostics::BranchProtectionRequiresAArch64);
1592 }
1593
1594 if let Some(dwarf_version) =
1595 sess.opts.cg.dwarf_version.or(sess.opts.unstable_opts.dwarf_version)
1596 {
1597 if dwarf_version < 2 || dwarf_version > 5 {
1599 sess.dcx().emit_err(diagnostics::UnsupportedDwarfVersion { dwarf_version });
1600 }
1601 }
1602
1603 if !sess.target.options.supported_split_debuginfo.contains(&sess.split_debuginfo())
1604 && !sess.opts.unstable_opts.unstable_options
1605 {
1606 sess.dcx().emit_err(diagnostics::SplitDebugInfoUnstablePlatform {
1607 debuginfo: sess.split_debuginfo(),
1608 });
1609 }
1610
1611 if sess.opts.unstable_opts.embed_source {
1612 let dwarf_version = sess.dwarf_version();
1613
1614 if dwarf_version < 5 {
1615 sess.dcx()
1616 .emit_warn(diagnostics::EmbedSourceInsufficientDwarfVersion { dwarf_version });
1617 }
1618
1619 if sess.opts.debuginfo == DebugInfo::None {
1620 sess.dcx().emit_warn(diagnostics::EmbedSourceRequiresDebugInfo);
1621 }
1622 }
1623
1624 if sess.opts.unstable_opts.instrument_mcount == InstrumentMcount::Fentry
1625 && !sess.target.options.supports_fentry
1626 {
1627 sess.dcx().emit_err(diagnostics::InstrumentationNotSupported { us: "fentry".to_string() });
1628 }
1629
1630 if sess.opts.unstable_opts.instrument_xray.is_some() && !sess.target.options.supports_xray {
1631 sess.dcx().emit_err(diagnostics::InstrumentationNotSupported { us: "XRay".to_string() });
1632 }
1633
1634 if let Some(flavor) = sess.opts.cg.linker_flavor
1635 && let Some(compatible_list) = sess.target.linker_flavor.check_compatibility(flavor)
1636 {
1637 let flavor = flavor.desc();
1638 sess.dcx().emit_err(diagnostics::IncompatibleLinkerFlavor { flavor, compatible_list });
1639 }
1640
1641 if sess.opts.unstable_opts.function_return != FunctionReturn::default() {
1642 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) {
1643 sess.dcx().emit_err(diagnostics::FunctionReturnRequiresX86OrX8664);
1644 }
1645 }
1646
1647 if sess.opts.unstable_opts.indirect_branch_cs_prefix {
1648 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) {
1649 sess.dcx().emit_err(diagnostics::IndirectBranchCsPrefixRequiresX86OrX8664);
1650 }
1651 }
1652
1653 if let Some(regparm) = sess.opts.unstable_opts.regparm {
1654 if regparm > 3 {
1655 sess.dcx().emit_err(diagnostics::UnsupportedRegparm { regparm });
1656 }
1657 if sess.target.arch != Arch::X86 {
1658 sess.dcx().emit_err(diagnostics::UnsupportedRegparmArch);
1659 }
1660 }
1661 if sess.opts.unstable_opts.reg_struct_return {
1662 if sess.target.arch != Arch::X86 {
1663 sess.dcx().emit_err(diagnostics::UnsupportedRegStructReturnArch);
1664 }
1665 }
1666
1667 match sess.opts.unstable_opts.function_return {
1671 FunctionReturn::Keep => (),
1672 FunctionReturn::ThunkExtern => {
1673 if let Some(code_model) = sess.code_model()
1676 && code_model == CodeModel::Large
1677 {
1678 sess.dcx()
1679 .emit_err(diagnostics::FunctionReturnThunkExternRequiresNonLargeCodeModel);
1680 }
1681 }
1682 }
1683
1684 if sess.opts.unstable_opts.packed_stack {
1685 if sess.target.arch != Arch::S390x {
1686 sess.dcx().emit_err(diagnostics::UnsupportedPackedStack);
1687 }
1688 }
1689
1690 if let Some(ref cpu_name) = sess.opts.cg.target_cpu {
1691 if cpu_name == NATIVE_CPU && sess.target.requires_consistent_cpu {
1692 sess.dcx().emit_fatal(diagnostics::NativeTargetCpuNotAllowed {
1693 target_triple: &sess.opts.target_triple,
1694 need_explicit_cpu: sess.target.need_explicit_cpu,
1695 });
1696 }
1697 }
1698}
1699
1700#[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::FinalizedOrRemoved =>
::core::fmt::Formatter::write_str(f, "FinalizedOrRemoved"),
}
}
}Debug)]
1702enum IncrCompSession {
1703 NotInitialized,
1706 Active { session_directory: PathBuf, _lock_file: flock::Lock },
1711 FinalizedOrRemoved,
1715}
1716
1717pub struct EarlyDiagCtxt {
1719 dcx: DiagCtxt,
1720}
1721
1722impl EarlyDiagCtxt {
1723 pub fn new(output: ErrorOutputType) -> Self {
1724 let emitter = mk_emitter(output);
1725 Self { dcx: DiagCtxt::new(emitter) }
1726 }
1727
1728 pub fn set_error_format(&mut self, output: ErrorOutputType) {
1731 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());
1732
1733 let emitter = mk_emitter(output);
1734 self.dcx = DiagCtxt::new(emitter);
1735 }
1736
1737 pub fn early_note(&self, msg: impl Into<DiagMessage>) {
1738 self.dcx.handle().note(msg)
1739 }
1740
1741 pub fn early_help(&self, msg: impl Into<DiagMessage>) {
1742 self.dcx.handle().struct_help(msg).emit()
1743 }
1744
1745 #[must_use = "raise_fatal must be called on the returned ErrorGuaranteed in order to exit with a non-zero status code"]
1746 pub fn early_err(&self, msg: impl Into<DiagMessage>) -> ErrorGuaranteed {
1747 self.dcx.handle().err(msg)
1748 }
1749
1750 pub fn early_fatal(&self, msg: impl Into<DiagMessage>) -> ! {
1751 self.dcx.handle().fatal(msg)
1752 }
1753
1754 pub fn early_struct_fatal(&self, msg: impl Into<DiagMessage>) -> Diag<'_, FatalAbort> {
1755 self.dcx.handle().struct_fatal(msg)
1756 }
1757
1758 pub fn early_warn(&self, msg: impl Into<DiagMessage>) {
1759 self.dcx.handle().warn(msg)
1760 }
1761
1762 pub fn early_struct_warn(&self, msg: impl Into<DiagMessage>) -> Diag<'_, ()> {
1763 self.dcx.handle().struct_warn(msg)
1764 }
1765}
1766
1767fn mk_emitter(output: ErrorOutputType) -> Box<DynEmitter> {
1768 let emitter: Box<DynEmitter> = match output {
1769 config::ErrorOutputType::HumanReadable { kind, color_config } => match kind {
1770 HumanReadableErrorType { short, unicode } => Box::new(
1771 AnnotateSnippetEmitter::new(stderr_destination(color_config))
1772 .theme(if unicode { OutputTheme::Unicode } else { OutputTheme::Ascii })
1773 .short_message(short),
1774 ),
1775 },
1776 config::ErrorOutputType::Json { pretty, json_rendered, color_config } => {
1777 Box::new(JsonEmitter::new(
1778 Box::new(io::BufWriter::new(io::stderr())),
1779 Some(Arc::new(SourceMap::new(FilePathMapping::empty()))),
1780 pretty,
1781 json_rendered,
1782 color_config,
1783 ))
1784 }
1785 };
1786 emitter
1787}