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};
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", &self.recursion_limit, "move_size_limit",
&self.move_size_limit, "type_length_limit",
&self.type_length_limit, "pattern_complexity_limit",
&&self.pattern_complexity_limit)
}
}Debug, const _: () =
{
impl ::rustc_data_structures::stable_hash::StableHash for Limits {
#[inline]
fn stable_hash<__Hcx: ::rustc_data_structures::stable_hash::StableHashCtxt>(&self,
__hcx: &mut __Hcx,
__hasher:
&mut ::rustc_data_structures::stable_hash::StableHasher) {
match *self {
Limits {
recursion_limit: ref __binding_0,
move_size_limit: ref __binding_1,
type_length_limit: ref __binding_2,
pattern_complexity_limit: ref __binding_3 } => {
{ __binding_0.stable_hash(__hcx, __hasher); }
{ __binding_1.stable_hash(__hcx, __hasher); }
{ __binding_2.stable_hash(__hcx, __hasher); }
{ __binding_3.stable_hash(__hcx, __hasher); }
}
}
}
}
};StableHash)]
62pub struct Limits {
63 pub recursion_limit: Limit,
66 pub move_size_limit: Limit,
69 pub type_length_limit: Limit,
71 pub pattern_complexity_limit: Limit,
73}
74
75pub struct CompilerIO {
76 pub input: Input,
77 pub output_dir: Option<PathBuf>,
78 pub output_file: Option<OutFileName>,
79 pub temps_dir: Option<PathBuf>,
80}
81
82pub trait DynLintStore: Any + DynSync + DynSend {
83 fn lint_groups_iter(&self) -> Box<dyn Iterator<Item = LintGroup> + '_>;
85}
86
87#[derive(#[automatically_derived]
#[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
432#[derive(#[automatically_derived]
impl ::core::default::Default for CodegenBackendInit {
#[inline]
fn default() -> Self {
Self {
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)]
434pub struct CodegenBackendInit {
435 pub global_backend_features: Vec<String>,
437
438 pub replaced_intrinsics: Vec<Symbol>,
440
441 pub fallback_intrinsics: Vec<Symbol>,
443
444 pub thin_lto_supported: bool = true,
446}
447
448pub struct Session {
451 pub early_sess: EarlySession,
455 pub wasm_proc_macro_tuple: TargetTuple,
456 pub wasm_proc_macro_target: Target,
457 pub target_tlib_path: SearchPath,
458 pub unstable_features: UnstableFeatures,
459 pub config: Cfg,
460 pub check_config: CheckCfg,
461 proc_macro_quoted_spans: AppendOnlyVec<Span>,
464
465 pub io: CompilerIO,
467
468 pub prof: SelfProfilerRef,
470
471 pub timings: TimingSectionHandler,
473
474 pub code_stats: CodeStats,
476
477 pub lint_store: Option<Arc<dyn DynLintStore>>,
479
480 pub driver_lint_caps: FxHashMap<lint::LintId, lint::Level>,
482
483 pub ctfe_backtrace: Lock<CtfeBacktrace>,
490
491 miri_unleashed_features: Lock<Vec<(Span, Option<Symbol>)>>,
496
497 pub asm_arch: Option<InlineAsmArch>,
499
500 pub internal_target_features: FxIndexSet<Symbol>,
505
506 pub global_backend_features: Vec<String>,
511
512 pub cfg_version: &'static str,
514
515 pub using_internal_features: &'static AtomicBool,
520
521 pub env_depinfo: Lock<FxIndexSet<(Symbol, Option<Symbol>)>>,
523
524 pub file_depinfo: Lock<FxIndexSet<Symbol>>,
526
527 target_filesearch: Arc<FileSearch>,
528 host_filesearch: Arc<FileSearch>,
529 wasm_proc_macro_filesearch: Option<Arc<FileSearch>>,
530
531 pub replaced_intrinsics: FxHashSet<Symbol>,
534
535 pub fallback_intrinsics: FxHashSet<Symbol>,
538
539 pub thin_lto_supported: bool,
541
542 pub mir_opt_bisect_eval_count: AtomicUsize,
547
548 pub removed_rustc_main_attr: AtomicBool,
551
552 pub pointer_auth_config: Option<PointerAuthConfig>,
554
555 sanitizers: SanitizerSet,
557}
558
559impl Deref for Session {
560 type Target = EarlySession;
561
562 fn deref(&self) -> &EarlySession {
563 &self.early_sess
564 }
565}
566
567impl DerefMut for Session {
568 fn deref_mut(&mut self) -> &mut EarlySession {
569 &mut self.early_sess
570 }
571}
572
573#[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)]
574pub enum CodegenUnits {
575 User(usize),
578
579 Default(usize),
583}
584
585impl CodegenUnits {
586 pub fn as_usize(self) -> usize {
587 match self {
588 CodegenUnits::User(n) => n,
589 CodegenUnits::Default(n) => n,
590 }
591 }
592}
593
594pub struct LintGroup {
595 pub name: &'static str,
596 pub lints: Vec<LintId>,
597 pub is_externally_loaded: bool,
598}
599
600impl Session {
601 pub fn miri_unleashed_feature(&self, span: Span, feature_gate: Option<Symbol>) {
602 self.miri_unleashed_features.lock().push((span, feature_gate));
603 }
604
605 pub fn local_crate_source_file(&self) -> Option<RealFileName> {
606 Some(
607 self.source_map()
608 .path_mapping()
609 .to_real_filename(self.source_map().working_dir(), self.io.input.opt_path()?),
610 )
611 }
612
613 fn check_miri_unleashed_features(&self) -> Option<ErrorGuaranteed> {
614 let mut guar = None;
615 let unleashed_features = self.miri_unleashed_features.lock();
616 if !unleashed_features.is_empty() {
617 let mut must_err = false;
618 self.dcx().emit_warn(diagnostics::SkippingConstChecks {
620 unleashed_features: unleashed_features
621 .iter()
622 .map(|(span, gate)| {
623 gate.map(|gate| {
624 must_err = true;
625 diagnostics::UnleashedFeatureHelp::Named { span: *span, gate }
626 })
627 .unwrap_or(diagnostics::UnleashedFeatureHelp::Unnamed { span: *span })
628 })
629 .collect(),
630 });
631
632 if must_err && self.dcx().has_errors().is_none() {
634 guar = Some(self.dcx().emit_err(diagnostics::NotCircumventFeature));
636 }
637 }
638 guar
639 }
640
641 pub fn finish_diagnostics(&self) -> Option<ErrorGuaranteed> {
643 let mut guar = None;
644 guar = guar.or(self.check_miri_unleashed_features());
645 guar = guar.or(self.dcx().emit_stashed_diagnostics());
646 self.dcx().print_error_count();
647 if self.opts.json_future_incompat {
648 self.dcx().emit_future_breakage_report();
649 }
650 guar
651 }
652
653 pub fn is_test_crate(&self) -> bool {
655 self.opts.test
656 }
657
658 #[track_caller]
660 pub fn create_feature_err<'a>(&'a self, err: impl Diagnostic<'a>, feature: Symbol) -> Diag<'a> {
661 let mut err = self.dcx().create_err(err);
662 if err.code.is_none() {
663 err.code(E0658);
664 }
665 diagnostics::add_feature_diagnostics(&mut err, self, feature);
666 err
667 }
668
669 pub fn record_trimmed_def_paths(&self) {
672 if self.opts.unstable_opts.print_type_sizes
673 || self.opts.unstable_opts.query_dep_graph
674 || self.opts.unstable_opts.dump_mir.is_some()
675 || self.opts.unstable_opts.unpretty.is_some()
676 || self.prof.is_args_recording_enabled()
677 || self.opts.output_types.contains_key(&OutputType::Mir)
678 || std::env::var_os("RUSTC_LOG").is_some()
679 {
680 return;
681 }
682
683 self.dcx().set_must_produce_diag()
684 }
685
686 pub fn proc_macro_quoted_spans(&self) -> impl Iterator<Item = (usize, Span)> {
687 self.proc_macro_quoted_spans.iter_enumerated()
690 }
691
692 pub fn save_proc_macro_span(&self, span: Span) -> usize {
693 self.proc_macro_quoted_spans.push(span)
694 }
695
696 pub fn enable_internal_lints(&self) -> bool {
700 self.unstable_options() && !self.opts.actually_rustdoc
701 }
702
703 pub fn instrument_coverage(&self) -> bool {
704 self.opts.cg.instrument_coverage() != InstrumentCoverage::No
705 }
706
707 pub fn instrument_coverage_branch(&self) -> bool {
708 self.instrument_coverage()
709 && self.opts.unstable_opts.coverage_options.level >= CoverageLevel::Branch
710 }
711
712 pub fn instrument_coverage_condition(&self) -> bool {
713 self.instrument_coverage()
714 && self.opts.unstable_opts.coverage_options.level >= CoverageLevel::Condition
715 }
716
717 pub fn coverage_options(&self) -> &CoverageOptions {
721 &self.opts.unstable_opts.coverage_options
722 }
723
724 pub fn is_sanitizer_cfi_enabled(&self) -> bool {
725 self.sanitizers().contains(SanitizerSet::CFI)
726 }
727
728 pub fn is_sanitizer_cfi_canonical_jump_tables_disabled(&self) -> bool {
729 self.opts.unstable_opts.sanitizer_cfi_canonical_jump_tables == Some(false)
730 }
731
732 pub fn is_sanitizer_cfi_canonical_jump_tables_enabled(&self) -> bool {
733 self.opts.unstable_opts.sanitizer_cfi_canonical_jump_tables == Some(true)
734 }
735
736 pub fn is_sanitizer_cfi_generalize_pointers_enabled(&self) -> bool {
737 self.opts.unstable_opts.sanitizer_cfi_generalize_pointers == Some(true)
738 }
739
740 pub fn is_sanitizer_cfi_normalize_integers_enabled(&self) -> bool {
741 self.opts.unstable_opts.sanitizer_cfi_normalize_integers == Some(true)
742 }
743
744 pub fn is_sanitizer_cfi_recover_enabled(&self) -> bool {
745 self.opts.unstable_opts.sanitizer_cfi_recover == Some(true)
746 }
747
748 pub fn is_sanitizer_cfi_diag_enabled(&self) -> bool {
749 self.opts.unstable_opts.sanitizer_cfi_diag == Some(true)
750 }
751
752 pub fn is_sanitizer_kcfi_arity_enabled(&self) -> bool {
753 self.opts.unstable_opts.sanitizer_kcfi_arity == Some(true)
754 }
755
756 pub fn is_sanitizer_kcfi_enabled(&self) -> bool {
757 self.sanitizers().contains(SanitizerSet::KCFI)
758 }
759
760 pub fn is_split_lto_unit_enabled(&self) -> bool {
761 self.opts.unstable_opts.split_lto_unit == Some(true)
762 }
763
764 pub fn crt_static(&self, crate_type: Option<CrateType>) -> bool {
766 if !self.target.crt_static_respected {
767 return self.target.crt_static_default;
769 }
770
771 let requested_features = self.opts.cg.target_feature.split(',');
772 let found_negative = requested_features.clone().any(|r| r == "-crt-static");
773 let found_positive = requested_features.clone().any(|r| r == "+crt-static");
774
775 #[allow(rustc::bad_opt_access)]
777 if found_positive || found_negative {
778 found_positive
779 } else if crate_type == Some(CrateType::ProcMacro)
780 || crate_type == None && self.opts.crate_types.contains(&CrateType::ProcMacro)
781 {
782 false
786 } else {
787 self.target.crt_static_default
788 }
789 }
790
791 pub fn is_wasi_reactor(&self) -> bool {
792 self.target.options.os == Os::Wasi
793 && #[allow(non_exhaustive_omitted_patterns)] match self.opts.unstable_opts.wasi_exec_model
{
Some(config::WasiExecModel::Reactor) => true,
_ => false,
}matches!(
794 self.opts.unstable_opts.wasi_exec_model,
795 Some(config::WasiExecModel::Reactor)
796 )
797 }
798
799 pub fn target_can_use_split_dwarf(&self) -> bool {
801 self.target.debuginfo_kind == DebuginfoKind::Dwarf
802 }
803
804 pub fn target_filesearch(&self) -> &filesearch::FileSearch {
805 &self.target_filesearch
806 }
807 pub fn host_filesearch(&self) -> &filesearch::FileSearch {
808 &self.host_filesearch
809 }
810 pub fn wasm_proc_macro_filesearch(&self) -> &filesearch::FileSearch {
811 self.wasm_proc_macro_filesearch.as_ref().expect("wasm_filesearch not set")
812 }
813
814 pub fn get_tools_search_paths(&self, self_contained: bool) -> Vec<PathBuf> {
818 let search_paths = self
819 .opts
820 .sysroot
821 .all_paths()
822 .map(|sysroot| filesearch::make_target_bin_path(&sysroot, config::host_tuple()));
823
824 if self_contained {
825 search_paths.flat_map(|path| [path.clone(), path.join("self-contained")]).collect()
829 } else {
830 search_paths.collect()
831 }
832 }
833
834 pub fn is_rust_2015(&self) -> bool {
836 self.edition().is_rust_2015()
837 }
838
839 pub fn at_least_rust_2018(&self) -> bool {
841 self.edition().at_least_rust_2018()
842 }
843
844 pub fn at_least_rust_2021(&self) -> bool {
846 self.edition().at_least_rust_2021()
847 }
848
849 pub fn at_least_rust_2024(&self) -> bool {
851 self.edition().at_least_rust_2024()
852 }
853
854 pub fn needs_plt(&self) -> bool {
856 let want_plt = self.target.plt_by_default;
859
860 let dbg_opts = &self.opts.unstable_opts;
861
862 let relro_level = self.opts.cg.relro_level.unwrap_or(self.target.relro_level);
863
864 let full_relro = RelroLevel::Full == relro_level;
868
869 dbg_opts.plt.unwrap_or(want_plt || !full_relro)
872 }
873
874 pub fn emit_lifetime_markers(&self) -> bool {
876 self.opts.optimize != config::OptLevel::No
877 || self.sanitizers().intersects(SanitizerSet::ADDRESS | SanitizerSet::KERNELADDRESS | SanitizerSet::MEMORY | SanitizerSet::HWADDRESS | SanitizerSet::KERNELHWADDRESS)
884 || self.opts.unstable_opts.codegen_emit_retag.is_some()
886 }
887
888 pub fn diagnostic_width(&self) -> usize {
889 let default_column_width = 140;
890 if let Some(width) = self.opts.diagnostic_width {
891 width
892 } else if self.opts.unstable_opts.ui_testing {
893 default_column_width
894 } else {
895 termize::dimensions().map_or(default_column_width, |(w, _)| w)
896 }
897 }
898
899 pub fn default_visibility(&self) -> SymbolVisibility {
901 self.opts
902 .unstable_opts
903 .default_visibility
904 .or(self.target.options.default_visibility)
905 .unwrap_or(SymbolVisibility::Interposable)
906 }
907
908 pub fn staticlib_components(&self, verbatim: bool) -> (&str, &str) {
909 if verbatim {
910 ("", "")
911 } else {
912 (&*self.target.staticlib_prefix, &*self.target.staticlib_suffix)
913 }
914 }
915
916 pub fn lint_groups_iter(&self) -> Box<dyn Iterator<Item = LintGroup> + '_> {
917 match self.lint_store {
918 Some(ref lint_store) => lint_store.lint_groups_iter(),
919 None => Box::new(std::iter::empty()),
920 }
921 }
922
923 pub fn resolve_path(&self, path: impl Into<PathBuf>, span: Span) -> PResult<'_, PathBuf> {
927 let path = path.into();
928
929 if !path.is_absolute() {
932 let callsite = span.source_callsite();
933 let source_map = self.source_map();
934 let Some(mut base_path) = source_map.span_to_filename(callsite).into_local_path()
935 else {
936 return Err(self.dcx().create_err(diagnostics::ResolveRelativePath {
937 span,
938 path: source_map
939 .filename_for_diagnostics(&source_map.span_to_filename(callsite))
940 .to_string(),
941 }));
942 };
943 base_path.pop();
944 base_path.push(path);
945 Ok(base_path)
946 } else {
947 match path.components().next() {
950 Some(Prefix(prefix)) if prefix.kind().is_verbatim() => {
951 Ok(path.components().collect())
952 }
953 _ => Ok(path),
954 }
955 }
956 }
957}
958
959#[allow(rustc::bad_opt_access)]
961impl Session {
962 pub fn verbose_internals(&self) -> bool {
963 self.opts.unstable_opts.verbose_internals
964 }
965
966 pub fn verify_llvm_ir(&self) -> bool {
967 self.opts.unstable_opts.verify_llvm_ir || ::core::option::Option::None::<&'static str>option_env!("RUSTC_VERIFY_LLVM_IR").is_some()
968 }
969
970 pub fn binary_dep_depinfo(&self) -> bool {
971 self.opts.unstable_opts.binary_dep_depinfo
972 }
973
974 pub fn mir_opt_level(&self) -> usize {
975 self.opts.unstable_opts.mir_opt_level.unwrap_or_else(|| self.opts.optimize.mir_opt_level())
976 }
977
978 pub fn lto(&self) -> config::Lto {
980 if self.target.requires_lto {
982 return config::Lto::Fat;
983 }
984
985 match self.opts.cg.lto {
989 config::LtoCli::Unspecified => {
990 }
993 config::LtoCli::No => {
994 return config::Lto::No;
996 }
997 config::LtoCli::Yes | config::LtoCli::Fat | config::LtoCli::NoParam => {
998 return config::Lto::Fat;
1000 }
1001 config::LtoCli::Thin => {
1002 if !self.thin_lto_supported {
1004 self.dcx().emit_warn(diagnostics::ThinLtoNotSupportedByBackend);
1006 return config::Lto::Fat;
1007 }
1008 return config::Lto::Thin;
1009 }
1010 }
1011
1012 if !self.thin_lto_supported {
1013 return config::Lto::No;
1014 }
1015
1016 if self.opts.cli_forced_local_thinlto_off {
1025 return config::Lto::No;
1026 }
1027
1028 if let Some(enabled) = self.opts.unstable_opts.thinlto {
1031 if enabled {
1032 return config::Lto::ThinLocal;
1033 } else {
1034 return config::Lto::No;
1035 }
1036 }
1037
1038 if self.codegen_units().as_usize() == 1 {
1041 return config::Lto::No;
1042 }
1043
1044 match self.opts.optimize {
1047 config::OptLevel::No => config::Lto::No,
1048 _ => config::Lto::ThinLocal,
1049 }
1050 }
1051
1052 pub fn fewer_names(&self) -> bool {
1053 if let Some(fewer_names) = self.opts.unstable_opts.fewer_names {
1054 fewer_names
1055 } else {
1056 let more_names = self.opts.output_types.contains_key(&OutputType::LlvmAssembly)
1057 || self.opts.output_types.contains_key(&OutputType::Bitcode)
1058 || self.sanitizers().intersects(SanitizerSet::ADDRESS | SanitizerSet::MEMORY);
1060 !more_names
1061 }
1062 }
1063
1064 pub fn unstable_options(&self) -> bool {
1065 self.opts.unstable_opts.unstable_options
1066 }
1067
1068 pub fn is_nightly_build(&self) -> bool {
1069 self.opts.unstable_features.is_nightly_build()
1070 }
1071
1072 pub fn overflow_checks(&self) -> bool {
1073 self.opts.cg.overflow_checks.unwrap_or(self.opts.debug_assertions)
1074 }
1075
1076 pub fn ub_checks(&self) -> bool {
1077 self.opts.unstable_opts.ub_checks.unwrap_or(self.opts.debug_assertions)
1078 }
1079
1080 pub fn contract_checks(&self) -> bool {
1081 self.opts.unstable_opts.contract_checks.unwrap_or(false)
1082 }
1083
1084 pub fn direct_access_external_data(&self) -> Option<bool> {
1085 self.opts
1086 .unstable_opts
1087 .direct_access_external_data
1088 .or(self.target.direct_access_external_data)
1089 }
1090
1091 pub fn split_debuginfo(&self) -> SplitDebuginfo {
1092 self.opts.cg.split_debuginfo.unwrap_or(self.target.split_debuginfo)
1093 }
1094
1095 pub fn dwarf_version(&self) -> u32 {
1097 self.opts
1098 .cg
1099 .dwarf_version
1100 .or(self.opts.unstable_opts.dwarf_version)
1101 .unwrap_or(self.target.default_dwarf_version)
1102 }
1103
1104 pub fn stack_protector(&self) -> StackProtector {
1105 if self.target.options.supports_stack_protector {
1106 self.opts.unstable_opts.stack_protector
1107 } else {
1108 StackProtector::None
1109 }
1110 }
1111
1112 pub fn branch_protection(&self) -> Option<BranchProtection> {
1118 let mut bp = self.opts.unstable_opts.branch_protection;
1119
1120 if let Some(bp) = bp.as_mut() {
1121 if self.target.os == Os::Windows && self.target.arch == Arch::AArch64 {
1125 if let Some(pac_ret) = bp.pac_ret.as_mut()
1126 && pac_ret.key == PAuthKey::A
1127 {
1128 pac_ret.key = PAuthKey::B;
1129 }
1130 }
1131 }
1132
1133 bp
1134 }
1135
1136 pub fn must_emit_unwind_tables(&self) -> bool {
1137 self.target.requires_uwtable
1166 || self
1167 .opts
1168 .cg
1169 .force_unwind_tables
1170 .unwrap_or(self.panic_strategy().unwinds() || self.target.default_uwtable)
1171 }
1172
1173 pub fn codegen_units(&self) -> CodegenUnits {
1176 if let Some(n) = self.opts.cli_forced_codegen_units {
1177 return CodegenUnits::User(n);
1178 }
1179 if let Some(n) = self.target.default_codegen_units {
1180 return CodegenUnits::Default(n as usize);
1181 }
1182
1183 if self.opts.incremental.is_some() {
1187 return CodegenUnits::Default(256);
1188 }
1189
1190 CodegenUnits::Default(16)
1241 }
1242
1243 pub fn teach(&self, code: ErrCode) -> bool {
1244 self.opts.unstable_opts.teach && self.dcx().must_teach(code)
1245 }
1246
1247 pub fn edition(&self) -> Edition {
1248 self.opts.edition
1249 }
1250
1251 pub fn link_dead_code(&self) -> bool {
1252 self.opts.cg.link_dead_code.unwrap_or(false)
1253 }
1254
1255 pub fn sanitizers(&self) -> SanitizerSet {
1256 self.sanitizers
1257 }
1258
1259 pub fn pointer_authentication(&self) -> bool {
1260 self.pointer_auth_config.is_some()
1261 }
1262
1263 pub fn pointer_authentication_functions(&self) -> Option<&PointerAuthSchema> {
1264 self.pointer_auth_config.as_ref().and_then(|cfg| cfg.function_pointers.as_ref())
1265 }
1266
1267 pub fn pointer_authentication_init_fini(&self) -> Option<&PointerAuthSchema> {
1268 self.pointer_auth_config.as_ref().and_then(|cfg| cfg.init_fini.as_ref())
1269 }
1270}
1271
1272#[allow(rustc::bad_opt_access)]
1274fn default_emitter(sopts: &config::Options, source_map: Arc<SourceMap>) -> Box<DynEmitter> {
1275 let macro_backtrace = sopts.unstable_opts.macro_backtrace;
1276 let track_diagnostics = sopts.unstable_opts.track_diagnostics;
1277 let terminal_url = match sopts.unstable_opts.terminal_urls {
1278 TerminalUrl::Auto => {
1279 match (std::env::var("COLORTERM").as_deref(), std::env::var("TERM").as_deref()) {
1280 (Ok("truecolor"), Ok("xterm-256color"))
1281 if sopts.unstable_features.is_nightly_build() =>
1282 {
1283 TerminalUrl::Yes
1284 }
1285 _ => TerminalUrl::No,
1286 }
1287 }
1288 t => t,
1289 };
1290
1291 let source_map = if sopts.unstable_opts.link_only { None } else { Some(source_map) };
1292
1293 match sopts.error_format {
1294 config::ErrorOutputType::HumanReadable { kind, color_config } => match kind {
1295 HumanReadableErrorType { short, unicode } => {
1296 let emitter = AnnotateSnippetEmitter::new(stderr_destination(color_config))
1297 .sm(source_map)
1298 .short_message(short)
1299 .diagnostic_width(sopts.diagnostic_width)
1300 .macro_backtrace(macro_backtrace)
1301 .track_diagnostics(track_diagnostics)
1302 .terminal_url(terminal_url)
1303 .theme(if unicode { OutputTheme::Unicode } else { OutputTheme::Ascii })
1304 .ignored_directories_in_source_blocks(
1305 sopts.unstable_opts.ignore_directory_in_diagnostics_source_blocks.clone(),
1306 );
1307 Box::new(emitter.ui_testing(sopts.unstable_opts.ui_testing))
1308 }
1309 },
1310 config::ErrorOutputType::Json { pretty, json_rendered, color_config } => Box::new(
1311 JsonEmitter::new(
1312 Box::new(io::BufWriter::new(io::stderr())),
1313 source_map,
1314 pretty,
1315 json_rendered,
1316 color_config,
1317 )
1318 .ui_testing(sopts.unstable_opts.ui_testing)
1319 .ignored_directories_in_source_blocks(
1320 sopts.unstable_opts.ignore_directory_in_diagnostics_source_blocks.clone(),
1321 )
1322 .diagnostic_width(sopts.diagnostic_width)
1323 .macro_backtrace(macro_backtrace)
1324 .track_diagnostics(track_diagnostics)
1325 .terminal_url(terminal_url),
1326 ),
1327 }
1328}
1329
1330#[allow(rustc::bad_opt_access)]
1332pub fn build_early_session(
1333 sopts: config::Options,
1334 target: Target,
1335 ice_file: Option<PathBuf>,
1336) -> EarlySession {
1337 let warnings_allow = sopts
1341 .lint_opts
1342 .iter()
1343 .rfind(|&(key, _)| *key == "warnings")
1344 .is_some_and(|&(_, level)| level == lint::Allow);
1345 let cap_lints_allow = sopts.lint_cap.is_some_and(|cap| cap == lint::Allow);
1346 let can_emit_warnings = !(warnings_allow || cap_lints_allow);
1347
1348 let source_map = rustc_span::source_map::get_source_map().unwrap();
1349 let emitter = default_emitter(&sopts, Arc::clone(&source_map));
1350
1351 let mut dcx =
1352 DiagCtxt::new(emitter).with_flags(sopts.unstable_opts.dcx_flags(can_emit_warnings));
1353 if let Some(ice_file) = ice_file {
1354 dcx = dcx.with_ice_file(ice_file);
1355 }
1356
1357 if let Some(msrv) = sopts.unstable_opts.hint_msrv {
1358 dcx = dcx.with_msrv(msrv);
1359 }
1360
1361 let host_triple = TargetTuple::from_tuple(config::host_tuple());
1362 let (host, target_warnings) =
1363 Target::search(&host_triple, sopts.sysroot.path(), sopts.unstable_opts.unstable_options)
1364 .unwrap_or_else(|e| {
1365 dcx.handle().fatal(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("Error loading host specification: {0}",
e))
})format!("Error loading host specification: {e}"))
1366 });
1367 for warning in target_warnings.warning_messages() {
1368 dcx.handle().warn(warning)
1369 }
1370
1371 let psess = ParseSess::with_dcx(dcx, source_map);
1372
1373 EarlySession { target, host, opts: sopts, psess }
1374}
1375
1376#[allow(rustc::bad_opt_access)]
1378pub fn build_session(
1379 early_sess: EarlySession,
1380 codegen_backend_init: CodegenBackendInit,
1381 io: CompilerIO,
1382 driver_lint_caps: FxHashMap<lint::LintId, lint::Level>,
1383 cfg_version: &'static str,
1384 using_internal_features: &'static AtomicBool,
1385) -> Session {
1386 let EarlySession { target, host, opts: sopts, psess } = &early_sess;
1387 let dcx = psess.dcx();
1388
1389 let wasm_proc_macro_tuple = TargetTuple::from_tuple("wasm32-wasip2");
1390 let (wasm_proc_macro_target, target_warnings) = Target::search(
1391 &wasm_proc_macro_tuple,
1392 sopts.sysroot.path(),
1393 sopts.unstable_opts.unstable_options,
1394 )
1395 .unwrap_or_else(|e| {
1396 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}"))
1397 });
1398 for warning in target_warnings.warning_messages() {
1399 dcx.warn(warning)
1400 }
1401
1402 let self_profiler = if let SwitchWithOptPath::Enabled(ref d) = sopts.unstable_opts.self_profile
1403 {
1404 let directory = if let Some(directory) = d { directory } else { std::path::Path::new(".") };
1405
1406 let profiler = SelfProfiler::new(
1407 directory,
1408 sopts.crate_name.as_deref(),
1409 sopts.unstable_opts.self_profile_events.as_deref(),
1410 &sopts.unstable_opts.self_profile_counter,
1411 );
1412 match profiler {
1413 Ok(profiler) => Some(Arc::new(profiler)),
1414 Err(e) => {
1415 dcx.emit_warn(diagnostics::FailedToCreateProfiler { err: e.to_string() });
1416 None
1417 }
1418 }
1419 } else {
1420 None
1421 };
1422
1423 let host_triple = config::host_tuple();
1424 let target_triple = sopts.target_triple.tuple();
1425 let host_tlib_path = SearchPath::from_sysroot_and_triple(sopts.sysroot.path(), host_triple);
1427 let target_tlib_path = SearchPath::from_sysroot_and_triple(sopts.sysroot.path(), target_triple);
1428 let wasm_proc_macro_tlib_path =
1429 SearchPath::from_sysroot_and_triple(sopts.sysroot.path(), wasm_proc_macro_tuple.tuple());
1430
1431 let prof = SelfProfilerRef::new(
1432 self_profiler,
1433 sopts.unstable_opts.time_passes.then(|| sopts.unstable_opts.time_passes_format),
1434 );
1435
1436 let ctfe_backtrace = Lock::new(match env::var("RUSTC_CTFE_BACKTRACE") {
1437 Ok(ref val) if val == "immediate" => CtfeBacktrace::Immediate,
1438 Ok(ref val) if val != "0" => CtfeBacktrace::Capture,
1439 _ => CtfeBacktrace::Disabled,
1440 });
1441
1442 let asm_arch = if target.allow_asm { InlineAsmArch::from_arch(&target.arch) } else { None };
1443 let target_filesearch = Arc::new(filesearch::FileSearch::new(
1444 &sopts.search_paths,
1445 &target_tlib_path,
1446 &target,
1447 sopts.unstable_opts.implicit_sysroot_deps,
1448 ));
1449 let host_filesearch = if target == host {
1450 Arc::clone(&target_filesearch)
1451 } else {
1452 Arc::new(filesearch::FileSearch::new(
1453 &sopts.search_paths,
1454 &host_tlib_path,
1455 &host,
1456 sopts.unstable_opts.implicit_sysroot_deps,
1457 ))
1458 };
1459 let wasm_proc_macro_filesearch = if sopts.unstable_opts.wasm_proc_macros {
1460 Some(Arc::new(FileSearch::new(
1461 &sopts.search_paths,
1462 &wasm_proc_macro_tlib_path,
1463 &wasm_proc_macro_target,
1464 sopts.unstable_opts.implicit_sysroot_deps,
1465 )))
1466 } else {
1467 None
1468 };
1469
1470 let timings = TimingSectionHandler::new(sopts.json_timings);
1471
1472 let pointer_auth_config: Option<PointerAuthConfig> =
1473 PointerAuthConfig::from_raw(&sopts.unstable_opts.pointer_authentication, &target);
1474
1475 let sanitizers = early_sess.sanitizers();
1478
1479 let CodegenBackendInit {
1480 global_backend_features,
1481 replaced_intrinsics,
1482 fallback_intrinsics,
1483 thin_lto_supported,
1484 } = codegen_backend_init;
1485
1486 let sess = Session {
1487 early_sess,
1488 wasm_proc_macro_tuple,
1489 wasm_proc_macro_target,
1490 target_tlib_path,
1491 unstable_features: UnstableFeatures::from_environment(None),
1492 config: Cfg::default(),
1493 check_config: CheckCfg::default(),
1494 proc_macro_quoted_spans: Default::default(),
1495 io,
1496 prof,
1497 timings,
1498 code_stats: Default::default(),
1499 lint_store: None,
1500 driver_lint_caps,
1501 ctfe_backtrace,
1502 miri_unleashed_features: Lock::new(Default::default()),
1503 asm_arch,
1504 internal_target_features: Default::default(),
1505 global_backend_features,
1506 cfg_version,
1507 using_internal_features,
1508 env_depinfo: Default::default(),
1509 file_depinfo: Default::default(),
1510 target_filesearch,
1511 host_filesearch,
1512 wasm_proc_macro_filesearch,
1513 replaced_intrinsics: FxHashSet::from_iter(replaced_intrinsics),
1514 fallback_intrinsics: FxHashSet::from_iter(fallback_intrinsics),
1515 thin_lto_supported,
1516 mir_opt_bisect_eval_count: AtomicUsize::new(0),
1517 removed_rustc_main_attr: AtomicBool::new(false),
1518 pointer_auth_config,
1519 sanitizers,
1520 };
1521
1522 validate_commandline_args_with_session_available(&sess);
1523
1524 sess
1525}
1526
1527pub fn generate_proc_macro_decls_symbol(stable_crate_id: StableCrateId) -> String {
1528 ::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())
1529}
1530
1531#[allow(rustc::bad_opt_access)]
1537fn validate_commandline_args_with_session_available(sess: &Session) {
1538 if sess.opts.cg.linker_plugin_lto.enabled()
1546 && sess.opts.cg.prefer_dynamic
1547 && sess.target.is_like_windows
1548 {
1549 sess.dcx().emit_err(diagnostics::LinkerPluginToWindowsNotSupported);
1550 }
1551
1552 if sess
1553 .pointer_auth_config
1554 .as_ref()
1555 .and_then(|cfg| cfg.function_pointers.as_ref())
1556 .is_some_and(|schema| #[allow(non_exhaustive_omitted_patterns)] match schema.discrimination_kind {
PointerAuthDiscrimination::Type => true,
_ => false,
}matches!(schema.discrimination_kind, PointerAuthDiscrimination::Type))
1557 {
1558 sess.dcx().emit_err(
1559 diagnostics::PointerAuthenticationTypeDiscriminationNotSupportedForTarget {
1560 target_triple: &sess.opts.target_triple,
1561 },
1562 );
1563 }
1564
1565 if sess.target.cfg_abi != CfgAbi::Pauthtest
1566 && !sess.opts.unstable_opts.pointer_authentication.is_empty()
1567 {
1568 sess.dcx().emit_warn(diagnostics::PointerAuthenticationNotSupportedForTarget {
1569 target_triple: &sess.opts.target_triple,
1570 });
1571 }
1572
1573 if let Some(ref path) = sess.opts.cg.profile_use {
1576 if !path.exists() {
1577 sess.dcx().emit_err(diagnostics::ProfileUseFileDoesNotExist { path });
1578 }
1579 }
1580
1581 if let Some(ref path) = sess.opts.cg.profile_sample_use {
1583 if !path.exists() {
1584 sess.dcx().emit_err(diagnostics::ProfileSampleUseFileDoesNotExist { path });
1585 }
1586 }
1587
1588 if let Some(include_uwtables) = sess.opts.cg.force_unwind_tables {
1590 if sess.target.requires_uwtable && !include_uwtables {
1591 sess.dcx().emit_err(diagnostics::TargetRequiresUnwindTables);
1592 }
1593 }
1594
1595 let supported_sanitizers = sess.target.options.supported_sanitizers;
1597 let mut unsupported_sanitizers = sess.sanitizers() - supported_sanitizers;
1598 if sess.opts.unstable_opts.fixed_x18 && sess.target.arch == Arch::AArch64 {
1601 unsupported_sanitizers -= SanitizerSet::SHADOWCALLSTACK;
1602 }
1603 match unsupported_sanitizers.into_iter().count() {
1604 0 => {}
1605 1 => {
1606 sess.dcx().emit_err(diagnostics::SanitizerNotSupported {
1607 us: unsupported_sanitizers.to_string(),
1608 });
1609 }
1610 _ => {
1611 sess.dcx().emit_err(diagnostics::SanitizersNotSupported {
1612 us: unsupported_sanitizers.to_string(),
1613 });
1614 }
1615 }
1616
1617 if let Some((first, second)) = sess.sanitizers().mutually_exclusive() {
1619 sess.dcx().emit_err(diagnostics::CannotMixAndMatchSanitizers {
1620 first: first.to_string(),
1621 second: second.to_string(),
1622 });
1623 }
1624
1625 if sess.crt_static(None) && !sess.sanitizers().is_empty() && !sess.target.is_like_msvc {
1627 sess.dcx().emit_err(diagnostics::CannotEnableCrtStaticLinux);
1628 }
1629
1630 if sess.crt_static(None) && sess.target.cfg_abi == CfgAbi::Pauthtest {
1634 sess.dcx().emit_err(diagnostics::CannotEnableCrtStaticPointerAuth);
1635 }
1636
1637 if sess.is_sanitizer_cfi_enabled()
1639 && !(sess.lto() == config::Lto::Fat || sess.opts.cg.linker_plugin_lto.enabled())
1640 {
1641 sess.dcx().emit_err(diagnostics::SanitizerCfiRequiresLto);
1642 }
1643
1644 if sess.is_sanitizer_kcfi_enabled() && sess.panic_strategy().unwinds() {
1646 sess.dcx().emit_err(diagnostics::SanitizerKcfiRequiresPanicAbort);
1647 }
1648
1649 if sess.is_sanitizer_cfi_enabled()
1651 && sess.lto() == config::Lto::Fat
1652 && (sess.codegen_units().as_usize() != 1)
1653 {
1654 sess.dcx().emit_err(diagnostics::SanitizerCfiRequiresSingleCodegenUnit);
1655 }
1656
1657 if sess.is_sanitizer_cfi_canonical_jump_tables_disabled() {
1659 if !sess.is_sanitizer_cfi_enabled() {
1660 sess.dcx().emit_err(diagnostics::SanitizerCfiCanonicalJumpTablesRequiresCfi);
1661 }
1662 }
1663
1664 if sess.is_sanitizer_kcfi_arity_enabled() && !sess.is_sanitizer_kcfi_enabled() {
1666 sess.dcx().emit_err(diagnostics::SanitizerKcfiArityRequiresKcfi);
1667 }
1668
1669 if sess.is_sanitizer_cfi_generalize_pointers_enabled() {
1671 if !(sess.is_sanitizer_cfi_enabled() || sess.is_sanitizer_kcfi_enabled()) {
1672 sess.dcx().emit_err(diagnostics::SanitizerCfiGeneralizePointersRequiresCfi);
1673 }
1674 }
1675
1676 if sess.is_sanitizer_cfi_recover_enabled() {
1678 if !sess.is_sanitizer_cfi_enabled() {
1679 sess.dcx().emit_err(diagnostics::SanitizerCfiRecoverRequiresCfi);
1680 }
1681 }
1682
1683 if sess.is_sanitizer_cfi_diag_enabled() {
1685 if !sess.is_sanitizer_cfi_enabled() {
1686 sess.dcx().emit_err(diagnostics::SanitizerCfiDiagRequiresCfi);
1687 }
1688 }
1689
1690 if sess.is_sanitizer_cfi_normalize_integers_enabled() {
1692 if !(sess.is_sanitizer_cfi_enabled() || sess.is_sanitizer_kcfi_enabled()) {
1693 sess.dcx().emit_err(diagnostics::SanitizerCfiNormalizeIntegersRequiresCfi);
1694 }
1695 }
1696
1697 if sess.is_split_lto_unit_enabled()
1699 && !(sess.lto() == config::Lto::Fat
1700 || sess.lto() == config::Lto::Thin
1701 || sess.opts.cg.linker_plugin_lto.enabled())
1702 {
1703 sess.dcx().emit_err(diagnostics::SplitLtoUnitRequiresLto);
1704 }
1705
1706 if sess.lto() != config::Lto::Fat {
1708 if sess.opts.unstable_opts.virtual_function_elimination {
1709 sess.dcx().emit_err(diagnostics::UnstableVirtualFunctionElimination);
1710 }
1711 }
1712
1713 if sess.opts.unstable_opts.stack_protector != StackProtector::None {
1714 if !sess.target.options.supports_stack_protector {
1715 sess.dcx().emit_warn(diagnostics::StackProtectorNotSupportedForTarget {
1716 stack_protector: sess.opts.unstable_opts.stack_protector,
1717 target_triple: &sess.opts.target_triple,
1718 });
1719 }
1720 }
1721
1722 if sess.opts.unstable_opts.small_data_threshold.is_some() {
1723 if sess.target.small_data_threshold_support() == SmallDataThresholdSupport::None {
1724 sess.dcx().emit_warn(diagnostics::SmallDataThresholdNotSupportedForTarget {
1725 target_triple: &sess.opts.target_triple,
1726 })
1727 }
1728 }
1729
1730 if sess.opts.unstable_opts.branch_protection.is_some() && sess.target.arch != Arch::AArch64 {
1731 sess.dcx().emit_err(diagnostics::BranchProtectionRequiresAArch64);
1732 }
1733
1734 if let Some(dwarf_version) =
1735 sess.opts.cg.dwarf_version.or(sess.opts.unstable_opts.dwarf_version)
1736 {
1737 if dwarf_version < 2 || dwarf_version > 5 {
1739 sess.dcx().emit_err(diagnostics::UnsupportedDwarfVersion { dwarf_version });
1740 }
1741 }
1742
1743 if !sess.target.options.supported_split_debuginfo.contains(&sess.split_debuginfo())
1744 && !sess.opts.unstable_opts.unstable_options
1745 {
1746 sess.dcx().emit_err(diagnostics::SplitDebugInfoUnstablePlatform {
1747 debuginfo: sess.split_debuginfo(),
1748 });
1749 }
1750
1751 if sess.opts.unstable_opts.embed_source {
1752 let dwarf_version = sess.dwarf_version();
1753
1754 if dwarf_version < 5 {
1755 sess.dcx()
1756 .emit_warn(diagnostics::EmbedSourceInsufficientDwarfVersion { dwarf_version });
1757 }
1758
1759 if sess.opts.debuginfo == DebugInfo::None {
1760 sess.dcx().emit_warn(diagnostics::EmbedSourceRequiresDebugInfo);
1761 }
1762 }
1763
1764 if let InstrumentMcount::Fentry(opts) = sess.opts.unstable_opts.instrument_mcount {
1765 if !sess.target.options.supports_fentry {
1766 sess.dcx()
1767 .emit_err(diagnostics::InstrumentationNotSupported { us: "fentry".to_string() });
1768 }
1769 if (opts.no_call || opts.record) && sess.target.arch != Arch::S390x {
1770 sess.dcx()
1771 .emit_err(diagnostics::InstrumentationNotSupported { us: "fentry-*".to_string() });
1772 }
1773 }
1774
1775 if sess.opts.unstable_opts.instrument_xray.is_some() && !sess.target.options.supports_xray {
1776 sess.dcx().emit_err(diagnostics::InstrumentationNotSupported { us: "XRay".to_string() });
1777 }
1778
1779 if let Some(flavor) = sess.opts.cg.linker_flavor
1780 && let Some(compatible_list) = sess.target.linker_flavor.check_compatibility(flavor)
1781 {
1782 let flavor = flavor.desc();
1783 sess.dcx().emit_err(diagnostics::IncompatibleLinkerFlavor { flavor, compatible_list });
1784 }
1785
1786 if sess.opts.unstable_opts.function_return != FunctionReturn::default() {
1787 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) {
1788 sess.dcx().emit_err(diagnostics::FunctionReturnRequiresX86OrX8664);
1789 }
1790 }
1791
1792 if sess.opts.unstable_opts.indirect_branch_cs_prefix {
1793 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) {
1794 sess.dcx().emit_err(diagnostics::IndirectBranchCsPrefixRequiresX86OrX8664);
1795 }
1796 }
1797
1798 if let Some(regparm) = sess.opts.unstable_opts.regparm {
1799 if regparm > 3 {
1800 sess.dcx().emit_err(diagnostics::UnsupportedRegparm { regparm });
1801 }
1802 if sess.target.arch != Arch::X86 {
1803 sess.dcx().emit_err(diagnostics::UnsupportedRegparmArch);
1804 }
1805 }
1806 if sess.opts.unstable_opts.reg_struct_return {
1807 if sess.target.arch != Arch::X86 {
1808 sess.dcx().emit_err(diagnostics::UnsupportedRegStructReturnArch);
1809 }
1810 }
1811
1812 match sess.opts.unstable_opts.function_return {
1816 FunctionReturn::Keep => (),
1817 FunctionReturn::ThunkExtern => {
1818 if let Some(code_model) = sess.code_model()
1821 && code_model == CodeModel::Large
1822 {
1823 sess.dcx()
1824 .emit_err(diagnostics::FunctionReturnThunkExternRequiresNonLargeCodeModel);
1825 }
1826 }
1827 }
1828
1829 if sess.opts.unstable_opts.packed_stack {
1830 if sess.target.arch != Arch::S390x {
1831 sess.dcx().emit_err(diagnostics::UnsupportedPackedStack);
1832 }
1833 }
1834
1835 if let Some(ref cpu_name) = sess.opts.cg.target_cpu {
1836 if cpu_name == NATIVE_CPU && sess.target.requires_consistent_cpu {
1837 sess.dcx().emit_fatal(diagnostics::NativeTargetCpuNotAllowed {
1838 target_triple: &sess.opts.target_triple,
1839 need_explicit_cpu: sess.target.need_explicit_cpu,
1840 });
1841 }
1842 }
1843}
1844
1845pub struct IncrCompSession {
1847 pub old_session_directory: Option<flock::LockedDir>,
1849 pub new_session_directory: flock::LockedDir,
1852}
1853
1854pub struct EarlyDiagCtxt {
1856 dcx: DiagCtxt,
1857}
1858
1859impl EarlyDiagCtxt {
1860 pub fn new(output: ErrorOutputType) -> Self {
1861 let emitter = mk_emitter(output);
1862 Self { dcx: DiagCtxt::new(emitter) }
1863 }
1864
1865 pub fn set_error_format(&mut self, output: ErrorOutputType) {
1868 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());
1869
1870 let emitter = mk_emitter(output);
1871 self.dcx = DiagCtxt::new(emitter);
1872 }
1873
1874 #[must_use = "raise_fatal must be called on the returned ErrorGuaranteed in order to exit with a non-zero status code"]
1875 pub fn early_err(&self, msg: impl Into<DiagMessage>) -> ErrorGuaranteed {
1876 self.dcx.handle().err(msg)
1877 }
1878
1879 pub fn early_fatal(&self, msg: impl Into<DiagMessage>) -> ! {
1880 self.dcx.handle().fatal(msg)
1881 }
1882
1883 pub fn early_struct_fatal(&self, msg: impl Into<DiagMessage>) -> Diag<'_> {
1884 self.dcx.handle().struct_fatal(msg)
1885 }
1886
1887 pub fn early_warn(&self, msg: impl Into<DiagMessage>) {
1888 self.dcx.handle().warn(msg)
1889 }
1890
1891 pub fn early_struct_warn(&self, msg: impl Into<DiagMessage>) -> Diag<'_> {
1892 self.dcx.handle().struct_warn(msg)
1893 }
1894}
1895
1896fn mk_emitter(output: ErrorOutputType) -> Box<DynEmitter> {
1897 let emitter: Box<DynEmitter> = match output {
1898 config::ErrorOutputType::HumanReadable { kind, color_config } => match kind {
1899 HumanReadableErrorType { short, unicode } => Box::new(
1900 AnnotateSnippetEmitter::new(stderr_destination(color_config))
1901 .theme(if unicode { OutputTheme::Unicode } else { OutputTheme::Ascii })
1902 .short_message(short),
1903 ),
1904 },
1905 config::ErrorOutputType::Json { pretty, json_rendered, color_config } => {
1906 Box::new(JsonEmitter::new(
1907 Box::new(io::BufWriter::new(io::stderr())),
1908 Some(Arc::new(SourceMap::new(FilePathMapping::empty()))),
1909 pretty,
1910 json_rendered,
1911 color_config,
1912 ))
1913 }
1914 };
1915 emitter
1916}