Skip to main content

rustc_metadata/
creader.rs

1//! Validates all used crates and extern libraries and loads their metadata
2
3use std::collections::BTreeMap;
4use std::error::Error;
5use std::path::Path;
6use std::str::FromStr;
7use std::time::Duration;
8use std::{cmp, env, iter};
9
10use rustc_ast::expand::allocator::{ALLOC_ERROR_HANDLER, AllocatorKind, global_fn_name};
11use rustc_ast::{self as ast, *};
12use rustc_data_structures::fx::FxHashSet;
13use rustc_data_structures::owned_slice::OwnedSlice;
14use rustc_data_structures::svh::Svh;
15use rustc_data_structures::sync::{self, FreezeReadGuard, FreezeWriteGuard};
16use rustc_data_structures::unord::UnordMap;
17use rustc_expand::base::SyntaxExtension;
18use rustc_fs_util::try_canonicalize;
19use rustc_hir as hir;
20use rustc_hir::def_id::{CrateNum, LOCAL_CRATE, LocalDefId, StableCrateId};
21use rustc_hir::definitions::Definitions;
22use rustc_index::IndexVec;
23use rustc_middle::bug;
24use rustc_middle::ty::data_structures::IndexSet;
25use rustc_middle::ty::{TyCtxt, TyCtxtFeed};
26use rustc_proc_macro::bridge::client::ProcMacro;
27use rustc_session::config::mitigation_coverage::DeniedPartialMitigationLevel;
28use rustc_session::config::{
29    CrateType, ExtendedTargetModifierInfo, ExternLocation, Externs, OptionsTargetModifiers,
30    TargetModifier,
31};
32use rustc_session::cstore::{CrateDepKind, CrateSource, ExternCrate, ExternCrateSource};
33use rustc_session::output::validate_crate_name;
34use rustc_session::search_paths::PathKind;
35use rustc_session::{Session, lint};
36use rustc_span::def_id::DefId;
37use rustc_span::edition::Edition;
38use rustc_span::{DUMMY_SP, Ident, Span, Symbol, sym};
39use rustc_target::spec::{PanicStrategy, Target};
40use tracing::{debug, info, trace};
41
42use crate::errors;
43use crate::locator::{CrateError, CrateLocator, CratePaths, CrateRejections};
44use crate::rmeta::{
45    CrateDep, CrateMetadata, CrateNumMap, CrateRoot, MetadataBlob, TargetModifiers,
46};
47
48/// The backend's way to give the crate store access to the metadata in a library.
49/// Note that it returns the raw metadata bytes stored in the library file, whether
50/// it is compressed, uncompressed, some weird mix, etc.
51/// rmeta files are backend independent and not handled here.
52pub trait MetadataLoader {
53    fn get_rlib_metadata(&self, target: &Target, filename: &Path) -> Result<OwnedSlice, String>;
54    fn get_dylib_metadata(&self, target: &Target, filename: &Path) -> Result<OwnedSlice, String>;
55}
56
57pub type MetadataLoaderDyn = dyn MetadataLoader + Send + Sync + sync::DynSend + sync::DynSync;
58
59pub struct CStore {
60    metadata_loader: Box<MetadataLoaderDyn>,
61
62    metas: IndexVec<CrateNum, Option<Box<CrateMetadata>>>,
63    injected_panic_runtime: Option<CrateNum>,
64    /// This crate needs an allocator and either provides it itself, or finds it in a dependency.
65    /// If the above is true, then this field denotes the kind of the found allocator.
66    allocator_kind: Option<AllocatorKind>,
67    /// This crate needs an allocation error handler and either provides it itself, or finds it in a dependency.
68    /// If the above is true, then this field denotes the kind of the found allocator.
69    alloc_error_handler_kind: Option<AllocatorKind>,
70    /// This crate has a `#[global_allocator]` item.
71    has_global_allocator: bool,
72    /// This crate has a `#[alloc_error_handler]` item.
73    has_alloc_error_handler: bool,
74
75    /// Names that were used to load the crates via `extern crate` or paths.
76    resolved_externs: UnordMap<Symbol, CrateNum>,
77
78    /// Unused externs of the crate
79    unused_externs: Vec<Symbol>,
80
81    used_extern_options: FxHashSet<Symbol>,
82    /// Whether there was a failure in resolving crate,
83    /// it's used to suppress some diagnostics that would otherwise too noisey.
84    has_crate_resolve_with_fail: bool,
85}
86
87impl std::fmt::Debug for CStore {
88    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
89        f.debug_struct("CStore").finish_non_exhaustive()
90    }
91}
92
93pub enum LoadedMacro {
94    MacroDef {
95        def: MacroDef,
96        ident: Ident,
97        attrs: Vec<hir::Attribute>,
98        span: Span,
99        edition: Edition,
100    },
101    ProcMacro(SyntaxExtension),
102}
103
104pub(crate) struct Library {
105    pub source: CrateSource,
106    pub metadata: MetadataBlob,
107}
108
109enum LoadResult {
110    Previous(CrateNum),
111    Loaded(Library),
112}
113
114struct CrateDump<'a>(&'a CStore);
115
116impl<'a> std::fmt::Debug for CrateDump<'a> {
117    fn fmt(&self, fmt: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
118        fmt.write_fmt(format_args!("resolved crates:\n"))writeln!(fmt, "resolved crates:")?;
119        for (cnum, data) in self.0.iter_crate_data() {
120            fmt.write_fmt(format_args!("  name: {0}\n", data.name()))writeln!(fmt, "  name: {}", data.name())?;
121            fmt.write_fmt(format_args!("  cnum: {0}\n", cnum))writeln!(fmt, "  cnum: {cnum}")?;
122            fmt.write_fmt(format_args!("  hash: {0}\n", data.hash()))writeln!(fmt, "  hash: {}", data.hash())?;
123            fmt.write_fmt(format_args!("  reqd: {0:?}\n", data.dep_kind()))writeln!(fmt, "  reqd: {:?}", data.dep_kind())?;
124            fmt.write_fmt(format_args!("  priv: {0:?}\n", data.is_private_dep()))writeln!(fmt, "  priv: {:?}", data.is_private_dep())?;
125            let CrateSource { dylib, rlib, rmeta, sdylib_interface } = data.source();
126            if let Some(dylib) = dylib {
127                fmt.write_fmt(format_args!("  dylib: {0}\n", dylib.display()))writeln!(fmt, "  dylib: {}", dylib.display())?;
128            }
129            if let Some(rlib) = rlib {
130                fmt.write_fmt(format_args!("   rlib: {0}\n", rlib.display()))writeln!(fmt, "   rlib: {}", rlib.display())?;
131            }
132            if let Some(rmeta) = rmeta {
133                fmt.write_fmt(format_args!("   rmeta: {0}\n", rmeta.display()))writeln!(fmt, "   rmeta: {}", rmeta.display())?;
134            }
135            if let Some(sdylib_interface) = sdylib_interface {
136                fmt.write_fmt(format_args!("   sdylib interface: {0}\n",
        sdylib_interface.display()))writeln!(fmt, "   sdylib interface: {}", sdylib_interface.display())?;
137            }
138        }
139        Ok(())
140    }
141}
142
143/// Reason that a crate is being sourced as a dependency.
144#[derive(#[automatically_derived]
impl<'a> ::core::clone::Clone for CrateOrigin<'a> {
    #[inline]
    fn clone(&self) -> CrateOrigin<'a> {
        let _: ::core::clone::AssertParamIsClone<&'a CratePaths>;
        let _: ::core::clone::AssertParamIsClone<bool>;
        let _: ::core::clone::AssertParamIsClone<&'a CrateDep>;
        *self
    }
}Clone, #[automatically_derived]
impl<'a> ::core::marker::Copy for CrateOrigin<'a> { }Copy)]
145enum CrateOrigin<'a> {
146    /// This crate was a dependency of another crate.
147    IndirectDependency {
148        /// Where this dependency was included from. Should only be used in error messages.
149        dep_root_for_errors: &'a CratePaths,
150        /// True if the parent is private, meaning the dependent should also be private.
151        parent_private: bool,
152        /// Dependency info about this crate.
153        dep: &'a CrateDep,
154    },
155    /// Injected by `rustc`.
156    Injected,
157    /// Provided by `extern crate foo` or as part of the extern prelude.
158    Extern,
159}
160
161impl<'a> CrateOrigin<'a> {
162    /// Return the dependency root, if any.
163    fn dep_root_for_errors(&self) -> Option<&'a CratePaths> {
164        match self {
165            CrateOrigin::IndirectDependency { dep_root_for_errors, .. } => {
166                Some(dep_root_for_errors)
167            }
168            _ => None,
169        }
170    }
171
172    /// Return dependency information, if any.
173    fn dep(&self) -> Option<&'a CrateDep> {
174        match self {
175            CrateOrigin::IndirectDependency { dep, .. } => Some(dep),
176            _ => None,
177        }
178    }
179
180    /// `Some(true)` if the dependency is private or its parent is private, `Some(false)` if the
181    /// dependency is not private, `None` if it could not be determined.
182    fn private_dep(&self) -> Option<bool> {
183        match self {
184            CrateOrigin::IndirectDependency { parent_private, dep, .. } => {
185                Some(dep.is_private || *parent_private)
186            }
187            CrateOrigin::Injected => Some(true),
188            _ => None,
189        }
190    }
191}
192
193impl CStore {
194    pub fn from_tcx(tcx: TyCtxt<'_>) -> FreezeReadGuard<'_, CStore> {
195        FreezeReadGuard::map(tcx.untracked().cstore.read(), |cstore| {
196            cstore.as_any().downcast_ref::<CStore>().expect("`tcx.cstore` is not a `CStore`")
197        })
198    }
199
200    pub fn from_tcx_mut(tcx: TyCtxt<'_>) -> FreezeWriteGuard<'_, CStore> {
201        FreezeWriteGuard::map(tcx.untracked().cstore.write(), |cstore| {
202            cstore.untracked_as_any().downcast_mut().expect("`tcx.cstore` is not a `CStore`")
203        })
204    }
205
206    fn intern_stable_crate_id<'tcx>(
207        &mut self,
208        tcx: TyCtxt<'tcx>,
209        root: &CrateRoot,
210    ) -> Result<TyCtxtFeed<'tcx, CrateNum>, CrateError> {
211        match (&self.metas.len(), &tcx.untracked().stable_crate_ids.read().len()) {
    (left_val, right_val) => {
        if !(*left_val == *right_val) {
            let kind = ::core::panicking::AssertKind::Eq;
            ::core::panicking::assert_failed(kind, &*left_val, &*right_val,
                ::core::option::Option::None);
        }
    }
};assert_eq!(self.metas.len(), tcx.untracked().stable_crate_ids.read().len());
212        let num = tcx.create_crate_num(root.stable_crate_id()).map_err(|existing| {
213            // Check for (potential) conflicts with the local crate
214            if existing == LOCAL_CRATE {
215                CrateError::SymbolConflictsCurrent(root.name())
216            } else if let Some(crate_name1) = self.metas[existing].as_ref().map(|data| data.name())
217            {
218                let crate_name0 = root.name();
219                CrateError::StableCrateIdCollision(crate_name0, crate_name1)
220            } else {
221                CrateError::NotFound(root.name())
222            }
223        })?;
224
225        self.metas.push(None);
226        Ok(num)
227    }
228
229    pub fn has_crate_data(&self, cnum: CrateNum) -> bool {
230        self.metas[cnum].is_some()
231    }
232
233    pub(crate) fn get_crate_data(&self, cnum: CrateNum) -> &CrateMetadata {
234        self.metas[cnum].as_ref().unwrap_or_else(|| {
    ::core::panicking::panic_fmt(format_args!("Failed to get crate data for {0:?}",
            cnum));
}panic!("Failed to get crate data for {cnum:?}"))
235    }
236
237    pub(crate) fn get_crate_data_mut(&mut self, cnum: CrateNum) -> &mut CrateMetadata {
238        self.metas[cnum].as_mut().unwrap_or_else(|| {
    ::core::panicking::panic_fmt(format_args!("Failed to get crate data for {0:?}",
            cnum));
}panic!("Failed to get crate data for {cnum:?}"))
239    }
240
241    fn set_crate_data(&mut self, cnum: CrateNum, data: CrateMetadata) {
242        if !self.metas[cnum].is_none() {
    {
        ::core::panicking::panic_fmt(format_args!("Overwriting crate metadata entry"));
    }
};assert!(self.metas[cnum].is_none(), "Overwriting crate metadata entry");
243        self.metas[cnum] = Some(Box::new(data));
244    }
245
246    /// Save the name used to resolve the extern crate in the local crate
247    ///
248    /// The name isn't always the crate's own name, because `sess.opts.externs` can assign it another name.
249    /// It's also not always the same as the `DefId`'s symbol due to renames `extern crate resolved_name as defid_name`.
250    pub(crate) fn set_resolved_extern_crate_name(&mut self, name: Symbol, extern_crate: CrateNum) {
251        self.resolved_externs.insert(name, extern_crate);
252    }
253
254    /// Crate resolved and loaded via the given extern name
255    /// (corresponds to names in `sess.opts.externs`)
256    ///
257    /// May be `None` if the crate wasn't used
258    pub fn resolved_extern_crate(&self, externs_name: Symbol) -> Option<CrateNum> {
259        self.resolved_externs.get(&externs_name).copied()
260    }
261
262    pub(crate) fn iter_crate_data(&self) -> impl Iterator<Item = (CrateNum, &CrateMetadata)> {
263        self.metas
264            .iter_enumerated()
265            .filter_map(|(cnum, data)| data.as_deref().map(|data| (cnum, data)))
266    }
267
268    pub fn all_proc_macro_def_ids(&self, tcx: TyCtxt<'_>) -> impl Iterator<Item = DefId> {
269        self.iter_crate_data().flat_map(move |(krate, data)| data.proc_macros_for_crate(tcx, krate))
270    }
271
272    fn push_dependencies_in_postorder(&self, deps: &mut IndexSet<CrateNum>, cnum: CrateNum) {
273        if !deps.contains(&cnum) {
274            let cdata = self.get_crate_data(cnum);
275            for dep in cdata.dependencies() {
276                if dep != cnum {
277                    self.push_dependencies_in_postorder(deps, dep);
278                }
279            }
280
281            deps.insert(cnum);
282        }
283    }
284
285    pub(crate) fn crate_dependencies_in_postorder(&self, cnum: CrateNum) -> IndexSet<CrateNum> {
286        let mut deps = IndexSet::default();
287        if cnum == LOCAL_CRATE {
288            for (cnum, _) in self.iter_crate_data() {
289                self.push_dependencies_in_postorder(&mut deps, cnum);
290            }
291        } else {
292            self.push_dependencies_in_postorder(&mut deps, cnum);
293        }
294        deps
295    }
296
297    pub(crate) fn injected_panic_runtime(&self) -> Option<CrateNum> {
298        self.injected_panic_runtime
299    }
300
301    pub(crate) fn allocator_kind(&self) -> Option<AllocatorKind> {
302        self.allocator_kind
303    }
304
305    pub(crate) fn alloc_error_handler_kind(&self) -> Option<AllocatorKind> {
306        self.alloc_error_handler_kind
307    }
308
309    pub(crate) fn has_global_allocator(&self) -> bool {
310        self.has_global_allocator
311    }
312
313    pub(crate) fn has_alloc_error_handler(&self) -> bool {
314        self.has_alloc_error_handler
315    }
316
317    pub fn had_extern_crate_load_failure(&self) -> bool {
318        self.has_crate_resolve_with_fail
319    }
320
321    pub fn report_unused_deps(&self, tcx: TyCtxt<'_>) {
322        let json_unused_externs = tcx.sess.opts.json_unused_externs;
323
324        // We put the check for the option before the lint_level_at_node call
325        // because the call mutates internal state and introducing it
326        // leads to some ui tests failing.
327        if !json_unused_externs.is_enabled() {
328            return;
329        }
330        let level = tcx
331            .lint_level_spec_at_node(
332                lint::builtin::UNUSED_CRATE_DEPENDENCIES,
333                rustc_hir::CRATE_HIR_ID,
334            )
335            .level();
336        if level != lint::Level::Allow {
337            let unused_externs =
338                self.unused_externs.iter().map(|ident| ident.to_ident_string()).collect::<Vec<_>>();
339            let unused_externs = unused_externs.iter().map(String::as_str).collect::<Vec<&str>>();
340            tcx.dcx().emit_unused_externs(level, json_unused_externs.is_loud(), &unused_externs);
341        }
342    }
343
344    fn report_target_modifiers_extended(
345        tcx: TyCtxt<'_>,
346        krate: &Crate,
347        mods: &TargetModifiers,
348        dep_mods: &TargetModifiers,
349        data: &CrateMetadata,
350    ) {
351        let span = krate.spans.inner_span.shrink_to_lo();
352        let allowed_flag_mismatches = &tcx.sess.opts.cg.unsafe_allow_abi_mismatch;
353        let local_crate = tcx.crate_name(LOCAL_CRATE);
354        let tmod_extender = |tmod: &TargetModifier| (tmod.extend(), tmod.clone());
355        let report_diff = |prefix: &String,
356                           opt_name: &String,
357                           flag_local_value: Option<&String>,
358                           flag_extern_value: Option<&String>| {
359            if allowed_flag_mismatches.contains(&opt_name) {
360                return;
361            }
362            let extern_crate = data.name();
363            let flag_name = opt_name.clone();
364            let flag_name_prefixed = ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("-{0}{1}", prefix, opt_name))
    })format!("-{}{}", prefix, opt_name);
