rustc_metadata/
creader.rs

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