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