Skip to main content

rustc_metadata/
creader.rs

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