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