Skip to main content

rustc_metadata/
creader.rs

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