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