1use std::any::Any;
2use std::ops::{Deref, DerefMut};
3use std::path::Component::Prefix;
4use std::path::PathBuf;
5use std::str::FromStr;
6use std::sync::Arc;
7use std::sync::atomic::{AtomicBool, AtomicUsize};
8use std::{env, io};
9
10use rustc_data_structures::flock;
11use rustc_data_structures::fx::{FxHashMap, FxHashSet, FxIndexSet};
12use rustc_data_structures::profiling::{SelfProfiler, SelfProfilerRef};
13use rustc_data_structures::sync::{AppendOnlyVec, DynSend, DynSync, Lock};
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, PResult, TerminalUrl,
21};
22use rustc_feature::UnstableFeatures;
23use rustc_macros::StableHash;
24pub use rustc_span::def_id::StableCrateId;
25use rustc_span::edition::Edition;
26use rustc_span::source_map::{FilePathMapping, SourceMap};
27use rustc_span::{RealFileName, Span, Symbol};
28use rustc_structures::{CrateType, Limit, LintName};
29use rustc_target::asm::InlineAsmArch;
30use rustc_target::spec::{
31 Arch, CfgAbi, CodeModel, DebuginfoKind, MergeFunctions, Os, PanicStrategy, RelocModel,
32 RelroLevel, SanitizerSet, SmallDataThresholdSupport, SplitDebuginfo, StackProtector,
33 SymbolVisibility, 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, DebugInfo,
40 ErrorOutputType, FunctionReturn, Input, InstrumentCoverage, InstrumentMcount, LtoCli,
41 NATIVE_CPU, 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]#[doc(hidden)]unsafe impl ::core::clone::TrivialClone
for CtfeBacktrace {
}
#[automatically_derived]impl ::core::clone::Clone for CtfeBacktrace {
#[inline]
fn clone(&self) -> Self { *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]#[doc(hidden)]unsafe impl ::core::clone::TrivialClone
for Limits {
}
#[automatically_derived]impl ::core::clone::Clone for Limits {
#[inline]
fn clone(&self) -> Self {
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 move_size_limit type_length_limit pattern_complexity_limit",
&self.recursion_limit, &self.move_size_limit,
&self.type_length_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]#[doc(hidden)]unsafe impl ::core::clone::TrivialClone
for PointerAuthARM8_3Key {
}
#[automatically_derived]impl ::core::clone::Clone for PointerAuthARM8_3Key {
#[inline]
fn clone(&self) -> Self { *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::marker::StructuralPartialEq for
PointerAuthARM8_3Key {
}
#[automatically_derived]impl ::core::cmp::PartialEq for PointerAuthARM8_3Key {
#[inline]
fn eq(&self, other: &Self) -> bool {
::core::intrinsics::discriminant_value(self) ==
::core::intrinsics::discriminant_value(other)
}
}PartialEq, #[automatically_derived]impl ::core::cmp::Eq for PointerAuthARM8_3Key { }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 EarlySession {
329 pub target: Target,
330 pub host: Target,
331 pub opts: config::Options,
332 pub psess: ParseSess,
333}
334
335#[allow(rustc::bad_opt_access)]
337impl EarlySession {
338 #[inline]
339 pub fn dcx(&self) -> DiagCtxtHandle<'_> {
340 self.psess.dcx()
341 }
342
343 #[inline]
344 pub fn source_map(&self) -> &SourceMap {
345 self.psess.source_map()
346 }
347
348 pub fn early_lto(&self) -> LtoCli {
351 self.opts.cg.lto
352 }
353
354 pub fn print_llvm_stats(&self) -> bool {
355 self.opts.unstable_opts.print_codegen_stats
356 }
357
358 pub fn print_llvm_stats_json(&self) -> Option<&String> {
359 self.opts.unstable_opts.print_codegen_stats_json.as_ref()
360 }
361
362 pub fn relocation_model(&self) -> RelocModel {
363 self.opts.cg.relocation_model.unwrap_or(self.target.relocation_model)
364 }
365
366 pub fn code_model(&self) -> Option<CodeModel> {
367 self.opts.cg.code_model.or(self.target.code_model)
368 }
369
370 pub fn tls_model(&self) -> TlsModel {
371 self.opts.unstable_opts.tls_model.unwrap_or(self.target.tls_model)
372 }
373
374 pub fn panic_strategy(&self) -> PanicStrategy {
377 self.opts.cg.panic.unwrap_or(self.target.panic_strategy)
378 }
379
380 pub fn apple_deployment_target(&self) -> apple::OSVersion {
385 let min = apple::OSVersion::minimum_deployment_target(&self.target);
386 let env_var = apple::deployment_target_env_var(&self.target.os);
387
388 if let Ok(deployment_target) = env::var(env_var) {
390 match apple::OSVersion::from_str(&deployment_target) {
391 Ok(version) => {
392 let os_min = apple::OSVersion::os_minimum_deployment_target(&self.target.os);
393 if version < os_min {
398 self.dcx().emit_warn(diagnostics::AppleDeploymentTarget::TooLow {
399 env_var,
400 version: version.fmt_pretty().to_string(),
401 os_min: os_min.fmt_pretty().to_string(),
402 });
403 }
404
405 version.max(min)
407 }
408 Err(error) => {
409 self.dcx()
410 .emit_err(diagnostics::AppleDeploymentTarget::Invalid { env_var, error });
411 min
412 }
413 }
414 } else {
415 min
417 }
418 }
419
420 pub fn sanitizers(&self) -> SanitizerSet {
421 self.opts
422 .unstable_opts
423 .sanitizer
424 .combine_with_defaults(self.target.options.default_sanitizers)
425 }
426
427 pub fn merge_functions(&self) -> MergeFunctions {
428 self.opts.unstable_opts.merge_functions.unwrap_or(self.target.merge_functions)
429 }
430
431 pub fn is_nightly_build(&self) -> bool {
432 self.opts.unstable_features.is_nightly_build()
433 }
434}
435
436#[derive(#[automatically_derived]impl ::core::default::Default for CodegenBackendInit {
#[inline]
fn default() -> Self {
CodegenBackendInit {
global_backend_features: ::core::default::Default::default(),
replaced_intrinsics: ::core::default::Default::default(),
fallback_intrinsics: ::core::default::Default::default(),
thin_lto_supported: const true,
}
}
}Default)]
438pub struct CodegenBackendInit {
439 pub global_backend_features: Vec<String>,
441
442 pub replaced_intrinsics: Vec<Symbol>,
444
445 pub fallback_intrinsics: Vec<Symbol>,
447
448 pub thin_lto_supported: bool = true,
450}
451
452pub struct Session {
455 pub early_sess: EarlySession,
459 pub wasm_proc_macro_tuple: TargetTuple,
460 pub wasm_proc_macro_target: Target,
461 pub target_tlib_path: SearchPath,
462 pub unstable_features: UnstableFeatures,
463 pub config: Cfg,
464 pub check_config: CheckCfg,
465 proc_macro_quoted_spans: AppendOnlyVec<Span>,
468
469 pub io: CompilerIO,
471
472 pub prof: SelfProfilerRef,
474
475 pub timings: TimingSectionHandler,
477
478 pub code_stats: CodeStats,
480
481 pub lint_store: Option<Arc<dyn DynLintStore>>,
483
484 pub driver_lint_caps: FxHashMap<lint::LintId, lint::Level>,
486
487 pub ctfe_backtrace: Lock<CtfeBacktrace>,
494
495 miri_unleashed_features: Lock<Vec<(Span, Option<Symbol>)>>,
500
501 pub asm_arch: Option<InlineAsmArch>,
503
504 pub internal_target_features: FxIndexSet<Symbol>,
509
510 pub global_backend_features: Vec<String>,
515
516 pub cfg_version: &'static str,
518
519 pub using_internal_features: &'static AtomicBool,
524
525 pub env_depinfo: Lock<FxIndexSet<(Symbol, Option<Symbol>)>>,
527
528 pub file_depinfo: Lock<FxIndexSet<Symbol>>,
530
531 target_filesearch: Arc<FileSearch>,
532 host_filesearch: Arc<FileSearch>,
533 wasm_proc_macro_filesearch: Option<Arc<FileSearch>>,
534
535 pub replaced_intrinsics: FxHashSet<Symbol>,
538
539 pub fallback_intrinsics: FxHashSet<Symbol>,
542
543 pub thin_lto_supported: bool,
545
546 pub mir_opt_bisect_eval_count: AtomicUsize,
551
552 pub removed_rustc_main_attr: AtomicBool,
555
556 pub pointer_auth_config: Option<PointerAuthConfig>,
558
559 sanitizers: SanitizerSet,
561}
562
563impl Deref for Session {
564 type Target = EarlySession;
565
566 fn deref(&self) -> &EarlySession {
567 &self.early_sess
568 }
569}
570
571impl DerefMut for Session {
572 fn deref_mut(&mut self) -> &mut EarlySession {
573 &mut self.early_sess
574 }
575}
576
577#[derive(#[automatically_derived]#[doc(hidden)]unsafe impl ::core::clone::TrivialClone
for CodegenUnits {
}
#[automatically_derived]impl ::core::clone::Clone for CodegenUnits {
#[inline]
fn clone(&self) -> Self {
let _: ::core::clone::AssertParamIsClone<usize>;
*self
}
}Clone, #[automatically_derived]impl ::core::marker::Copy for CodegenUnits { }Copy)]
578pub enum CodegenUnits {
579 User(usize),
582
583 Default(usize),
587}
588
589impl CodegenUnits {
590 pub fn as_usize(self) -> usize {
591 match self {
592 CodegenUnits::User(n) => n,
593 CodegenUnits::Default(n) => n,
594 }
595 }
596}
597
598pub struct LintGroup {
599 pub name: LintName,
600 pub lints: Vec<LintId>,
601 pub is_externally_loaded: bool,
602}
603
604impl Session {
605 pub fn miri_unleashed_feature(&self, span: Span, feature_gate: Option<Symbol>) {
606 self.miri_unleashed_features.lock().push((span, feature_gate));
607 }
608
609 pub fn local_crate_source_file(&self) -> Option<RealFileName> {
610 Some(
611 self.source_map()
612 .path_mapping()
613 .to_real_filename(self.source_map().working_dir(), self.io.input.opt_path()?),
614 )
615 }
616
617 fn check_miri_unleashed_features(&self) -> Option<ErrorGuaranteed> {
618 let mut guar = None;
619 let unleashed_features = self.miri_unleashed_features.lock();
620 if !unleashed_features.is_empty() {
621 let mut must_err = false;
622 self.dcx().emit_warn(diagnostics::SkippingConstChecks {
624 unleashed_features: unleashed_features
625 .iter()
626 .map(|(span, gate)| {
627 gate.map(|gate| {
628 must_err = true;
629 diagnostics::UnleashedFeatureHelp::Named { span: *span, gate }
630 })
631 .unwrap_or(diagnostics::UnleashedFeatureHelp::Unnamed { span: *span })
632 })
633 .collect(),
634 });
635
636 if must_err && self.dcx().has_errors().is_none() {
638 guar = Some(self.dcx().emit_err(diagnostics::NotCircumventFeature));
640 }
641 }
642 guar
643 }
644
645 pub fn finish_diagnostics(&self) -> Option<ErrorGuaranteed> {
647 let mut guar = None;
648 guar = guar.or(self.check_miri_unleashed_features());
649 guar = guar.or(self.dcx().emit_stashed_diagnostics());
650 self.dcx().print_error_count();
651 if self.opts.json_future_incompat {
652 self.dcx().emit_future_breakage_report();
653 }
654 guar
655 }
656
657 pub fn is_test_crate(&self) -> bool {
659 self.opts.test
660 }
661
662 #[track_caller]
664 pub fn create_feature_err<'a>(&'a self, err: impl Diagnostic<'a>, feature: Symbol) -> Diag<'a> {
665 let mut err = self.dcx().create_err(err);
666 if err.code.is_none() {
667 err.code(E0658);
668 }
669 diagnostics::add_feature_diagnostics(&mut err, self, feature);
670 err
671 }
672
673 pub fn record_trimmed_def_paths(&self) {
676 if self.opts.unstable_opts.print_type_sizes
677 || self.opts.unstable_opts.query_dep_graph
678 || self.opts.unstable_opts.dump_mir.is_some()
679 || self.opts.unstable_opts.unpretty.is_some()
680 || self.prof.is_args_recording_enabled()
681 || self.opts.output_types.contains_key(&OutputType::Mir)
682 || std::env::var_os("RUSTC_LOG").is_some()
683 {
684 return;
685 }
686
687 self.dcx().set_must_produce_diag()
688 }
689
690 pub fn proc_macro_quoted_spans(&self) -> impl Iterator<Item = (usize, Span)> {
691 self.proc_macro_quoted_spans.iter_enumerated()
694 }
695
696 pub fn save_proc_macro_span(&self, span: Span) -> usize {
697 self.proc_macro_quoted_spans.push(span)
698 }
699
700 pub fn enable_internal_lints(&self) -> bool {
704 self.unstable_options() && !self.opts.actually_rustdoc
705 }
706
707 pub fn instrument_coverage(&self) -> bool {
708 self.opts.cg.instrument_coverage() != InstrumentCoverage::No
709 }
710
711 pub fn instrument_coverage_branch(&self) -> bool {
712 self.instrument_coverage()
713 && self.opts.unstable_opts.coverage_options.level >= CoverageLevel::Branch
714 }
715
716 pub fn instrument_coverage_condition(&self) -> bool {
717 self.instrument_coverage()
718 && self.opts.unstable_opts.coverage_options.level >= CoverageLevel::Condition
719 }
720
721 pub fn coverage_options(&self) -> &CoverageOptions {
725 &self.opts.unstable_opts.coverage_options
726 }
727
728 pub fn is_sanitizer_cfi_enabled(&self) -> bool {
729 self.sanitizers().contains(SanitizerSet::CFI)
730 }
731
732 pub fn is_sanitizer_cfi_canonical_jump_tables_disabled(&self) -> bool {
733 self.opts.unstable_opts.sanitizer_cfi_canonical_jump_tables == Some(false)
734 }
735
736 pub fn is_sanitizer_cfi_canonical_jump_tables_enabled(&self) -> bool {
737 self.opts.unstable_opts.sanitizer_cfi_canonical_jump_tables == Some(true)
738 }
739
740 pub fn is_sanitizer_cfi_generalize_pointers_enabled(&self) -> bool {
741 self.opts.unstable_opts.sanitizer_cfi_generalize_pointers == Some(true)
742 }
743
744 pub fn is_sanitizer_cfi_normalize_integers_enabled(&self) -> bool {
745 self.opts.unstable_opts.sanitizer_cfi_normalize_integers == Some(true)
746 }
747
748 pub fn is_sanitizer_cfi_recover_enabled(&self) -> bool {
749 self.opts.unstable_opts.sanitizer_cfi_recover == Some(true)
750 }
751
752 pub fn is_sanitizer_cfi_diag_enabled(&self) -> bool {
753 self.opts.unstable_opts.sanitizer_cfi_diag == Some(true)
754 }
755
756 pub fn is_sanitizer_cfi_minimal_runtime_enabled(&self) -> bool {
757 self.opts.unstable_opts.sanitizer_cfi_minimal_runtime == Some(true)
758 }
759
760 pub fn is_sanitizer_kcfi_arity_enabled(&self) -> bool {
761 self.opts.unstable_opts.sanitizer_kcfi_arity == Some(true)
762 }
763
764 pub fn is_sanitizer_kcfi_enabled(&self) -> bool {
765 self.sanitizers().contains(SanitizerSet::KCFI)
766 }
767
768 pub fn is_split_lto_unit_enabled(&self) -> bool {
769 self.opts.unstable_opts.split_lto_unit == Some(true)
770 }
771
772 pub fn crt_static(&self, crate_type: Option<CrateType>) -> bool {
774 if !self.target.crt_static_respected {
775 return self.target.crt_static_default;
777 }
778
779 let requested_features = self.opts.cg.target_feature.split(',');
780 let found_negative = requested_features.clone().any(|r| r == "-crt-static");
781 let found_positive = requested_features.clone().any(|r| r == "+crt-static");
782
783 #[allow(rustc::bad_opt_access)]
785 if found_positive || found_negative {
786 found_positive
787 } else if crate_type == Some(CrateType::ProcMacro)
788 || crate_type == None && self.opts.crate_types.contains(&CrateType::ProcMacro)
789 {
790 false
794 } else {
795 self.target.crt_static_default
796 }
797 }
798
799 pub fn is_wasi_reactor(&self) -> bool {
800 self.target.options.os == Os::Wasi
801 && #[allow(non_exhaustive_omitted_patterns)] match self.opts.unstable_opts.wasi_exec_model
{
Some(config::WasiExecModel::Reactor) => true,
_ => false,
}matches!(
802 self.opts.unstable_opts.wasi_exec_model,
803 Some(config::WasiExecModel::Reactor)
804 )
805 }
806
807 pub fn target_can_use_split_dwarf(&self) -> bool {
809 self.target.debuginfo_kind == DebuginfoKind::Dwarf
810 }
811
812 pub fn target_filesearch(&self) -> &filesearch::FileSearch {
813 &self.target_filesearch
814 }
815 pub fn host_filesearch(&self) -> &filesearch::FileSearch {
816 &self.host_filesearch
817 }
818 pub fn wasm_proc_macro_filesearch(&self) -> &filesearch::FileSearch {
819 self.wasm_proc_macro_filesearch.as_ref().expect("wasm_filesearch not set")
820 }
821
822 pub fn get_tools_search_paths(&self, self_contained: bool) -> Vec<PathBuf> {
826 let search_paths = self
827 .opts
828 .sysroot
829 .all_paths()
830 .map(|sysroot| filesearch::make_target_bin_path(&sysroot, config::host_tuple()));
831
832 if self_contained {
833 search_paths.flat_map(|path| [path.clone(), path.join("self-contained")]).collect()
837 } else {
838 search_paths.collect()
839 }
840 }
841
842 pub fn is_rust_2015(&self) -> bool {
844 self.edition().is_rust_2015()
845 }
846
847 pub fn at_least_rust_2018(&self) -> bool {
849 self.edition().at_least_rust_2018()
850 }
851
852 pub fn at_least_rust_2021(&self) -> bool {
854 self.edition().at_least_rust_2021()
855 }
856
857 pub fn at_least_rust_2024(&self) -> bool {
859 self.edition().at_least_rust_2024()
860 }
861
862 pub fn needs_plt(&self) -> bool {
864 let want_plt = self.target.plt_by_default;
867
868 let dbg_opts = &self.opts.unstable_opts;
869
870 let relro_level = self.opts.cg.relro_level.unwrap_or(self.target.relro_level);
871
872 let full_relro = RelroLevel::Full == relro_level;
876
877 dbg_opts.plt.unwrap_or(want_plt || !full_relro)
880 }
881
882 pub fn emit_lifetime_markers(&self) -> bool {
884 self.opts.optimize != config::OptLevel::No
885 || self.sanitizers().intersects(SanitizerSet::ADDRESS | SanitizerSet::KERNELADDRESS | SanitizerSet::MEMORY | SanitizerSet::HWADDRESS | SanitizerSet::KERNELHWADDRESS)
892 || self.opts.unstable_opts.codegen_emit_retag.is_some()
894 }
895
896 pub fn diagnostic_width(&self) -> usize {
897 let default_column_width = 140;
898 if let Some(width) = self.opts.diagnostic_width {
899 width
900 } else if self.opts.unstable_opts.ui_testing {
901 default_column_width
902 } else {
903 termize::dimensions().map_or(default_column_width, |(w, _)| w)
904 }
905 }
906
907 pub fn default_visibility(&self) -> SymbolVisibility {
909 self.opts
910 .unstable_opts
911 .default_visibility
912 .or(self.target.options.default_visibility)
913 .unwrap_or(SymbolVisibility::Interposable)
914 }
915
916 pub fn staticlib_components(&self, verbatim: bool) -> (&str, &str) {
917 if verbatim {
918 ("", "")
919 } else {
920 (&*self.target.staticlib_prefix, &*self.target.staticlib_suffix)
921 }
922 }
923
924 pub fn lint_groups_iter(&self) -> Box<dyn Iterator<Item = LintGroup> + '_> {
925 match self.lint_store {
926 Some(ref lint_store) => lint_store.lint_groups_iter(),
927 None => Box::new(std::iter::empty()),
928 }
929 }
930
931 pub fn resolve_path(&self, path: impl Into<PathBuf>, span: Span) -> PResult<'_, PathBuf> {
935 let path = path.into();
936
937 if !path.is_absolute() {
940 let callsite = span.source_callsite();
941 let source_map = self.source_map();
942 let Some(mut base_path) = source_map.span_to_filename(callsite).into_local_path()
943 else {
944 return Err(self.dcx().create_err(diagnostics::ResolveRelativePath {
945 span,
946 path: source_map
947 .filename_for_diagnostics(&source_map.span_to_filename(callsite))
948 .to_string(),
949 }));
950 };
951 base_path.pop();
952 base_path.push(path);
953 Ok(base_path)
954 } else {
955 match path.components().next() {
958 Some(Prefix(prefix)) if prefix.kind().is_verbatim() => {
959 Ok(path.components().collect())
960 }
961 _ => Ok(path),
962 }
963 }
964 }
965
966 pub fn embed_metadata(&self) -> bool {
968 self.opts.cg.embed_metadata.or(self.opts.unstable_opts.embed_metadata).unwrap_or(true)
969 }
970}
971
972#[allow(rustc::bad_opt_access)]
974impl Session {
975 pub fn verbose_internals(&self) -> bool {
976 self.opts.unstable_opts.verbose_internals
977 }
978
979 pub fn verify_llvm_ir(&self) -> bool {
980 self.opts.unstable_opts.verify_llvm_ir || ::core::option::Option::None::<&'static str>option_env!("RUSTC_VERIFY_LLVM_IR").is_some()
981 }
982
983 pub fn binary_dep_depinfo(&self) -> bool {
984 self.opts.unstable_opts.binary_dep_depinfo
985 }
986
987 pub fn mir_opt_level(&self) -> usize {
988 self.opts.unstable_opts.mir_opt_level.unwrap_or_else(|| self.opts.optimize.mir_opt_level())
989 }
990
991 pub fn optimization_objective(&self) -> config::OptimizationObjective {
993 self.opts.optimize.objective()
994 }
995
996 pub fn lto(&self) -> config::Lto {
998 if self.target.requires_lto {
1000 return config::Lto::Fat;
1001 }
1002
1003 match self.opts.cg.lto {
1007 config::LtoCli::Unspecified => {
1008 }
1011 config::LtoCli::No => {
1012 return config::Lto::No;
1014 }
1015 config::LtoCli::Yes | config::LtoCli::Fat | config::LtoCli::NoParam => {
1016 return config::Lto::Fat;
1018 }
1019 config::LtoCli::Thin => {
1020 if !self.thin_lto_supported {
1022 self.dcx().emit_warn(diagnostics::ThinLtoNotSupportedByBackend);
1024 return config::Lto::Fat;
1025 }
1026 return config::Lto::Thin;
1027 }
1028 }
1029
1030 if !self.thin_lto_supported {
1031 return config::Lto::No;
1032 }
1033
1034 if self.opts.cli_forced_local_thinlto_off {
1043 return config::Lto::No;
1044 }
1045
1046 if let Some(enabled) = self.opts.unstable_opts.thinlto {
1049 if enabled {
1050 return config::Lto::ThinLocal;
1051 } else {
1052 return config::Lto::No;
1053 }
1054 }
1055
1056 if self.codegen_units().as_usize() == 1 {
1059 return config::Lto::No;
1060 }
1061
1062 match self.opts.optimize {
1065 config::OptLevel::No => config::Lto::No,
1066 _ => config::Lto::ThinLocal,
1067 }
1068 }
1069
1070 pub fn fewer_names(&self) -> bool {
1071 if let Some(fewer_names) = self.opts.unstable_opts.fewer_names {
1072 fewer_names
1073 } else {
1074 let more_names = self.opts.output_types.contains_key(&OutputType::LlvmAssembly)
1075 || self.opts.output_types.contains_key(&OutputType::Bitcode)
1076 || self.sanitizers().intersects(SanitizerSet::ADDRESS | SanitizerSet::MEMORY);
1078 !more_names
1079 }
1080 }
1081
1082 pub fn unstable_options(&self) -> bool {
1083 self.opts.unstable_opts.unstable_options
1084 }
1085
1086 pub fn is_nightly_build(&self) -> bool {
1087 self.opts.unstable_features.is_nightly_build()
1088 }
1089
1090 pub fn overflow_checks(&self) -> bool {
1091 self.opts.cg.overflow_checks.unwrap_or(self.opts.debug_assertions)
1092 }
1093
1094 pub fn ub_checks(&self) -> bool {
1095 self.opts.unstable_opts.ub_checks.unwrap_or(self.opts.debug_assertions)
1096 }
1097
1098 pub fn contract_checks(&self) -> bool {
1099 self.opts.unstable_opts.contract_checks.unwrap_or(false)
1100 }
1101
1102 pub fn direct_access_external_data(&self) -> Option<bool> {
1103 self.opts
1104 .unstable_opts
1105 .direct_access_external_data
1106 .or(self.target.direct_access_external_data)
1107 }
1108
1109 pub fn split_debuginfo(&self) -> SplitDebuginfo {
1110 self.opts.cg.split_debuginfo.unwrap_or(self.target.split_debuginfo)
1111 }
1112
1113 pub fn dwarf_version(&self) -> u32 {
1115 self.opts
1116 .cg
1117 .dwarf_version
1118 .or(self.opts.unstable_opts.dwarf_version)
1119 .unwrap_or(self.target.default_dwarf_version)
1120 }
1121
1122 pub fn stack_protector(&self) -> StackProtector {
1123 if self.target.options.supports_stack_protector {
1124 self.opts.unstable_opts.stack_protector
1125 } else {
1126 StackProtector::None
1127 }
1128 }
1129
1130 pub fn branch_protection(&self) -> Option<BranchProtection> {
1136 let mut bp = self.opts.unstable_opts.branch_protection;
1137
1138 if let Some(bp) = bp.as_mut() {
1139 if self.target.os == Os::Windows && self.target.arch == Arch::AArch64 {
1143 if let Some(pac_ret) = bp.pac_ret.as_mut()
1144 && pac_ret.key == PAuthKey::A
1145 {
1146 pac_ret.key = PAuthKey::B;
1147 }
1148 }
1149 }
1150
1151 bp
1152 }
1153
1154 pub fn must_emit_unwind_tables(&self) -> bool {
1155 self.target.requires_uwtable
1184 || self
1185 .opts
1186 .cg
1187 .force_unwind_tables
1188 .unwrap_or(self.panic_strategy().unwinds() || self.target.default_uwtable)
1189 }
1190
1191 pub fn codegen_units(&self) -> CodegenUnits {
1194 if let Some(n) = self.opts.cli_forced_codegen_units {
1195 return CodegenUnits::User(n);
1196 }
1197 if let Some(n) = self.target.default_codegen_units {
1198 return CodegenUnits::Default(n as usize);
1199 }
1200
1201 if self.opts.incremental.is_some() {
1205 return CodegenUnits::Default(256);
1206 }
1207
1208 CodegenUnits::Default(16)
1259 }
1260
1261 pub fn teach(&self, code: ErrCode) -> bool {
1262 self.opts.unstable_opts.teach && self.dcx().must_teach(code)
1263 }
1264
1265 pub fn edition(&self) -> Edition {
1266 self.opts.edition
1267 }
1268
1269 pub fn link_dead_code(&self) -> bool {
1270 self.opts.cg.link_dead_code.unwrap_or(false)
1271 }
1272
1273 pub fn sanitizers(&self) -> SanitizerSet {
1274 self.sanitizers
1275 }
1276
1277 pub fn pointer_authentication(&self) -> bool {
1278 self.pointer_auth_config.is_some()
1279 }
1280
1281 pub fn pointer_authentication_functions(&self) -> Option<&PointerAuthSchema> {
1282 self.pointer_auth_config.as_ref().and_then(|cfg| cfg.function_pointers.as_ref())
1283 }
1284
1285 pub fn pointer_authentication_init_fini(&self) -> Option<&PointerAuthSchema> {
1286 self.pointer_auth_config.as_ref().and_then(|cfg| cfg.init_fini.as_ref())
1287 }
1288}
1289
1290#[allow(rustc::bad_opt_access)]
1292fn default_emitter(sopts: &config::Options, source_map: Arc<SourceMap>) -> Box<DynEmitter> {
1293 let macro_backtrace = sopts.unstable_opts.macro_backtrace;
1294 let track_diagnostics = sopts.unstable_opts.track_diagnostics;
1295 let terminal_url = match sopts.unstable_opts.terminal_urls {
1296 TerminalUrl::Auto => {
1297 match (std::env::var("COLORTERM").as_deref(), std::env::var("TERM").as_deref()) {
1298 (Ok("truecolor"), Ok("xterm-256color"))
1299 if sopts.unstable_features.is_nightly_build() =>
1300 {
1301 TerminalUrl::Yes
1302 }
1303 _ => TerminalUrl::No,
1304 }
1305 }
1306 t => t,
1307 };
1308
1309 let source_map = if sopts.unstable_opts.link_only { None } else { Some(source_map) };
1310
1311 match sopts.error_format {
1312 config::ErrorOutputType::HumanReadable { kind, color_config } => match kind {
1313 HumanReadableErrorType { short, unicode } => {
1314 let emitter = AnnotateSnippetEmitter::new(stderr_destination(color_config))
1315 .sm(source_map)
1316 .short_message(short)
1317 .diagnostic_width(sopts.diagnostic_width)
1318 .macro_backtrace(macro_backtrace)
1319 .track_diagnostics(track_diagnostics)
1320 .terminal_url(terminal_url)
1321 .theme(if unicode { OutputTheme::Unicode } else { OutputTheme::Ascii })
1322 .ignored_directories_in_source_blocks(
1323 sopts.unstable_opts.ignore_directory_in_diagnostics_source_blocks.clone(),
1324 );
1325 Box::new(emitter.ui_testing(sopts.unstable_opts.ui_testing))
1326 }
1327 },
1328 config::ErrorOutputType::Json { pretty, json_rendered, color_config } => Box::new(
1329 JsonEmitter::new(
1330 Box::new(io::BufWriter::new(io::stderr())),
1331 source_map,
1332 pretty,
1333 json_rendered,
1334 color_config,
1335 )
1336 .ui_testing(sopts.unstable_opts.ui_testing)
1337 .ignored_directories_in_source_blocks(
1338 sopts.unstable_opts.ignore_directory_in_diagnostics_source_blocks.clone(),
1339 )
1340 .diagnostic_width(sopts.diagnostic_width)
1341 .macro_backtrace(macro_backtrace)
1342 .track_diagnostics(track_diagnostics)
1343 .terminal_url(terminal_url),
1344 ),
1345 }
1346}
1347
1348#[allow(rustc::bad_opt_access)]
1350pub fn build_early_session(
1351 sopts: config::Options,
1352 target: Target,
1353 ice_file: Option<PathBuf>,
1354) -> EarlySession {
1355 let warnings_allow = sopts
1359 .lint_opts
1360 .iter()
1361 .rfind(|&(key, _)| *key == "warnings")
1362 .is_some_and(|&(_, level)| level == lint::Allow);
1363 let cap_lints_allow = sopts.lint_cap.is_some_and(|cap| cap == lint::Allow);
1364 let can_emit_warnings = !(warnings_allow || cap_lints_allow);
1365
1366 let source_map = rustc_span::source_map::get_source_map().unwrap();
1367 let emitter = default_emitter(&sopts, Arc::clone(&source_map));
1368
1369 let mut dcx =
1370 DiagCtxt::new(emitter).with_flags(sopts.unstable_opts.dcx_flags(can_emit_warnings));
1371 if let Some(ice_file) = ice_file {
1372 dcx = dcx.with_ice_file(ice_file);
1373 }
1374
1375 if let Some(msrv) = sopts.unstable_opts.hint_msrv {
1376 dcx = dcx.with_msrv(msrv);
1377 }
1378
1379 let host_triple = TargetTuple::from_tuple(config::host_tuple());
1380 let (host, target_warnings) =
1381 Target::search(&host_triple, sopts.sysroot.path(), sopts.unstable_opts.unstable_options)
1382 .unwrap_or_else(|e| {
1383 dcx.handle().fatal(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("Error loading host specification: {0}",
e))
})format!("Error loading host specification: {e}"))
1384 });
1385 for warning in target_warnings.warning_messages() {
1386 dcx.handle().warn(warning)
1387 }
1388
1389 let psess = ParseSess::with_dcx(dcx, source_map);
1390
1391 EarlySession { target, host, opts: sopts, psess }
1392}
1393
1394#[allow(rustc::bad_opt_access)]
1396pub fn build_session(
1397 early_sess: EarlySession,
1398 codegen_backend_init: CodegenBackendInit,
1399 io: CompilerIO,
1400 driver_lint_caps: FxHashMap<lint::LintId, lint::Level>,
1401 cfg_version: &'static str,
1402 using_internal_features: &'static AtomicBool,
1403) -> Session {
1404 let EarlySession { target, host, opts: sopts, psess } = &early_sess;
1405 let dcx = psess.dcx();
1406
1407 let wasm_proc_macro_tuple = TargetTuple::from_tuple("wasm32-wasip2");
1408 let (wasm_proc_macro_target, target_warnings) = Target::search(
1409 &wasm_proc_macro_tuple,
1410 sopts.sysroot.path(),
1411 sopts.unstable_opts.unstable_options,
1412 )
1413 .unwrap_or_else(|e| {
1414 dcx.fatal(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("Error loading wasm proc-macro target specification: {0}",
e))
})format!("Error loading wasm proc-macro target specification: {e}"))
1415 });
1416 for warning in target_warnings.warning_messages() {
1417 dcx.warn(warning)
1418 }
1419
1420 let self_profiler = if let SwitchWithOptPath::Enabled(ref d) = sopts.unstable_opts.self_profile
1421 {
1422 let directory = if let Some(directory) = d { directory } else { std::path::Path::new(".") };
1423
1424 let profiler = SelfProfiler::new(
1425 directory,
1426 sopts.crate_name.as_deref(),
1427 sopts.unstable_opts.self_profile_events.as_deref(),
1428 &sopts.unstable_opts.self_profile_counter,
1429 );
1430 match profiler {
1431 Ok(profiler) => Some(Arc::new(profiler)),
1432 Err(e) => {
1433 dcx.emit_warn(diagnostics::FailedToCreateProfiler { err: e.to_string() });
1434 None
1435 }
1436 }
1437 } else {
1438 None
1439 };
1440
1441 let host_triple = config::host_tuple();
1442 let target_triple = sopts.target_triple.tuple();
1443 let host_tlib_path = SearchPath::from_sysroot_and_triple(sopts.sysroot.path(), host_triple);
1445 let target_tlib_path = SearchPath::from_sysroot_and_triple(sopts.sysroot.path(), target_triple);
1446 let wasm_proc_macro_tlib_path =
1447 SearchPath::from_sysroot_and_triple(sopts.sysroot.path(), wasm_proc_macro_tuple.tuple());
1448
1449 let prof = SelfProfilerRef::new(
1450 self_profiler,
1451 sopts.unstable_opts.time_passes.then(|| sopts.unstable_opts.time_passes_format),
1452 );
1453
1454 let ctfe_backtrace = Lock::new(match env::var("RUSTC_CTFE_BACKTRACE") {
1455 Ok(ref val) if val == "immediate" => CtfeBacktrace::Immediate,
1456 Ok(ref val) if val != "0" => CtfeBacktrace::Capture,
1457 _ => CtfeBacktrace::Disabled,
1458 });
1459
1460 let asm_arch = if target.allow_asm { InlineAsmArch::from_arch(&target.arch) } else { None };
1461 let target_filesearch = Arc::new(filesearch::FileSearch::new(
1462 &sopts.search_paths,
1463 &target_tlib_path,
1464 &target,
1465 sopts.unstable_opts.implicit_sysroot_deps,
1466 ));
1467 let host_filesearch = if target == host {
1468 Arc::clone(&target_filesearch)
1469 } else {
1470 Arc::new(filesearch::FileSearch::new(
1471 &sopts.search_paths,
1472 &host_tlib_path,
1473 &host,
1474 sopts.unstable_opts.implicit_sysroot_deps,
1475 ))
1476 };
1477 let wasm_proc_macro_filesearch = if sopts.unstable_opts.wasm_proc_macros {
1478 Some(Arc::new(FileSearch::new(
1479 &sopts.search_paths,
1480 &wasm_proc_macro_tlib_path,
1481 &wasm_proc_macro_target,
1482 sopts.unstable_opts.implicit_sysroot_deps,
1483 )))
1484 } else {
1485 None
1486 };
1487
1488 let timings = TimingSectionHandler::new(sopts.json_timings);
1489
1490 let pointer_auth_config: Option<PointerAuthConfig> =
1491 PointerAuthConfig::from_raw(&sopts.unstable_opts.pointer_authentication, &target);
1492
1493 let sanitizers = early_sess.sanitizers();
1496
1497 let CodegenBackendInit {
1498 global_backend_features,
1499 replaced_intrinsics,
1500 fallback_intrinsics,
1501 thin_lto_supported,
1502 } = codegen_backend_init;
1503
1504 let sess = Session {
1505 early_sess,
1506 wasm_proc_macro_tuple,
1507 wasm_proc_macro_target,
1508 target_tlib_path,
1509 unstable_features: UnstableFeatures::from_environment(None),
1510 config: Cfg::default(),
1511 check_config: CheckCfg::default(),
1512 proc_macro_quoted_spans: Default::default(),
1513 io,
1514 prof,
1515 timings,
1516 code_stats: Default::default(),
1517 lint_store: None,
1518 driver_lint_caps,
1519 ctfe_backtrace,
1520 miri_unleashed_features: Lock::new(Default::default()),
1521 asm_arch,
1522 internal_target_features: Default::default(),
1523 global_backend_features,
1524 cfg_version,
1525 using_internal_features,
1526 env_depinfo: Default::default(),
1527 file_depinfo: Default::default(),
1528 target_filesearch,
1529 host_filesearch,
1530 wasm_proc_macro_filesearch,
1531 replaced_intrinsics: FxHashSet::from_iter(replaced_intrinsics),
1532 fallback_intrinsics: FxHashSet::from_iter(fallback_intrinsics),
1533 thin_lto_supported,
1534 mir_opt_bisect_eval_count: AtomicUsize::new(0),
1535 removed_rustc_main_attr: AtomicBool::new(false),
1536 pointer_auth_config,
1537 sanitizers,
1538 };
1539
1540 validate_commandline_args_with_session_available(&sess);
1541
1542 sess
1543}
1544
1545pub fn generate_proc_macro_decls_symbol(stable_crate_id: StableCrateId) -> String {
1546 ::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())
1547}
1548
1549#[allow(rustc::bad_opt_access)]
1555fn validate_commandline_args_with_session_available(sess: &Session) {
1556 if sess.opts.cg.linker_plugin_lto.enabled()
1564 && sess.opts.cg.prefer_dynamic
1565 && sess.target.is_like_windows
1566 {
1567 sess.dcx().emit_err(diagnostics::LinkerPluginToWindowsNotSupported);
1568 }
1569
1570 if sess
1571 .pointer_auth_config
1572 .as_ref()
1573 .and_then(|cfg| cfg.function_pointers.as_ref())
1574 .is_some_and(|schema| #[allow(non_exhaustive_omitted_patterns)] match schema.discrimination_kind {
PointerAuthDiscrimination::Type => true,
_ => false,
}matches!(schema.discrimination_kind, PointerAuthDiscrimination::Type))
1575 {
1576 sess.dcx().emit_err(
1577 diagnostics::PointerAuthenticationTypeDiscriminationNotSupportedForTarget {
1578 target_triple: &sess.opts.target_triple,
1579 },
1580 );
1581 }
1582
1583 if sess.target.cfg_abi != CfgAbi::Pauthtest
1584 && !sess.opts.unstable_opts.pointer_authentication.is_empty()
1585 {
1586 sess.dcx().emit_warn(diagnostics::PointerAuthenticationNotSupportedForTarget {
1587 target_triple: &sess.opts.target_triple,
1588 });
1589 }
1590
1591 if let Some(ref path) = sess.opts.cg.profile_use {
1594 if !path.exists() {
1595 sess.dcx().emit_err(diagnostics::ProfileUseFileDoesNotExist { path });
1596 }
1597 }
1598
1599 if let Some(ref path) = sess.opts.cg.profile_sample_use {
1601 if !path.exists() {
1602 sess.dcx().emit_err(diagnostics::ProfileSampleUseFileDoesNotExist { path });
1603 }
1604 }
1605
1606 if let Some(include_uwtables) = sess.opts.cg.force_unwind_tables {
1608 if sess.target.requires_uwtable && !include_uwtables {
1609 sess.dcx().emit_err(diagnostics::TargetRequiresUnwindTables);
1610 }
1611 }
1612
1613 let supported_sanitizers = sess.target.options.supported_sanitizers;
1615 let mut unsupported_sanitizers = sess.sanitizers() - supported_sanitizers;
1616 if sess.opts.unstable_opts.fixed_x18 && sess.target.arch == Arch::AArch64 {
1619 unsupported_sanitizers -= SanitizerSet::SHADOWCALLSTACK;
1620 }
1621 match unsupported_sanitizers.into_iter().count() {
1622 0 => {}
1623 1 => {
1624 sess.dcx().emit_err(diagnostics::SanitizerNotSupported {
1625 us: unsupported_sanitizers.to_string(),
1626 });
1627 }
1628 _ => {
1629 sess.dcx().emit_err(diagnostics::SanitizersNotSupported {
1630 us: unsupported_sanitizers.to_string(),
1631 });
1632 }
1633 }
1634
1635 if let Some((first, second)) = sess.sanitizers().mutually_exclusive() {
1637 sess.dcx().emit_err(diagnostics::CannotMixAndMatchSanitizers {
1638 first: first.to_string(),
1639 second: second.to_string(),
1640 });
1641 }
1642
1643 if sess.crt_static(None) && !sess.sanitizers().is_empty() && !sess.target.is_like_msvc {
1645 sess.dcx().emit_err(diagnostics::CannotEnableCrtStaticLinux);
1646 }
1647
1648 if sess.crt_static(None) && sess.target.cfg_abi == CfgAbi::Pauthtest {
1652 sess.dcx().emit_err(diagnostics::CannotEnableCrtStaticPointerAuth);
1653 }
1654
1655 if sess.is_sanitizer_cfi_enabled()
1657 && !(sess.lto() == config::Lto::Fat || sess.opts.cg.linker_plugin_lto.enabled())
1658 {
1659 sess.dcx().emit_err(diagnostics::SanitizerCfiRequiresLto);
1660 }
1661
1662 if sess.is_sanitizer_kcfi_enabled() && sess.panic_strategy().unwinds() {
1664 sess.dcx().emit_err(diagnostics::SanitizerKcfiRequiresPanicAbort);
1665 }
1666
1667 if sess.is_sanitizer_cfi_enabled()
1669 && sess.lto() == config::Lto::Fat
1670 && (sess.codegen_units().as_usize() != 1)
1671 {
1672 sess.dcx().emit_err(diagnostics::SanitizerCfiRequiresSingleCodegenUnit);
1673 }
1674
1675 if sess.is_sanitizer_cfi_canonical_jump_tables_disabled() {
1677 if !sess.is_sanitizer_cfi_enabled() {
1678 sess.dcx().emit_err(diagnostics::SanitizerCfiCanonicalJumpTablesRequiresCfi);
1679 }
1680 }
1681
1682 if sess.is_sanitizer_kcfi_arity_enabled() && !sess.is_sanitizer_kcfi_enabled() {
1684 sess.dcx().emit_err(diagnostics::SanitizerKcfiArityRequiresKcfi);
1685 }
1686
1687 if sess.is_sanitizer_cfi_generalize_pointers_enabled() {
1689 if !(sess.is_sanitizer_cfi_enabled() || sess.is_sanitizer_kcfi_enabled()) {
1690 sess.dcx().emit_err(diagnostics::SanitizerCfiGeneralizePointersRequiresCfi);
1691 }
1692 }
1693
1694 if sess.is_sanitizer_cfi_recover_enabled() {
1696 if !sess.is_sanitizer_cfi_enabled() {
1697 sess.dcx().emit_err(diagnostics::SanitizerCfiRecoverRequiresCfi);
1698 }
1699 }
1700
1701 if sess.is_sanitizer_cfi_diag_enabled() {
1703 if !sess.is_sanitizer_cfi_enabled() {
1704 sess.dcx().emit_err(diagnostics::SanitizerCfiDiagRequiresCfi);
1705 }
1706 }
1707
1708 if sess.is_sanitizer_cfi_minimal_runtime_enabled() {
1710 if !sess.is_sanitizer_cfi_enabled() {
1711 sess.dcx().emit_err(diagnostics::SanitizerCfiMinimalRuntimeRequiresCfi);
1712 } else if !(sess.is_sanitizer_cfi_recover_enabled() || sess.is_sanitizer_cfi_diag_enabled())
1713 {
1714 sess.dcx().emit_err(diagnostics::SanitizerCfiMinimalRuntimeRequiresCfiRecoverOrDiag);
1715 }
1716 }
1717
1718 if sess.is_sanitizer_cfi_normalize_integers_enabled() {
1720 if !(sess.is_sanitizer_cfi_enabled() || sess.is_sanitizer_kcfi_enabled()) {
1721 sess.dcx().emit_err(diagnostics::SanitizerCfiNormalizeIntegersRequiresCfi);
1722 }
1723 }
1724
1725 if sess.is_split_lto_unit_enabled()
1727 && !(sess.lto() == config::Lto::Fat
1728 || sess.lto() == config::Lto::Thin
1729 || sess.opts.cg.linker_plugin_lto.enabled())
1730 {
1731 sess.dcx().emit_err(diagnostics::SplitLtoUnitRequiresLto);
1732 }
1733
1734 if sess.lto() != config::Lto::Fat {
1736 if sess.opts.unstable_opts.virtual_function_elimination {
1737 sess.dcx().emit_err(diagnostics::UnstableVirtualFunctionElimination);
1738 }
1739 }
1740
1741 if sess.opts.unstable_opts.stack_protector != StackProtector::None {
1742 if !sess.target.options.supports_stack_protector {
1743 sess.dcx().emit_warn(diagnostics::StackProtectorNotSupportedForTarget {
1744 stack_protector: sess.opts.unstable_opts.stack_protector,
1745 target_triple: &sess.opts.target_triple,
1746 });
1747 }
1748 }
1749
1750 if sess.opts.unstable_opts.small_data_threshold.is_some() {
1751 if sess.target.small_data_threshold_support() == SmallDataThresholdSupport::None {
1752 sess.dcx().emit_warn(diagnostics::SmallDataThresholdNotSupportedForTarget {
1753 target_triple: &sess.opts.target_triple,
1754 })
1755 }
1756 }
1757
1758 if sess.opts.unstable_opts.branch_protection.is_some() && sess.target.arch != Arch::AArch64 {
1759 sess.dcx().emit_err(diagnostics::BranchProtectionRequiresAArch64);
1760 }
1761
1762 if let Some(dwarf_version) =
1763 sess.opts.cg.dwarf_version.or(sess.opts.unstable_opts.dwarf_version)
1764 {
1765 if dwarf_version < 2 || dwarf_version > 5 {
1767 sess.dcx().emit_err(diagnostics::UnsupportedDwarfVersion { dwarf_version });
1768 }
1769 }
1770
1771 if !sess.target.options.supported_split_debuginfo.contains(&sess.split_debuginfo())
1772 && !sess.opts.unstable_opts.unstable_options
1773 {
1774 sess.dcx().emit_err(diagnostics::SplitDebugInfoUnstablePlatform {
1775 debuginfo: sess.split_debuginfo(),
1776 });
1777 }
1778
1779 if sess.opts.unstable_opts.embed_source {
1780 let dwarf_version = sess.dwarf_version();
1781
1782 if dwarf_version < 5 {
1783 sess.dcx()
1784 .emit_warn(diagnostics::EmbedSourceInsufficientDwarfVersion { dwarf_version });
1785 }
1786
1787 if sess.opts.debuginfo == DebugInfo::None {
1788 sess.dcx().emit_warn(diagnostics::EmbedSourceRequiresDebugInfo);
1789 }
1790 }
1791
1792 if let InstrumentMcount::Fentry(opts) = sess.opts.unstable_opts.instrument_mcount {
1793 if !sess.target.options.supports_fentry {
1794 sess.dcx()
1795 .emit_err(diagnostics::InstrumentationNotSupported { us: "fentry".to_string() });
1796 }
1797 if (opts.no_call || opts.record) && sess.target.arch != Arch::S390x {
1798 sess.dcx()
1799 .emit_err(diagnostics::InstrumentationNotSupported { us: "fentry-*".to_string() });
1800 }
1801 }
1802
1803 if sess.opts.unstable_opts.instrument_xray.is_some() && !sess.target.options.supports_xray {
1804 sess.dcx().emit_err(diagnostics::InstrumentationNotSupported { us: "XRay".to_string() });
1805 }
1806
1807 if let Some(flavor) = sess.opts.cg.linker_flavor
1808 && let Some(compatible_list) = sess.target.linker_flavor.check_compatibility(flavor)
1809 {
1810 let flavor = flavor.desc();
1811 sess.dcx().emit_err(diagnostics::IncompatibleLinkerFlavor { flavor, compatible_list });
1812 }
1813
1814 if sess.opts.unstable_opts.function_return != FunctionReturn::default() {
1815 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) {
1816 sess.dcx().emit_err(diagnostics::FunctionReturnRequiresX86OrX8664);
1817 }
1818 }
1819
1820 if sess.opts.unstable_opts.indirect_branch_cs_prefix {
1821 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) {
1822 sess.dcx().emit_err(diagnostics::IndirectBranchCsPrefixRequiresX86OrX8664);
1823 }
1824 }
1825
1826 if let Some(regparm) = sess.opts.unstable_opts.regparm {
1827 if regparm > 3 {
1828 sess.dcx().emit_err(diagnostics::UnsupportedRegparm { regparm });
1829 }
1830 if sess.target.arch != Arch::X86 {
1831 sess.dcx().emit_err(diagnostics::UnsupportedRegparmArch);
1832 }
1833 }
1834 if sess.opts.unstable_opts.reg_struct_return {
1835 if sess.target.arch != Arch::X86 {
1836 sess.dcx().emit_err(diagnostics::UnsupportedRegStructReturnArch);
1837 }
1838 }
1839
1840 match sess.opts.unstable_opts.function_return {
1844 FunctionReturn::Keep => (),
1845 FunctionReturn::ThunkExtern => {
1846 if let Some(code_model) = sess.code_model()
1849 && code_model == CodeModel::Large
1850 {
1851 sess.dcx()
1852 .emit_err(diagnostics::FunctionReturnThunkExternRequiresNonLargeCodeModel);
1853 }
1854 }
1855 }
1856
1857 if sess.opts.unstable_opts.packed_stack {
1858 if sess.target.arch != Arch::S390x {
1859 sess.dcx().emit_err(diagnostics::UnsupportedPackedStack);
1860 }
1861 }
1862
1863 if let Some(ref cpu_name) = sess.opts.cg.target_cpu {
1864 if cpu_name == NATIVE_CPU && sess.target.requires_consistent_cpu {
1865 sess.dcx().emit_fatal(diagnostics::NativeTargetCpuNotAllowed {
1866 target_triple: &sess.opts.target_triple,
1867 need_explicit_cpu: sess.target.need_explicit_cpu,
1868 });
1869 }
1870 }
1871}
1872
1873pub struct IncrCompSession {
1875 pub old_session_directory: Option<flock::LockedDir>,
1877 pub new_session_directory: flock::LockedDir,
1880 borrows: Arc<()>,
1881}
1882
1883impl IncrCompSession {
1884 pub fn new(
1885 old_session_directory: Option<flock::LockedDir>,
1886 new_session_directory: flock::LockedDir,
1887 ) -> Self {
1888 IncrCompSession { old_session_directory, new_session_directory, borrows: Arc::new(()) }
1889 }
1890
1891 pub fn borrow(&self) -> BorrowedIncrCompSession {
1892 BorrowedIncrCompSession {
1893 old_session_directory: self.old_session_directory.as_deref().map(ToOwned::to_owned),
1894 new_session_directory: (&*self.new_session_directory).to_owned(),
1895 _borrows: Arc::clone(&self.borrows),
1896 }
1897 }
1898}
1899
1900impl Drop for IncrCompSession {
1901 fn drop(&mut self) {
1902 if !(Arc::strong_count(&self.borrows) == 1) {
{
::core::panicking::panic_fmt(format_args!("Incr comp session dropped while there are still references"));
}
};assert!(
1908 Arc::strong_count(&self.borrows) == 1,
1909 "Incr comp session dropped while there are still references",
1910 );
1911 }
1912}
1913
1914pub struct BorrowedIncrCompSession {
1916 pub old_session_directory: Option<PathBuf>,
1917 pub new_session_directory: PathBuf,
1918 _borrows: Arc<()>,
1919}
1920
1921pub struct EarlyDiagCtxt {
1923 dcx: DiagCtxt,
1924}
1925
1926impl EarlyDiagCtxt {
1927 pub fn new(output: ErrorOutputType) -> Self {
1928 let emitter = mk_emitter(output);
1929 Self { dcx: DiagCtxt::new(emitter) }
1930 }
1931
1932 pub fn set_error_format(&mut self, output: ErrorOutputType) {
1935 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());
1936
1937 let emitter = mk_emitter(output);
1938 self.dcx = DiagCtxt::new(emitter);
1939 }
1940
1941 #[must_use = "raise_fatal must be called on the returned ErrorGuaranteed in order to exit with a non-zero status code"]
1942 pub fn early_err(&self, msg: impl Into<DiagMessage>) -> ErrorGuaranteed {
1943 self.dcx.handle().err(msg)
1944 }
1945
1946 pub fn early_fatal(&self, msg: impl Into<DiagMessage>) -> ! {
1947 self.dcx.handle().fatal(msg)
1948 }
1949
1950 pub fn early_struct_fatal(&self, msg: impl Into<DiagMessage>) -> Diag<'_> {
1951 self.dcx.handle().struct_fatal(msg)
1952 }
1953
1954 pub fn early_warn(&self, msg: impl Into<DiagMessage>) {
1955 self.dcx.handle().warn(msg)
1956 }
1957
1958 pub fn early_struct_warn(&self, msg: impl Into<DiagMessage>) -> Diag<'_> {
1959 self.dcx.handle().struct_warn(msg)
1960 }
1961}
1962
1963fn mk_emitter(output: ErrorOutputType) -> Box<DynEmitter> {
1964 let emitter: Box<DynEmitter> = match output {
1965 config::ErrorOutputType::HumanReadable { kind, color_config } => match kind {
1966 HumanReadableErrorType { short, unicode } => Box::new(
1967 AnnotateSnippetEmitter::new(stderr_destination(color_config))
1968 .theme(if unicode { OutputTheme::Unicode } else { OutputTheme::Ascii })
1969 .short_message(short),
1970 ),
1971 },
1972 config::ErrorOutputType::Json { pretty, json_rendered, color_config } => {
1973 Box::new(JsonEmitter::new(
1974 Box::new(io::BufWriter::new(io::stderr())),
1975 Some(Arc::new(SourceMap::new(FilePathMapping::empty()))),
1976 pretty,
1977 json_rendered,
1978 color_config,
1979 ))
1980 }
1981 };
1982 emitter
1983}