Skip to main content

rustc_metadata/
creader.rs

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