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);
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<'_>) {
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                        mitigation_name: my_mitigation.kind.to_string(),
504                        mitigation_level: my_mitigation.level.level_str().to_string(),
505                        extern_crate: data.name(),
506                    });
507                }
508            }
509        }
510    }
511
512    // Report about async drop types in dependency if async drop feature is disabled
513    pub fn report_incompatible_async_drop_feature(&self, tcx: TyCtxt<'_>, krate: &Crate) {
514        if tcx.features().async_drop() {
515            return;
516        }
517        for (_cnum, data) in self.iter_crate_data() {
518            if data.is_proc_macro_crate() {
519                continue;
520            }
521            if data.has_async_drops() {
522                let extern_crate = data.name();
523                let local_crate = tcx.crate_name(LOCAL_CRATE);
524                tcx.dcx().emit_warn(diagnostics::AsyncDropTypesInDependency {
525                    span: krate.spans.inner_span.shrink_to_lo(),
526                    extern_crate,
527                    local_crate,
528                });
529            }
530        }
531    }
532
533    pub fn new(metadata_loader: Box<MetadataLoaderDyn>) -> CStore {
534        CStore {
535            metadata_loader,
536            // We add an empty entry for LOCAL_CRATE (which maps to zero) in
537            // order to make array indices in `metas` match with the
538            // corresponding `CrateNum`. This first entry will always remain
539            // `None`.
540            metas: IndexVec::from_iter(iter::once(None)),
541            injected_panic_runtime: None,
542            allocator_kind: None,
543            alloc_error_handler_kind: None,
544            has_global_allocator: false,
545            has_alloc_error_handler: false,
546            hash_to_cnum: UnordMap::default(),
547            resolved_externs: UnordMap::default(),
548            unused_externs: Vec::new(),
549            used_extern_options: Default::default(),
550            has_crate_resolve_with_fail: false,
551        }
552    }
553
554    fn existing_match(&self, name: Symbol, hash: Option<Svh>) -> Option<CrateNum> {
555        let hash = hash?;
556        let cnum = *self.hash_to_cnum.get(&hash)?;
557        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);
558        Some(cnum)
559    }
560
561    /// Determine whether a dependency should be considered private.
562    ///
563    /// Dependencies are private if they get extern option specified, e.g. `--extern priv:mycrate`.
564    /// This is stored in metadata, so `private_dep`  can be correctly set during load. A `Some`
565    /// value for `private_dep` indicates that the crate is known to be private or public (note
566    /// that any `None` or `Some(false)` use of the same crate will make it public).
567    ///
568    /// Sometimes the directly dependent crate is not specified by `--extern`, in this case,
569    /// `private-dep` is none during loading. This is equivalent to the scenario where the
570    /// command parameter is set to `public-dependency`
571    fn is_private_dep(&self, externs: &Externs, name: Symbol, private_dep: Option<bool>) -> bool {
572        let extern_private = externs.get(name.as_str()).map(|e| e.is_private_dep);
573        match (extern_private, private_dep) {
574            // Explicit non-private via `--extern`, explicit non-private from metadata, or
575            // unspecified with default to public.
576            (Some(false), _) | (_, Some(false)) | (None, None) => false,
577            // Marked private via `--extern priv:mycrate` or in metadata.
578            (Some(true) | None, Some(true) | None) => true,
579        }
580    }
581
582    fn register_crate<'tcx>(
583        &mut self,
584        tcx: TyCtxt<'tcx>,
585        host_lib: Option<Library>,
586        origin: CrateOrigin<'_>,
587        lib: Library,
588        dep_kind: CrateDepKind,
589        name: Symbol,
590        private_dep: Option<bool>,
591    ) -> Result<CrateNum, CrateError> {
592        let _prof_timer =
593            tcx.sess.prof.generic_activity_with_arg("metadata_register_crate", name.as_str());
594
595        let Library { source, metadata } = lib;
596        let crate_root = metadata.get_root();
597        let host_hash = host_lib.as_ref().map(|lib| lib.metadata.get_root().hash());
598        let private_dep = self.is_private_dep(&tcx.sess.opts.externs, name, private_dep);
599
600        // Claim this crate number and cache it
601        let feed = self.intern_stable_crate_id(tcx, &crate_root)?;
602        let cnum = feed.key();
603
604        {
    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:604",
                        "rustc_metadata::creader", ::tracing::Level::INFO,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_metadata/src/creader.rs"),
                        ::tracing_core::__macro_support::Option::Some(604u32),
                        ::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!(
605            "register crate `{}` (cnum = {}. private_dep = {})",
606            crate_root.name(),
607            cnum,
608            private_dep
609        );
610
611        // Maintain a reference to the top most crate.
612        // Stash paths for top-most crate locally if necessary.
613        let crate_paths;
614        let dep_root_for_errors = if let Some(dep_root_for_errors) = origin.dep_root_for_errors() {
615            dep_root_for_errors
616        } else {
617            crate_paths = CratePaths::new(crate_root.name(), source.clone());
618            &crate_paths
619        };
620
621        let cnum_map = self.resolve_crate_deps(
622            tcx,
623            dep_root_for_errors,
624            &crate_root,
625            &metadata,
626            cnum,
627            dep_kind,
628            private_dep,
629        )?;
630
631        let raw_proc_macros = if crate_root.is_proc_macro_crate() {
632            let temp_root;
633            let (dlsym_source, dlsym_root) = match &host_lib {
634                Some(host_lib) => (&host_lib.source, {
635                    temp_root = host_lib.metadata.get_root();
636                    &temp_root
637                }),
638                None => (&source, &crate_root),
639            };
640            let dlsym_dylib = dlsym_source.dylib.as_ref().expect("no dylib for a proc-macro crate");
641            Some(self.dlsym_proc_macros(dlsym_dylib, dlsym_root.stable_crate_id())?)
642        } else {
643            None
644        };
645
646        let crate_metadata = CrateMetadata::new(
647            tcx,
648            metadata,
649            crate_root,
650            raw_proc_macros,
651            cnum,
652            cnum_map,
653            dep_kind,
654            source,
655            private_dep,
656            host_hash,
657        );
658
659        self.set_crate_data(cnum, crate_metadata);
660
661        Ok(cnum)
662    }
663
664    fn load_proc_macro<'a, 'b>(
665        &self,
666        sess: &'a Session,
667        locator: &mut CrateLocator<'b>,
668        crate_rejections: &mut CrateRejections,
669        path_kind: PathKind,
670        host_hash: Option<Svh>,
671    ) -> Result<Option<(LoadResult, Option<Library>)>, CrateError>
672    where
673        'a: 'b,
674    {
675        if sess.opts.unstable_opts.dual_proc_macros {
676            // Use a new crate locator and crate rejections so trying to load a proc macro doesn't
677            // affect the error message we emit
678            let mut proc_macro_locator = locator.clone();
679
680            // Try to load a proc macro
681            proc_macro_locator.for_target_proc_macro(sess, path_kind);
682
683            // Load the proc macro crate for the target
684            let target_result =
685                match self.load(&mut proc_macro_locator, &mut CrateRejections::default())? {
686                    Some(LoadResult::Previous(cnum)) => {
687                        return Ok(Some((LoadResult::Previous(cnum), None)));
688                    }
689                    Some(LoadResult::Loaded(library)) => Some(LoadResult::Loaded(library)),
690                    None => return Ok(None),
691                };
692
693            // Use the existing crate_rejections as we want the error message to be affected by
694            // loading the host proc macro.
695            *crate_rejections = CrateRejections::default();
696
697            // Load the proc macro crate for the host
698            locator.for_proc_macro(sess, path_kind);
699
700            locator.hash = host_hash;
701
702            let Some(host_result) = self.load(locator, crate_rejections)? else {
703                return Ok(None);
704            };
705
706            let host_result = match host_result {
707                LoadResult::Previous(..) => {
708                    {
    ::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")
709                }
710                LoadResult::Loaded(library) => library,
711            };
712            Ok(Some((target_result.unwrap(), Some(host_result))))
713        } else {
714            // Use a new crate locator and crate rejections so trying to load a proc macro doesn't
715            // affect the error message we emit
716            let mut proc_macro_locator = locator.clone();
717
718            // Load the proc macro crate for the host
719            proc_macro_locator.for_proc_macro(sess, path_kind);
720
721            let Some(host_result) =
722                self.load(&mut proc_macro_locator, &mut CrateRejections::default())?
723            else {
724                return Ok(None);
725            };
726
727            Ok(Some((host_result, None)))
728        }
729    }
730
731    fn resolve_crate<'tcx>(
732        &mut self,
733        tcx: TyCtxt<'tcx>,
734        name: Symbol,
735        span: Span,
736        dep_kind: CrateDepKind,
737        origin: CrateOrigin<'_>,
738    ) -> Option<CrateNum> {
739        self.used_extern_options.insert(name);
740        match self.maybe_resolve_crate(tcx, name, dep_kind, origin) {
741            Ok(cnum) => {
742                self.set_used_recursively(cnum);
743                Some(cnum)
744            }
745            Err(err) => {
746                {
    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:746",
                        "rustc_metadata::creader", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_metadata/src/creader.rs"),
                        ::tracing_core::__macro_support::Option::Some(746u32),
                        ::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);
747                // crate maybe injrected with `standard_library_imports::inject`, their span is dummy.
748                // we ignore compiler-injected prelude/sysroot loads here so they don't suppress
749                // unrelated diagnostics, such as `unsupported targets for std library` etc,
750                // these maybe helpful for users to resolve crate loading failure.
751                if !tcx.sess.dcx().has_errors().is_some() && !span.is_dummy() {
752                    self.has_crate_resolve_with_fail = true;
753                }
754                let missing_core = self
755                    .maybe_resolve_crate(
756                        tcx,
757                        sym::core,
758                        CrateDepKind::Unconditional,
759                        CrateOrigin::Extern,
760                    )
761                    .is_err();
762                err.report(tcx.sess, span, missing_core);
763                None
764            }
765        }
766    }
767
768    fn maybe_resolve_crate<'b, 'tcx>(
769        &'b mut self,
770        tcx: TyCtxt<'tcx>,
771        name: Symbol,
772        mut dep_kind: CrateDepKind,
773        origin: CrateOrigin<'b>,
774    ) -> Result<CrateNum, CrateError> {
775        {
    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:775",
                        "rustc_metadata::creader", ::tracing::Level::INFO,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_metadata/src/creader.rs"),
                        ::tracing_core::__macro_support::Option::Some(775u32),
                        ::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);
776        if !name.as_str().is_ascii() {
777            return Err(CrateError::NonAsciiName(name));
778        }
779
780        let dep_root_for_errors = origin.dep_root_for_errors();
781        let dep = origin.dep();
782        let hash = dep.map(|d| d.hash);
783        let host_hash = dep.map(|d| d.host_hash).flatten();
784        let extra_filename = dep.map(|d| &d.extra_filename[..]);
785        let path_kind = if dep.is_some() { PathKind::Dependency } else { PathKind::Crate };
786        let private_dep = origin.private_dep();
787
788        let result = if let Some(cnum) = self.existing_match(name, hash) {
789            (LoadResult::Previous(cnum), None)
790        } else {
791            {
    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:791",
                        "rustc_metadata::creader", ::tracing::Level::INFO,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_metadata/src/creader.rs"),
                        ::tracing_core::__macro_support::Option::Some(791u32),
                        ::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");
792            let mut locator = CrateLocator::new(
793                tcx.sess,
794                &*self.metadata_loader,
795                name,
796                // The all loop is because `--crate-type=rlib --crate-type=rlib` is
797                // legal and produces both inside this type.
798                tcx.crate_types().iter().all(|c| *c == CrateType::Rlib),
799                hash,
800                extra_filename,
801                path_kind,
802            );
803            let mut crate_rejections = CrateRejections::default();
804
805            match self.load(&mut locator, &mut crate_rejections)? {
806                Some(res) => (res, None),
807                None => {
808                    {
    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:808",
                        "rustc_metadata::creader", ::tracing::Level::INFO,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_metadata/src/creader.rs"),
                        ::tracing_core::__macro_support::Option::Some(808u32),
                        ::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");
809                    dep_kind = CrateDepKind::MacrosOnly;
810                    match self.load_proc_macro(
811                        tcx.sess,
812                        &mut locator,
813                        &mut crate_rejections,
814                        path_kind,
815                        host_hash,
816                    )? {
817                        Some(res) => res,
818                        None => {
819                            return Err(
820                                locator.into_error(crate_rejections, dep_root_for_errors.cloned())
821                            );
822                        }
823                    }
824                }
825            }
826        };
827
828        match result {
829            (LoadResult::Previous(cnum), None) => {
830                {
    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:830",
                        "rustc_metadata::creader", ::tracing::Level::INFO,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_metadata/src/creader.rs"),
                        ::tracing_core::__macro_support::Option::Some(830u32),
                        ::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);
831                // When `private_dep` is none, it indicates the directly dependent crate. If it is
832                // not specified by `--extern` on command line parameters, it may be
833                // `private-dependency` when `register_crate` is called for the first time. Then it must be updated to
834                // `public-dependency` here.
835                let private_dep = self.is_private_dep(&tcx.sess.opts.externs, name, private_dep);
836                let cdata = self.get_crate_data_mut(cnum);
837                if cdata.is_proc_macro_crate() {
838                    dep_kind = CrateDepKind::MacrosOnly;
839                }
840                cdata.set_dep_kind(cmp::max(cdata.dep_kind(), dep_kind));
841                cdata.update_and_private_dep(private_dep);
842                Ok(cnum)
843            }
844            (LoadResult::Loaded(library), host_library) => {
845                {
    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:845",
                        "rustc_metadata::creader", ::tracing::Level::INFO,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_metadata/src/creader.rs"),
                        ::tracing_core::__macro_support::Option::Some(845u32),
                        ::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);
846                self.register_crate(tcx, host_library, origin, library, dep_kind, name, private_dep)
847            }
848            _ => ::core::panicking::panic("explicit panic")panic!(),
849        }
850    }
851
852    fn load(
853        &self,
854        locator: &CrateLocator<'_>,
855        crate_rejections: &mut CrateRejections,
856    ) -> Result<Option<LoadResult>, CrateError> {
857        let Some(library) = locator.maybe_load_library_crate(crate_rejections)? else {
858            return Ok(None);
859        };
860
861        // In the case that we're loading a crate, but not matching
862        // against a hash, we could load a crate which has the same hash
863        // as an already loaded crate. If this is the case prevent
864        // duplicates by just using the first crate.
865        let root = library.metadata.get_root();
866        let mut result = LoadResult::Loaded(library);
867        for (cnum, data) in self.iter_crate_data() {
868            if data.name() == root.name() && root.hash() == data.hash() {
869                if !locator.hash.is_none() {
    ::core::panicking::panic("assertion failed: locator.hash.is_none()")
};assert!(locator.hash.is_none());
870                {
    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:870",
                        "rustc_metadata::creader", ::tracing::Level::INFO,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_metadata/src/creader.rs"),
                        ::tracing_core::__macro_support::Option::Some(870u32),
                        ::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);
871                result = LoadResult::Previous(cnum);
872                break;
873            }
874        }
875        Ok(Some(result))
876    }
877
878    /// Go through the crate metadata and load any crates that it references.
879    fn resolve_crate_deps(
880        &mut self,
881        tcx: TyCtxt<'_>,
882        dep_root_for_errors: &CratePaths,
883        crate_root: &CrateRoot,
884        metadata: &MetadataBlob,
885        krate: CrateNum,
886        dep_kind: CrateDepKind,
887        parent_is_private: bool,
888    ) -> Result<CrateNumMap, CrateError> {
889        {
    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:889",
                        "rustc_metadata::creader", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_metadata/src/creader.rs"),
                        ::tracing_core::__macro_support::Option::Some(889u32),
                        ::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!(
890            "resolving deps of external crate `{}` with dep root `{}`",
891            crate_root.name(),
892            dep_root_for_errors.name
893        );
894        if crate_root.is_proc_macro_crate() {
895            return Ok(CrateNumMap::new());
896        }
897
898        // The map from crate numbers in the crate we're resolving to local crate numbers.
899        // We map 0 and all other holes in the map to our parent crate. The "additional"
900        // self-dependencies should be harmless.
901        let deps = crate_root.decode_crate_deps(metadata);
902        let mut crate_num_map = CrateNumMap::with_capacity(1 + deps.len());
903        crate_num_map.push(krate);
904        for dep in deps {
905            {
    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:905",
                        "rustc_metadata::creader", ::tracing::Level::INFO,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_metadata/src/creader.rs"),
                        ::tracing_core::__macro_support::Option::Some(905u32),
                        ::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!(
906                "resolving dep `{}`->`{}` hash: `{}` extra filename: `{}` private {}",
907                crate_root.name(),
908                dep.name,
909                dep.hash,
910                dep.extra_filename,
911                dep.is_private,
912            );
913            let dep_kind = match dep_kind {
914                CrateDepKind::MacrosOnly => CrateDepKind::MacrosOnly,
915                _ => dep.kind,
916            };
917            let cnum = self.maybe_resolve_crate(
918                tcx,
919                dep.name,
920                dep_kind,
921                CrateOrigin::IndirectDependency {
922                    dep_root_for_errors,
923                    parent_private: parent_is_private,
924                    dep: &dep,
925                },
926            )?;
927            crate_num_map.push(cnum);
928        }
929
930        {
    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:930",
                        "rustc_metadata::creader", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_metadata/src/creader.rs"),
                        ::tracing_core::__macro_support::Option::Some(930u32),
                        ::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);
931        Ok(crate_num_map)
932    }
933
934    fn dlsym_proc_macros(
935        &self,
936        path: &Path,
937        stable_crate_id: StableCrateId,
938    ) -> Result<&'static [ProcMacroClient], CrateError> {
939        Ok(crate::host_dylib::dlsym_proc_macros(path, stable_crate_id)?)
940    }
941
942    fn inject_panic_runtime(&mut self, tcx: TyCtxt<'_>, krate: &ast::Crate) {
943        // If we're only compiling an rlib, then there's no need to select a
944        // panic runtime, so we just skip this section entirely.
945        let only_rlib = tcx.crate_types().iter().all(|ct| *ct == CrateType::Rlib);
946        if only_rlib {
947            {
    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:947",
                        "rustc_metadata::creader", ::tracing::Level::INFO,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_metadata/src/creader.rs"),
                        ::tracing_core::__macro_support::Option::Some(947u32),
                        ::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");
948            return;
949        }
950
951        // If we need a panic runtime, we try to find an existing one here. At
952        // the same time we perform some general validation of the DAG we've got
953        // going such as ensuring everything has a compatible panic strategy.
954        let mut needs_panic_runtime = attr::contains_name(&krate.attrs, sym::needs_panic_runtime);
955        for (_cnum, data) in self.iter_crate_data() {
956            needs_panic_runtime |= data.needs_panic_runtime();
957        }
958
959        // If we just don't need a panic runtime at all, then we're done here
960        // and there's nothing else to do.
961        if !needs_panic_runtime {
962            return;
963        }
964
965        // By this point we know that we need a panic runtime. Here we just load
966        // an appropriate default runtime for our panic strategy.
967        //
968        // We may resolve to an already loaded crate (as the crate may not have
969        // been explicitly linked prior to this), but this is fine.
970        //
971        // Also note that we have yet to perform validation of the crate graph
972        // in terms of everyone has a compatible panic runtime format, that's
973        // performed later as part of the `dependency_format` module.
974        let desired_strategy = tcx.sess.panic_strategy();
975        let name = match desired_strategy {
976            PanicStrategy::Unwind => sym::panic_unwind,
977            PanicStrategy::Abort => sym::panic_abort,
978            PanicStrategy::ImmediateAbort => {
979                // Immediate-aborting panics don't use a runtime.
980                return;
981            }
982        };
983        {
    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:983",
                        "rustc_metadata::creader", ::tracing::Level::INFO,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_metadata/src/creader.rs"),
                        ::tracing_core::__macro_support::Option::Some(983u32),
                        ::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);
984
985        // This has to be conditional as both panic_unwind and panic_abort may be present in the
986        // crate graph at the same time. One of them will later be activated in dependency_formats.
987        let Some(cnum) = self.resolve_crate(
988            tcx,
989            name,
990            DUMMY_SP,
991            CrateDepKind::Conditional,
992            CrateOrigin::Injected,
993        ) else {
994            return;
995        };
996        let cdata = self.get_crate_data(cnum);
997
998        // Sanity check the loaded crate to ensure it is indeed a panic runtime
999        // and the panic strategy is indeed what we thought it was.
1000        if !cdata.is_panic_runtime() {
1001            tcx.dcx().emit_err(diagnostics::CrateNotPanicRuntime { crate_name: name });
1002        }
1003        if cdata.required_panic_strategy() != Some(desired_strategy) {
1004            tcx.dcx().emit_err(diagnostics::NoPanicStrategy {
1005                crate_name: name,
1006                strategy: desired_strategy,
1007            });
1008        }
1009
1010        self.injected_panic_runtime = Some(cnum);
1011    }
1012
1013    fn inject_profiler_runtime(&mut self, tcx: TyCtxt<'_>) {
1014        let needs_profiler_runtime =
1015            tcx.sess.instrument_coverage() || tcx.sess.opts.cg.profile_generate.enabled();
1016        if !needs_profiler_runtime || tcx.sess.opts.unstable_opts.no_profiler_runtime {
1017            return;
1018        }
1019
1020        {
    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:1020",
                        "rustc_metadata::creader", ::tracing::Level::INFO,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_metadata/src/creader.rs"),
                        ::tracing_core::__macro_support::Option::Some(1020u32),
                        ::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");
1021
1022        // HACK: This uses conditional despite actually being unconditional to ensure that
1023        // there is no error emitted when two dylibs independently depend on profiler_builtins.
1024        // This is fine as profiler_builtins is always statically linked into the dylib just
1025        // like compiler_builtins. Unlike compiler_builtins however there is no guaranteed
1026        // common dylib that the duplicate crate check believes the crate to be included in.
1027        // add_upstream_rust_crates has a corresponding check that forces profiler_builtins
1028        // to be statically linked in even when marked as NotLinked.
1029        let name = Symbol::intern(&tcx.sess.opts.unstable_opts.profiler_runtime);
1030        let Some(cnum) = self.resolve_crate(
1031            tcx,
1032            name,
1033            DUMMY_SP,
1034            CrateDepKind::Conditional,
1035            CrateOrigin::Injected,
1036        ) else {
1037            return;
1038        };
1039        let cdata = self.get_crate_data(cnum);
1040
1041        // Sanity check the loaded crate to ensure it is indeed a profiler runtime
1042        if !cdata.is_profiler_runtime() {
1043            tcx.dcx().emit_err(diagnostics::NotProfilerRuntime { crate_name: name });
1044        }
1045    }
1046
1047    fn inject_allocator_crate(&mut self, tcx: TyCtxt<'_>, krate: &ast::Crate) {
1048        self.has_global_allocator =
1049            match &*fn_spans(krate, Symbol::intern(&global_fn_name(sym::alloc))) {
1050                [span1, span2, ..] => {
1051                    tcx.dcx().emit_err(diagnostics::NoMultipleGlobalAlloc {
1052                        span2: *span2,
1053                        span1: *span1,
1054                    });
1055                    true
1056                }
1057                spans => !spans.is_empty(),
1058            };
1059        let alloc_error_handler = Symbol::intern(&global_fn_name(ALLOC_ERROR_HANDLER));
1060        self.has_alloc_error_handler = match &*fn_spans(krate, alloc_error_handler) {
1061            [span1, span2, ..] => {
1062                tcx.dcx().emit_err(diagnostics::NoMultipleAllocErrorHandler {
1063                    span2: *span2,
1064                    span1: *span1,
1065                });
1066                true
1067            }
1068            spans => !spans.is_empty(),
1069        };
1070
1071        // Check to see if we actually need an allocator. This desire comes
1072        // about through the `#![needs_allocator]` attribute and is typically
1073        // written down in liballoc.
1074        if !attr::contains_name(&krate.attrs, sym::needs_allocator)
1075            && !self.iter_crate_data().any(|(_, data)| data.needs_allocator())
1076        {
1077            return;
1078        }
1079
1080        // At this point we've determined that we need an allocator. Let's see
1081        // if our compilation session actually needs an allocator based on what
1082        // we're emitting.
1083        let all_rlib = tcx.crate_types().iter().all(|ct| #[allow(non_exhaustive_omitted_patterns)] match *ct {
    CrateType::Rlib => true,
    _ => false,
}matches!(*ct, CrateType::Rlib));
1084        if all_rlib {
1085            return;
1086        }
1087
1088        // Ok, we need an allocator. Not only that but we're actually going to
1089        // create an artifact that needs one linked in. Let's go find the one
1090        // that we're going to link in.
1091        //
1092        // First up we check for global allocators. Look at the crate graph here
1093        // and see what's a global allocator, including if we ourselves are a
1094        // global allocator.
1095        #[allow(rustc::symbol_intern_string_literal)]
1096        let this_crate = Symbol::intern("this crate");
1097
1098        let mut global_allocator = self.has_global_allocator.then_some(this_crate);
1099        for (_, data) in self.iter_crate_data() {
1100            if data.has_global_allocator() {
1101                match global_allocator {
1102                    Some(other_crate) => {
1103                        tcx.dcx().emit_err(diagnostics::ConflictingGlobalAlloc {
1104                            crate_name: data.name(),
1105                            other_crate_name: other_crate,
1106                        });
1107                    }
1108                    None => global_allocator = Some(data.name()),
1109                }
1110            }
1111        }
1112        let mut alloc_error_handler = self.has_alloc_error_handler.then_some(this_crate);
1113        for (_, data) in self.iter_crate_data() {
1114            if data.has_alloc_error_handler() {
1115                match alloc_error_handler {
1116                    Some(other_crate) => {
1117                        tcx.dcx().emit_err(diagnostics::ConflictingAllocErrorHandler {
1118                            crate_name: data.name(),
1119                            other_crate_name: other_crate,
1120                        });
1121                    }
1122                    None => alloc_error_handler = Some(data.name()),
1123                }
1124            }
1125        }
1126
1127        if global_allocator.is_some() {
1128            self.allocator_kind = Some(AllocatorKind::Global);
1129        } else {
1130            // Ok we haven't found a global allocator but we still need an
1131            // allocator. At this point our allocator request is typically fulfilled
1132            // by the standard library, denoted by the `#![default_lib_allocator]`
1133            // attribute.
1134            if !attr::contains_name(&krate.attrs, sym::default_lib_allocator)
1135                && !self.iter_crate_data().any(|(_, data)| data.has_default_lib_allocator())
1136            {
1137                tcx.dcx().emit_err(diagnostics::GlobalAllocRequired);
1138            }
1139            self.allocator_kind = Some(AllocatorKind::Default);
1140        }
1141
1142        if alloc_error_handler.is_some() {
1143            self.alloc_error_handler_kind = Some(AllocatorKind::Global);
1144        } else {
1145            // The alloc crate provides a default allocation error handler if
1146            // one isn't specified.
1147            self.alloc_error_handler_kind = Some(AllocatorKind::Default);
1148        }
1149    }
1150
1151    fn inject_forced_externs(&mut self, tcx: TyCtxt<'_>) {
1152        for (name, entry) in tcx.sess.opts.externs.iter() {
1153            if entry.force {
1154                let name_interned = Symbol::intern(name);
1155                if !self.used_extern_options.contains(&name_interned) {
1156                    self.resolve_crate(
1157                        tcx,
1158                        name_interned,
1159                        DUMMY_SP,
1160                        CrateDepKind::Unconditional,
1161                        CrateOrigin::Extern,
1162                    );
1163                }
1164            }
1165        }
1166    }
1167
1168    /// Inject the `compiler_builtins` crate if it is not already in the graph.
1169    fn inject_compiler_builtins(&mut self, tcx: TyCtxt<'_>, krate: &ast::Crate) {
1170        // `compiler_builtins` does not get extern builtins, nor do `#![no_core]` crates
1171        if attr::contains_name(&krate.attrs, sym::compiler_builtins)
1172            || attr::contains_name(&krate.attrs, sym::no_core)
1173        {
1174            {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_metadata/src/creader.rs:1174",
                        "rustc_metadata::creader", ::tracing::Level::INFO,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_metadata/src/creader.rs"),
                        ::tracing_core::__macro_support::Option::Some(1174u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_metadata::creader"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::INFO <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::INFO <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                __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");
1175            return;
1176        }
1177
1178        // If a `#![compiler_builtins]` crate already exists, avoid injecting it twice. This is
1179        // the common case since usually it appears as a dependency of `std` or `alloc`.
1180        for (cnum, cmeta) in self.iter_crate_data() {
1181            if cmeta.is_compiler_builtins() {
1182                {
    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:1182",
                        "rustc_metadata::creader", ::tracing::Level::INFO,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_metadata/src/creader.rs"),
                        ::tracing_core::__macro_support::Option::Some(1182u32),
                        ::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");
1183                return;
1184            }
1185        }
1186
1187        // `compiler_builtins` is not yet in the graph; inject it. Error on resolution failure.
1188        let Some(cnum) = self.resolve_crate(
1189            tcx,
1190            sym::compiler_builtins,
1191            krate.spans.inner_span.shrink_to_lo(),
1192            CrateDepKind::Unconditional,
1193            CrateOrigin::Injected,
1194        ) else {
1195            {
    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:1195",
                        "rustc_metadata::creader", ::tracing::Level::INFO,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_metadata/src/creader.rs"),
                        ::tracing_core::__macro_support::Option::Some(1195u32),
                        ::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");
1196            return;
1197        };
1198
1199        // Sanity check that the loaded crate is `#![compiler_builtins]`
1200        let cdata = self.get_crate_data(cnum);
1201        if !cdata.is_compiler_builtins() {
1202            tcx.dcx().emit_err(diagnostics::CrateNotCompilerBuiltins { crate_name: cdata.name() });
1203        }
1204    }
1205
1206    fn report_unused_deps_in_crate(&mut self, tcx: TyCtxt<'_>, krate: &ast::Crate) {
1207        // Make a point span rather than covering the whole file
1208        let span = krate.spans.inner_span.shrink_to_lo();
1209        // Complain about anything left over
1210        for (name, entry) in tcx.sess.opts.externs.iter() {
1211            if let ExternLocation::FoundInLibrarySearchDirectories = entry.location {
1212                // Don't worry about pathless `--extern foo` sysroot references
1213                continue;
1214            }
1215            if entry.nounused_dep || entry.force {
1216                // We're not worried about this one
1217                continue;
1218            }
1219            let name_interned = Symbol::intern(name);
1220            if self.used_extern_options.contains(&name_interned) {
1221                continue;
1222            }
1223
1224            // Got a real unused --extern
1225            if tcx.sess.opts.json_unused_externs.is_enabled() {
1226                self.unused_externs.push(name_interned);
1227                continue;
1228            }
1229
1230            tcx.sess.psess.buffer_lint(
1231                lint::builtin::UNUSED_CRATE_DEPENDENCIES,
1232                span,
1233                ast::CRATE_NODE_ID,
1234                diagnostics::UnusedCrateDependency {
1235                    extern_crate: name_interned,
1236                    local_crate: tcx.crate_name(LOCAL_CRATE),
1237                },
1238            );
1239        }
1240    }
1241
1242    fn report_future_incompatible_deps(&self, tcx: TyCtxt<'_>, krate: &ast::Crate) {
1243        let name = tcx.crate_name(LOCAL_CRATE);
1244
1245        if name.as_str() == "wasm_bindgen" {
1246            let major = env::var("CARGO_PKG_VERSION_MAJOR")
1247                .ok()
1248                .and_then(|major| u64::from_str(&major).ok());
1249            let minor = env::var("CARGO_PKG_VERSION_MINOR")
1250                .ok()
1251                .and_then(|minor| u64::from_str(&minor).ok());
1252            let patch = env::var("CARGO_PKG_VERSION_PATCH")
1253                .ok()
1254                .and_then(|patch| u64::from_str(&patch).ok());
1255
1256            match (major, minor, patch) {
1257                // v1 or bigger is valid.
1258                (Some(1..), _, _) => return,
1259                // v0.3 or bigger is valid.
1260                (Some(0), Some(3..), _) => return,
1261                // v0.2.88 or bigger is valid.
1262                (Some(0), Some(2), Some(88..)) => return,
1263                // Not using Cargo.
1264                (None, None, None) => return,
1265                _ => (),
1266            }
1267
1268            // Make a point span rather than covering the whole file
1269            let span = krate.spans.inner_span.shrink_to_lo();
1270
1271            tcx.sess.dcx().emit_err(diagnostics::WasmCAbi { span });
1272        }
1273    }
1274
1275    pub fn postprocess(&mut self, tcx: TyCtxt<'_>, krate: &ast::Crate) {
1276        self.inject_compiler_builtins(tcx, krate);
1277        self.inject_forced_externs(tcx);
1278        self.inject_profiler_runtime(tcx);
1279        self.inject_allocator_crate(tcx, krate);
1280        self.inject_panic_runtime(tcx, krate);
1281
1282        self.report_unused_deps_in_crate(tcx, krate);
1283        self.report_future_incompatible_deps(tcx, krate);
1284
1285        {
    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:1285",
                        "rustc_metadata::creader", ::tracing::Level::INFO,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_metadata/src/creader.rs"),
                        ::tracing_core::__macro_support::Option::Some(1285u32),
                        ::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));
1286    }
1287
1288    /// Process an `extern crate foo` AST node.
1289    pub fn process_extern_crate(
1290        &mut self,
1291        tcx: TyCtxt<'_>,
1292        item: &ast::Item,
1293        def_id: LocalDefId,
1294        definitions: &Definitions,
1295    ) -> Option<CrateNum> {
1296        match item.kind {
1297            ast::ItemKind::ExternCrate(orig_name, ident) => {
1298                {
    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:1298",
                        "rustc_metadata::creader", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_metadata/src/creader.rs"),
                        ::tracing_core::__macro_support::Option::Some(1298u32),
                        ::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);
1299                let name = match orig_name {
1300                    Some(orig_name) => {
1301                        validate_crate_name(tcx.sess, orig_name, Some(item.span));
1302                        orig_name
1303                    }
1304                    None => ident.name,
1305                };
1306                let dep_kind = if attr::contains_name(&item.attrs, sym::no_link) {
1307                    CrateDepKind::MacrosOnly
1308                } else {
1309                    CrateDepKind::Unconditional
1310                };
1311
1312                let cnum =
1313                    self.resolve_crate(tcx, name, item.span, dep_kind, CrateOrigin::Extern)?;
1314
1315                let path_len = definitions.def_path(def_id).data.len();
1316                self.update_extern_crate(
1317                    cnum,
1318                    name,
1319                    ExternCrate {
1320                        src: ExternCrateSource::Extern(def_id.to_def_id()),
1321                        span: item.span,
1322                        path_len,
1323                        dependency_of: LOCAL_CRATE,
1324                    },
1325                );
1326                Some(cnum)
1327            }
1328            _ => ::rustc_middle::util::bug::bug_fmt(format_args!("impossible case reached"))bug!(),
1329        }
1330    }
1331
1332    pub fn process_path_extern(
1333        &mut self,
1334        tcx: TyCtxt<'_>,
1335        name: Symbol,
1336        span: Span,
1337    ) -> Option<CrateNum> {
1338        let cnum =
1339            self.resolve_crate(tcx, name, span, CrateDepKind::Unconditional, CrateOrigin::Extern)?;
1340
1341        self.update_extern_crate(
1342            cnum,
1343            name,
1344            ExternCrate {
1345                src: ExternCrateSource::Path,
1346                span,
1347                // to have the least priority in `update_extern_crate`
1348                path_len: usize::MAX,
1349                dependency_of: LOCAL_CRATE,
1350            },
1351        );
1352
1353        Some(cnum)
1354    }
1355
1356    pub fn maybe_process_path_extern(&mut self, tcx: TyCtxt<'_>, name: Symbol) -> Option<CrateNum> {
1357        self.maybe_resolve_crate(tcx, name, CrateDepKind::Unconditional, CrateOrigin::Extern).ok()
1358    }
1359}
1360
1361fn fn_spans(krate: &ast::Crate, name: Symbol) -> Vec<Span> {
1362    struct Finder {
1363        name: Symbol,
1364        spans: Vec<Span>,
1365    }
1366    impl<'ast> visit::Visitor<'ast> for Finder {
1367        fn visit_item(&mut self, item: &'ast ast::Item) {
1368            if let Some(ident) = item.kind.ident()
1369                && ident.name == self.name
1370                && attr::contains_name(&item.attrs, sym::rustc_std_internal_symbol)
1371            {
1372                self.spans.push(item.span);
1373            }
1374            visit::walk_item(self, item)
1375        }
1376    }
1377
1378    let mut f = Finder { name, spans: Vec::new() };
1379    visit::walk_crate(&mut f, krate);
1380    f.spans
1381}