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