365
366            match (flag_local_value, flag_extern_value) {
367                (Some(local_value), Some(extern_value)) => {
368                    tcx.dcx().emit_err(errors::IncompatibleTargetModifiers {
369                        span,
370                        extern_crate,
371                        local_crate,
372                        flag_name,
373                        flag_name_prefixed,
374                        local_value: local_value.to_string(),
375                        extern_value: extern_value.to_string(),
376                    })
377                }
378                (None, Some(extern_value)) => {
379                    tcx.dcx().emit_err(errors::IncompatibleTargetModifiersLMissed {
380                        span,
381                        extern_crate,
382                        local_crate,
383                        flag_name,
384                        flag_name_prefixed,
385                        extern_value: extern_value.to_string(),
386                    })
387                }
388                (Some(local_value), None) => {
389                    tcx.dcx().emit_err(errors::IncompatibleTargetModifiersRMissed {
390                        span,
391                        extern_crate,
392                        local_crate,
393                        flag_name,
394                        flag_name_prefixed,
395                        local_value: local_value.to_string(),
396                    })
397                }
398                (None, None) => {
    ::core::panicking::panic_fmt(format_args!("Incorrect target modifiers report_diff(None, None)"));
}panic!("Incorrect target modifiers report_diff(None, None)"),
399            };
400        };
401        let mut it1 = mods.iter().map(tmod_extender);
402        let mut it2 = dep_mods.iter().map(tmod_extender);
403        let mut left_name_val: Option<(ExtendedTargetModifierInfo, TargetModifier)> = None;
404        let mut right_name_val: Option<(ExtendedTargetModifierInfo, TargetModifier)> = None;
405        loop {
406            left_name_val = left_name_val.or_else(|| it1.next());
407            right_name_val = right_name_val.or_else(|| it2.next());
408            match (&left_name_val, &right_name_val) {
409                (Some(l), Some(r)) => match l.1.opt.cmp(&r.1.opt) {
410                    cmp::Ordering::Equal => {
411                        if !l.1.consistent(&tcx.sess, Some(&r.1)) {
412                            report_diff(
413                                &l.0.prefix,
414                                &l.0.name,
415                                Some(&l.1.value_name),
416                                Some(&r.1.value_name),
417                            );
418                        }
419                        left_name_val = None;
420                        right_name_val = None;
421                    }
422                    cmp::Ordering::Greater => {
423                        if !r.1.consistent(&tcx.sess, None) {
424                            report_diff(&r.0.prefix, &r.0.name, None, Some(&r.1.value_name));
425                        }
426                        right_name_val = None;
427                    }
428                    cmp::Ordering::Less => {
429                        if !l.1.consistent(&tcx.sess, None) {
430                            report_diff(&l.0.prefix, &l.0.name, Some(&l.1.value_name), None);
431                        }
432                        left_name_val = None;
433                    }
434                },
435                (Some(l), None) => {
436                    if !l.1.consistent(&tcx.sess, None) {
437                        report_diff(&l.0.prefix, &l.0.name, Some(&l.1.value_name), None);
438                    }
439                    left_name_val = None;
440                }
441                (None, Some(r)) => {
442                    if !r.1.consistent(&tcx.sess, None) {
443                        report_diff(&r.0.prefix, &r.0.name, None, Some(&r.1.value_name));
444                    }
445                    right_name_val = None;
446                }
447                (None, None) => break,
448            }
449        }
450    }
451
452    pub fn report_session_incompatibilities(&self, tcx: TyCtxt<'_>, krate: &Crate) {
453        self.report_incompatible_target_modifiers(tcx, krate);
454        self.report_incompatible_partial_mitigations(tcx, krate);
455        self.report_incompatible_async_drop_feature(tcx, krate);
456    }
457
458    pub fn report_incompatible_target_modifiers(&self, tcx: TyCtxt<'_>, krate: &Crate) {
459        for flag_name in &tcx.sess.opts.cg.unsafe_allow_abi_mismatch {
460            if !OptionsTargetModifiers::is_target_modifier(flag_name) {
461                tcx.dcx().emit_err(errors::UnknownTargetModifierUnsafeAllowed {
462                    span: krate.spans.inner_span.shrink_to_lo(),
463                    flag_name: flag_name.clone(),
464                });
465            }
466        }
467        let mods = tcx.sess.opts.gather_target_modifiers();
468        for (_cnum, data) in self.iter_crate_data() {
469            if data.is_proc_macro_crate() {
470                continue;
471            }
472            let dep_mods = data.target_modifiers();
473            if mods != dep_mods {
474                Self::report_target_modifiers_extended(tcx, krate, &mods, &dep_mods, data);
475            }
476        }
477    }
478
479    pub fn report_incompatible_partial_mitigations(&self, tcx: TyCtxt<'_>, krate: &Crate) {
480        let my_mitigations = tcx.sess.gather_enabled_denied_partial_mitigations();
481        let mut my_mitigations: BTreeMap<_, _> =
482            my_mitigations.iter().map(|mitigation| (mitigation.kind, mitigation)).collect();
483        for skipped_mitigation in tcx.sess.opts.allowed_partial_mitigations(tcx.sess.edition()) {
484            my_mitigations.remove(&skipped_mitigation);
485        }
486        const MAX_ERRORS_PER_MITIGATION: usize = 5;
487        let mut errors_per_mitigation = BTreeMap::new();
488        for (_cnum, data) in self.iter_crate_data() {
489            if data.is_proc_macro_crate() {
490                continue;
491            }
492            let their_mitigations = data.enabled_denied_partial_mitigations();
493            for my_mitigation in my_mitigations.values() {
494                let their_mitigation = their_mitigations
495                    .iter()
496                    .find(|mitigation| mitigation.kind == my_mitigation.kind)
497                    .map_or(DeniedPartialMitigationLevel::Enabled(false), |m| m.level);
498                if their_mitigation < my_mitigation.level {
499                    let errors = errors_per_mitigation.entry(my_mitigation.kind).or_insert(0);
500                    if *errors >= MAX_ERRORS_PER_MITIGATION {
501                        continue;
502                    }
503                    *errors += 1;
504
505                    tcx.dcx().emit_err(errors::MitigationLessStrictInDependency {
506                        span: krate.spans.inner_span.shrink_to_lo(),
507                        mitigation_name: my_mitigation.kind.to_string(),
508                        mitigation_level: my_mitigation.level.level_str().to_string(),
509                        extern_crate: data.name(),
510                    });
511                }
512            }
513        }
514    }
515
516    // Report about async drop types in dependency if async drop feature is disabled
517    pub fn report_incompatible_async_drop_feature(&self, tcx: TyCtxt<'_>, krate: &Crate) {
518        if tcx.features().async_drop() {
519            return;
520        }
521        for (_cnum, data) in self.iter_crate_data() {
522            if data.is_proc_macro_crate() {
523                continue;
524            }
525            if data.has_async_drops() {
526                let extern_crate = data.name();
527                let local_crate = tcx.crate_name(LOCAL_CRATE);
528                tcx.dcx().emit_warn(errors::AsyncDropTypesInDependency {
529                    span: krate.spans.inner_span.shrink_to_lo(),
530                    extern_crate,
531                    local_crate,
532                });
533            }
534        }
535    }
536
537    pub fn new(metadata_loader: Box<MetadataLoaderDyn>) -> CStore {
538        CStore {
539            metadata_loader,
540            // We add an empty entry for LOCAL_CRATE (which maps to zero) in
541            // order to make array indices in `metas` match with the
542            // corresponding `CrateNum`. This first entry will always remain
543            // `None`.
544            metas: IndexVec::from_iter(iter::once(None)),
545            injected_panic_runtime: None,
546            allocator_kind: None,
547            alloc_error_handler_kind: None,
548            has_global_allocator: false,
549            has_alloc_error_handler: false,
550            resolved_externs: UnordMap::default(),
551            unused_externs: Vec::new(),
552            used_extern_options: Default::default(),
553            has_crate_resolve_with_fail: false,
554        }
555    }
556
557    fn existing_match(&self, name: Symbol, hash: Option<Svh>) -> Option<CrateNum> {
558        let hash = hash?;
559
560        for (cnum, data) in self.iter_crate_data() {
561            if data.name() != name {
562                {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_metadata/src/creader.rs:562",
                        "rustc_metadata::creader", ::tracing::Level::TRACE,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_metadata/src/creader.rs"),
                        ::tracing_core::__macro_support::Option::Some(562u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_metadata::creader"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::TRACE <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::TRACE <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                let mut iter = __CALLSITE.metadata().fields().iter();
                __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                    ::tracing::__macro_support::Option::Some(&format_args!("{0} did not match {1}",
                                                    data.name(), name) as &dyn Value))])
            });
    } else { ; }
};trace!("{} did not match {}", data.name(), name);
563                continue;
564            }
565
566            if hash == data.hash() {
567                return Some(cnum);
568            } else {
569                {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_metadata/src/creader.rs:569",
                        "rustc_metadata::creader", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_metadata/src/creader.rs"),
                        ::tracing_core::__macro_support::Option::Some(569u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_metadata::creader"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                let mut iter = __CALLSITE.metadata().fields().iter();
                __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                    ::tracing::__macro_support::Option::Some(&format_args!("actual hash {0} did not match expected {1}",
                                                    hash, data.hash()) as &dyn Value))])
            });
    } else { ; }
};debug!("actual hash {} did not match expected {}", hash, data.hash());
570            }
571        }
572
573        None
574    }
575
576    /// Determine whether a dependency should be considered private.
577    ///
578    /// Dependencies are private if they get extern option specified, e.g. `--extern priv:mycrate`.
579    /// This is stored in metadata, so `private_dep`  can be correctly set during load. A `Some`
580    /// value for `private_dep` indicates that the crate is known to be private or public (note
581    /// that any `None` or `Some(false)` use of the same crate will make it public).
582    ///
583    /// Sometimes the directly dependent crate is not specified by `--extern`, in this case,
584    /// `private-dep` is none during loading. This is equivalent to the scenario where the
585    /// command parameter is set to `public-dependency`
586    fn is_private_dep(&self, externs: &Externs, name: Symbol, private_dep: Option<bool>) -> bool {
587        let extern_private = externs.get(name.as_str()).map(|e| e.is_private_dep);
588        match (extern_private, private_dep) {
589            // Explicit non-private via `--extern`, explicit non-private from metadata, or
590            // unspecified with default to public.
591            (Some(false), _) | (_, Some(false)) | (None, None) => false,
592            // Marked private via `--extern priv:mycrate` or in metadata.
593            (Some(true) | None, Some(true) | None) => true,
594        }
595    }
596
597    fn register_crate<'tcx>(
598        &mut self,
599        tcx: TyCtxt<'tcx>,
600        host_lib: Option<Library>,
601        origin: CrateOrigin<'_>,
602        lib: Library,
603        dep_kind: CrateDepKind,
604        name: Symbol,
605        private_dep: Option<bool>,
606    ) -> Result<CrateNum, CrateError> {
607        let _prof_timer =
608            tcx.sess.prof.generic_activity_with_arg("metadata_register_crate", name.as_str());
609
610        let Library { source, metadata } = lib;
611        let crate_root = metadata.get_root();
612        let host_hash = host_lib.as_ref().map(|lib| lib.metadata.get_root().hash());
613        let private_dep = self.is_private_dep(&tcx.sess.opts.externs, name, private_dep);
614
615        // Claim this crate number and cache it
616        let feed = self.intern_stable_crate_id(tcx, &crate_root)?;
617        let cnum = feed.key();
618
619        {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_metadata/src/creader.rs:619",
                        "rustc_metadata::creader", ::tracing::Level::INFO,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_metadata/src/creader.rs"),
                        ::tracing_core::__macro_support::Option::Some(619u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_metadata::creader"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::INFO <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::INFO <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                let mut iter = __CALLSITE.metadata().fields().iter();
                __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                    ::tracing::__macro_support::Option::Some(&format_args!("register crate `{0}` (cnum = {1}. private_dep = {2})",
                                                    crate_root.name(), cnum, private_dep) as &dyn Value))])
            });
    } else { ; }
};info!(
620            "register crate `{}` (cnum = {}. private_dep = {})",
621            crate_root.name(),
622            cnum,
623            private_dep
624        );
625
626        // Maintain a reference to the top most crate.
627        // Stash paths for top-most crate locally if necessary.
628        let crate_paths;
629        let dep_root_for_errors = if let Some(dep_root_for_errors) = origin.dep_root_for_errors() {
630            dep_root_for_errors
631        } else {
632            crate_paths = CratePaths::new(crate_root.name(), source.clone());
633            &crate_paths
634        };
635
636        let cnum_map = self.resolve_crate_deps(
637            tcx,
638            dep_root_for_errors,
639            &crate_root,
640            &metadata,
641            cnum,
642            dep_kind,
643            private_dep,
644        )?;
645
646        let raw_proc_macros = if crate_root.is_proc_macro_crate() {
647            let temp_root;
648            let (dlsym_source, dlsym_root) = match &host_lib {
649                Some(host_lib) => (&host_lib.source, {
650                    temp_root = host_lib.metadata.get_root();
651                    &temp_root
652                }),
653                None => (&source, &crate_root),
654            };
655            let dlsym_dylib = dlsym_source.dylib.as_ref().expect("no dylib for a proc-macro crate");
656            Some(self.dlsym_proc_macros(tcx.sess, dlsym_dylib, dlsym_root.stable_crate_id())?)
657        } else {
658            None
659        };
660
661        let crate_metadata = CrateMetadata::new(
662            tcx,
663            metadata,
664            crate_root,
665            raw_proc_macros,
666            cnum,
667            cnum_map,
668            dep_kind,
669            source,
670            private_dep,
671            host_hash,
672        );
673
674        self.set_crate_data(cnum, crate_metadata);
675
676        Ok(cnum)
677    }
678
679    fn load_proc_macro<'a, 'b>(
680        &self,
681        sess: &'a Session,
682        locator: &mut CrateLocator<'b>,
683        crate_rejections: &mut CrateRejections,
684        path_kind: PathKind,
685        host_hash: Option<Svh>,
686    ) -> Result<Option<(LoadResult, Option<Library>)>, CrateError>
687    where
688        'a: 'b,
689    {
690        if sess.opts.unstable_opts.dual_proc_macros {
691            // Use a new crate locator and crate rejections so trying to load a proc macro doesn't
692            // affect the error message we emit
693            let mut proc_macro_locator = locator.clone();
694
695            // Try to load a proc macro
696            proc_macro_locator.for_target_proc_macro(sess, path_kind);
697
698            // Load the proc macro crate for the target
699            let target_result =
700                match self.load(&mut proc_macro_locator, &mut CrateRejections::default())? {
701                    Some(LoadResult::Previous(cnum)) => {
702                        return Ok(Some((LoadResult::Previous(cnum), None)));
703                    }
704                    Some(LoadResult::Loaded(library)) => Some(LoadResult::Loaded(library)),
705                    None => return Ok(None),
706                };
707
708            // Use the existing crate_rejections as we want the error message to be affected by
709            // loading the host proc macro.
710            *crate_rejections = CrateRejections::default();
711
712            // Load the proc macro crate for the host
713            locator.for_proc_macro(sess, path_kind);
714
715            locator.hash = host_hash;
716
717            let Some(host_result) = self.load(locator, crate_rejections)? else {
718                return Ok(None);
719            };
720
721            let host_result = match host_result {
722                LoadResult::Previous(..) => {
723                    {
    ::core::panicking::panic_fmt(format_args!("host and target proc macros must be loaded in lock-step"));
}panic!("host and target proc macros must be loaded in lock-step")
724                }
725                LoadResult::Loaded(library) => library,
726            };
727            Ok(Some((target_result.unwrap(), Some(host_result))))
728        } else {
729            // Use a new crate locator and crate rejections so trying to load a proc macro doesn't
730            // affect the error message we emit
731            let mut proc_macro_locator = locator.clone();
732
733            // Load the proc macro crate for the host
734            proc_macro_locator.for_proc_macro(sess, path_kind);
735
736            let Some(host_result) =
737                self.load(&mut proc_macro_locator, &mut CrateRejections::default())?
738            else {
739                return Ok(None);
740            };
741
742            Ok(Some((host_result, None)))
743        }
744    }
745
746    fn resolve_crate<'tcx>(
747        &mut self,
748        tcx: TyCtxt<'tcx>,
749        name: Symbol,
750        span: Span,
751        dep_kind: CrateDepKind,
752        origin: CrateOrigin<'_>,
753    ) -> Option<CrateNum> {
754        self.used_extern_options.insert(name);
755        match self.maybe_resolve_crate(tcx, name, dep_kind, origin) {
756            Ok(cnum) => {
757                self.set_used_recursively(cnum);
758                Some(cnum)
759            }
760            Err(err) => {
761                {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_metadata/src/creader.rs:761",
                        "rustc_metadata::creader", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_metadata/src/creader.rs"),
                        ::tracing_core::__macro_support::Option::Some(761u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_metadata::creader"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                let mut iter = __CALLSITE.metadata().fields().iter();
                __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                    ::tracing::__macro_support::Option::Some(&format_args!("failed to resolve crate {0} {1:?}",
                                                    name, dep_kind) as &dyn Value))])
            });
    } else { ; }
};debug!("failed to resolve crate {} {:?}", name, dep_kind);
762                // crate maybe injrected with `standard_library_imports::inject`, their span is dummy.
763                // we ignore compiler-injected prelude/sysroot loads here so they don't suppress
764                // unrelated diagnostics, such as `unsupported targets for std library` etc,
765                // these maybe helpful for users to resolve crate loading failure.
766                if !tcx.sess.dcx().has_errors().is_some() && !span.is_dummy() {
767                    self.has_crate_resolve_with_fail = true;
768                }
769                let missing_core = self
770                    .maybe_resolve_crate(
771                        tcx,
772                        sym::core,
773                        CrateDepKind::Unconditional,
774                        CrateOrigin::Extern,
775                    )
776                    .is_err();
777                err.report(tcx.sess, span, missing_core);
778                None
779            }
780        }
781    }
782
783    fn maybe_resolve_crate<'b, 'tcx>(
784        &'b mut self,
785        tcx: TyCtxt<'tcx>,
786        name: Symbol,
787        mut dep_kind: CrateDepKind,
788        origin: CrateOrigin<'b>,
789    ) -> Result<CrateNum, CrateError> {
790        {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_metadata/src/creader.rs:790",
                        "rustc_metadata::creader", ::tracing::Level::INFO,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_metadata/src/creader.rs"),
                        ::tracing_core::__macro_support::Option::Some(790u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_metadata::creader"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::INFO <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::INFO <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                let mut iter = __CALLSITE.metadata().fields().iter();
                __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                    ::tracing::__macro_support::Option::Some(&format_args!("resolving crate `{0}`",
                                                    name) as &dyn Value))])
            });
    } else { ; }
};info!("resolving crate `{}`", name);
791        if !name.as_str().is_ascii() {
792            return Err(CrateError::NonAsciiName(name));
793        }
794
795        let dep_root_for_errors = origin.dep_root_for_errors();
796        let dep = origin.dep();
797        let hash = dep.map(|d| d.hash);
798        let host_hash = dep.map(|d| d.host_hash).flatten();
799        let extra_filename = dep.map(|d| &d.extra_filename[..]);
800        let path_kind = if dep.is_some() { PathKind::Dependency } else { PathKind::Crate };
801        let private_dep = origin.private_dep();
802
803        let result = if let Some(cnum) = self.existing_match(name, hash) {
804            (LoadResult::Previous(cnum), None)
805        } else {
806            {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_metadata/src/creader.rs:806",
                        "rustc_metadata::creader", ::tracing::Level::INFO,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_metadata/src/creader.rs"),
                        ::tracing_core::__macro_support::Option::Some(806u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_metadata::creader"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::INFO <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::INFO <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                let mut iter = __CALLSITE.metadata().fields().iter();
                __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                    ::tracing::__macro_support::Option::Some(&format_args!("falling back to a load")
                                            as &dyn Value))])
            });
    } else { ; }
};info!("falling back to a load");
807            let mut locator = CrateLocator::new(
808                tcx.sess,
809                &*self.metadata_loader,
810                name,
811                // The all loop is because `--crate-type=rlib --crate-type=rlib` is
812                // legal and produces both inside this type.
813                tcx.crate_types().iter().all(|c| *c == CrateType::Rlib),
814                hash,
815                extra_filename,
816                path_kind,
817            );
818            let mut crate_rejections = CrateRejections::default();
819
820            match self.load(&mut locator, &mut crate_rejections)? {
821                Some(res) => (res, None),
822                None => {
823                    {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_metadata/src/creader.rs:823",
                        "rustc_metadata::creader", ::tracing::Level::INFO,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_metadata/src/creader.rs"),
                        ::tracing_core::__macro_support::Option::Some(823u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_metadata::creader"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::INFO <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::INFO <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                let mut iter = __CALLSITE.metadata().fields().iter();
                __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                    ::tracing::__macro_support::Option::Some(&format_args!("falling back to loading proc_macro")
                                            as &dyn Value))])
            });
    } else { ; }
};info!("falling back to loading proc_macro");
824                    dep_kind = CrateDepKind::MacrosOnly;
825                    match self.load_proc_macro(
826                        tcx.sess,
827                        &mut locator,
828                        &mut crate_rejections,
829                        path_kind,
830                        host_hash,
831                    )? {
832                        Some(res) => res,
833                        None => {
834                            return Err(
835                                locator.into_error(crate_rejections, dep_root_for_errors.cloned())
836                            );
837                        }
838                    }
839                }
840            }
841        };
842
843        match result {
844            (LoadResult::Previous(cnum), None) => {
845                {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_metadata/src/creader.rs:845",
                        "rustc_metadata::creader", ::tracing::Level::INFO,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_metadata/src/creader.rs"),
                        ::tracing_core::__macro_support::Option::Some(845u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_metadata::creader"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::INFO <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::INFO <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                let mut iter = __CALLSITE.metadata().fields().iter();
                __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                    ::tracing::__macro_support::Option::Some(&format_args!("library for `{0}` was loaded previously, cnum {1}",
                                                    name, cnum) as &dyn Value))])
            });
    } else { ; }
};info!("library for `{}` was loaded previously, cnum {cnum}", name);
846                // When `private_dep` is none, it indicates the directly dependent crate. If it is
847                // not specified by `--extern` on command line parameters, it may be
848                // `private-dependency` when `register_crate` is called for the first time. Then it must be updated to
849                // `public-dependency` here.
850                let private_dep = self.is_private_dep(&tcx.sess.opts.externs, name, private_dep);
851                let cdata = self.get_crate_data_mut(cnum);
852                if cdata.is_proc_macro_crate() {
853                    dep_kind = CrateDepKind::MacrosOnly;
854                }
855                cdata.set_dep_kind(cmp::max(cdata.dep_kind(), dep_kind));
856                cdata.update_and_private_dep(private_dep);
857                Ok(cnum)
858            }
859            (LoadResult::Loaded(library), host_library) => {
860                {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_metadata/src/creader.rs:860",
                        "rustc_metadata::creader", ::tracing::Level::INFO,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_metadata/src/creader.rs"),
                        ::tracing_core::__macro_support::Option::Some(860u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_metadata::creader"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::INFO <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::INFO <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                let mut iter = __CALLSITE.metadata().fields().iter();
                __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                    ::tracing::__macro_support::Option::Some(&format_args!("register newly loaded library for `{0}`",
                                                    name) as &dyn Value))])
            });
    } else { ; }
};info!("register newly loaded library for `{}`", name);
861                self.register_crate(tcx, host_library, origin, library, dep_kind, name, private_dep)
862            }
863            _ => ::core::panicking::panic("explicit panic")panic!(),
864        }
865    }
866
867    fn load(
868        &self,
869        locator: &CrateLocator<'_>,
870        crate_rejections: &mut CrateRejections,
871    ) -> Result<Option<LoadResult>, CrateError> {
872        let Some(library) = locator.maybe_load_library_crate(crate_rejections)? else {
873            return Ok(None);
874        };
875
876        // In the case that we're loading a crate, but not matching
877        // against a hash, we could load a crate which has the same hash
878        // as an already loaded crate. If this is the case prevent
879        // duplicates by just using the first crate.
880        let root = library.metadata.get_root();
881        let mut result = LoadResult::Loaded(library);
882        for (cnum, data) in self.iter_crate_data() {
883            if data.name() == root.name() && root.hash() == data.hash() {
884                if !locator.hash.is_none() {
    ::core::panicking::panic("assertion failed: locator.hash.is_none()")
};assert!(locator.hash.is_none());
885                {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_metadata/src/creader.rs:885",
                        "rustc_metadata::creader", ::tracing::Level::INFO,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_metadata/src/creader.rs"),
                        ::tracing_core::__macro_support::Option::Some(885u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_metadata::creader"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::INFO <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::INFO <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                let mut iter = __CALLSITE.metadata().fields().iter();
                __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                    ::tracing::__macro_support::Option::Some(&format_args!("load success, going to previous cnum: {0}",
                                                    cnum) as &dyn Value))])
            });
    } else { ; }
};info!("load success, going to previous cnum: {}", cnum);
886                result = LoadResult::Previous(cnum);
887                break;
888            }
889        }
890        Ok(Some(result))
891    }
892
893    /// Go through the crate metadata and load any crates that it references.
894    fn resolve_crate_deps(
895        &mut self,
896        tcx: TyCtxt<'_>,
897        dep_root_for_errors: &CratePaths,
898        crate_root: &CrateRoot,
899        metadata: &MetadataBlob,
900        krate: CrateNum,
901        dep_kind: CrateDepKind,
902        parent_is_private: bool,
903    ) -> Result<CrateNumMap, CrateError> {
904        {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_metadata/src/creader.rs:904",
                        "rustc_metadata::creader", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_metadata/src/creader.rs"),
                        ::tracing_core::__macro_support::Option::Some(904u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_metadata::creader"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                let mut iter = __CALLSITE.metadata().fields().iter();
                __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                    ::tracing::__macro_support::Option::Some(&format_args!("resolving deps of external crate `{0}` with dep root `{1}`",
                                                    crate_root.name(), dep_root_for_errors.name) as
                                            &dyn Value))])
            });
    } else { ; }
};debug!(
905            "resolving deps of external crate `{}` with dep root `{}`",
906            crate_root.name(),
907            dep_root_for_errors.name
908        );
909        if crate_root.is_proc_macro_crate() {
910            return Ok(CrateNumMap::new());
911        }
912
913        // The map from crate numbers in the crate we're resolving to local crate numbers.
914        // We map 0 and all other holes in the map to our parent crate. The "additional"
915        // self-dependencies should be harmless.
916        let deps = crate_root.decode_crate_deps(metadata);
917        let mut crate_num_map = CrateNumMap::with_capacity(1 + deps.len());
918        crate_num_map.push(krate);
919        for dep in deps {
920            {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_metadata/src/creader.rs:920",
                        "rustc_metadata::creader", ::tracing::Level::INFO,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_metadata/src/creader.rs"),
                        ::tracing_core::__macro_support::Option::Some(920u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_metadata::creader"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::INFO <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::INFO <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                let mut iter = __CALLSITE.metadata().fields().iter();
                __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                    ::tracing::__macro_support::Option::Some(&format_args!("resolving dep `{0}`->`{1}` hash: `{2}` extra filename: `{3}` private {4}",
                                                    crate_root.name(), dep.name, dep.hash, dep.extra_filename,
                                                    dep.is_private) as &dyn Value))])
            });
    } else { ; }
};info!(
921                "resolving dep `{}`->`{}` hash: `{}` extra filename: `{}` private {}",
922                crate_root.name(),
923                dep.name,
924                dep.hash,
925                dep.extra_filename,
926                dep.is_private,
927            );
928            let dep_kind = match dep_kind {
929                CrateDepKind::MacrosOnly => CrateDepKind::MacrosOnly,
930                _ => dep.kind,
931            };
932            let cnum = self.maybe_resolve_crate(
933                tcx,
934                dep.name,
935                dep_kind,
936                CrateOrigin::IndirectDependency {
937                    dep_root_for_errors,
938                    parent_private: parent_is_private,
939                    dep: &dep,
940                },
941            )?;
942            crate_num_map.push(cnum);
943        }
944
945        {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_metadata/src/creader.rs:945",
                        "rustc_metadata::creader", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_metadata/src/creader.rs"),
                        ::tracing_core::__macro_support::Option::Some(945u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_metadata::creader"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                let mut iter = __CALLSITE.metadata().fields().iter();
                __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                    ::tracing::__macro_support::Option::Some(&format_args!("resolve_crate_deps: cnum_map for {0:?} is {1:?}",
                                                    krate, crate_num_map) as &dyn Value))])
            });
    } else { ; }
};debug!("resolve_crate_deps: cnum_map for {:?} is {:?}", krate, crate_num_map);
946        Ok(crate_num_map)
947    }
948
949    fn dlsym_proc_macros(
950        &self,
951        sess: &Session,
952        path: &Path,
953        stable_crate_id: StableCrateId,
954    ) -> Result<&'static [ProcMacro], CrateError> {
955        let sym_name = sess.generate_proc_macro_decls_symbol(stable_crate_id);
956        {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_metadata/src/creader.rs:956",
                        "rustc_metadata::creader", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_metadata/src/creader.rs"),
                        ::tracing_core::__macro_support::Option::Some(956u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_metadata::creader"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                let mut iter = __CALLSITE.metadata().fields().iter();
                __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                    ::tracing::__macro_support::Option::Some(&format_args!("trying to dlsym proc_macros {0} for symbol `{1}`",
                                                    path.display(), sym_name) as &dyn Value))])
            });
    } else { ; }
};debug!("trying to dlsym proc_macros {} for symbol `{}`", path.display(), sym_name);
957
958        unsafe {
959            let result = load_symbol_from_dylib::<*const &[ProcMacro]>(path, &sym_name);
960            match result {
961                Ok(result) => {
962                    {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_metadata/src/creader.rs:962",
                        "rustc_metadata::creader", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_metadata/src/creader.rs"),
                        ::tracing_core::__macro_support::Option::Some(962u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_metadata::creader"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                let mut iter = __CALLSITE.metadata().fields().iter();
                __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                    ::tracing::__macro_support::Option::Some(&format_args!("loaded dlsym proc_macros {0} for symbol `{1}`",
                                                    path.display(), sym_name) as &dyn Value))])
            });
    } else { ; }
};debug!("loaded dlsym proc_macros {} for symbol `{}`", path.display(), sym_name);
963                    Ok(*result)
964                }
965                Err(err) => {
966                    {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_metadata/src/creader.rs:966",
                        "rustc_metadata::creader", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_metadata/src/creader.rs"),
                        ::tracing_core::__macro_support::Option::Some(966u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_metadata::creader"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                let mut iter = __CALLSITE.metadata().fields().iter();
                __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                    ::tracing::__macro_support::Option::Some(&format_args!("failed to dlsym proc_macros {0} for symbol `{1}`",
                                                    path.display(), sym_name) as &dyn Value))])
            });
    } else { ; }
};debug!(
967                        "failed to dlsym proc_macros {} for symbol `{}`",
968                        path.display(),
969                        sym_name
970                    );
971                    Err(err.into())
972                }
973            }
974        }
975    }
976
977    fn inject_panic_runtime(&mut self, tcx: TyCtxt<'_>, krate: &ast::Crate) {
978        // If we're only compiling an rlib, then there's no need to select a
979        // panic runtime, so we just skip this section entirely.
980        let only_rlib = tcx.crate_types().iter().all(|ct| *ct == CrateType::Rlib);
981        if only_rlib {
982            {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_metadata/src/creader.rs:982",
                        "rustc_metadata::creader", ::tracing::Level::INFO,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_metadata/src/creader.rs"),
                        ::tracing_core::__macro_support::Option::Some(982u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_metadata::creader"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::INFO <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::INFO <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                let mut iter = __CALLSITE.metadata().fields().iter();
                __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                    ::tracing::__macro_support::Option::Some(&format_args!("panic runtime injection skipped, only generating rlib")
                                            as &dyn Value))])
            });
    } else { ; }
};info!("panic runtime injection skipped, only generating rlib");
983            return;
984        }
985
986        // If we need a panic runtime, we try to find an existing one here. At
987        // the same time we perform some general validation of the DAG we've got
988        // going such as ensuring everything has a compatible panic strategy.
989        let mut needs_panic_runtime = attr::contains_name(&krate.attrs, sym::needs_panic_runtime);
990        for (_cnum, data) in self.iter_crate_data() {
991            needs_panic_runtime |= data.needs_panic_runtime();
992        }
993
994        // If we just don't need a panic runtime at all, then we're done here
995        // and there's nothing else to do.
996        if !needs_panic_runtime {
997            return;
998        }
999
1000        // By this point we know that we need a panic runtime. Here we just load
1001        // an appropriate default runtime for our panic strategy.
1002        //
1003        // We may resolve to an already loaded crate (as the crate may not have
1004        // been explicitly linked prior to this), but this is fine.
1005        //
1006        // Also note that we have yet to perform validation of the crate graph
1007        // in terms of everyone has a compatible panic runtime format, that's
1008        // performed later as part of the `dependency_format` module.
1009        let desired_strategy = tcx.sess.panic_strategy();
1010        let name = match desired_strategy {
1011            PanicStrategy::Unwind => sym::panic_unwind,
1012            PanicStrategy::Abort => sym::panic_abort,
1013            PanicStrategy::ImmediateAbort => {
1014                // Immediate-aborting panics don't use a runtime.
1015                return;
1016            }
1017        };
1018        {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_metadata/src/creader.rs:1018",
                        "rustc_metadata::creader", ::tracing::Level::INFO,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_metadata/src/creader.rs"),
                        ::tracing_core::__macro_support::Option::Some(1018u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_metadata::creader"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::INFO <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::INFO <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                let mut iter = __CALLSITE.metadata().fields().iter();
                __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                    ::tracing::__macro_support::Option::Some(&format_args!("panic runtime not found -- loading {0}",
                                                    name) as &dyn Value))])
            });
    } else { ; }
};info!("panic runtime not found -- loading {}", name);
1019
1020        // This has to be conditional as both panic_unwind and panic_abort may be present in the
1021        // crate graph at the same time. One of them will later be activated in dependency_formats.
1022        let Some(cnum) = self.resolve_crate(
1023            tcx,
1024            name,
1025            DUMMY_SP,
1026            CrateDepKind::Conditional,
1027            CrateOrigin::Injected,
1028        ) else {
1029            return;
1030        };
1031        let cdata = self.get_crate_data(cnum);
1032
1033        // Sanity check the loaded crate to ensure it is indeed a panic runtime
1034        // and the panic strategy is indeed what we thought it was.
1035        if !cdata.is_panic_runtime() {
1036            tcx.dcx().emit_err(errors::CrateNotPanicRuntime { crate_name: name });
1037        }
1038        if cdata.required_panic_strategy() != Some(desired_strategy) {
1039            tcx.dcx()
1040                .emit_err(errors::NoPanicStrategy { crate_name: name, strategy: desired_strategy });
1041        }
1042
1043        self.injected_panic_runtime = Some(cnum);
1044    }
1045
1046    fn inject_profiler_runtime(&mut self, tcx: TyCtxt<'_>) {
1047        let needs_profiler_runtime =
1048            tcx.sess.instrument_coverage() || tcx.sess.opts.cg.profile_generate.enabled();
1049        if !needs_profiler_runtime || tcx.sess.opts.unstable_opts.no_profiler_runtime {
1050            return;
1051        }
1052
1053        {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_metadata/src/creader.rs:1053",
                        "rustc_metadata::creader", ::tracing::Level::INFO,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_metadata/src/creader.rs"),
                        ::tracing_core::__macro_support::Option::Some(1053u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_metadata::creader"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::INFO <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::INFO <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                let mut iter = __CALLSITE.metadata().fields().iter();
                __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                    ::tracing::__macro_support::Option::Some(&format_args!("loading profiler")
                                            as &dyn Value))])
            });
    } else { ; }
};info!("loading profiler");
1054
1055        // HACK: This uses conditional despite actually being unconditional to ensure that
1056        // there is no error emitted when two dylibs independently depend on profiler_builtins.
1057        // This is fine as profiler_builtins is always statically linked into the dylib just
1058        // like compiler_builtins. Unlike compiler_builtins however there is no guaranteed
1059        // common dylib that the duplicate crate check believes the crate to be included in.
1060        // add_upstream_rust_crates has a corresponding check that forces profiler_builtins
1061        // to be statically linked in even when marked as NotLinked.
1062        let name = Symbol::intern(&tcx.sess.opts.unstable_opts.profiler_runtime);
1063        let Some(cnum) = self.resolve_crate(
1064            tcx,
1065            name,
1066            DUMMY_SP,
1067            CrateDepKind::Conditional,
1068            CrateOrigin::Injected,
1069        ) else {
1070            return;
1071        };
1072        let cdata = self.get_crate_data(cnum);
1073
1074        // Sanity check the loaded crate to ensure it is indeed a profiler runtime
1075        if !cdata.is_profiler_runtime() {
1076            tcx.dcx().emit_err(errors::NotProfilerRuntime { crate_name: name });
1077        }
1078    }
1079
1080    fn inject_allocator_crate(&mut self, tcx: TyCtxt<'_>, krate: &ast::Crate) {
1081        self.has_global_allocator =
1082            match &*fn_spans(krate, Symbol::intern(&global_fn_name(sym::alloc))) {
1083                [span1, span2, ..] => {
1084                    tcx.dcx()
1085                        .emit_err(errors::NoMultipleGlobalAlloc { span2: *span2, span1: *span1 });
1086                    true
1087                }
1088                spans => !spans.is_empty(),
1089            };
1090        let alloc_error_handler = Symbol::intern(&global_fn_name(ALLOC_ERROR_HANDLER));
1091        self.has_alloc_error_handler = match &*fn_spans(krate, alloc_error_handler) {
1092            [span1, span2, ..] => {
1093                tcx.dcx()
1094                    .emit_err(errors::NoMultipleAllocErrorHandler { span2: *span2, span1: *span1 });
1095                true
1096            }
1097            spans => !spans.is_empty(),
1098        };
1099
1100        // Check to see if we actually need an allocator. This desire comes
1101        // about through the `#![needs_allocator]` attribute and is typically
1102        // written down in liballoc.
1103        if !attr::contains_name(&krate.attrs, sym::needs_allocator)
1104            && !self.iter_crate_data().any(|(_, data)| data.needs_allocator())
1105        {
1106            return;
1107        }
1108
1109        // At this point we've determined that we need an allocator. Let's see
1110        // if our compilation session actually needs an allocator based on what
1111        // we're emitting.
1112        let all_rlib = tcx.crate_types().iter().all(|ct| #[allow(non_exhaustive_omitted_patterns)] match *ct {
    CrateType::Rlib => true,
    _ => false,
}matches!(*ct, CrateType::Rlib));
1113        if all_rlib {
1114            return;
1115        }
1116
1117        // Ok, we need an allocator. Not only that but we're actually going to
1118        // create an artifact that needs one linked in. Let's go find the one
1119        // that we're going to link in.
1120        //
1121        // First up we check for global allocators. Look at the crate graph here
1122        // and see what's a global allocator, including if we ourselves are a
1123        // global allocator.
1124        #[allow(rustc::symbol_intern_string_literal)]
1125        let this_crate = Symbol::intern("this crate");
1126
1127        let mut global_allocator = self.has_global_allocator.then_some(this_crate);
1128        for (_, data) in self.iter_crate_data() {
1129            if data.has_global_allocator() {
1130                match global_allocator {
1131                    Some(other_crate) => {
1132                        tcx.dcx().emit_err(errors::ConflictingGlobalAlloc {
1133                            crate_name: data.name(),
1134                            other_crate_name: other_crate,
1135                        });
1136                    }
1137                    None => global_allocator = Some(data.name()),
1138                }
1139            }
1140        }
1141        let mut alloc_error_handler = self.has_alloc_error_handler.then_some(this_crate);
1142        for (_, data) in self.iter_crate_data() {
1143            if data.has_alloc_error_handler() {
1144                match alloc_error_handler {
1145                    Some(other_crate) => {
1146                        tcx.dcx().emit_err(errors::ConflictingAllocErrorHandler {
1147                            crate_name: data.name(),
1148                            other_crate_name: other_crate,
1149                        });
1150                    }
1151                    None => alloc_error_handler = Some(data.name()),
1152                }
1153            }
1154        }
1155
1156        if global_allocator.is_some() {
1157            self.allocator_kind = Some(AllocatorKind::Global);
1158        } else {
1159            // Ok we haven't found a global allocator but we still need an
1160            // allocator. At this point our allocator request is typically fulfilled
1161            // by the standard library, denoted by the `#![default_lib_allocator]`
1162            // attribute.
1163            if !attr::contains_name(&krate.attrs, sym::default_lib_allocator)
1164                && !self.iter_crate_data().any(|(_, data)| data.has_default_lib_allocator())
1165            {
1166                tcx.dcx().emit_err(errors::GlobalAllocRequired);
1167            }
1168            self.allocator_kind = Some(AllocatorKind::Default);
1169        }
1170
1171        if alloc_error_handler.is_some() {
1172            self.alloc_error_handler_kind = Some(AllocatorKind::Global);
1173        } else {
1174            // The alloc crate provides a default allocation error handler if
1175            // one isn't specified.
1176            self.alloc_error_handler_kind = Some(AllocatorKind::Default);
1177        }
1178    }
1179
1180    fn inject_forced_externs(&mut self, tcx: TyCtxt<'_>) {
1181        for (name, entry) in tcx.sess.opts.externs.iter() {
1182            if entry.force {
1183                let name_interned = Symbol::intern(name);
1184                if !self.used_extern_options.contains(&name_interned) {
1185                    self.resolve_crate(
1186                        tcx,
1187                        name_interned,
1188                        DUMMY_SP,
1189                        CrateDepKind::Unconditional,
1190                        CrateOrigin::Extern,
1191                    );
1192                }
1193            }
1194        }
1195    }
1196
1197    /// Inject the `compiler_builtins` crate if it is not already in the graph.
1198    fn inject_compiler_builtins(&mut self, tcx: TyCtxt<'_>, krate: &ast::Crate) {
1199        // `compiler_builtins` does not get extern builtins, nor do `#![no_core]` crates
1200        if attr::contains_name(&krate.attrs, sym::compiler_builtins)
1201            || attr::contains_name(&krate.attrs, sym::no_core)
1202        {
1203            {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_metadata/src/creader.rs:1203",
                        "rustc_metadata::creader", ::tracing::Level::INFO,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_metadata/src/creader.rs"),
                        ::tracing_core::__macro_support::Option::Some(1203u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_metadata::creader"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::INFO <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::INFO <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                let mut iter = __CALLSITE.metadata().fields().iter();
                __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                    ::tracing::__macro_support::Option::Some(&format_args!("`compiler_builtins` unneeded")
                                            as &dyn Value))])
            });
    } else { ; }
};info!("`compiler_builtins` unneeded");
1204            return;
1205        }
1206
1207        // If a `#![compiler_builtins]` crate already exists, avoid injecting it twice. This is
1208        // the common case since usually it appears as a dependency of `std` or `alloc`.
1209        for (cnum, cmeta) in self.iter_crate_data() {
1210            if cmeta.is_compiler_builtins() {
1211                {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_metadata/src/creader.rs:1211",
                        "rustc_metadata::creader", ::tracing::Level::INFO,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_metadata/src/creader.rs"),
                        ::tracing_core::__macro_support::Option::Some(1211u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_metadata::creader"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::INFO <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::INFO <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                let mut iter = __CALLSITE.metadata().fields().iter();
                __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                    ::tracing::__macro_support::Option::Some(&format_args!("`compiler_builtins` already exists (cnum = {0}); skipping injection",
                                                    cnum) as &dyn Value))])
            });
    } else { ; }
};info!("`compiler_builtins` already exists (cnum = {cnum}); skipping injection");
1212                return;
1213            }
1214        }
1215
1216        // `compiler_builtins` is not yet in the graph; inject it. Error on resolution failure.
1217        let Some(cnum) = self.resolve_crate(
1218            tcx,
1219            sym::compiler_builtins,
1220            krate.spans.inner_span.shrink_to_lo(),
1221            CrateDepKind::Unconditional,
1222            CrateOrigin::Injected,
1223        ) else {
1224            {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_metadata/src/creader.rs:1224",
                        "rustc_metadata::creader", ::tracing::Level::INFO,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_metadata/src/creader.rs"),
                        ::tracing_core::__macro_support::Option::Some(1224u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_metadata::creader"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::INFO <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::INFO <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                let mut iter = __CALLSITE.metadata().fields().iter();
                __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                    ::tracing::__macro_support::Option::Some(&format_args!("`compiler_builtins` not resolved")
                                            as &dyn Value))])
            });
    } else { ; }
};info!("`compiler_builtins` not resolved");
1225            return;
1226        };
1227
1228        // Sanity check that the loaded crate is `#![compiler_builtins]`
1229        let cdata = self.get_crate_data(cnum);
1230        if !cdata.is_compiler_builtins() {
1231            tcx.dcx().emit_err(errors::CrateNotCompilerBuiltins { crate_name: cdata.name() });
1232        }
1233    }
1234
1235    fn report_unused_deps_in_crate(&mut self, tcx: TyCtxt<'_>, krate: &ast::Crate) {
1236        // Make a point span rather than covering the whole file
1237        let span = krate.spans.inner_span.shrink_to_lo();
1238        // Complain about anything left over
1239        for (name, entry) in tcx.sess.opts.externs.iter() {
1240            if let ExternLocation::FoundInLibrarySearchDirectories = entry.location {
1241                // Don't worry about pathless `--extern foo` sysroot references
1242                continue;
1243            }
1244            if entry.nounused_dep || entry.force {
1245                // We're not worried about this one
1246                continue;
1247            }
1248            let name_interned = Symbol::intern(name);
1249            if self.used_extern_options.contains(&name_interned) {
1250                continue;
1251            }
1252
1253            // Got a real unused --extern
1254            if tcx.sess.opts.json_unused_externs.is_enabled() {
1255                self.unused_externs.push(name_interned);
1256                continue;
1257            }
1258
1259            tcx.sess.psess.buffer_lint(
1260                lint::builtin::UNUSED_CRATE_DEPENDENCIES,
1261                span,
1262                ast::CRATE_NODE_ID,
1263                errors::UnusedCrateDependency {
1264                    extern_crate: name_interned,
1265                    local_crate: tcx.crate_name(LOCAL_CRATE),
1266                },
1267            );
1268        }
1269    }
1270
1271    fn report_future_incompatible_deps(&self, tcx: TyCtxt<'_>, krate: &ast::Crate) {
1272        let name = tcx.crate_name(LOCAL_CRATE);
1273
1274        if name.as_str() == "wasm_bindgen" {
1275            let major = env::var("CARGO_PKG_VERSION_MAJOR")
1276                .ok()
1277                .and_then(|major| u64::from_str(&major).ok());
1278            let minor = env::var("CARGO_PKG_VERSION_MINOR")
1279                .ok()
1280                .and_then(|minor| u64::from_str(&minor).ok());
1281            let patch = env::var("CARGO_PKG_VERSION_PATCH")
1282                .ok()
1283                .and_then(|patch| u64::from_str(&patch).ok());
1284
1285            match (major, minor, patch) {
1286                // v1 or bigger is valid.
1287                (Some(1..), _, _) => return,
1288                // v0.3 or bigger is valid.
1289                (Some(0), Some(3..), _) => return,
1290                // v0.2.88 or bigger is valid.
1291                (Some(0), Some(2), Some(88..)) => return,
1292                // Not using Cargo.
1293                (None, None, None) => return,
1294                _ => (),
1295            }
1296
1297            // Make a point span rather than covering the whole file
1298            let span = krate.spans.inner_span.shrink_to_lo();
1299
1300            tcx.sess.dcx().emit_err(errors::WasmCAbi { span });
1301        }
1302    }
1303
1304    pub fn postprocess(&mut self, tcx: TyCtxt<'_>, krate: &ast::Crate) {
1305        self.inject_compiler_builtins(tcx, krate);
1306        self.inject_forced_externs(tcx);
1307        self.inject_profiler_runtime(tcx);
1308        self.inject_allocator_crate(tcx, krate);
1309        self.inject_panic_runtime(tcx, krate);
1310
1311        self.report_unused_deps_in_crate(tcx, krate);
1312        self.report_future_incompatible_deps(tcx, krate);
1313
1314        {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_metadata/src/creader.rs:1314",
                        "rustc_metadata::creader", ::tracing::Level::INFO,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_metadata/src/creader.rs"),
                        ::tracing_core::__macro_support::Option::Some(1314u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_metadata::creader"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::INFO <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::INFO <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                let mut iter = __CALLSITE.metadata().fields().iter();
                __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                    ::tracing::__macro_support::Option::Some(&format_args!("{0:?}",
                                                    CrateDump(self)) as &dyn Value))])
            });
    } else { ; }
};info!("{:?}", CrateDump(self));
1315    }
1316
1317    /// Process an `extern crate foo` AST node.
1318    pub fn process_extern_crate(
1319        &mut self,
1320        tcx: TyCtxt<'_>,
1321        item: &ast::Item,
1322        def_id: LocalDefId,
1323        definitions: &Definitions,
1324    ) -> Option<CrateNum> {
1325        match item.kind {
1326            ast::ItemKind::ExternCrate(orig_name, ident) => {
1327                {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_metadata/src/creader.rs:1327",
                        "rustc_metadata::creader", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_metadata/src/creader.rs"),
                        ::tracing_core::__macro_support::Option::Some(1327u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_metadata::creader"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                let mut iter = __CALLSITE.metadata().fields().iter();
                __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                    ::tracing::__macro_support::Option::Some(&format_args!("resolving extern crate stmt. ident: {0} orig_name: {1:?}",
                                                    ident, orig_name) as &dyn Value))])
            });
    } else { ; }
};debug!("resolving extern crate stmt. ident: {} orig_name: {:?}", ident, orig_name);
1328                let name = match orig_name {
1329                    Some(orig_name) => {
1330                        validate_crate_name(tcx.sess, orig_name, Some(item.span));
1331                        orig_name
1332                    }
1333                    None => ident.name,
1334                };
1335                let dep_kind = if attr::contains_name(&item.attrs, sym::no_link) {
1336                    CrateDepKind::MacrosOnly
1337                } else {
1338                    CrateDepKind::Unconditional
1339                };
1340
1341                let cnum =
1342                    self.resolve_crate(tcx, name, item.span, dep_kind, CrateOrigin::Extern)?;
1343
1344                let path_len = definitions.def_path(def_id).data.len();
1345                self.update_extern_crate(
1346                    cnum,
1347                    name,
1348                    ExternCrate {
1349                        src: ExternCrateSource::Extern(def_id.to_def_id()),
1350                        span: item.span,
1351                        path_len,
1352                        dependency_of: LOCAL_CRATE,
1353                    },
1354                );
1355                Some(cnum)
1356            }
1357            _ => ::rustc_middle::util::bug::bug_fmt(format_args!("impossible case reached"))bug!(),
1358        }
1359    }
1360
1361    pub fn process_path_extern(
1362        &mut self,
1363        tcx: TyCtxt<'_>,
1364        name: Symbol,
1365        span: Span,
1366    ) -> Option<CrateNum> {
1367        let cnum =
1368            self.resolve_crate(tcx, name, span, CrateDepKind::Unconditional, CrateOrigin::Extern)?;
1369
1370        self.update_extern_crate(
1371            cnum,
1372            name,
1373            ExternCrate {
1374                src: ExternCrateSource::Path,
1375                span,
1376                // to have the least priority in `update_extern_crate`
1377                path_len: usize::MAX,
1378                dependency_of: LOCAL_CRATE,
1379            },
1380        );
1381
1382        Some(cnum)
1383    }
1384
1385    pub fn maybe_process_path_extern(&mut self, tcx: TyCtxt<'_>, name: Symbol) -> Option<CrateNum> {
1386        self.maybe_resolve_crate(tcx, name, CrateDepKind::Unconditional, CrateOrigin::Extern).ok()
1387    }
1388}
1389
1390fn fn_spans(krate: &ast::Crate, name: Symbol) -> Vec<Span> {
1391    struct Finder {
1392        name: Symbol,
1393        spans: Vec<Span>,
1394    }
1395    impl<'ast> visit::Visitor<'ast> for Finder {
1396        fn visit_item(&mut self, item: &'ast ast::Item) {
1397            if let Some(ident) = item.kind.ident()
1398                && ident.name == self.name
1399                && attr::contains_name(&item.attrs, sym::rustc_std_internal_symbol)
1400            {
1401                self.spans.push(item.span);
1402            }
1403            visit::walk_item(self, item)
1404        }
1405    }
1406
1407    let mut f = Finder { name, spans: Vec::new() };
1408    visit::walk_crate(&mut f, krate);
1409    f.spans
1410}
1411
1412fn format_dlopen_err(e: &(dyn std::error::Error + 'static)) -> String {
1413    e.sources().map(|e| ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!(": {0}", e))
    })format!(": {e}")).collect()
