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