rustc_metadata/
creader.rs

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