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