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::{AppendOnlyVec, DynSend, DynSync, Lock};
11use rustc_data_structures::{Limit, flock};
12use rustc_errors::annotate_snippet_emitter_writer::AnnotateSnippetEmitter;
13use rustc_errors::codes::*;
14use rustc_errors::emitter::{DynEmitter, HumanReadableErrorType, OutputTheme, stderr_destination};
15use rustc_errors::json::JsonEmitter;
16use rustc_errors::timings::TimingSectionHandler;
17use rustc_errors::{
18 Diag, DiagCtxt, DiagCtxtHandle, DiagMessage, Diagnostic, ErrorGuaranteed, FatalAbort,
19 TerminalUrl,
20};
21use rustc_feature::UnstableFeatures;
22use rustc_macros::StableHash;
23pub use rustc_span::def_id::StableCrateId;
24use rustc_span::edition::Edition;
25use rustc_span::source_map::{FilePathMapping, SourceMap};
26use rustc_span::{RealFileName, Span, Symbol};
27use rustc_target::asm::InlineAsmArch;
28use rustc_target::spec::{
29 Arch, CfgAbi, CodeModel, DebuginfoKind, Os, PanicStrategy, RelocModel, RelroLevel,
30 SanitizerSet, SmallDataThresholdSupport, SplitDebuginfo, StackProtector, SymbolVisibility,
31 Target, TargetTuple, TlsModel, apple,
32};
33
34use crate::code_stats::CodeStats;
35pub use crate::code_stats::{DataTypeKind, FieldInfo, FieldKind, SizeKind, VariantInfo};
36use crate::config::{
37 self, BranchProtection, Cfg, CheckCfg, CoverageLevel, CoverageOptions, CrateType, DebugInfo,
38 ErrorOutputType, FunctionReturn, Input, InstrumentCoverage, InstrumentMcount, NATIVE_CPU,
39 OptLevel, OutFileName, OutputType, PAuthKey, PointerAuthOption, SwitchWithOptPath,
40};
41use crate::filesearch::FileSearch;
42use crate::lint::LintId;
43use crate::parse::ParseSess;
44use crate::search_paths::SearchPath;
45use crate::{diagnostics, filesearch, lint};
46
47#[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)]
49pub enum CtfeBacktrace {
50 Disabled,
52 Capture,
55 Immediate,
57}
58
59#[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)]
60pub struct Limits {
61 pub recursion_limit: Limit,
64 pub move_size_limit: Limit,
67 pub type_length_limit: Limit,
69 pub pattern_complexity_limit: Limit,
71}
72
73pub struct CompilerIO {
74 pub input: Input,
75 pub output_dir: Option<PathBuf>,
76 pub output_file: Option<OutFileName>,
77 pub temps_dir: Option<PathBuf>,
78}
79
80pub trait DynLintStore: Any + DynSync + DynSend {
81 fn lint_groups_iter(&self) -> Box<dyn Iterator<Item = LintGroup> + '_>;
83}
84
85#[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)]
88pub enum PointerAuthARM8_3Key {
89 ASIA = 0,
90 ASIB = 1,
91 ASDA = 2,
92 ASDB = 3,
93}
94
95pub enum PointerAuthDiscrimination {
97 None,
99 Type,
101 Decl,
103 Constant,
105}
106
107pub enum PointerAuthAddressDiscriminator {
109 HardwareAddress(bool),
111 Synthetic(u64),
114}
115
116pub struct PointerAuthSchema {
117 pub is_address_discriminated: PointerAuthAddressDiscriminator,
118 pub discrimination_kind: PointerAuthDiscrimination,
119 pub key: PointerAuthARM8_3Key,
120 pub constant_discriminator: u16,
121}
122impl PointerAuthSchema {
123 pub fn function_pointers_default(target: &Target) -> Self {
124 if !(target.cfg_abi == CfgAbi::Pauthtest) {
::core::panicking::panic("assertion failed: target.cfg_abi == CfgAbi::Pauthtest")
};assert!(target.cfg_abi == CfgAbi::Pauthtest);
125 return Self {
126 is_address_discriminated: PointerAuthAddressDiscriminator::HardwareAddress(false),
127 discrimination_kind: PointerAuthDiscrimination::None,
128 key: PointerAuthARM8_3Key::ASIA,
129 constant_discriminator: 0,
130 };
131 }
132 pub fn init_fini_default(target: &Target) -> Self {
133 if !(target.cfg_abi == CfgAbi::Pauthtest) {
::core::panicking::panic("assertion failed: target.cfg_abi == CfgAbi::Pauthtest")
};assert!(target.cfg_abi == CfgAbi::Pauthtest);
134 return Self {
135 is_address_discriminated: PointerAuthAddressDiscriminator::Synthetic(1),
136 discrimination_kind: PointerAuthDiscrimination::None,
137 key: PointerAuthARM8_3Key::ASIA,
138 constant_discriminator: 0xd9d4,
140 };
141 }
142}
143
144pub struct PointerAuthConfig {
145 pub return_addresses: bool,
147 pub auth_traps: bool,
149 pub indirect_gotos: bool,
151 pub elf_got: bool,
153 pub aarch64_jump_table_hardening: bool,
155 pub function_pointers: Option<PointerAuthSchema>,
157 pub init_fini: Option<PointerAuthSchema>,
159 pub intrinsics: bool,
161 pub typeinfo_vt_ptr_discrimination: bool,
164 pub vt_ptr_addr_discrimination: bool,
165 pub vt_ptr_type_discrimination: bool,
166}
167impl PointerAuthConfig {
168 fn default(target: &Target) -> Self {
169 if !(target.cfg_abi == CfgAbi::Pauthtest) {
::core::panicking::panic("assertion failed: target.cfg_abi == CfgAbi::Pauthtest")
};assert!(target.cfg_abi == CfgAbi::Pauthtest);
170 return Self {
171 return_addresses: true,
172 auth_traps: true,
173 indirect_gotos: true,
174 elf_got: false,
175 aarch64_jump_table_hardening: true,
176 function_pointers: Some(PointerAuthSchema::function_pointers_default(target)),
177 init_fini: Some(PointerAuthSchema::init_fini_default(target)),
178 intrinsics: true,
179 typeinfo_vt_ptr_discrimination: true,
180 vt_ptr_addr_discrimination: true,
181 vt_ptr_type_discrimination: true,
182 };
183 }
184 pub fn calculate_pauth_abi_version(&self, target: &Target) -> u32 {
185 if !(target.cfg_abi == CfgAbi::Pauthtest) {
::core::panicking::panic("assertion failed: target.cfg_abi == CfgAbi::Pauthtest")
};assert!(target.cfg_abi == CfgAbi::Pauthtest);
186 const INTRINSICS: u32 = 0;
196 const CALLS: u32 = 1;
197 const RETURNS: u32 = 2;
198 const AUTHTRAPS: u32 = 3;
199 const VT_PTR_ADDR_DISCR: u32 = 4;
200 const VT_PTR_TYPE_DISCR: u32 = 5;
201 const INIT_FINI: u32 = 6;
202 const INIT_FINI_ADDR_DISC: u32 = 7;
203 const GOT: u32 = 8;
204 const GOTOS: u32 = 9;
205 const TYPEINFO_VT_PTR_DISCR: u32 = 10;
206 let pauth_abi_version: u32 = (u32::from(self.intrinsics) << INTRINSICS)
210 | (u32::from(self.function_pointers.is_some()) << CALLS)
211 | (u32::from(self.return_addresses) << RETURNS)
212 | (u32::from(self.auth_traps) << AUTHTRAPS)
213 | (u32::from(self.vt_ptr_addr_discrimination) << VT_PTR_ADDR_DISCR)
214 | (u32::from(self.vt_ptr_type_discrimination) << VT_PTR_TYPE_DISCR)
215 | (u32::from(self.init_fini.is_some()) << INIT_FINI)
216 | (u32::from(self.init_fini.as_ref().is_some_and(|schema| {
217 #[allow(non_exhaustive_omitted_patterns)] match schema.is_address_discriminated
{
PointerAuthAddressDiscriminator::HardwareAddress(true) |
PointerAuthAddressDiscriminator::Synthetic(_) => true,
_ => false,
}matches!(
218 schema.is_address_discriminated,
219 PointerAuthAddressDiscriminator::HardwareAddress(true)
220 | PointerAuthAddressDiscriminator::Synthetic(_)
221 )
222 })) << INIT_FINI_ADDR_DISC)
223 | (u32::from(self.elf_got) << GOT)
224 | (u32::from(self.indirect_gotos) << GOTOS)
225 | (u32::from(self.typeinfo_vt_ptr_discrimination) << TYPEINFO_VT_PTR_DISCR);
226
227 pauth_abi_version
228 }
229 pub fn from_raw(raw: &[(PointerAuthOption, bool)], target: &Target) -> Option<Self> {
230 if target.cfg_abi != CfgAbi::Pauthtest {
231 return None;
232 }
233
234 let mut cfg = Self::default(target);
235 if raw.is_empty() {
236 return Some(cfg);
237 }
238
239 for (opt, enabled) in raw {
240 match opt {
241 PointerAuthOption::Calls => {
242 if *enabled {
243 cfg.function_pointers.get_or_insert_with(|| {
244 PointerAuthSchema::function_pointers_default(target)
245 });
246 } else {
247 cfg.function_pointers = None;
248 }
249 }
250 PointerAuthOption::FunctionPointerTypeDiscrimination => {
251 if *enabled {
252 let schema = cfg.function_pointers.get_or_insert_with(|| {
253 PointerAuthSchema::function_pointers_default(target)
254 });
255 schema.discrimination_kind = PointerAuthDiscrimination::Type;
256 } else if let Some(schema) = &mut cfg.function_pointers {
257 schema.discrimination_kind = PointerAuthDiscrimination::None;
258 }
259 }
260 PointerAuthOption::ReturnAddresses => cfg.return_addresses = *enabled,
261 PointerAuthOption::AuthTraps => cfg.auth_traps = *enabled,
262 PointerAuthOption::IndirectGotos => cfg.indirect_gotos = *enabled,
263 PointerAuthOption::ElfGot => cfg.elf_got = *enabled,
264 PointerAuthOption::Aarch64JumpTableHardening => {
265 cfg.aarch64_jump_table_hardening = *enabled
266 }
267 PointerAuthOption::InitFini => {
268 if *enabled {
269 cfg.init_fini
270 .get_or_insert_with(|| PointerAuthSchema::init_fini_default(target));
271 } else {
272 cfg.init_fini = None;
273 }
274 }
275 PointerAuthOption::InitFiniAddressDiscrimination => {
276 if *enabled {
277 let schema = cfg
278 .init_fini
279 .get_or_insert_with(|| PointerAuthSchema::init_fini_default(target));
280 schema.is_address_discriminated =
281 PointerAuthAddressDiscriminator::HardwareAddress(true);
282 } else if let Some(schema) = &mut cfg.init_fini {
283 schema.is_address_discriminated =
284 PointerAuthAddressDiscriminator::Synthetic(1);
285 }
286 }
287
288 PointerAuthOption::Intrinsics => cfg.intrinsics = *enabled,
289 PointerAuthOption::TypeInfoVTPtrDisc => {
290 cfg.typeinfo_vt_ptr_discrimination = *enabled
291 }
292 PointerAuthOption::VTPtrAddrDisc => cfg.vt_ptr_addr_discrimination = *enabled,
293 PointerAuthOption::VTPtrTypeDisc => cfg.vt_ptr_type_discrimination = *enabled,
294 }
295 }
296
297 Some(cfg)
298 }
299 pub fn fn_attrs(&self) -> Vec<&'static str> {
300 let mut attrs = ::alloc::vec::Vec::new()vec![];
304 if self.aarch64_jump_table_hardening {
305 attrs.push("aarch64-jump-table-hardening");
306 }
307 if self.auth_traps {
308 attrs.push("ptrauth-auth-traps");
309 }
310 if self.function_pointers.is_some() {
311 attrs.push("ptrauth-calls");
312 }
313 if self.indirect_gotos {
314 attrs.push("ptrauth-indirect-gotos");
315 }
316 if self.return_addresses {
317 attrs.push("ptrauth-returns");
318 }
319
320 attrs
321 }
322}
323
324pub struct Session {
327 pub target: Target,
328 pub host: Target,
329 pub opts: config::Options,
330 pub target_tlib_path: SearchPath,
331 pub psess: ParseSess,
332 pub unstable_features: UnstableFeatures,
333 pub config: Cfg,
334 pub check_config: CheckCfg,
335 proc_macro_quoted_spans: AppendOnlyVec<Span>,
338
339 pub io: CompilerIO,
341
342 pub prof: SelfProfilerRef,
344
345 pub timings: TimingSectionHandler,
347
348 pub code_stats: CodeStats,
350
351 pub lint_store: Option<Arc<dyn DynLintStore>>,
353
354 pub driver_lint_caps: FxHashMap<lint::LintId, lint::Level>,
356
357 pub ctfe_backtrace: Lock<CtfeBacktrace>,
364
365 miri_unleashed_features: Lock<Vec<(Span, Option<Symbol>)>>,
370
371 pub asm_arch: Option<InlineAsmArch>,
373
374 pub internal_target_features: FxIndexSet<Symbol>,
379
380 pub cfg_version: &'static str,
382
383 pub using_internal_features: &'static AtomicBool,
388
389 pub env_depinfo: Lock<FxIndexSet<(Symbol, Option<Symbol>)>>,
391
392 pub file_depinfo: Lock<FxIndexSet<Symbol>>,
394
395 target_filesearch: Arc<FileSearch>,
396 host_filesearch: Arc<FileSearch>,
397
398 pub replaced_intrinsics: FxHashSet<Symbol>,
401 pub fallback_intrinsics: FxHashSet<Symbol>,
404
405 pub thin_lto_supported: bool,
407
408 pub mir_opt_bisect_eval_count: AtomicUsize,
413
414 pub used_features: Lock<FxHashMap<Symbol, u32>>,
418
419 pub removed_rustc_main_attr: AtomicBool,
422
423 pub pointer_auth_config: Option<PointerAuthConfig>,
425}
426
427#[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)]
428pub enum CodegenUnits {
429 User(usize),
432
433 Default(usize),
437}
438
439impl CodegenUnits {
440 pub fn as_usize(self) -> usize {
441 match self {
442 CodegenUnits::User(n) => n,
443 CodegenUnits::Default(n) => n,
444 }
445 }
446}
447
448pub struct LintGroup {
449 pub name: &'static str,
450 pub lints: Vec<LintId>,
451 pub is_externally_loaded: bool,
452}
453
454impl Session {
455 pub fn miri_unleashed_feature(&self, span: Span, feature_gate: Option<Symbol>) {
456 self.miri_unleashed_features.lock().push((span, feature_gate));
457 }
458
459 pub fn local_crate_source_file(&self) -> Option<RealFileName> {
460 Some(
461 self.source_map()
462 .path_mapping()
463 .to_real_filename(self.source_map().working_dir(), self.io.input.opt_path()?),
464 )
465 }
466
467 fn check_miri_unleashed_features(&self) -> Option<ErrorGuaranteed> {
468 let mut guar = None;
469 let unleashed_features = self.miri_unleashed_features.lock();
470 if !unleashed_features.is_empty() {
471 let mut must_err = false;
472 self.dcx().emit_warn(diagnostics::SkippingConstChecks {
474 unleashed_features: unleashed_features
475 .iter()
476 .map(|(span, gate)| {
477 gate.map(|gate| {
478 must_err = true;
479 diagnostics::UnleashedFeatureHelp::Named { span: *span, gate }
480 })
481 .unwrap_or(diagnostics::UnleashedFeatureHelp::Unnamed { span: *span })
482 })
483 .collect(),
484 });
485
486 if must_err && self.dcx().has_errors().is_none() {
488 guar = Some(self.dcx().emit_err(diagnostics::NotCircumventFeature));
490 }
491 }
492 guar
493 }
494
495 pub fn finish_diagnostics(&self) -> Option<ErrorGuaranteed> {
497 let mut guar = None;
498 guar = guar.or(self.check_miri_unleashed_features());
499 guar = guar.or(self.dcx().emit_stashed_diagnostics());
500 self.dcx().print_error_count();
501 if self.opts.json_future_incompat {
502 self.dcx().emit_future_breakage_report();
503 }
504 guar
505 }
506
507 pub fn is_test_crate(&self) -> bool {
509 self.opts.test
510 }
511
512 #[track_caller]
514 pub fn create_feature_err<'a>(&'a self, err: impl Diagnostic<'a>, feature: Symbol) -> Diag<'a> {
515 let mut err = self.dcx().create_err(err);
516 if err.code.is_none() {
517 err.code(E0658);
518 }
519 diagnostics::add_feature_diagnostics(&mut err, self, feature);
520 err
521 }
522
523 pub fn record_trimmed_def_paths(&self) {
526 if self.opts.unstable_opts.print_type_sizes
527 || self.opts.unstable_opts.query_dep_graph
528 || self.opts.unstable_opts.dump_mir.is_some()
529 || self.opts.unstable_opts.unpretty.is_some()
530 || self.prof.is_args_recording_enabled()
531 || self.opts.output_types.contains_key(&OutputType::Mir)
532 || std::env::var_os("RUSTC_LOG").is_some()
533 {
534 return;
535 }
536
537 self.dcx().set_must_produce_diag()
538 }
539
540 #[inline]
541 pub fn dcx(&self) -> DiagCtxtHandle<'_> {
542 self.psess.dcx()
543 }
544
545 #[inline]
546 pub fn source_map(&self) -> &SourceMap {
547 self.psess.source_map()
548 }
549
550 pub fn proc_macro_quoted_spans(&self) -> impl Iterator<Item = (usize, Span)> {
551 self.proc_macro_quoted_spans.iter_enumerated()
554 }
555
556 pub fn save_proc_macro_span(&self, span: Span) -> usize {
557 self.proc_macro_quoted_spans.push(span)
558 }
559
560 pub fn enable_internal_lints(&self) -> bool {
564 self.unstable_options() && !self.opts.actually_rustdoc
565 }
566
567 pub fn instrument_coverage(&self) -> bool {
568 self.opts.cg.instrument_coverage() != InstrumentCoverage::No
569 }
570
571 pub fn instrument_coverage_branch(&self) -> bool {
572 self.instrument_coverage()
573 && self.opts.unstable_opts.coverage_options.level >= CoverageLevel::Branch
574 }
575
576 pub fn instrument_coverage_condition(&self) -> bool {
577 self.instrument_coverage()
578 && self.opts.unstable_opts.coverage_options.level >= CoverageLevel::Condition
579 }
580
581 pub fn coverage_options(&self) -> &CoverageOptions {
585 &self.opts.unstable_opts.coverage_options
586 }
587
588 pub fn is_sanitizer_cfi_enabled(&self) -> bool {
589 self.sanitizers().contains(SanitizerSet::CFI)
590 }
591
592 pub fn is_sanitizer_cfi_canonical_jump_tables_disabled(&self) -> bool {
593 self.opts.unstable_opts.sanitizer_cfi_canonical_jump_tables == Some(false)
594 }
595
596 pub fn is_sanitizer_cfi_canonical_jump_tables_enabled(&self) -> bool {
597 self.opts.unstable_opts.sanitizer_cfi_canonical_jump_tables == Some(true)
598 }
599
600 pub fn is_sanitizer_cfi_generalize_pointers_enabled(&self) -> bool {
601 self.opts.unstable_opts.sanitizer_cfi_generalize_pointers == Some(true)
602 }
603
604 pub fn is_sanitizer_cfi_normalize_integers_enabled(&self) -> bool {
605 self.opts.unstable_opts.sanitizer_cfi_normalize_integers == Some(true)
606 }
607
608 pub fn is_sanitizer_kcfi_arity_enabled(&self) -> bool {
609 self.opts.unstable_opts.sanitizer_kcfi_arity == Some(true)
610 }
611
612 pub fn is_sanitizer_kcfi_enabled(&self) -> bool {
613 self.sanitizers().contains(SanitizerSet::KCFI)
614 }
615
616 pub fn is_split_lto_unit_enabled(&self) -> bool {
617 self.opts.unstable_opts.split_lto_unit == Some(true)
618 }
619
620 pub fn crt_static(&self, crate_type: Option<CrateType>) -> bool {
622 if !self.target.crt_static_respected {
623 return self.target.crt_static_default;
625 }
626
627 let requested_features = self.opts.cg.target_feature.split(',');
628 let found_negative = requested_features.clone().any(|r| r == "-crt-static");
629 let found_positive = requested_features.clone().any(|r| r == "+crt-static");
630
631 #[allow(rustc::bad_opt_access)]
633 if found_positive || found_negative {
634 found_positive
635 } else if crate_type == Some(CrateType::ProcMacro)
636 || crate_type == None && self.opts.crate_types.contains(&CrateType::ProcMacro)
637 {
638 false
642 } else {
643 self.target.crt_static_default
644 }
645 }
646
647 pub fn is_wasi_reactor(&self) -> bool {
648 self.target.options.os == Os::Wasi
649 && #[allow(non_exhaustive_omitted_patterns)] match self.opts.unstable_opts.wasi_exec_model
{
Some(config::WasiExecModel::Reactor) => true,
_ => false,
}matches!(
650 self.opts.unstable_opts.wasi_exec_model,
651 Some(config::WasiExecModel::Reactor)
652 )
653 }
654
655 pub fn target_can_use_split_dwarf(&self) -> bool {
657 self.target.debuginfo_kind == DebuginfoKind::Dwarf
658 }
659
660 pub fn target_filesearch(&self) -> &filesearch::FileSearch {
661 &self.target_filesearch
662 }
663 pub fn host_filesearch(&self) -> &filesearch::FileSearch {
664 &self.host_filesearch
665 }
666
667 pub fn get_tools_search_paths(&self, self_contained: bool) -> Vec<PathBuf> {
671 let search_paths = self
672 .opts
673 .sysroot
674 .all_paths()
675 .map(|sysroot| filesearch::make_target_bin_path(&sysroot, config::host_tuple()));
676
677 if self_contained {
678 search_paths.flat_map(|path| [path.clone(), path.join("self-contained")]).collect()
682 } else {
683 search_paths.collect()
684 }
685 }
686
687 pub fn is_rust_2015(&self) -> bool {
689 self.edition().is_rust_2015()
690 }
691
692 pub fn at_least_rust_2018(&self) -> bool {
694 self.edition().at_least_rust_2018()
695 }
696
697 pub fn at_least_rust_2021(&self) -> bool {
699 self.edition().at_least_rust_2021()
700 }
701
702 pub fn at_least_rust_2024(&self) -> bool {
704 self.edition().at_least_rust_2024()
705 }
706
707 pub fn needs_plt(&self) -> bool {
709 let want_plt = self.target.plt_by_default;
712
713 let dbg_opts = &self.opts.unstable_opts;
714
715 let relro_level = self.opts.cg.relro_level.unwrap_or(self.target.relro_level);
716
717 let full_relro = RelroLevel::Full == relro_level;
721
722 dbg_opts.plt.unwrap_or(want_plt || !full_relro)
725 }
726
727 pub fn emit_lifetime_markers(&self) -> bool {
729 self.opts.optimize != config::OptLevel::No
730 || self.sanitizers().intersects(SanitizerSet::ADDRESS | SanitizerSet::KERNELADDRESS | SanitizerSet::MEMORY | SanitizerSet::HWADDRESS | SanitizerSet::KERNELHWADDRESS)
737 || self.opts.unstable_opts.codegen_emit_retag.is_some()
739 }
740
741 pub fn diagnostic_width(&self) -> usize {
742 let default_column_width = 140;
743 if let Some(width) = self.opts.diagnostic_width {
744 width
745 } else if self.opts.unstable_opts.ui_testing {
746 default_column_width
747 } else {
748 termize::dimensions().map_or(default_column_width, |(w, _)| w)
749 }
750 }
751
752 pub fn default_visibility(&self) -> SymbolVisibility {
754 self.opts
755 .unstable_opts
756 .default_visibility
757 .or(self.target.options.default_visibility)
758 .unwrap_or(SymbolVisibility::Interposable)
759 }
760
761 pub fn staticlib_components(&self, verbatim: bool) -> (&str, &str) {
762 if verbatim {
763 ("", "")
764 } else {
765 (&*self.target.staticlib_prefix, &*self.target.staticlib_suffix)
766 }
767 }
768
769 pub fn lint_groups_iter(&self) -> Box<dyn Iterator<Item = LintGroup> + '_> {
770 match self.lint_store {
771 Some(ref lint_store) => lint_store.lint_groups_iter(),
772 None => Box::new(std::iter::empty()),
773 }
774 }
775}
776
777#[allow(rustc::bad_opt_access)]
779impl Session {
780 pub fn verbose_internals(&self) -> bool {
781 self.opts.unstable_opts.verbose_internals
782 }
783
784 pub fn print_llvm_stats(&self) -> bool {
785 self.opts.unstable_opts.print_codegen_stats
786 }
787
788 pub fn print_llvm_stats_json(&self) -> Option<&String> {
789 self.opts.unstable_opts.print_codegen_stats_json.as_ref()
790 }
791
792 pub fn verify_llvm_ir(&self) -> bool {
793 self.opts.unstable_opts.verify_llvm_ir || ::core::option::Option::None::<&'static str>option_env!("RUSTC_VERIFY_LLVM_IR").is_some()
794 }
795
796 pub fn binary_dep_depinfo(&self) -> bool {
797 self.opts.unstable_opts.binary_dep_depinfo
798 }
799
800 pub fn mir_opt_level(&self) -> usize {
801 self.opts
802 .unstable_opts
803 .mir_opt_level
804 .unwrap_or_else(|| if self.opts.optimize != OptLevel::No { 2 } else { 1 })
805 }
806
807 pub fn lto(&self) -> config::Lto {
809 if self.target.requires_lto {
811 return config::Lto::Fat;
812 }
813
814 match self.opts.cg.lto {
818 config::LtoCli::Unspecified => {
819 }
822 config::LtoCli::No => {
823 return config::Lto::No;
825 }
826 config::LtoCli::Yes | config::LtoCli::Fat | config::LtoCli::NoParam => {
827 return config::Lto::Fat;
829 }
830 config::LtoCli::Thin => {
831 if !self.thin_lto_supported {
833 self.dcx().emit_warn(diagnostics::ThinLtoNotSupportedByBackend);
835 return config::Lto::Fat;
836 }
837 return config::Lto::Thin;
838 }
839 }
840
841 if !self.thin_lto_supported {
842 return config::Lto::No;
843 }
844
845 if self.opts.cli_forced_local_thinlto_off {
854 return config::Lto::No;
855 }
856
857 if let Some(enabled) = self.opts.unstable_opts.thinlto {
860 if enabled {
861 return config::Lto::ThinLocal;
862 } else {
863 return config::Lto::No;
864 }
865 }
866
867 if self.codegen_units().as_usize() == 1 {
870 return config::Lto::No;
871 }
872
873 match self.opts.optimize {
876 config::OptLevel::No => config::Lto::No,
877 _ => config::Lto::ThinLocal,
878 }
879 }
880
881 pub fn panic_strategy(&self) -> PanicStrategy {
884 self.opts.cg.panic.unwrap_or(self.target.panic_strategy)
885 }
886
887 pub fn fewer_names(&self) -> bool {
888 if let Some(fewer_names) = self.opts.unstable_opts.fewer_names {
889 fewer_names
890 } else {
891 let more_names = self.opts.output_types.contains_key(&OutputType::LlvmAssembly)
892 || self.opts.output_types.contains_key(&OutputType::Bitcode)
893 || self.opts.unstable_opts.sanitizer.intersects(SanitizerSet::ADDRESS | SanitizerSet::MEMORY);
895 !more_names
896 }
897 }
898
899 pub fn unstable_options(&self) -> bool {
900 self.opts.unstable_opts.unstable_options
901 }
902
903 pub fn is_nightly_build(&self) -> bool {
904 self.opts.unstable_features.is_nightly_build()
905 }
906
907 pub fn overflow_checks(&self) -> bool {
908 self.opts.cg.overflow_checks.unwrap_or(self.opts.debug_assertions)
909 }
910
911 pub fn ub_checks(&self) -> bool {
912 self.opts.unstable_opts.ub_checks.unwrap_or(self.opts.debug_assertions)
913 }
914
915 pub fn contract_checks(&self) -> bool {
916 self.opts.unstable_opts.contract_checks.unwrap_or(false)
917 }
918
919 pub fn relocation_model(&self) -> RelocModel {
920 self.opts.cg.relocation_model.unwrap_or(self.target.relocation_model)
921 }
922
923 pub fn code_model(&self) -> Option<CodeModel> {
924 self.opts.cg.code_model.or(self.target.code_model)
925 }
926
927 pub fn tls_model(&self) -> TlsModel {
928 self.opts.unstable_opts.tls_model.unwrap_or(self.target.tls_model)
929 }
930
931 pub fn direct_access_external_data(&self) -> Option<bool> {
932 self.opts
933 .unstable_opts
934 .direct_access_external_data
935 .or(self.target.direct_access_external_data)
936 }
937
938 pub fn split_debuginfo(&self) -> SplitDebuginfo {
939 self.opts.cg.split_debuginfo.unwrap_or(self.target.split_debuginfo)
940 }
941
942 pub fn dwarf_version(&self) -> u32 {
944 self.opts
945 .cg
946 .dwarf_version
947 .or(self.opts.unstable_opts.dwarf_version)
948 .unwrap_or(self.target.default_dwarf_version)
949 }
950
951 pub fn stack_protector(&self) -> StackProtector {
952 if self.target.options.supports_stack_protector {
953 self.opts.unstable_opts.stack_protector
954 } else {
955 StackProtector::None
956 }
957 }
958
959 pub fn branch_protection(&self) -> Option<BranchProtection> {
965 let mut bp = self.opts.unstable_opts.branch_protection;
966
967 if let Some(bp) = bp.as_mut() {
968 if self.target.os == Os::Windows && self.target.arch == Arch::AArch64 {
972 if let Some(pac_ret) = bp.pac_ret.as_mut()
973 && pac_ret.key == PAuthKey::A
974 {
975 pac_ret.key = PAuthKey::B;
976 }
977 }
978 }
979
980 bp
981 }
982
983 pub fn must_emit_unwind_tables(&self) -> bool {
984 self.target.requires_uwtable
1013 || self
1014 .opts
1015 .cg
1016 .force_unwind_tables
1017 .unwrap_or(self.panic_strategy().unwinds() || self.target.default_uwtable)
1018 }
1019
1020 pub fn codegen_units(&self) -> CodegenUnits {
1023 if let Some(n) = self.opts.cli_forced_codegen_units {
1024 return CodegenUnits::User(n);
1025 }
1026 if let Some(n) = self.target.default_codegen_units {
1027 return CodegenUnits::Default(n as usize);
1028 }
1029
1030 if self.opts.incremental.is_some() {
1034 return CodegenUnits::Default(256);
1035 }
1036
1037 CodegenUnits::Default(16)
1088 }
1089
1090 pub fn teach(&self, code: ErrCode) -> bool {
1091 self.opts.unstable_opts.teach && self.dcx().must_teach(code)
1092 }
1093
1094 pub fn edition(&self) -> Edition {
1095 self.opts.edition
1096 }
1097
1098 pub fn link_dead_code(&self) -> bool {
1099 self.opts.cg.link_dead_code.unwrap_or(false)
1100 }
1101
1102 pub fn apple_deployment_target(&self) -> apple::OSVersion {
1107 let min = apple::OSVersion::minimum_deployment_target(&self.target);
1108 let env_var = apple::deployment_target_env_var(&self.target.os);
1109
1110 if let Ok(deployment_target) = env::var(env_var) {
1112 match apple::OSVersion::from_str(&deployment_target) {
1113 Ok(version) => {
1114 let os_min = apple::OSVersion::os_minimum_deployment_target(&self.target.os);
1115 if version < os_min {
1120 self.dcx().emit_warn(diagnostics::AppleDeploymentTarget::TooLow {
1121 env_var,
1122 version: version.fmt_pretty().to_string(),
1123 os_min: os_min.fmt_pretty().to_string(),
1124 });
1125 }
1126
1127 version.max(min)
1129 }
1130 Err(error) => {
1131 self.dcx()
1132 .emit_err(diagnostics::AppleDeploymentTarget::Invalid { env_var, error });
1133 min
1134 }
1135 }
1136 } else {
1137 min
1139 }
1140 }
1141
1142 pub fn sanitizers(&self) -> SanitizerSet {
1143 return self.opts.unstable_opts.sanitizer | self.target.options.default_sanitizers;
1144 }
1145
1146 pub fn pointer_authentication(&self) -> bool {
1147 self.pointer_auth_config.is_some()
1148 }
1149
1150 pub fn pointer_authentication_functions(&self) -> Option<&PointerAuthSchema> {
1151 self.pointer_auth_config.as_ref().and_then(|cfg| cfg.function_pointers.as_ref())
1152 }
1153
1154 pub fn pointer_authentication_init_fini(&self) -> Option<&PointerAuthSchema> {
1155 self.pointer_auth_config.as_ref().and_then(|cfg| cfg.init_fini.as_ref())
1156 }
1157}
1158
1159#[allow(rustc::bad_opt_access)]
1161fn default_emitter(sopts: &config::Options, source_map: Arc<SourceMap>) -> Box<DynEmitter> {
1162 let macro_backtrace = sopts.unstable_opts.macro_backtrace;
1163 let track_diagnostics = sopts.unstable_opts.track_diagnostics;
1164 let terminal_url = match sopts.unstable_opts.terminal_urls {
1165 TerminalUrl::Auto => {
1166 match (std::env::var("COLORTERM").as_deref(), std::env::var("TERM").as_deref()) {
1167 (Ok("truecolor"), Ok("xterm-256color"))
1168 if sopts.unstable_features.is_nightly_build() =>
1169 {
1170 TerminalUrl::Yes
1171 }
1172 _ => TerminalUrl::No,
1173 }
1174 }
1175 t => t,
1176 };
1177
1178 let source_map = if sopts.unstable_opts.link_only { None } else { Some(source_map) };
1179
1180 match sopts.error_format {
1181 config::ErrorOutputType::HumanReadable { kind, color_config } => match kind {
1182 HumanReadableErrorType { short, unicode } => {
1183 let emitter = AnnotateSnippetEmitter::new(stderr_destination(color_config))
1184 .sm(source_map)
1185 .short_message(short)
1186 .diagnostic_width(sopts.diagnostic_width)
1187 .macro_backtrace(macro_backtrace)
1188 .track_diagnostics(track_diagnostics)
1189 .terminal_url(terminal_url)
1190 .theme(if unicode { OutputTheme::Unicode } else { OutputTheme::Ascii })
1191 .ignored_directories_in_source_blocks(
1192 sopts.unstable_opts.ignore_directory_in_diagnostics_source_blocks.clone(),
1193 );
1194 Box::new(emitter.ui_testing(sopts.unstable_opts.ui_testing))
1195 }
1196 },
1197 config::ErrorOutputType::Json { pretty, json_rendered, color_config } => Box::new(
1198 JsonEmitter::new(
1199 Box::new(io::BufWriter::new(io::stderr())),
1200 source_map,
1201 pretty,
1202 json_rendered,
1203 color_config,
1204 )
1205 .ui_testing(sopts.unstable_opts.ui_testing)
1206 .ignored_directories_in_source_blocks(
1207 sopts.unstable_opts.ignore_directory_in_diagnostics_source_blocks.clone(),
1208 )
1209 .diagnostic_width(sopts.diagnostic_width)
1210 .macro_backtrace(macro_backtrace)
1211 .track_diagnostics(track_diagnostics)
1212 .terminal_url(terminal_url),
1213 ),
1214 }
1215}
1216
1217#[allow(rustc::bad_opt_access)]
1219pub fn build_session(
1220 sopts: config::Options,
1221 io: CompilerIO,
1222 driver_lint_caps: FxHashMap<lint::LintId, lint::Level>,
1223 target: Target,
1224 cfg_version: &'static str,
1225 ice_file: Option<PathBuf>,
1226 using_internal_features: &'static AtomicBool,
1227) -> Session {
1228 let warnings_allow = sopts
1232 .lint_opts
1233 .iter()
1234 .rfind(|&(key, _)| *key == "warnings")
1235 .is_some_and(|&(_, level)| level == lint::Allow);
1236 let cap_lints_allow = sopts.lint_cap.is_some_and(|cap| cap == lint::Allow);
1237 let can_emit_warnings = !(warnings_allow || cap_lints_allow);
1238
1239 let source_map = rustc_span::source_map::get_source_map().unwrap();
1240 let emitter = default_emitter(&sopts, Arc::clone(&source_map));
1241
1242 let mut dcx =
1243 DiagCtxt::new(emitter).with_flags(sopts.unstable_opts.dcx_flags(can_emit_warnings));
1244 if let Some(ice_file) = ice_file {
1245 dcx = dcx.with_ice_file(ice_file);
1246 }
1247
1248 if let Some(msrv) = sopts.unstable_opts.hint_msrv {
1249 dcx = dcx.with_msrv(msrv);
1250 }
1251
1252 let host_triple = TargetTuple::from_tuple(config::host_tuple());
1253 let (host, target_warnings) =
1254 Target::search(&host_triple, sopts.sysroot.path(), sopts.unstable_opts.unstable_options)
1255 .unwrap_or_else(|e| {
1256 dcx.handle().fatal(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("Error loading host specification: {0}",
e))
})format!("Error loading host specification: {e}"))
1257 });
1258 for warning in target_warnings.warning_messages() {
1259 dcx.handle().warn(warning)
1260 }
1261
1262 let self_profiler = if let SwitchWithOptPath::Enabled(ref d) = sopts.unstable_opts.self_profile
1263 {
1264 let directory = if let Some(directory) = d { directory } else { std::path::Path::new(".") };
1265
1266 let profiler = SelfProfiler::new(
1267 directory,
1268 sopts.crate_name.as_deref(),
1269 sopts.unstable_opts.self_profile_events.as_deref(),
1270 &sopts.unstable_opts.self_profile_counter,
1271 );
1272 match profiler {
1273 Ok(profiler) => Some(Arc::new(profiler)),
1274 Err(e) => {
1275 dcx.handle().emit_warn(diagnostics::FailedToCreateProfiler { err: e.to_string() });
1276 None
1277 }
1278 }
1279 } else {
1280 None
1281 };
1282
1283 let psess = ParseSess::with_dcx(dcx, source_map);
1284
1285 let host_triple = config::host_tuple();
1286 let target_triple = sopts.target_triple.tuple();
1287 let host_tlib_path = SearchPath::from_sysroot_and_triple(sopts.sysroot.path(), host_triple);
1289 let target_tlib_path = SearchPath::from_sysroot_and_triple(sopts.sysroot.path(), target_triple);
1290
1291 let prof = SelfProfilerRef::new(
1292 self_profiler,
1293 sopts.unstable_opts.time_passes.then(|| sopts.unstable_opts.time_passes_format),
1294 );
1295
1296 let ctfe_backtrace = Lock::new(match env::var("RUSTC_CTFE_BACKTRACE") {
1297 Ok(ref val) if val == "immediate" => CtfeBacktrace::Immediate,
1298 Ok(ref val) if val != "0" => CtfeBacktrace::Capture,
1299 _ => CtfeBacktrace::Disabled,
1300 });
1301
1302 let asm_arch = if target.allow_asm { InlineAsmArch::from_arch(&target.arch) } else { None };
1303 let target_filesearch = Arc::new(filesearch::FileSearch::new(
1304 &sopts.search_paths,
1305 &target_tlib_path,
1306 &target,
1307 sopts.unstable_opts.implicit_sysroot_deps,
1308 ));
1309 let host_filesearch = if target == host {
1310 Arc::clone(&target_filesearch)
1311 } else {
1312 Arc::new(filesearch::FileSearch::new(
1313 &sopts.search_paths,
1314 &host_tlib_path,
1315 &host,
1316 sopts.unstable_opts.implicit_sysroot_deps,
1317 ))
1318 };
1319
1320 let timings = TimingSectionHandler::new(sopts.json_timings);
1321
1322 let pointer_auth_config: Option<PointerAuthConfig> =
1323 PointerAuthConfig::from_raw(&sopts.unstable_opts.pointer_authentication, &target);
1324
1325 let sess = Session {
1326 target,
1327 host,
1328 opts: sopts,
1329 target_tlib_path,
1330 psess,
1331 unstable_features: UnstableFeatures::from_environment(None),
1332 config: Cfg::default(),
1333 check_config: CheckCfg::default(),
1334 proc_macro_quoted_spans: Default::default(),
1335 io,
1336 prof,
1337 timings,
1338 code_stats: Default::default(),
1339 lint_store: None,
1340 driver_lint_caps,
1341 ctfe_backtrace,
1342 miri_unleashed_features: Lock::new(Default::default()),
1343 asm_arch,
1344 internal_target_features: Default::default(),
1345 cfg_version,
1346 using_internal_features,
1347 env_depinfo: Default::default(),
1348 file_depinfo: Default::default(),
1349 target_filesearch,
1350 host_filesearch,
1351 replaced_intrinsics: FxHashSet::default(), fallback_intrinsics: FxHashSet::default(), thin_lto_supported: true, mir_opt_bisect_eval_count: AtomicUsize::new(0),
1355 used_features: Lock::default(),
1356 removed_rustc_main_attr: AtomicBool::new(false),
1357 pointer_auth_config,
1358 };
1359
1360 validate_commandline_args_with_session_available(&sess);
1361
1362 sess
1363}
1364
1365pub fn generate_proc_macro_decls_symbol(stable_crate_id: StableCrateId) -> String {
1366 ::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())
1367}
1368
1369#[allow(rustc::bad_opt_access)]
1375fn validate_commandline_args_with_session_available(sess: &Session) {
1376 if sess.opts.cg.linker_plugin_lto.enabled()
1384 && sess.opts.cg.prefer_dynamic
1385 && sess.target.is_like_windows
1386 {
1387 sess.dcx().emit_err(diagnostics::LinkerPluginToWindowsNotSupported);
1388 }
1389
1390 if sess
1391 .pointer_auth_config
1392 .as_ref()
1393 .and_then(|cfg| cfg.function_pointers.as_ref())
1394 .is_some_and(|schema| #[allow(non_exhaustive_omitted_patterns)] match schema.discrimination_kind {
PointerAuthDiscrimination::Type => true,
_ => false,
}matches!(schema.discrimination_kind, PointerAuthDiscrimination::Type))
1395 {
1396 sess.dcx().emit_err(
1397 diagnostics::PointerAuthenticationTypeDiscriminationNotSupportedForTarget {
1398 target_triple: &sess.opts.target_triple,
1399 },
1400 );
1401 }
1402
1403 if sess.target.cfg_abi != CfgAbi::Pauthtest
1404 && !sess.opts.unstable_opts.pointer_authentication.is_empty()
1405 {
1406 sess.dcx().emit_warn(diagnostics::PointerAuthenticationNotSupportedForTarget {
1407 target_triple: &sess.opts.target_triple,
1408 });
1409 }
1410
1411 if let Some(ref path) = sess.opts.cg.profile_use {
1414 if !path.exists() {
1415 sess.dcx().emit_err(diagnostics::ProfileUseFileDoesNotExist { path });
1416 }
1417 }
1418
1419 if let Some(ref path) = sess.opts.unstable_opts.profile_sample_use {
1421 if !path.exists() {
1422 sess.dcx().emit_err(diagnostics::ProfileSampleUseFileDoesNotExist { path });
1423 }
1424 }
1425
1426 if let Some(include_uwtables) = sess.opts.cg.force_unwind_tables {
1428 if sess.target.requires_uwtable && !include_uwtables {
1429 sess.dcx().emit_err(diagnostics::TargetRequiresUnwindTables);
1430 }
1431 }
1432
1433 let supported_sanitizers = sess.target.options.supported_sanitizers;
1435 let mut unsupported_sanitizers = sess.opts.unstable_opts.sanitizer - supported_sanitizers;
1436 if sess.opts.unstable_opts.fixed_x18 && sess.target.arch == Arch::AArch64 {
1439 unsupported_sanitizers -= SanitizerSet::SHADOWCALLSTACK;
1440 }
1441 match unsupported_sanitizers.into_iter().count() {
1442 0 => {}
1443 1 => {
1444 sess.dcx().emit_err(diagnostics::SanitizerNotSupported {
1445 us: unsupported_sanitizers.to_string(),
1446 });
1447 }
1448 _ => {
1449 sess.dcx().emit_err(diagnostics::SanitizersNotSupported {
1450 us: unsupported_sanitizers.to_string(),
1451 });
1452 }
1453 }
1454
1455 if let Some((first, second)) = sess.opts.unstable_opts.sanitizer.mutually_exclusive() {
1457 sess.dcx().emit_err(diagnostics::CannotMixAndMatchSanitizers {
1458 first: first.to_string(),
1459 second: second.to_string(),
1460 });
1461 }
1462
1463 if sess.crt_static(None)
1465 && !sess.opts.unstable_opts.sanitizer.is_empty()
1466 && !sess.target.is_like_msvc
1467 {
1468 sess.dcx().emit_err(diagnostics::CannotEnableCrtStaticLinux);
1469 }
1470
1471 if sess.crt_static(None) && sess.target.cfg_abi == CfgAbi::Pauthtest {
1475 sess.dcx().emit_err(diagnostics::CannotEnableCrtStaticPointerAuth);
1476 }
1477
1478 if sess.is_sanitizer_cfi_enabled()
1480 && !(sess.lto() == config::Lto::Fat || sess.opts.cg.linker_plugin_lto.enabled())
1481 {
1482 sess.dcx().emit_err(diagnostics::SanitizerCfiRequiresLto);
1483 }
1484
1485 if sess.is_sanitizer_kcfi_enabled() && sess.panic_strategy().unwinds() {
1487 sess.dcx().emit_err(diagnostics::SanitizerKcfiRequiresPanicAbort);
1488 }
1489
1490 if sess.is_sanitizer_cfi_enabled()
1492 && sess.lto() == config::Lto::Fat
1493 && (sess.codegen_units().as_usize() != 1)
1494 {
1495 sess.dcx().emit_err(diagnostics::SanitizerCfiRequiresSingleCodegenUnit);
1496 }
1497
1498 if sess.is_sanitizer_cfi_canonical_jump_tables_disabled() {
1500 if !sess.is_sanitizer_cfi_enabled() {
1501 sess.dcx().emit_err(diagnostics::SanitizerCfiCanonicalJumpTablesRequiresCfi);
1502 }
1503 }
1504
1505 if sess.is_sanitizer_kcfi_arity_enabled() && !sess.is_sanitizer_kcfi_enabled() {
1507 sess.dcx().emit_err(diagnostics::SanitizerKcfiArityRequiresKcfi);
1508 }
1509
1510 if sess.is_sanitizer_cfi_generalize_pointers_enabled() {
1512 if !(sess.is_sanitizer_cfi_enabled() || sess.is_sanitizer_kcfi_enabled()) {
1513 sess.dcx().emit_err(diagnostics::SanitizerCfiGeneralizePointersRequiresCfi);
1514 }
1515 }
1516
1517 if sess.is_sanitizer_cfi_normalize_integers_enabled() {
1519 if !(sess.is_sanitizer_cfi_enabled() || sess.is_sanitizer_kcfi_enabled()) {
1520 sess.dcx().emit_err(diagnostics::SanitizerCfiNormalizeIntegersRequiresCfi);
1521 }
1522 }
1523
1524 if sess.is_split_lto_unit_enabled()
1526 && !(sess.lto() == config::Lto::Fat
1527 || sess.lto() == config::Lto::Thin
1528 || sess.opts.cg.linker_plugin_lto.enabled())
1529 {
1530 sess.dcx().emit_err(diagnostics::SplitLtoUnitRequiresLto);
1531 }
1532
1533 if sess.lto() != config::Lto::Fat {
1535 if sess.opts.unstable_opts.virtual_function_elimination {
1536 sess.dcx().emit_err(diagnostics::UnstableVirtualFunctionElimination);
1537 }
1538 }
1539
1540 if sess.opts.unstable_opts.stack_protector != StackProtector::None {
1541 if !sess.target.options.supports_stack_protector {
1542 sess.dcx().emit_warn(diagnostics::StackProtectorNotSupportedForTarget {
1543 stack_protector: sess.opts.unstable_opts.stack_protector,
1544 target_triple: &sess.opts.target_triple,
1545 });
1546 }
1547 }
1548
1549 if sess.opts.unstable_opts.small_data_threshold.is_some() {
1550 if sess.target.small_data_threshold_support() == SmallDataThresholdSupport::None {
1551 sess.dcx().emit_warn(diagnostics::SmallDataThresholdNotSupportedForTarget {
1552 target_triple: &sess.opts.target_triple,
1553 })
1554 }
1555 }
1556
1557 if sess.opts.unstable_opts.branch_protection.is_some() && sess.target.arch != Arch::AArch64 {
1558 sess.dcx().emit_err(diagnostics::BranchProtectionRequiresAArch64);
1559 }
1560
1561 if let Some(dwarf_version) =
1562 sess.opts.cg.dwarf_version.or(sess.opts.unstable_opts.dwarf_version)
1563 {
1564 if dwarf_version < 2 || dwarf_version > 5 {
1566 sess.dcx().emit_err(diagnostics::UnsupportedDwarfVersion { dwarf_version });
1567 }
1568 }
1569
1570 if !sess.target.options.supported_split_debuginfo.contains(&sess.split_debuginfo())
1571 && !sess.opts.unstable_opts.unstable_options
1572 {
1573 sess.dcx().emit_err(diagnostics::SplitDebugInfoUnstablePlatform {
1574 debuginfo: sess.split_debuginfo(),
1575 });
1576 }
1577
1578 if sess.opts.unstable_opts.embed_source {
1579 let dwarf_version = sess.dwarf_version();
1580
1581 if dwarf_version < 5 {
1582 sess.dcx()
1583 .emit_warn(diagnostics::EmbedSourceInsufficientDwarfVersion { dwarf_version });
1584 }
1585
1586 if sess.opts.debuginfo == DebugInfo::None {
1587 sess.dcx().emit_warn(diagnostics::EmbedSourceRequiresDebugInfo);
1588 }
1589 }
1590
1591 if let InstrumentMcount::Fentry(opts) = sess.opts.unstable_opts.instrument_mcount {
1592 if !sess.target.options.supports_fentry {
1593 sess.dcx()
1594 .emit_err(diagnostics::InstrumentationNotSupported { us: "fentry".to_string() });
1595 }
1596 if (opts.no_call || opts.record) && sess.target.arch != Arch::S390x {
1597 sess.dcx()
1598 .emit_err(diagnostics::InstrumentationNotSupported { us: "fentry-*".to_string() });
1599 }
1600 }
1601
1602 if sess.opts.unstable_opts.instrument_xray.is_some() && !sess.target.options.supports_xray {
1603 sess.dcx().emit_err(diagnostics::InstrumentationNotSupported { us: "XRay".to_string() });
1604 }
1605
1606 if let Some(flavor) = sess.opts.cg.linker_flavor
1607 && let Some(compatible_list) = sess.target.linker_flavor.check_compatibility(flavor)
1608 {
1609 let flavor = flavor.desc();
1610 sess.dcx().emit_err(diagnostics::IncompatibleLinkerFlavor { flavor, compatible_list });
1611 }
1612
1613 if sess.opts.unstable_opts.function_return != FunctionReturn::default() {
1614 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) {
1615 sess.dcx().emit_err(diagnostics::FunctionReturnRequiresX86OrX8664);
1616 }
1617 }
1618
1619 if sess.opts.unstable_opts.indirect_branch_cs_prefix {
1620 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) {
1621 sess.dcx().emit_err(diagnostics::IndirectBranchCsPrefixRequiresX86OrX8664);
1622 }
1623 }
1624
1625 if let Some(regparm) = sess.opts.unstable_opts.regparm {
1626 if regparm > 3 {
1627 sess.dcx().emit_err(diagnostics::UnsupportedRegparm { regparm });
1628 }
1629 if sess.target.arch != Arch::X86 {
1630 sess.dcx().emit_err(diagnostics::UnsupportedRegparmArch);
1631 }
1632 }
1633 if sess.opts.unstable_opts.reg_struct_return {
1634 if sess.target.arch != Arch::X86 {
1635 sess.dcx().emit_err(diagnostics::UnsupportedRegStructReturnArch);
1636 }
1637 }
1638
1639 match sess.opts.unstable_opts.function_return {
1643 FunctionReturn::Keep => (),
1644 FunctionReturn::ThunkExtern => {
1645 if let Some(code_model) = sess.code_model()
1648 && code_model == CodeModel::Large
1649 {
1650 sess.dcx()
1651 .emit_err(diagnostics::FunctionReturnThunkExternRequiresNonLargeCodeModel);
1652 }
1653 }
1654 }
1655
1656 if sess.opts.unstable_opts.packed_stack {
1657 if sess.target.arch != Arch::S390x {
1658 sess.dcx().emit_err(diagnostics::UnsupportedPackedStack);
1659 }
1660 }
1661
1662 if let Some(ref cpu_name) = sess.opts.cg.target_cpu {
1663 if cpu_name == NATIVE_CPU && sess.target.requires_consistent_cpu {
1664 sess.dcx().emit_fatal(diagnostics::NativeTargetCpuNotAllowed {
1665 target_triple: &sess.opts.target_triple,
1666 need_explicit_cpu: sess.target.need_explicit_cpu,
1667 });
1668 }
1669 }
1670}
1671
1672pub struct IncrCompSession {
1674 pub session_directory: PathBuf,
1678 pub _lock_file: flock::Lock,
1682}
1683
1684pub struct EarlyDiagCtxt {
1686 dcx: DiagCtxt,
1687}
1688
1689impl EarlyDiagCtxt {
1690 pub fn new(output: ErrorOutputType) -> Self {
1691 let emitter = mk_emitter(output);
1692 Self { dcx: DiagCtxt::new(emitter) }
1693 }
1694
1695 pub fn set_error_format(&mut self, output: ErrorOutputType) {
1698 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());
1699
1700 let emitter = mk_emitter(output);
1701 self.dcx = DiagCtxt::new(emitter);
1702 }
1703
1704 pub fn early_note(&self, msg: impl Into<DiagMessage>) {
1705 self.dcx.handle().note(msg)
1706 }
1707
1708 pub fn early_help(&self, msg: impl Into<DiagMessage>) {
1709 self.dcx.handle().struct_help(msg).emit()
1710 }
1711
1712 #[must_use = "raise_fatal must be called on the returned ErrorGuaranteed in order to exit with a non-zero status code"]
1713 pub fn early_err(&self, msg: impl Into<DiagMessage>) -> ErrorGuaranteed {
1714 self.dcx.handle().err(msg)
1715 }
1716
1717 pub fn early_fatal(&self, msg: impl Into<DiagMessage>) -> ! {
1718 self.dcx.handle().fatal(msg)
1719 }
1720
1721 pub fn early_struct_fatal(&self, msg: impl Into<DiagMessage>) -> Diag<'_, FatalAbort> {
1722 self.dcx.handle().struct_fatal(msg)
1723 }
1724
1725 pub fn early_warn(&self, msg: impl Into<DiagMessage>) {
1726 self.dcx.handle().warn(msg)
1727 }
1728
1729 pub fn early_struct_warn(&self, msg: impl Into<DiagMessage>) -> Diag<'_, ()> {
1730 self.dcx.handle().struct_warn(msg)
1731 }
1732}
1733
1734fn mk_emitter(output: ErrorOutputType) -> Box<DynEmitter> {
1735 let emitter: Box<DynEmitter> = match output {
1736 config::ErrorOutputType::HumanReadable { kind, color_config } => match kind {
1737 HumanReadableErrorType { short, unicode } => Box::new(
1738 AnnotateSnippetEmitter::new(stderr_destination(color_config))
1739 .theme(if unicode { OutputTheme::Unicode } else { OutputTheme::Ascii })
1740 .short_message(short),
1741 ),
1742 },
1743 config::ErrorOutputType::Json { pretty, json_rendered, color_config } => {
1744 Box::new(JsonEmitter::new(
1745 Box::new(io::BufWriter::new(io::stderr())),
1746 Some(Arc::new(SourceMap::new(FilePathMapping::empty()))),
1747 pretty,
1748 json_rendered,
1749 color_config,
1750 ))
1751 }
1752 };
1753 emitter
1754}