1414}
1415
1416fn attempt_load_dylib(path: &Path) -> Result<libloading::Library, libloading::Error> {
1417    #[cfg(target_os = "aix")]
1418    if let Some(ext) = path.extension()
1419        && ext.eq("a")
1420    {
1421        // On AIX, we ship all libraries as .a big_af archive
1422        // the expected format is lib<name>.a(libname.so) for the actual
1423        // dynamic library
1424        let library_name = path.file_stem().expect("expect a library name");
1425        let mut archive_member = std::ffi::OsString::from("a(");
1426        archive_member.push(library_name);
1427        archive_member.push(".so)");
1428        let new_path = path.with_extension(archive_member);
1429
1430        // On AIX, we need RTLD_MEMBER to dlopen an archived shared
1431        let flags = libc::RTLD_LAZY | libc::RTLD_LOCAL | libc::RTLD_MEMBER;
1432        return unsafe { libloading::os::unix::Library::open(Some(&new_path), flags) }
1433            .map(|lib| lib.into());
1434    }
1435
1436    unsafe { libloading::Library::new(&path) }
1437}
1438
1439// On Windows the compiler would sometimes intermittently fail to open the
1440// proc-macro DLL with `Error::LoadLibraryExW`. It is suspected that something in the
1441// system still holds a lock on the file, so we retry a few times before calling it
1442// an error.
1443fn load_dylib(path: &Path, max_attempts: usize) -> Result<libloading::Library, String> {
1444    if !(max_attempts > 0) {
    ::core::panicking::panic("assertion failed: max_attempts > 0")
};assert!(max_attempts > 0);
1445
1446    let mut last_error = None;
1447
1448    for attempt in 0..max_attempts {
1449        {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_metadata/src/creader.rs:1449",
                        "rustc_metadata::creader", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_metadata/src/creader.rs"),
                        ::tracing_core::__macro_support::Option::Some(1449u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_metadata::creader"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                let mut iter = __CALLSITE.metadata().fields().iter();
                __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                    ::tracing::__macro_support::Option::Some(&format_args!("Attempt to load proc-macro `{0}`.",
                                                    path.display()) as &dyn Value))])
            });
    } else { ; }
};debug!("Attempt to load proc-macro `{}`.", path.display());
1450        match attempt_load_dylib(path) {
1451            Ok(lib) => {
1452                if attempt > 0 {
1453                    {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_metadata/src/creader.rs:1453",
                        "rustc_metadata::creader", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_metadata/src/creader.rs"),
                        ::tracing_core::__macro_support::Option::Some(1453u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_metadata::creader"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                let mut iter = __CALLSITE.metadata().fields().iter();
                __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                    ::tracing::__macro_support::Option::Some(&format_args!("Loaded proc-macro `{0}` after {1} attempts.",
                                                    path.display(), attempt + 1) as &dyn Value))])
            });
    } else { ; }
};debug!(
1454                        "Loaded proc-macro `{}` after {} attempts.",
1455                        path.display(),
1456                        attempt + 1
1457                    );
1458                }
1459                return Ok(lib);
1460            }
1461            Err(err) => {
1462                // Only try to recover from this specific error.
1463                if !#[allow(non_exhaustive_omitted_patterns)] match err {
    libloading::Error::LoadLibraryExW { .. } => true,
    _ => false,
}matches!(err, libloading::Error::LoadLibraryExW { .. }) {
1464                    {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_metadata/src/creader.rs:1464",
                        "rustc_metadata::creader", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_metadata/src/creader.rs"),
                        ::tracing_core::__macro_support::Option::Some(1464u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_metadata::creader"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                let mut iter = __CALLSITE.metadata().fields().iter();
                __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                    ::tracing::__macro_support::Option::Some(&format_args!("Failed to load proc-macro `{0}`. Not retrying",
                                                    path.display()) as &dyn Value))])
            });
    } else { ; }
};debug!("Failed to load proc-macro `{}`. Not retrying", path.display());
1465                    let err = format_dlopen_err(&err);
1466                    // We include the path of the dylib in the error ourselves, so
1467                    // if it's in the error, we strip it.
1468                    if let Some(err) = err.strip_prefix(&::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!(": {0}", path.display()))
    })format!(": {}", path.display())) {
1469                        return Err(err.to_string());
1470                    }
1471                    return Err(err);
1472                }
1473
1474                last_error = Some(err);
1475                std::thread::sleep(Duration::from_millis(100));
1476                {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_metadata/src/creader.rs:1476",
                        "rustc_metadata::creader", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_metadata/src/creader.rs"),
                        ::tracing_core::__macro_support::Option::Some(1476u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_metadata::creader"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                let mut iter = __CALLSITE.metadata().fields().iter();
                __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                    ::tracing::__macro_support::Option::Some(&format_args!("Failed to load proc-macro `{0}`. Retrying.",
                                                    path.display()) as &dyn Value))])
            });
    } else { ; }
};debug!("Failed to load proc-macro `{}`. Retrying.", path.display());
1477            }
1478        }
1479    }
1480
1481    {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_metadata/src/creader.rs:1481",
                        "rustc_metadata::creader", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_metadata/src/creader.rs"),
                        ::tracing_core::__macro_support::Option::Some(1481u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_metadata::creader"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                let mut iter = __CALLSITE.metadata().fields().iter();
                __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                    ::tracing::__macro_support::Option::Some(&format_args!("Failed to load proc-macro `{0}` even after {1} attempts.",
                                                    path.display(), max_attempts) as &dyn Value))])
            });
    } else { ; }
};debug!("Failed to load proc-macro `{}` even after {} attempts.", path.display(), max_attempts);
1482
1483    let last_error = last_error.unwrap();
1484    let message = if let Some(src) = last_error.source() {
1485        ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{0} ({1}) (retried {2} times)",
                format_dlopen_err(&last_error), src, max_attempts))
    })format!("{} ({src}) (retried {max_attempts} times)", format_dlopen_err(&last_error))
