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_abi::PackCoroutineLayout;
11use rustc_data_structures::flock;
12use rustc_data_structures::fx::{FxHashMap, FxHashSet, FxIndexSet};
13use rustc_data_structures::profiling::{SelfProfiler, SelfProfilerRef};
14use rustc_data_structures::sync::{AppendOnlyVec, DynSend, DynSync, Lock};
15use rustc_errors::annotate_snippet_emitter_writer::AnnotateSnippetEmitter;
16use rustc_errors::codes::*;
17use rustc_errors::emitter::{DynEmitter, HumanReadableErrorType, OutputTheme, stderr_destination};
18use rustc_errors::json::JsonEmitter;
19use rustc_errors::timings::TimingSectionHandler;
20use rustc_errors::{
21 Diag, DiagCtxt, DiagCtxtHandle, DiagMessage, Diagnostic, ErrorGuaranteed, PResult, TerminalUrl,
22};
23use rustc_feature::UnstableFeatures;
24use rustc_lint_defs::{CheckLintNameResult, LintName, RegisteredTools};
25use rustc_macros::StableHash;
26pub use rustc_span::def_id::StableCrateId;
27use rustc_span::edition::Edition;
28use rustc_span::source_map::{FilePathMapping, SourceMap};
29use rustc_span::{RealFileName, Span, Symbol};
30use rustc_structures::{CrateType, Limit};
31use rustc_target::asm::InlineAsmArch;
32use rustc_target::spec::{
33 Arch, CfgAbi, CodeModel, DebuginfoKind, MergeFunctions, Os, PanicStrategy, RelocModel,
34 RelroLevel, SanitizerSet, SmallDataThresholdSupport, SplitDebuginfo, StackProtector,
35 SymbolVisibility, Target, TargetTuple, TlsModel, apple,
36};
37
38use crate::code_stats::CodeStats;
39pub use crate::code_stats::{DataTypeKind, FieldInfo, FieldKind, SizeKind, VariantInfo};
40use crate::config::{
41 self, BranchProtection, Cfg, CheckCfg, CoverageLevel, CoverageOptions, DebugInfo,
42 FunctionReturn, Input, InstrumentCoverage, InstrumentMcount, LtoCli, NATIVE_CPU, OutFileName,
43 PAuthKey, PointerAuthOption, SwitchWithOptPath,
44};
45use crate::filesearch::FileSearch;
46use crate::lint::LintId;
47use crate::output::{ErrorOutputType, OutputType};
48use crate::parse::ParseSess;
49use crate::search_paths::SearchPath;
50use crate::{diagnostics, filesearch, lint};
51
52#[derive(#[automatically_derived]#[doc(hidden)]unsafe impl ::core::clone::TrivialClone
for CtfeBacktrace {
}
#[automatically_derived]impl ::core::clone::Clone for CtfeBacktrace {
#[inline]
#[rustc_trivial_field_reads]
fn clone(&self) -> Self { *self }
}Clone, #[automatically_derived]impl ::core::marker::Copy for CtfeBacktrace { }Copy)]
54pub enum CtfeBacktrace {
55 Disabled,
57 Capture,
60 Immediate,
62}
63
64#[derive(#[automatically_derived]#[doc(hidden)]unsafe impl ::core::clone::TrivialClone
for Limits {
}
#[automatically_derived]impl ::core::clone::Clone for Limits {
#[inline]
#[rustc_trivial_field_reads]
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]
#[rustc_trivial_field_reads]
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)]
65pub struct Limits {
66 pub recursion_limit: Limit,
69 pub move_size_limit: Limit,
72 pub type_length_limit: Limit,
74 pub pattern_complexity_limit: Limit,
76}
77
78pub struct CompilerIO {
79 pub input: Input,
80 pub output_dir: Option<PathBuf>,
81 pub output_file: Option<OutFileName>,
82 pub temps_dir: Option<PathBuf>,
83}
84
85pub trait DynLintStore: Any + DynSync + DynSend {
86 fn lint_groups_iter(&self) -> Box<dyn Iterator<Item = LintGroup> + '_>;
88
89 fn check_attribute_lint_name(
90 &self,
91 lint_name: LintName,
92 lint_tools: &RegisteredTools,
93 ) -> CheckLintNameResult<'_>;
94}
95
96#[derive(#[automatically_derived]#[doc(hidden)]unsafe impl ::core::clone::TrivialClone
for PointerAuthARM8_3Key {
}
#[automatically_derived]impl ::core::clone::Clone for PointerAuthARM8_3Key {
#[inline]
#[rustc_trivial_field_reads]
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]
#[rustc_trivial_field_reads]
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)]
99pub enum PointerAuthARM8_3Key {
100 ASIA = 0,
101 ASIB = 1,
102 ASDA = 2,
103 ASDB = 3,
104}
105
106pub enum PointerAuthDiscrimination {
108 None,
110 Type,
112 Decl,
114 Constant,
116}
117
118pub enum PointerAuthAddressDiscriminator {
120 HardwareAddress(bool),
122 Synthetic(u64),
125}
126
127pub struct PointerAuthSchema {
128 pub is_address_discriminated: PointerAuthAddressDiscriminator,
129 pub discrimination_kind: PointerAuthDiscrimination,
130 pub key: PointerAuthARM8_3Key,
131 pub constant_discriminator: u16,
132}
133impl PointerAuthSchema {
134 pub fn function_pointers_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::HardwareAddress(false),
138 discrimination_kind: PointerAuthDiscrimination::None,
139 key: PointerAuthARM8_3Key::ASIA,
140 constant_discriminator: 0,
141 };
142 }
143 pub fn init_fini_default(target: &Target) -> Self {
144 if !(target.cfg_abi == CfgAbi::Pauthtest) {
::core::panicking::panic("assertion failed: target.cfg_abi == CfgAbi::Pauthtest")
};assert!(target.cfg_abi == CfgAbi::Pauthtest);
145 return Self {
146 is_address_discriminated: PointerAuthAddressDiscriminator::Synthetic(1),
147 discrimination_kind: PointerAuthDiscrimination::None,
148 key: PointerAuthARM8_3Key::ASIA,
149 constant_discriminator: 0xd9d4,
151 };
152 }
153}
154
155pub struct PointerAuthConfig {
156 pub return_addresses: bool,
158 pub auth_traps: bool,
160 pub indirect_gotos: bool,
162 pub elf_got: bool,
164 pub aarch64_jump_table_hardening: bool,
166 pub function_pointers: Option<PointerAuthSchema>,
168 pub init_fini: Option<PointerAuthSchema>,
170 pub intrinsics: bool,
172 pub typeinfo_vt_ptr_discrimination: bool,
175 pub vt_ptr_addr_discrimination: bool,
176 pub vt_ptr_type_discrimination: bool,
177}
178impl PointerAuthConfig {
179 fn default(target: &Target) -> Self {
180 if !(target.cfg_abi == CfgAbi::Pauthtest) {
::core::panicking::panic("assertion failed: target.cfg_abi == CfgAbi::Pauthtest")
};assert!(target.cfg_abi == CfgAbi::Pauthtest);
181 return Self {
182 return_addresses: true,
183 auth_traps: true,
184 indirect_gotos: true,
185 elf_got: false,
186 aarch64_jump_table_hardening: true,
187 function_pointers: Some(PointerAuthSchema::function_pointers_default(target)),
188 init_fini: Some(PointerAuthSchema::init_fini_default(target)),
189 intrinsics: true,
190 typeinfo_vt_ptr_discrimination: true,
191 vt_ptr_addr_discrimination: true,
192 vt_ptr_type_discrimination: true,
193 };
194 }
195 pub fn calculate_pauth_abi_version(&self, target: &Target) -> u32 {
196 if !(target.cfg_abi == CfgAbi::Pauthtest) {
::core::panicking::panic("assertion failed: target.cfg_abi == CfgAbi::Pauthtest")
};assert!(target.cfg_abi == CfgAbi::Pauthtest);
197 const INTRINSICS: u32 = 0;
207 const CALLS: u32 = 1;
208 const RETURNS: u32 = 2;
209 const AUTHTRAPS: u32 = 3;
210 const VT_PTR_ADDR_DISCR: u32 = 4;
211 const VT_PTR_TYPE_DISCR: u32 = 5;
212 const INIT_FINI: u32 = 6;
213 const INIT_FINI_ADDR_DISC: u32 = 7;
214 const GOT: u32 = 8;
215 const GOTOS: u32 = 9;
216 const TYPEINFO_VT_PTR_DISCR: u32 = 10;
217 let pauth_abi_version: u32 = (u32::from(self.intrinsics) << INTRINSICS)
221 | (u32::from(self.function_pointers.is_some()) << CALLS)
222 | (u32::from(self.return_addresses) << RETURNS)
223 | (u32::from(self.auth_traps) << AUTHTRAPS)
224 | (u32::from(self.vt_ptr_addr_discrimination) << VT_PTR_ADDR_DISCR)
225 | (u32::from(self.vt_ptr_type_discrimination) << VT_PTR_TYPE_DISCR)
226 | (u32::from(self.init_fini.is_some()) << INIT_FINI)
227 | (u32::from(self.init_fini.as_ref().is_some_and(|schema| {
228 #[allow(non_exhaustive_omitted_patterns)] match schema.is_address_discriminated
{
PointerAuthAddressDiscriminator::HardwareAddress(true) |
PointerAuthAddressDiscriminator::Synthetic(_) => true,
_ => false,
}matches!(
229 schema.is_address_discriminated,
230 PointerAuthAddressDiscriminator::HardwareAddress(true)
231 | PointerAuthAddressDiscriminator::Synthetic(_)
232 )
233 })) << INIT_FINI_ADDR_DISC)
234 | (u32::from(self.elf_got) << GOT)
235 | (u32::from(self.indirect_gotos) << GOTOS)
236 | (u32::from(self.typeinfo_vt_ptr_discrimination) << TYPEINFO_VT_PTR_DISCR);
237
238 pauth_abi_version
239 }
240 pub fn from_raw(raw: &[(PointerAuthOption, bool)], target: &Target) -> Option<Self> {
241 if target.cfg_abi != CfgAbi::Pauthtest {
242 return None;
243 }
244
245 let mut cfg = Self::default(target);
246 if raw.is_empty() {
247 return Some(cfg);
248 }
249
250 for (opt, enabled) in raw {
251 match opt {
252 PointerAuthOption::Calls => {
253 if *enabled {
254 cfg.function_pointers.get_or_insert_with(|| {
255 PointerAuthSchema::function_pointers_default(target)
256 });
257 } else {
258 cfg.function_pointers = None;
259 }
260 }
261 PointerAuthOption::FunctionPointerTypeDiscrimination => {
262 if *enabled {
263 let schema = cfg.function_pointers.get_or_insert_with(|| {
264 PointerAuthSchema::function_pointers_default(target)
265 });
266 schema.discrimination_kind = PointerAuthDiscrimination::Type;
267 } else if let Some(schema) = &mut cfg.function_pointers {
268 schema.discrimination_kind = PointerAuthDiscrimination::None;
269 }
270 }
271 PointerAuthOption::ReturnAddresses => cfg.return_addresses = *enabled,
272 PointerAuthOption::AuthTraps => cfg.auth_traps = *enabled,
273 PointerAuthOption::IndirectGotos => cfg.indirect_gotos = *enabled,
274 PointerAuthOption::ElfGot => cfg.elf_got = *enabled,
275 PointerAuthOption::Aarch64JumpTableHardening => {
276 cfg.aarch64_jump_table_hardening = *enabled
277 }
278 PointerAuthOption::InitFini => {
279 if *enabled {
280 cfg.init_fini
281 .get_or_insert_with(|| PointerAuthSchema::init_fini_default(target));
282 } else {
283 cfg.init_fini = None;
284 }
285 }
286 PointerAuthOption::InitFiniAddressDiscrimination => {
287 if *enabled {
288 let schema = cfg
289 .init_fini
290 .get_or_insert_with(|| PointerAuthSchema::init_fini_default(target));
291 schema.is_address_discriminated =
292 PointerAuthAddressDiscriminator::HardwareAddress(true);
293 } else if let Some(schema) = &mut cfg.init_fini {
294 schema.is_address_discriminated =
295 PointerAuthAddressDiscriminator::Synthetic(1);
296 }
297 }
298
299 PointerAuthOption::Intrinsics => cfg.intrinsics = *enabled,
300 PointerAuthOption::TypeInfoVTPtrDisc => {
301 cfg.typeinfo_vt_ptr_discrimination = *enabled
302 }
303 PointerAuthOption::VTPtrAddrDisc => cfg.vt_ptr_addr_discrimination = *enabled,
304 PointerAuthOption::VTPtrTypeDisc => cfg.vt_ptr_type_discrimination = *enabled,
305 }
306 }
307
308 Some(cfg)
309 }
310 pub fn fn_attrs(&self) -> Vec<&'static str> {
311 let mut attrs = ::alloc::vec::Vec::new()vec![];
315 if self.aarch64_jump_table_hardening {
316 attrs.push("aarch64-jump-table-hardening");
317 }
318 if self.auth_traps {
319 attrs.push("ptrauth-auth-traps");
320 }
321 if self.function_pointers.is_some() {
322 attrs.push("ptrauth-calls");
323 }
324 if self.indirect_gotos {
325 attrs.push("ptrauth-indirect-gotos");
326 }
327 if self.return_addresses {
328 attrs.push("ptrauth-returns");
329 }
330
331 attrs
332 }
333}
334
335pub struct EarlySession {
338 pub target: Target,
339 pub host: Target,
340 pub opts: config::Options,
341 pub psess: ParseSess,
342}
343
344#[allow(rustc::bad_opt_access)]
346impl EarlySession {
347 #[inline]
348 pub fn dcx(&self) -> DiagCtxtHandle<'_> {
349 self.psess.dcx()
350 }
351
352 #[inline]
353 pub fn source_map(&self) -> &SourceMap {
354 self.psess.source_map()
355 }
356
357 pub fn early_lto(&self) -> LtoCli {
360 self.opts.cg.lto
361 }
362
363 pub fn print_llvm_stats(&self) -> bool {
364 self.opts.unstable_opts.print_codegen_stats
365 }
366
367 pub fn print_llvm_stats_json(&self) -> Option<&String> {
368 self.opts.unstable_opts.print_codegen_stats_json.as_ref()
369 }
370
371 pub fn relocation_model(&self) -> RelocModel {
372 self.opts.cg.relocation_model.unwrap_or(self.target.relocation_model)
373 }
374
375 pub fn code_model(&self) -> Option<CodeModel> {
376 self.opts.cg.code_model.or(self.target.code_model)
377 }
378
379 pub fn tls_model(&self) -> TlsModel {
380 self.opts.unstable_opts.tls_model.unwrap_or(self.target.tls_model)
381 }
382
383 pub fn panic_strategy(&self) -> PanicStrategy {
386 self.opts.cg.panic.unwrap_or(self.target.panic_strategy)
387 }
388
389 pub fn apple_deployment_target(&self) -> apple::OSVersion {
394 let min = apple::OSVersion::minimum_deployment_target(&self.target);
395 let env_var = apple::deployment_target_env_var(&self.target.os);
396
397 if let Ok(deployment_target) = env::var(env_var) {
399 match apple::OSVersion::from_str(&deployment_target) {
400 Ok(version) => {
401 let os_min = apple::OSVersion::os_minimum_deployment_target(&self.target.os);
402 if version < os_min {
407 self.dcx().emit_warn(diagnostics::AppleDeploymentTarget::TooLow {
408 env_var,
409 version: version.fmt_pretty().to_string(),
410 os_min: os_min.fmt_pretty().to_string(),
411 });
412 }
413
414 version.max(min)
416 }
417 Err(error) => {
418 self.dcx()
419 .emit_err(diagnostics::AppleDeploymentTarget::Invalid { env_var, error });
420 min
421 }
422 }
423 } else {
424 min
426 }
427 }
428
429 pub fn sanitizers(&self) -> SanitizerSet {
430 self.opts
431 .unstable_opts
432 .sanitizer
433 .combine_with_defaults(self.target.options.default_sanitizers)
434 }
435
436 pub fn merge_functions(&self) -> MergeFunctions {
437 self.opts.unstable_opts.merge_functions.unwrap_or(self.target.merge_functions)
438 }
439
440 pub fn is_nightly_build(&self) -> bool {
441 self.opts.unstable_features.is_nightly_build()
442 }
443}
444
445#[derive(#[automatically_derived]impl ::core::default::Default for CodegenBackendInit {
#[inline]
fn default() -> Self {
CodegenBackendInit {
global_backend_features: ::core::default::Default::default(),
replaced_rustc_intrinsics: ::core::default::Default::default(),
fallback_rustc_intrinsics: ::core::default::Default::default(),
thin_lto_supported: const true,
}
}
}Default)]
447pub struct CodegenBackendInit {
448 pub global_backend_features: Vec<String>,
450
451 pub replaced_rustc_intrinsics: Vec<Symbol>,
453
454 pub fallback_rustc_intrinsics: Vec<Symbol>,
456
457 pub thin_lto_supported: bool = true,
459}
460
461pub struct Session {
464 pub early_sess: EarlySession,
468 pub wasm_proc_macro_tuple: TargetTuple,
469 pub wasm_proc_macro_target: Target,
470 pub target_tlib_path: SearchPath,
471 pub unstable_features: UnstableFeatures,
472 pub config: Cfg,
473 pub check_config: CheckCfg,
474 proc_macro_quoted_spans: AppendOnlyVec<Span>,
477
478 pub io: CompilerIO,
480
481 pub prof: SelfProfilerRef,
483
484 pub timings: TimingSectionHandler,
486
487 pub code_stats: CodeStats,
489
490 pub lint_store: Option<Arc<dyn DynLintStore>>,
492
493 pub driver_lint_caps: FxHashMap<lint::LintId, lint::Level>,
495
496 pub ctfe_backtrace: Lock<CtfeBacktrace>,
503
504 miri_unleashed_features: Lock<Vec<(Span, Option<Symbol>)>>,
509
510 pub asm_arch: Option<InlineAsmArch>,
512
513 pub internal_target_features: FxIndexSet<Symbol>,
518
519 pub global_backend_features: Vec<String>,
524
525 pub cfg_version: &'static str,
527
528 pub using_internal_features: &'static AtomicBool,
533
534 pub env_depinfo: Lock<FxIndexSet<(Symbol, Option<Symbol>)>>,
536
537 pub file_depinfo: Lock<FxIndexSet<Symbol>>,
539
540 target_filesearch: Arc<FileSearch>,
541 host_filesearch: Arc<FileSearch>,
542 wasm_proc_macro_filesearch: Option<Arc<FileSearch>>,
543
544 pub replaced_rustc_intrinsics: FxHashSet<Symbol>,
547
548 pub fallback_rustc_intrinsics: FxHashSet<Symbol>,
551
552 pub thin_lto_supported: bool,
554
555 pub mir_opt_bisect_eval_count: AtomicUsize,
560
561 pub removed_rustc_main_attr: AtomicBool,
564
565 pub pointer_auth_config: Option<PointerAuthConfig>,
567
568 sanitizers: SanitizerSet,
570}
571
572impl Deref for Session {
573 type Target = EarlySession;
574
575 fn deref(&self) -> &EarlySession {
576 &self.early_sess
577 }
578}
579
580impl DerefMut for Session {
581 fn deref_mut(&mut self) -> &mut EarlySession {
582 &mut self.early_sess
583 }
584}
585
586#[derive(#[automatically_derived]#[doc(hidden)]unsafe impl ::core::clone::TrivialClone
for CodegenUnits {
}
#[automatically_derived]impl ::core::clone::Clone for CodegenUnits {
#[inline]
#[rustc_trivial_field_reads]
fn clone(&self) -> Self {
let _: ::core::clone::AssertParamIsClone<usize>;
*self
}
}Clone, #[automatically_derived]impl ::core::marker::Copy for CodegenUnits { }Copy)]
587pub enum CodegenUnits {
588 User(usize),
591
592 Default(usize),
596}
597
598impl CodegenUnits {
599 pub fn as_usize(self) -> usize {
600 match self {
601 CodegenUnits::User(n) => n,
602 CodegenUnits::Default(n) => n,
603 }
604 }
605}
606
607pub struct LintGroup {
608 pub name: LintName,
609 pub lints: Vec<LintId>,
610 pub is_externally_loaded: bool,
611}
612
613impl Session {
614 pub fn miri_unleashed_feature(&self, span: Span, feature_gate: Option<Symbol>) {
615 self.miri_unleashed_features.lock().push((span, feature_gate));
616 }
617
618 pub fn local_crate_source_file(&self) -> Option<RealFileName> {
619 Some(
620 self.source_map()
621 .path_mapping()
622 .to_real_filename(self.source_map().working_dir(), self.io.input.opt_path()?),
623 )
624 }
625
626 fn check_miri_unleashed_features(&self) -> Option<ErrorGuaranteed> {
627 let mut guar = None;
628 let unleashed_features = self.miri_unleashed_features.lock();
629 if !unleashed_features.is_empty() {
630 let mut must_err = false;
631 self.dcx().emit_warn(diagnostics::SkippingConstChecks {
633 unleashed_features: unleashed_features
634 .iter()
635 .map(|(span, gate)| {
636 gate.map(|gate| {
637 must_err = true;
638 diagnostics::UnleashedFeatureHelp::Named { span: *span, gate }
639 })
640 .unwrap_or(diagnostics::UnleashedFeatureHelp::Unnamed { span: *span })
641 })
642 .collect(),
643 });
644
645 if must_err && self.dcx().has_errors().is_none() {
647 guar = Some(self.dcx().emit_err(diagnostics::NotCircumventFeature));
649 }
650 }
651 guar
652 }
653
654 pub fn finish_diagnostics(&self) -> Option<ErrorGuaranteed> {
656 let mut guar = None;
657 guar = guar.or(self.check_miri_unleashed_features());
658 guar = guar.or(self.dcx().emit_stashed_diagnostics());
659 self.dcx().print_error_count();
660 if self.opts.json_future_incompat {
661 self.dcx().emit_future_breakage_report();
662 }
663 guar
664 }
665
666 pub fn is_test_crate(&self) -> bool {
668 self.opts.test
669 }
670
671 #[track_caller]
673 pub fn create_feature_err<'a>(&'a self, err: impl Diagnostic<'a>, feature: Symbol) -> Diag<'a> {
674 let mut err = self.dcx().create_err(err);
675 if err.code.is_none() {
676 err.code(E0658);
677 }
678 diagnostics::add_feature_diagnostics(&mut err, self, feature);
679 err
680 }
681
682 pub fn record_trimmed_def_paths(&self) {
685 if self.opts.unstable_opts.print_type_sizes
686 || self.opts.unstable_opts.query_dep_graph
687 || self.opts.unstable_opts.dump_mir.is_some()
688 || self.opts.unstable_opts.unpretty.is_some()
689 || self.prof.is_args_recording_enabled()
690 || self.opts.output_types.contains_key(&OutputType::Mir)
691 || std::env::var_os("RUSTC_LOG").is_some()
692 {
693 return;
694 }
695
696 self.dcx().set_must_produce_diag()
697 }
698
699 pub fn proc_macro_quoted_spans(&self) -> impl Iterator<Item = (usize, Span)> {
700 self.proc_macro_quoted_spans.iter_enumerated()
703 }
704
705 pub fn save_proc_macro_span(&self, span: Span) -> usize {
706 self.proc_macro_quoted_spans.push(span)
707 }
708
709 pub fn enable_internal_lints(&self) -> bool {
713 self.unstable_options() && !self.opts.actually_rustdoc
714 }
715
716 pub fn instrument_coverage(&self) -> bool {
717 self.opts.cg.instrument_coverage() != InstrumentCoverage::No
718 }
719
720 pub fn instrument_coverage_branch(&self) -> bool {
721 self.instrument_coverage()
722 && self.opts.unstable_opts.coverage_options.level >= CoverageLevel::Branch
723 }
724
725 pub fn instrument_coverage_condition(&self) -> bool {
726 self.instrument_coverage()
727 && self.opts.unstable_opts.coverage_options.level >= CoverageLevel::Condition
728 }
729
730 pub fn coverage_options(&self) -> &CoverageOptions {
734 &self.opts.unstable_opts.coverage_options
735 }
736
737 pub fn is_sanitizer_cfi_enabled(&self) -> bool {
738 self.sanitizers().contains(SanitizerSet::CFI)
739 }
740
741 pub fn is_sanitizer_cfi_canonical_jump_tables_disabled(&self) -> bool {
742 self.opts.unstable_opts.sanitizer_cfi_canonical_jump_tables == Some(false)
743 }
744
745 pub fn is_sanitizer_cfi_canonical_jump_tables_enabled(&self) -> bool {
746 self.opts.unstable_opts.sanitizer_cfi_canonical_jump_tables == Some(true)
747 }
748
749 pub fn is_sanitizer_cfi_generalize_pointers_enabled(&self) -> bool {
750 self.opts.unstable_opts.sanitizer_cfi_generalize_pointers == Some(true)
751 }
752
753 pub fn is_sanitizer_cfi_normalize_integers_enabled(&self) -> bool {
754 self.opts.unstable_opts.sanitizer_cfi_normalize_integers == Some(true)
755 }
756
757 pub fn is_sanitizer_cfi_recover_enabled(&self) -> bool {
758 self.opts.unstable_opts.sanitizer_cfi_recover == Some(true)
759 }
760
761 pub fn is_sanitizer_cfi_diag_enabled(&self) -> bool {
762 self.opts.unstable_opts.sanitizer_cfi_diag == Some(true)
763 }
764
765 pub fn is_sanitizer_cfi_minimal_runtime_enabled(&self) -> bool {
766 self.opts.unstable_opts.sanitizer_cfi_minimal_runtime == Some(true)
767 }
768
769 pub fn is_sanitizer_kcfi_arity_enabled(&self) -> bool {
770 self.opts.unstable_opts.sanitizer_kcfi_arity == Some(true)
771 }
772
773 pub fn is_sanitizer_kcfi_enabled(&self) -> bool {
774 self.sanitizers().contains(SanitizerSet::KCFI)
775 }
776
777 pub fn is_split_lto_unit_enabled(&self) -> bool {
778 self.opts.unstable_opts.split_lto_unit == Some(true)
779 }
780
781 pub fn crt_static(&self, crate_type: Option<CrateType>) -> bool {
783 if !self.target.crt_static_respected {
784 return self.target.crt_static_default;
786 }
787
788 let requested_features = self.opts.cg.target_feature.split(',');
789 let found_negative = requested_features.clone().any(|r| r == "-crt-static");
790 let found_positive = requested_features.clone().any(|r| r == "+crt-static");
791
792 #[allow(rustc::bad_opt_access)]
794 if found_positive || found_negative {
795 found_positive
796 } else if crate_type == Some(CrateType::ProcMacro)
797 || crate_type == None && self.opts.crate_types.contains(&CrateType::ProcMacro)
798 {
799 false
803 } else {
804 self.target.crt_static_default
805 }
806 }
807
808 pub fn is_wasi_reactor(&self) -> bool {
809 self.target.options.os == Os::Wasi
810 && #[allow(non_exhaustive_omitted_patterns)] match self.opts.unstable_opts.wasi_exec_model
{
Some(config::WasiExecModel::Reactor) => true,
_ => false,
}matches!(
811 self.opts.unstable_opts.wasi_exec_model,
812 Some(config::WasiExecModel::Reactor)
813 )
814 }
815
816 pub fn target_can_use_split_dwarf(&self) -> bool {
818 self.target.debuginfo_kind == DebuginfoKind::Dwarf
819 }
820
821 pub fn target_filesearch(&self) -> &filesearch::FileSearch {
822 &self.target_filesearch
823 }
824 pub fn host_filesearch(&self) -> &filesearch::FileSearch {
825 &self.host_filesearch
826 }
827 pub fn wasm_proc_macro_filesearch(&self) -> &filesearch::FileSearch {
828 self.wasm_proc_macro_filesearch.as_ref().expect("wasm_filesearch not set")
829 }
830
831 pub fn get_tools_search_paths(&self, self_contained: bool) -> Vec<PathBuf> {
835 let search_paths = self
836 .opts
837 .sysroot
838 .all_paths()
839 .map(|sysroot| filesearch::make_target_bin_path(&sysroot, config::host_tuple()));
840
841 if self_contained {
842 search_paths.flat_map(|path| [path.clone(), path.join("self-contained")]).collect()
846 } else {
847 search_paths.collect()
848 }
849 }
850
851 pub fn is_rust_2015(&self) -> bool {
853 self.edition().is_rust_2015()
854 }
855
856 pub fn at_least_rust_2018(&self) -> bool {
858 self.edition().at_least_rust_2018()
859 }
860
861 pub fn at_least_rust_2021(&self) -> bool {
863 self.edition().at_least_rust_2021()
864 }
865
866 pub fn at_least_rust_2024(&self) -> bool {
868 self.edition().at_least_rust_2024()
869 }
870
871 pub fn needs_plt(&self) -> bool {
873 let want_plt = self.target.plt_by_default;
876
877 let dbg_opts = &self.opts.unstable_opts;
878
879 let relro_level = self.opts.cg.relro_level.unwrap_or(self.target.relro_level);
880
881 let full_relro = RelroLevel::Full == relro_level;
885
886 dbg_opts.plt.unwrap_or(want_plt || !full_relro)
889 }
890
891 pub fn emit_lifetime_markers(&self) -> bool {
893 self.opts.optimize != config::OptLevel::No
894 || self.sanitizers().intersects(SanitizerSet::ADDRESS | SanitizerSet::KERNELADDRESS | SanitizerSet::MEMORY | SanitizerSet::HWADDRESS | SanitizerSet::KERNELHWADDRESS)
901 || self.opts.unstable_opts.codegen_emit_retag.is_some()
903 }
904
905 pub fn diagnostic_width(&self) -> usize {
906 let default_column_width = 140;
907 if let Some(width) = self.opts.diagnostic_width {
908 width
909 } else if self.opts.unstable_opts.ui_testing {
910 default_column_width
911 } else {
912 termize::dimensions().map_or(default_column_width, |(w, _)| w)
913 }
914 }
915
916 pub fn default_visibility(&self) -> SymbolVisibility {
918 self.opts
919 .unstable_opts
920 .default_visibility
921 .or(self.target.options.default_visibility)
922 .unwrap_or(SymbolVisibility::Interposable)
923 }
924
925 pub fn staticlib_components(&self, verbatim: bool) -> (&str, &str) {
926 if verbatim {
927 ("", "")
928 } else {
929 (&*self.target.staticlib_prefix, &*self.target.staticlib_suffix)
930 }
931 }
932
933 pub fn lint_groups_iter(&self) -> Box<dyn Iterator<Item = LintGroup> + '_> {
934 match self.lint_store {
935 Some(ref lint_store) => lint_store.lint_groups_iter(),
936 None => Box::new(std::iter::empty()),
937 }
938 }
939
940 pub fn resolve_path(&self, path: impl Into<PathBuf>, span: Span) -> PResult<'_, PathBuf> {
944 let path = path.into();
945
946 if !path.is_absolute() {
949 let callsite = span.source_callsite();
950 let source_map = self.source_map();
951 let Some(mut base_path) = source_map.span_to_filename(callsite).into_local_path()
952 else {
953 return Err(self.dcx().create_err(diagnostics::ResolveRelativePath {
954 span,
955 path: source_map
956 .filename_for_diagnostics(&source_map.span_to_filename(callsite))
957 .to_string(),
958 }));
959 };
960 base_path.pop();
961 base_path.push(path);
962 Ok(base_path)
963 } else {
964 match path.components().next() {
967 Some(Prefix(prefix)) if prefix.kind().is_verbatim() => {
968 Ok(path.components().collect())
969 }
970 _ => Ok(path),
971 }
972 }
973 }
974
975 pub fn embed_metadata(&self) -> bool {
977 self.opts.cg.embed_metadata.or(self.opts.unstable_opts.embed_metadata).unwrap_or(true)
978 }
979}
980
981#[allow(rustc::bad_opt_access)]
983impl Session {
984 pub fn verbose_internals(&self) -> bool {
985 self.opts.unstable_opts.verbose_internals
986 }
987
988 pub fn verify_llvm_ir(&self) -> bool {
989 self.opts.unstable_opts.verify_llvm_ir || ::core::option::Option::None::<&'static str>option_env!("RUSTC_VERIFY_LLVM_IR").is_some()
990 }
991
992 pub fn binary_dep_depinfo(&self) -> bool {
993 self.opts.unstable_opts.binary_dep_depinfo
994 }
995
996 pub fn mir_opt_level(&self) -> usize {
997 self.opts.unstable_opts.mir_opt_level.unwrap_or_else(|| self.opts.optimize.mir_opt_level())
998 }
999
1000 pub fn optimization_objective(&self) -> config::OptimizationObjective {
1002 self.opts.optimize.objective()
1003 }
1004
1005 pub fn lto(&self) -> config::Lto {
1007 if self.target.requires_lto {
1009 return config::Lto::Fat;
1010 }
1011
1012 match self.opts.cg.lto {
1016 config::LtoCli::Unspecified => {
1017 }
1020 config::LtoCli::No => {
1021 return config::Lto::No;
1023 }
1024 config::LtoCli::Yes | config::LtoCli::Fat | config::LtoCli::NoParam => {
1025 return config::Lto::Fat;
1027 }
1028 config::LtoCli::Thin => {
1029 if !self.thin_lto_supported {
1031 self.dcx().emit_warn(diagnostics::ThinLtoNotSupportedByBackend);
1033 return config::Lto::Fat;
1034 }
1035 return config::Lto::Thin;
1036 }
1037 }
1038
1039 if !self.thin_lto_supported {
1040 return config::Lto::No;
1041 }
1042
1043 if self.opts.cli_forced_local_thinlto_off {
1052 return config::Lto::No;
1053 }
1054
1055 if let Some(enabled) = self.opts.unstable_opts.thinlto {
1058 if enabled {
1059 return config::Lto::ThinLocal;
1060 } else {
1061 return config::Lto::No;
1062 }
1063 }
1064
1065 if self.codegen_units().as_usize() == 1 {
1068 return config::Lto::No;
1069 }
1070
1071 match self.opts.optimize {
1074 config::OptLevel::No => config::Lto::No,
1075 _ => config::Lto::ThinLocal,
1076 }
1077 }
1078
1079 pub fn fewer_names(&self) -> bool {
1080 if let Some(fewer_names) = self.opts.unstable_opts.fewer_names {
1081 fewer_names
1082 } else {
1083 let more_names = self.opts.output_types.contains_key(&OutputType::LlvmAssembly)
1084 || self.opts.output_types.contains_key(&OutputType::Bitcode)
1085 || self.sanitizers().intersects(SanitizerSet::ADDRESS | SanitizerSet::MEMORY);
1087 !more_names
1088 }
1089 }
1090
1091 pub fn unstable_options(&self) -> bool {
1092 self.opts.unstable_opts.unstable_options
1093 }
1094
1095 pub fn is_nightly_build(&self) -> bool {
1096 self.opts.unstable_features.is_nightly_build()
1097 }
1098
1099 pub fn overflow_checks(&self) -> bool {
1100 self.opts.cg.overflow_checks.unwrap_or(self.opts.debug_assertions)
1101 }
1102
1103 pub fn ub_checks(&self) -> bool {
1104 self.opts.unstable_opts.ub_checks.unwrap_or(self.opts.debug_assertions)
1105 }
1106
1107 pub fn contract_checks(&self) -> bool {
1108 self.opts.unstable_opts.contract_checks.unwrap_or(false)
1109 }
1110
1111 pub fn direct_access_external_data(&self) -> Option<bool> {
1112 self.opts
1113 .unstable_opts
1114 .direct_access_external_data
1115 .or(self.target.direct_access_external_data)
1116 }
1117
1118 pub fn split_debuginfo(&self) -> SplitDebuginfo {
1119 self.opts.cg.split_debuginfo.unwrap_or(self.target.split_debuginfo)
1120 }
1121
1122 pub fn dwarf_version(&self) -> u32 {
1124 self.opts
1125 .cg
1126 .dwarf_version
1127 .or(self.opts.unstable_opts.dwarf_version)
1128 .unwrap_or(self.target.default_dwarf_version)
1129 }
1130
1131 pub fn stack_protector(&self) -> StackProtector {
1132 if self.target.options.supports_stack_protector {
1133 self.opts.unstable_opts.stack_protector
1134 } else {
1135 StackProtector::None
1136 }
1137 }
1138
1139 pub fn branch_protection(&self) -> Option<BranchProtection> {
1145 let mut bp = self.opts.unstable_opts.branch_protection;
1146
1147 if let Some(bp) = bp.as_mut() {
1148 if self.target.os == Os::Windows && self.target.arch == Arch::AArch64 {
1152 if let Some(pac_ret) = bp.pac_ret.as_mut()
1153 && pac_ret.key == PAuthKey::A
1154 {
1155 pac_ret.key = PAuthKey::B;
1156 }
1157 }
1158 }
1159
1160 bp
1161 }
1162
1163 pub fn must_emit_unwind_tables(&self) -> bool {
1164 self.target.requires_uwtable
1193 || self
1194 .opts
1195 .cg
1196 .force_unwind_tables
1197 .unwrap_or(self.panic_strategy().unwinds() || self.target.default_uwtable)
1198 }
1199
1200 pub fn codegen_units(&self) -> CodegenUnits {
1203 if let Some(n) = self.opts.cli_forced_codegen_units {
1204 return CodegenUnits::User(n);
1205 }
1206 if let Some(n) = self.target.default_codegen_units {
1207 return CodegenUnits::Default(n as usize);
1208 }
1209
1210 if self.opts.incremental.is_some() {
1214 return CodegenUnits::Default(256);
1215 }
1216
1217 CodegenUnits::Default(16)
1268 }
1269
1270 pub fn teach(&self, code: ErrCode) -> bool {
1271 self.opts.unstable_opts.teach && self.dcx().must_teach(code)
1272 }
1273
1274 pub fn edition(&self) -> Edition {
1275 self.opts.edition
1276 }
1277
1278 pub fn link_dead_code(&self) -> bool {
1279 self.opts.cg.link_dead_code.unwrap_or(false)
1280 }
1281
1282 pub fn sanitizers(&self) -> SanitizerSet {
1283 self.sanitizers
1284 }
1285
1286 pub fn pointer_authentication(&self) -> bool {
1287 self.pointer_auth_config.is_some()
1288 }
1289
1290 pub fn pointer_authentication_functions(&self) -> Option<&PointerAuthSchema> {
1291 self.pointer_auth_config.as_ref().and_then(|cfg| cfg.function_pointers.as_ref())
1292 }
1293
1294 pub fn pointer_authentication_init_fini(&self) -> Option<&PointerAuthSchema> {
1295 self.pointer_auth_config.as_ref().and_then(|cfg| cfg.init_fini.as_ref())
1296 }
1297}
1298
1299#[allow(rustc::bad_opt_access)]
1301fn default_emitter(sopts: &config::Options, source_map: Arc<SourceMap>) -> Box<DynEmitter> {
1302 let macro_backtrace = sopts.unstable_opts.macro_backtrace;
1303 let track_diagnostics = sopts.unstable_opts.track_diagnostics;
1304 let terminal_url = match sopts.unstable_opts.terminal_urls {
1305 TerminalUrl::Auto => {
1306 match (std::env::var("COLORTERM").as_deref(), std::env::var("TERM").as_deref()) {
1307 (Ok("truecolor"), Ok("xterm-256color"))
1308 if sopts.unstable_features.is_nightly_build() =>
1309 {
1310 TerminalUrl::Yes
1311 }
1312 _ => TerminalUrl::No,
1313 }
1314 }
1315 t => t,
1316 };
1317
1318 let source_map = if sopts.unstable_opts.link_only { None } else { Some(source_map) };
1319
1320 match sopts.error_format {
1321 ErrorOutputType::HumanReadable { kind, color_config } => match kind {
1322 HumanReadableErrorType { no_graphics, short, unicode } => {
1323 let emitter = AnnotateSnippetEmitter::new(stderr_destination(color_config))
1324 .sm(source_map)
1325 .short_message(short)
1326 .diagnostic_width(sopts.diagnostic_width)
1327 .macro_backtrace(macro_backtrace)
1328 .track_diagnostics(track_diagnostics)
1329 .terminal_url(terminal_url)
1330 .theme(if unicode { OutputTheme::Unicode } else { OutputTheme::Ascii })
1331 .ignored_directories_in_source_blocks(
1332 sopts.unstable_opts.ignore_directory_in_diagnostics_source_blocks.clone(),
1333 )
1334 .no_graphics(no_graphics);
1335 Box::new(emitter.ui_testing(sopts.unstable_opts.ui_testing))
1336 }
1337 },
1338 ErrorOutputType::Json { pretty, json_rendered, color_config } => Box::new(
1339 JsonEmitter::new(
1340 Box::new(io::BufWriter::new(io::stderr())),
1341 source_map,
1342 pretty,
1343 json_rendered,
1344 color_config,
1345 )
1346 .ui_testing(sopts.unstable_opts.ui_testing)
1347 .ignored_directories_in_source_blocks(
1348 sopts.unstable_opts.ignore_directory_in_diagnostics_source_blocks.clone(),
1349 )
1350 .diagnostic_width(sopts.diagnostic_width)
1351 .macro_backtrace(macro_backtrace)
1352 .track_diagnostics(track_diagnostics)
1353 .terminal_url(terminal_url),
1354 ),
1355 }
1356}
1357
1358#[allow(rustc::bad_opt_access)]
1360pub fn build_early_session(
1361 sopts: config::Options,
1362 target: Target,
1363 ice_file: Option<PathBuf>,
1364) -> EarlySession {
1365 let warnings_allow = sopts
1369 .lint_opts
1370 .iter()
1371 .rfind(|&(key, _)| *key == "warnings")
1372 .is_some_and(|&(_, level)| level == lint::Allow);
1373 let cap_lints_allow = sopts.lint_cap.is_some_and(|cap| cap == lint::Allow);
1374 let can_emit_warnings = !(warnings_allow || cap_lints_allow);
1375
1376 let source_map = rustc_span::source_map::get_source_map().unwrap();
1377 let emitter = default_emitter(&sopts, Arc::clone(&source_map));
1378
1379 let mut dcx =
1380 DiagCtxt::new(emitter).with_flags(sopts.unstable_opts.dcx_flags(can_emit_warnings));
1381 if let Some(ice_file) = ice_file {
1382 dcx = dcx.with_ice_file(ice_file);
1383 }
1384
1385 if let Some(msrv) = sopts.unstable_opts.hint_msrv {
1386 dcx = dcx.with_msrv(msrv);
1387 }
1388
1389 let host_triple = TargetTuple::from_tuple(config::host_tuple());
1390 let (host, target_warnings) =
1391 Target::search(&host_triple, sopts.sysroot.path(), sopts.unstable_opts.unstable_options)
1392 .unwrap_or_else(|e| {
1393 dcx.handle().fatal(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("Error loading host specification: {0}",
e))
})format!("Error loading host specification: {e}"))
1394 });
1395 for warning in target_warnings.warning_messages() {
1396 dcx.handle().warn(warning)
1397 }
1398
1399 let psess = ParseSess::with_dcx(dcx, source_map);
1400
1401 EarlySession { target, host, opts: sopts, psess }
1402}
1403
1404#[allow(rustc::bad_opt_access)]
1406pub fn build_session(
1407 early_sess: EarlySession,
1408 codegen_backend_init: CodegenBackendInit,
1409 io: CompilerIO,
1410 driver_lint_caps: FxHashMap<lint::LintId, lint::Level>,
1411 cfg_version: &'static str,
1412 using_internal_features: &'static AtomicBool,
1413) -> Session {
1414 let EarlySession { target, host, opts: sopts, psess } = &early_sess;
1415 let dcx = psess.dcx();
1416
1417 let wasm_proc_macro_tuple = TargetTuple::from_tuple("wasm32-wasip2");
1418 let (wasm_proc_macro_target, target_warnings) = Target::search(
1419 &wasm_proc_macro_tuple,
1420 sopts.sysroot.path(),
1421 sopts.unstable_opts.unstable_options,
1422 )
1423 .unwrap_or_else(|e| {
1424 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}"))
1425 });
1426 for warning in target_warnings.warning_messages() {
1427 dcx.warn(warning)
1428 }
1429
1430 let self_profiler = if let SwitchWithOptPath::Enabled(ref d) = sopts.unstable_opts.self_profile
1431 {
1432 let directory = if let Some(directory) = d { directory } else { std::path::Path::new(".") };
1433
1434 let profiler = SelfProfiler::new(
1435 directory,
1436 sopts.crate_name.as_deref(),
1437 sopts.unstable_opts.self_profile_events.as_deref(),
1438 &sopts.unstable_opts.self_profile_counter,
1439 );
1440 match profiler {
1441 Ok(profiler) => Some(Arc::new(profiler)),
1442 Err(e) => {
1443 dcx.emit_warn(diagnostics::FailedToCreateProfiler { err: e.to_string() });
1444 None
1445 }
1446 }
1447 } else {
1448 None
1449 };
1450
1451 let host_triple = config::host_tuple();
1452 let target_triple = sopts.target_triple.tuple();
1453 let host_tlib_path = SearchPath::from_sysroot_and_triple(sopts.sysroot.path(), host_triple);
1455 let target_tlib_path = SearchPath::from_sysroot_and_triple(sopts.sysroot.path(), target_triple);
1456 let wasm_proc_macro_tlib_path =
1457 SearchPath::from_sysroot_and_triple(sopts.sysroot.path(), wasm_proc_macro_tuple.tuple());
1458
1459 let prof = SelfProfilerRef::new(
1460 self_profiler,
1461 sopts.unstable_opts.time_passes.then(|| sopts.unstable_opts.time_passes_format),
1462 );
1463
1464 let ctfe_backtrace = Lock::new(match env::var("RUSTC_CTFE_BACKTRACE") {
1465 Ok(ref val) if val == "immediate" => CtfeBacktrace::Immediate,
1466 Ok(ref val) if val != "0" => CtfeBacktrace::Capture,
1467 _ => CtfeBacktrace::Disabled,
1468 });
1469
1470 let asm_arch = if target.allow_asm { InlineAsmArch::from_arch(&target.arch) } else { None };
1471 let target_filesearch = Arc::new(filesearch::FileSearch::new(
1472 &sopts.search_paths,
1473 &target_tlib_path,
1474 &target,
1475 sopts.unstable_opts.implicit_sysroot_deps,
1476 ));
1477 let host_filesearch = if target == host {
1478 Arc::clone(&target_filesearch)
1479 } else {
1480 Arc::new(filesearch::FileSearch::new(
1481 &sopts.search_paths,
1482 &host_tlib_path,
1483 &host,
1484 sopts.unstable_opts.implicit_sysroot_deps,
1485 ))
1486 };
1487 let wasm_proc_macro_filesearch = if sopts.unstable_opts.wasm_proc_macros {
1488 Some(Arc::new(FileSearch::new(
1489 &sopts.search_paths,
1490 &wasm_proc_macro_tlib_path,
1491 &wasm_proc_macro_target,
1492 sopts.unstable_opts.implicit_sysroot_deps,
1493 )))
1494 } else {
1495 None
1496 };
1497
1498 let timings = TimingSectionHandler::new(sopts.json_timings);
1499
1500 let pointer_auth_config: Option<PointerAuthConfig> =
1501 PointerAuthConfig::from_raw(&sopts.unstable_opts.pointer_authentication, &target);
1502
1503 let sanitizers = early_sess.sanitizers();
1506
1507 let CodegenBackendInit {
1508 global_backend_features,
1509 replaced_rustc_intrinsics: replaced_intrinsics,
1510 fallback_rustc_intrinsics: fallback_intrinsics,
1511 thin_lto_supported,
1512 } = codegen_backend_init;
1513
1514 let sess = Session {
1515 early_sess,
1516 wasm_proc_macro_tuple,
1517 wasm_proc_macro_target,
1518 target_tlib_path,
1519 unstable_features: UnstableFeatures::from_environment(None),
1520 config: Cfg::default(),
1521 check_config: CheckCfg::default(),
1522 proc_macro_quoted_spans: Default::default(),
1523 io,
1524 prof,
1525 timings,
1526 code_stats: Default::default(),
1527 lint_store: None,
1528 driver_lint_caps,
1529 ctfe_backtrace,
1530 miri_unleashed_features: Lock::new(Default::default()),
1531 asm_arch,
1532 internal_target_features: Default::default(),
1533 global_backend_features,
1534 cfg_version,
1535 using_internal_features,
1536 env_depinfo: Default::default(),
1537 file_depinfo: Default::default(),
1538 target_filesearch,
1539 host_filesearch,
1540 wasm_proc_macro_filesearch,
1541 replaced_rustc_intrinsics: FxHashSet::from_iter(replaced_intrinsics),
1542 fallback_rustc_intrinsics: FxHashSet::from_iter(fallback_intrinsics),
1543 thin_lto_supported,
1544 mir_opt_bisect_eval_count: AtomicUsize::new(0),
1545 removed_rustc_main_attr: AtomicBool::new(false),
1546 pointer_auth_config,
1547 sanitizers,
1548 };
1549
1550 validate_commandline_args_with_session_available(&sess);
1551
1552 sess
1553}
1554
1555pub fn generate_proc_macro_decls_symbol(stable_crate_id: StableCrateId) -> String {
1556 ::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())
1557}
1558
1559#[allow(rustc::bad_opt_access)]
1565fn validate_commandline_args_with_session_available(sess: &Session) {
1566 if sess.opts.cg.linker_plugin_lto.enabled()
1574 && sess.opts.cg.prefer_dynamic
1575 && sess.target.is_like_windows
1576 {
1577 sess.dcx().emit_err(diagnostics::LinkerPluginToWindowsNotSupported);
1578 }
1579
1580 if sess
1581 .pointer_auth_config
1582 .as_ref()
1583 .and_then(|cfg| cfg.function_pointers.as_ref())
1584 .is_some_and(|schema| #[allow(non_exhaustive_omitted_patterns)] match schema.discrimination_kind {
PointerAuthDiscrimination::Type => true,
_ => false,
}matches!(schema.discrimination_kind, PointerAuthDiscrimination::Type))
1585 {
1586 sess.dcx().emit_err(
1587 diagnostics::PointerAuthenticationTypeDiscriminationNotSupportedForTarget {
1588 target_triple: &sess.opts.target_triple,
1589 },
1590 );
1591 }
1592
1593 if sess.target.cfg_abi != CfgAbi::Pauthtest
1594 && !sess.opts.unstable_opts.pointer_authentication.is_empty()
1595 {
1596 sess.dcx().emit_warn(diagnostics::PointerAuthenticationNotSupportedForTarget {
1597 target_triple: &sess.opts.target_triple,
1598 });
1599 }
1600
1601 if let Some(ref path) = sess.opts.cg.profile_use {
1604 if !path.exists() {
1605 sess.dcx().emit_err(diagnostics::ProfileUseFileDoesNotExist { path });
1606 }
1607 }
1608
1609 if let Some(ref path) = sess.opts.cg.profile_sample_use {
1611 if !path.exists() {
1612 sess.dcx().emit_err(diagnostics::ProfileSampleUseFileDoesNotExist { path });
1613 }
1614 }
1615
1616 if let Some(include_uwtables) = sess.opts.cg.force_unwind_tables {
1618 if sess.target.requires_uwtable && !include_uwtables {
1619 sess.dcx().emit_err(diagnostics::TargetRequiresUnwindTables);
1620 }
1621 }
1622
1623 let supported_sanitizers = sess.target.options.supported_sanitizers;
1625 let mut unsupported_sanitizers = sess.sanitizers() - supported_sanitizers;
1626 if sess.opts.unstable_opts.fixed_x18 && sess.target.arch == Arch::AArch64 {
1629 unsupported_sanitizers -= SanitizerSet::SHADOWCALLSTACK;
1630 }
1631 match unsupported_sanitizers.into_iter().count() {
1632 0 => {}
1633 1 => {
1634 sess.dcx().emit_err(diagnostics::SanitizerNotSupported {
1635 us: unsupported_sanitizers.to_string(),
1636 });
1637 }
1638 _ => {
1639 sess.dcx().emit_err(diagnostics::SanitizersNotSupported {
1640 us: unsupported_sanitizers.to_string(),
1641 });
1642 }
1643 }
1644
1645 if let Some((first, second)) = sess.sanitizers().mutually_exclusive() {
1647 sess.dcx().emit_err(diagnostics::CannotMixAndMatchSanitizers {
1648 first: first.to_string(),
1649 second: second.to_string(),
1650 });
1651 }
1652
1653 if sess.crt_static(None) && !sess.sanitizers().is_empty() && !sess.target.is_like_msvc {
1655 sess.dcx().emit_err(diagnostics::CannotEnableCrtStaticLinux);
1656 }
1657
1658 if sess.crt_static(None) && sess.target.cfg_abi == CfgAbi::Pauthtest {
1662 sess.dcx().emit_err(diagnostics::CannotEnableCrtStaticPointerAuth);
1663 }
1664
1665 if sess.is_sanitizer_cfi_enabled()
1667 && !(sess.lto() == config::Lto::Fat || sess.opts.cg.linker_plugin_lto.enabled())
1668 {
1669 sess.dcx().emit_err(diagnostics::SanitizerCfiRequiresLto);
1670 }
1671
1672 if sess.is_sanitizer_kcfi_enabled() && sess.panic_strategy().unwinds() {
1674 sess.dcx().emit_err(diagnostics::SanitizerKcfiRequiresPanicAbort);
1675 }
1676
1677 if sess.is_sanitizer_cfi_enabled()
1679 && sess.lto() == config::Lto::Fat
1680 && (sess.codegen_units().as_usize() != 1)
1681 {
1682 sess.dcx().emit_err(diagnostics::SanitizerCfiRequiresSingleCodegenUnit);
1683 }
1684
1685 if sess.is_sanitizer_cfi_canonical_jump_tables_disabled() {
1687 if !sess.is_sanitizer_cfi_enabled() {
1688 sess.dcx().emit_err(diagnostics::SanitizerCfiCanonicalJumpTablesRequiresCfi);
1689 }
1690 }
1691
1692 if sess.is_sanitizer_kcfi_arity_enabled() && !sess.is_sanitizer_kcfi_enabled() {
1694 sess.dcx().emit_err(diagnostics::SanitizerKcfiArityRequiresKcfi);
1695 }
1696
1697 if sess.is_sanitizer_cfi_generalize_pointers_enabled() {
1699 if !(sess.is_sanitizer_cfi_enabled() || sess.is_sanitizer_kcfi_enabled()) {
1700 sess.dcx().emit_err(diagnostics::SanitizerCfiGeneralizePointersRequiresCfi);
1701 }
1702 }
1703
1704 if sess.is_sanitizer_cfi_recover_enabled() {
1706 if !sess.is_sanitizer_cfi_enabled() {
1707 sess.dcx().emit_err(diagnostics::SanitizerCfiRecoverRequiresCfi);
1708 }
1709 }
1710
1711 if sess.is_sanitizer_cfi_diag_enabled() {
1713 if !sess.is_sanitizer_cfi_enabled() {
1714 sess.dcx().emit_err(diagnostics::SanitizerCfiDiagRequiresCfi);
1715 }
1716 }
1717
1718 if sess.is_sanitizer_cfi_minimal_runtime_enabled() {
1720 if !sess.is_sanitizer_cfi_enabled() {
1721 sess.dcx().emit_err(diagnostics::SanitizerCfiMinimalRuntimeRequiresCfi);
1722 } else if !(sess.is_sanitizer_cfi_recover_enabled() || sess.is_sanitizer_cfi_diag_enabled())
1723 {
1724 sess.dcx().emit_err(diagnostics::SanitizerCfiMinimalRuntimeRequiresCfiRecoverOrDiag);
1725 }
1726 }
1727
1728 if sess.is_sanitizer_cfi_normalize_integers_enabled() {
1730 if !(sess.is_sanitizer_cfi_enabled() || sess.is_sanitizer_kcfi_enabled()) {
1731 sess.dcx().emit_err(diagnostics::SanitizerCfiNormalizeIntegersRequiresCfi);
1732 }
1733 }
1734
1735 if sess.is_split_lto_unit_enabled()
1737 && !(sess.lto() == config::Lto::Fat
1738 || sess.lto() == config::Lto::Thin
1739 || sess.opts.cg.linker_plugin_lto.enabled())
1740 {
1741 sess.dcx().emit_err(diagnostics::SplitLtoUnitRequiresLto);
1742 }
1743
1744 if sess.lto() != config::Lto::Fat {
1746 if sess.opts.unstable_opts.virtual_function_elimination {
1747 sess.dcx().emit_err(diagnostics::UnstableVirtualFunctionElimination);
1748 }
1749 }
1750
1751 if sess.opts.unstable_opts.stack_protector != StackProtector::None {
1752 if !sess.target.options.supports_stack_protector {
1753 sess.dcx().emit_warn(diagnostics::StackProtectorNotSupportedForTarget {
1754 stack_protector: sess.opts.unstable_opts.stack_protector,
1755 target_triple: &sess.opts.target_triple,
1756 });
1757 }
1758 }
1759
1760 if sess.opts.unstable_opts.small_data_threshold.is_some() {
1761 if sess.target.small_data_threshold_support() == SmallDataThresholdSupport::None {
1762 sess.dcx().emit_warn(diagnostics::SmallDataThresholdNotSupportedForTarget {
1763 target_triple: &sess.opts.target_triple,
1764 })
1765 }
1766 }
1767
1768 if sess.opts.unstable_opts.branch_protection.is_some() && sess.target.arch != Arch::AArch64 {
1769 sess.dcx().emit_err(diagnostics::BranchProtectionRequiresAArch64);
1770 }
1771
1772 if let Some(dwarf_version) =
1773 sess.opts.cg.dwarf_version.or(sess.opts.unstable_opts.dwarf_version)
1774 {
1775 if dwarf_version < 2 || dwarf_version > 5 {
1777 sess.dcx().emit_err(diagnostics::UnsupportedDwarfVersion { dwarf_version });
1778 }
1779 }
1780
1781 if !sess.target.options.supported_split_debuginfo.contains(&sess.split_debuginfo())
1782 && !sess.opts.unstable_opts.unstable_options
1783 {
1784 sess.dcx().emit_err(diagnostics::SplitDebugInfoUnstablePlatform {
1785 debuginfo: sess.split_debuginfo(),
1786 });
1787 }
1788
1789 if sess.opts.unstable_opts.embed_source {
1790 let dwarf_version = sess.dwarf_version();
1791
1792 if dwarf_version < 5 {
1793 sess.dcx()
1794 .emit_warn(diagnostics::EmbedSourceInsufficientDwarfVersion { dwarf_version });
1795 }
1796
1797 if sess.opts.debuginfo == DebugInfo::None {
1798 sess.dcx().emit_warn(diagnostics::EmbedSourceRequiresDebugInfo);
1799 }
1800 }
1801
1802 if let InstrumentMcount::Fentry(opts) = sess.opts.unstable_opts.instrument_mcount {
1803 if !sess.target.options.supports_fentry {
1804 sess.dcx()
1805 .emit_err(diagnostics::InstrumentationNotSupported { us: "fentry".to_string() });
1806 }
1807 if (opts.no_call || opts.record) && sess.target.arch != Arch::S390x {
1808 sess.dcx()
1809 .emit_err(diagnostics::InstrumentationNotSupported { us: "fentry-*".to_string() });
1810 }
1811 }
1812
1813 if sess.opts.unstable_opts.instrument_xray.is_some() && !sess.target.options.supports_xray {
1814 sess.dcx().emit_err(diagnostics::InstrumentationNotSupported { us: "XRay".to_string() });
1815 }
1816
1817 if let Some(flavor) = sess.opts.cg.linker_flavor
1818 && let Some(compatible_list) = sess.target.linker_flavor.check_compatibility(flavor)
1819 {
1820 let flavor = flavor.desc();
1821 sess.dcx().emit_err(diagnostics::IncompatibleLinkerFlavor { flavor, compatible_list });
1822 }
1823
1824 if sess.opts.unstable_opts.function_return != FunctionReturn::default() {
1825 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) {
1826 sess.dcx().emit_err(diagnostics::FunctionReturnRequiresX86OrX8664);
1827 }
1828 }
1829
1830 if sess.opts.unstable_opts.indirect_branch_cs_prefix {
1831 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) {
1832 sess.dcx().emit_err(diagnostics::IndirectBranchCsPrefixRequiresX86OrX8664);
1833 }
1834 }
1835
1836 if let Some(regparm) = sess.opts.unstable_opts.regparm {
1837 if regparm > 3 {
1838 sess.dcx().emit_err(diagnostics::UnsupportedRegparm { regparm });
1839 }
1840 if sess.target.arch != Arch::X86 {
1841 sess.dcx().emit_err(diagnostics::UnsupportedRegparmArch);
1842 }
1843 }
1844 if sess.opts.unstable_opts.reg_struct_return {
1845 if sess.target.arch != Arch::X86 {
1846 sess.dcx().emit_err(diagnostics::UnsupportedRegStructReturnArch);
1847 }
1848 }
1849
1850 match sess.opts.unstable_opts.function_return {
1854 FunctionReturn::Keep => (),
1855 FunctionReturn::ThunkExtern => {
1856 if let Some(code_model) = sess.code_model()
1859 && code_model == CodeModel::Large
1860 {
1861 sess.dcx()
1862 .emit_err(diagnostics::FunctionReturnThunkExternRequiresNonLargeCodeModel);
1863 }
1864 }
1865 }
1866
1867 if sess.opts.unstable_opts.packed_stack {
1868 if sess.target.arch != Arch::S390x {
1869 sess.dcx().emit_err(diagnostics::UnsupportedPackedStack);
1870 }
1871 }
1872
1873 match sess.opts.unstable_opts.pack_coroutine_layout {
1874 PackCoroutineLayout::Classic => {}
1875 PackCoroutineLayout::CapturesOnly => {
1876 sess.dcx().emit_warn(diagnostics::PackCoroutineLayoutNotImplemented);
1877 }
1878 }
1879
1880 if let Some(ref cpu_name) = sess.opts.cg.target_cpu {
1881 if cpu_name == NATIVE_CPU && sess.target.requires_consistent_cpu {
1882 sess.dcx().emit_fatal(diagnostics::NativeTargetCpuNotAllowed {
1883 target_triple: &sess.opts.target_triple,
1884 need_explicit_cpu: sess.target.need_explicit_cpu,
1885 });
1886 }
1887 }
1888}
1889
1890pub struct IncrCompSession {
1892 pub old_session_directory: Option<flock::LockedDir>,
1894 pub new_session_directory: flock::LockedDir,
1897 borrows: Arc<()>,
1898}
1899
1900impl IncrCompSession {
1901 pub fn new(
1902 old_session_directory: Option<flock::LockedDir>,
1903 new_session_directory: flock::LockedDir,
1904 ) -> Self {
1905 IncrCompSession { old_session_directory, new_session_directory, borrows: Arc::new(()) }
1906 }
1907
1908 pub fn borrow(&self) -> BorrowedIncrCompSession {
1909 BorrowedIncrCompSession {
1910 old_session_directory: self.old_session_directory.as_deref().map(ToOwned::to_owned),
1911 new_session_directory: (&*self.new_session_directory).to_owned(),
1912 _borrows: Arc::clone(&self.borrows),
1913 }
1914 }
1915}
1916
1917impl Drop for IncrCompSession {
1918 fn drop(&mut self) {
1919 if !(Arc::strong_count(&self.borrows) == 1) {
{
::core::panicking::panic_fmt(format_args!("Incr comp session dropped while there are still references"));
}
};assert!(
1925 Arc::strong_count(&self.borrows) == 1,
1926 "Incr comp session dropped while there are still references",
1927 );
1928 }
1929}
1930
1931pub struct BorrowedIncrCompSession {
1933 pub old_session_directory: Option<PathBuf>,
1934 pub new_session_directory: PathBuf,
1935 _borrows: Arc<()>,
1936}
1937
1938pub struct EarlyDiagCtxt {
1940 dcx: DiagCtxt,
1941}
1942
1943impl EarlyDiagCtxt {
1944 pub fn new(output: ErrorOutputType) -> Self {
1945 let emitter = mk_emitter(output);
1946 Self { dcx: DiagCtxt::new(emitter) }
1947 }
1948
1949 pub fn set_error_format(&mut self, output: ErrorOutputType) {
1952 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());
1953
1954 let emitter = mk_emitter(output);
1955 self.dcx = DiagCtxt::new(emitter);
1956 }
1957
1958 #[must_use = "raise_fatal must be called on the returned ErrorGuaranteed in order to exit with a non-zero status code"]
1959 pub fn early_err(&self, msg: impl Into<DiagMessage>) -> ErrorGuaranteed {
1960 self.dcx.handle().err(msg)
1961 }
1962
1963 pub fn early_fatal(&self, msg: impl Into<DiagMessage>) -> ! {
1964 self.dcx.handle().fatal(msg)
1965 }
1966
1967 pub fn early_struct_fatal(&self, msg: impl Into<DiagMessage>) -> Diag<'_> {
1968 self.dcx.handle().struct_fatal(msg)
1969 }
1970
1971 pub fn early_warn(&self, msg: impl Into<DiagMessage>) {
1972 self.dcx.handle().warn(msg)
1973 }
1974
1975 pub fn early_struct_warn(&self, msg: impl Into<DiagMessage>) -> Diag<'_> {
1976 self.dcx.handle().struct_warn(msg)
1977 }
1978}
1979
1980fn mk_emitter(output: ErrorOutputType) -> Box<DynEmitter> {
1981 let emitter: Box<DynEmitter> = match output {
1982 ErrorOutputType::HumanReadable { kind, color_config } => match kind {
1983 HumanReadableErrorType { no_graphics, short, unicode } => Box::new(
1984 AnnotateSnippetEmitter::new(stderr_destination(color_config))
1985 .theme(if unicode { OutputTheme::Unicode } else { OutputTheme::Ascii })
1986 .short_message(short)
1987 .no_graphics(no_graphics),
1988 ),
1989 },
1990 ErrorOutputType::Json { pretty, json_rendered, color_config } => {
1991 Box::new(JsonEmitter::new(
1992 Box::new(io::BufWriter::new(io::stderr())),
1993 Some(Arc::new(SourceMap::new(FilePathMapping::empty()))),
1994 pretty,
1995 json_rendered,
1996 color_config,
1997 ))
1998 }
1999 };
2000 emitter
2001}