1486    } else {
1487        ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{0} (retried {1} times)",
                format_dlopen_err(&last_error), max_attempts))
    })format!("{} (retried {max_attempts} times)", format_dlopen_err(&last_error))
1488    };
1489    Err(message)
1490}
1491
1492pub enum DylibError {
1493    DlOpen(String, String),
1494    DlSym(String, String),
1495}
1496
1497impl From<DylibError> for CrateError {
1498    fn from(err: DylibError) -> CrateError {
1499        match err {
1500            DylibError::DlOpen(path, err) => CrateError::DlOpen(path, err),
1501            DylibError::DlSym(path, err) => CrateError::DlSym(path, err),
1502        }
1503    }
1504}
1505
1506pub unsafe fn load_symbol_from_dylib<T: Copy>(
1507    path: &Path,
1508    sym_name: &str,
1509) -> Result<T, DylibError> {
1510    // Make sure the path contains a / or the linker will search for it.
1511    let path = try_canonicalize(path).unwrap();
1512    let lib =
1513        load_dylib(&path, 5).map_err(|err| DylibError::DlOpen(path.display().to_string(), err))?;
1514
1515    let sym = unsafe { lib.get::<T>(sym_name.as_bytes()) }
1516        .map_err(|err| DylibError::DlSym(path.display().to_string(), format_dlopen_err(&err)))?;
1517
1518    // Intentionally leak the dynamic library. We can't ever unload it
1519    // since the library can make things that will live arbitrarily long.
1520    let sym = unsafe { sym.into_raw() };
1521    std::mem::forget(lib);
1522
1523    Ok(*sym)
1524}