]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_metadata/src/creader.rs
Auto merge of #106449 - GuillaumeGomez:rustdoc-gui-retry-mechanism, r=Mark-Simulacrum
[rust.git] / compiler / rustc_metadata / src / creader.rs
1 //! Validates all used crates and extern libraries and loads their metadata
2
3 use crate::errors::{
4     ConflictingAllocErrorHandler, ConflictingGlobalAlloc, CrateNotPanicRuntime,
5     GlobalAllocRequired, NoMultipleAllocErrorHandler, NoMultipleGlobalAlloc, NoPanicStrategy,
6     NoTransitiveNeedsDep, NotProfilerRuntime, ProfilerBuiltinsNeedsCore,
7 };
8 use crate::locator::{CrateError, CrateLocator, CratePaths};
9 use crate::rmeta::{CrateDep, CrateMetadata, CrateNumMap, CrateRoot, MetadataBlob};
10
11 use rustc_ast::expand::allocator::AllocatorKind;
12 use rustc_ast::{self as ast, *};
13 use rustc_data_structures::fx::{FxHashMap, FxHashSet};
14 use rustc_data_structures::svh::Svh;
15 use rustc_data_structures::sync::{Lrc, ReadGuard};
16 use rustc_expand::base::SyntaxExtension;
17 use rustc_hir::def_id::{CrateNum, LocalDefId, StableCrateId, LOCAL_CRATE};
18 use rustc_hir::definitions::Definitions;
19 use rustc_index::vec::IndexVec;
20 use rustc_middle::ty::TyCtxt;
21 use rustc_session::config::{self, CrateType, ExternLocation};
22 use rustc_session::cstore::{CrateDepKind, CrateSource, ExternCrate};
23 use rustc_session::cstore::{ExternCrateSource, MetadataLoaderDyn};
24 use rustc_session::lint;
25 use rustc_session::output::validate_crate_name;
26 use rustc_session::search_paths::PathKind;
27 use rustc_session::Session;
28 use rustc_span::edition::Edition;
29 use rustc_span::symbol::{sym, Symbol};
30 use rustc_span::{Span, DUMMY_SP};
31 use rustc_target::spec::{PanicStrategy, TargetTriple};
32
33 use proc_macro::bridge::client::ProcMacro;
34 use std::ops::Fn;
35 use std::path::Path;
36 use std::{cmp, env};
37
38 #[derive(Clone)]
39 pub struct CStore {
40     metas: IndexVec<CrateNum, Option<Lrc<CrateMetadata>>>,
41     injected_panic_runtime: Option<CrateNum>,
42     /// This crate needs an allocator and either provides it itself, or finds it in a dependency.
43     /// If the above is true, then this field denotes the kind of the found allocator.
44     allocator_kind: Option<AllocatorKind>,
45     /// This crate needs an allocation error handler and either provides it itself, or finds it in a dependency.
46     /// If the above is true, then this field denotes the kind of the found allocator.
47     alloc_error_handler_kind: Option<AllocatorKind>,
48     /// This crate has a `#[global_allocator]` item.
49     has_global_allocator: bool,
50     /// This crate has a `#[alloc_error_handler]` item.
51     has_alloc_error_handler: bool,
52
53     /// This map is used to verify we get no hash conflicts between
54     /// `StableCrateId` values.
55     pub(crate) stable_crate_ids: FxHashMap<StableCrateId, CrateNum>,
56
57     /// Unused externs of the crate
58     unused_externs: Vec<Symbol>,
59 }
60
61 impl std::fmt::Debug for CStore {
62     fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
63         f.debug_struct("CStore").finish_non_exhaustive()
64     }
65 }
66
67 pub struct CrateLoader<'a> {
68     // Immutable configuration.
69     sess: &'a Session,
70     metadata_loader: &'a MetadataLoaderDyn,
71     definitions: ReadGuard<'a, Definitions>,
72     local_crate_name: Symbol,
73     // Mutable output.
74     cstore: &'a mut CStore,
75     used_extern_options: &'a mut FxHashSet<Symbol>,
76 }
77
78 pub enum LoadedMacro {
79     MacroDef(ast::Item, Edition),
80     ProcMacro(SyntaxExtension),
81 }
82
83 pub(crate) struct Library {
84     pub source: CrateSource,
85     pub metadata: MetadataBlob,
86 }
87
88 enum LoadResult {
89     Previous(CrateNum),
90     Loaded(Library),
91 }
92
93 /// A reference to `CrateMetadata` that can also give access to whole crate store when necessary.
94 #[derive(Clone, Copy)]
95 pub(crate) struct CrateMetadataRef<'a> {
96     pub cdata: &'a CrateMetadata,
97     pub cstore: &'a CStore,
98 }
99
100 impl std::ops::Deref for CrateMetadataRef<'_> {
101     type Target = CrateMetadata;
102
103     fn deref(&self) -> &Self::Target {
104         self.cdata
105     }
106 }
107
108 struct CrateDump<'a>(&'a CStore);
109
110 impl<'a> std::fmt::Debug for CrateDump<'a> {
111     fn fmt(&self, fmt: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
112         writeln!(fmt, "resolved crates:")?;
113         for (cnum, data) in self.0.iter_crate_data() {
114             writeln!(fmt, "  name: {}", data.name())?;
115             writeln!(fmt, "  cnum: {cnum}")?;
116             writeln!(fmt, "  hash: {}", data.hash())?;
117             writeln!(fmt, "  reqd: {:?}", data.dep_kind())?;
118             let CrateSource { dylib, rlib, rmeta } = data.source();
119             if let Some(dylib) = dylib {
120                 writeln!(fmt, "  dylib: {}", dylib.0.display())?;
121             }
122             if let Some(rlib) = rlib {
123                 writeln!(fmt, "   rlib: {}", rlib.0.display())?;
124             }
125             if let Some(rmeta) = rmeta {
126                 writeln!(fmt, "   rmeta: {}", rmeta.0.display())?;
127             }
128         }
129         Ok(())
130     }
131 }
132
133 impl CStore {
134     pub fn from_tcx(tcx: TyCtxt<'_>) -> &CStore {
135         tcx.cstore_untracked()
136             .as_any()
137             .downcast_ref::<CStore>()
138             .expect("`tcx.cstore` is not a `CStore`")
139     }
140
141     fn alloc_new_crate_num(&mut self) -> CrateNum {
142         self.metas.push(None);
143         CrateNum::new(self.metas.len() - 1)
144     }
145
146     pub fn has_crate_data(&self, cnum: CrateNum) -> bool {
147         self.metas[cnum].is_some()
148     }
149
150     pub(crate) fn get_crate_data(&self, cnum: CrateNum) -> CrateMetadataRef<'_> {
151         let cdata = self.metas[cnum]
152             .as_ref()
153             .unwrap_or_else(|| panic!("Failed to get crate data for {cnum:?}"));
154         CrateMetadataRef { cdata, cstore: self }
155     }
156
157     fn set_crate_data(&mut self, cnum: CrateNum, data: CrateMetadata) {
158         assert!(self.metas[cnum].is_none(), "Overwriting crate metadata entry");
159         self.metas[cnum] = Some(Lrc::new(data));
160     }
161
162     pub(crate) fn iter_crate_data(&self) -> impl Iterator<Item = (CrateNum, &CrateMetadata)> {
163         self.metas
164             .iter_enumerated()
165             .filter_map(|(cnum, data)| data.as_deref().map(|data| (cnum, data)))
166     }
167
168     fn push_dependencies_in_postorder(&self, deps: &mut Vec<CrateNum>, cnum: CrateNum) {
169         if !deps.contains(&cnum) {
170             let data = self.get_crate_data(cnum);
171             for &dep in data.dependencies().iter() {
172                 if dep != cnum {
173                     self.push_dependencies_in_postorder(deps, dep);
174                 }
175             }
176
177             deps.push(cnum);
178         }
179     }
180
181     pub(crate) fn crate_dependencies_in_postorder(&self, cnum: CrateNum) -> Vec<CrateNum> {
182         let mut deps = Vec::new();
183         if cnum == LOCAL_CRATE {
184             for (cnum, _) in self.iter_crate_data() {
185                 self.push_dependencies_in_postorder(&mut deps, cnum);
186             }
187         } else {
188             self.push_dependencies_in_postorder(&mut deps, cnum);
189         }
190         deps
191     }
192
193     fn crate_dependencies_in_reverse_postorder(&self, cnum: CrateNum) -> Vec<CrateNum> {
194         let mut deps = self.crate_dependencies_in_postorder(cnum);
195         deps.reverse();
196         deps
197     }
198
199     pub(crate) fn injected_panic_runtime(&self) -> Option<CrateNum> {
200         self.injected_panic_runtime
201     }
202
203     pub(crate) fn allocator_kind(&self) -> Option<AllocatorKind> {
204         self.allocator_kind
205     }
206
207     pub(crate) fn alloc_error_handler_kind(&self) -> Option<AllocatorKind> {
208         self.alloc_error_handler_kind
209     }
210
211     pub(crate) fn has_global_allocator(&self) -> bool {
212         self.has_global_allocator
213     }
214
215     pub(crate) fn has_alloc_error_handler(&self) -> bool {
216         self.has_alloc_error_handler
217     }
218
219     pub fn report_unused_deps(&self, tcx: TyCtxt<'_>) {
220         let json_unused_externs = tcx.sess.opts.json_unused_externs;
221
222         // We put the check for the option before the lint_level_at_node call
223         // because the call mutates internal state and introducing it
224         // leads to some ui tests failing.
225         if !json_unused_externs.is_enabled() {
226             return;
227         }
228         let level = tcx
229             .lint_level_at_node(lint::builtin::UNUSED_CRATE_DEPENDENCIES, rustc_hir::CRATE_HIR_ID)
230             .0;
231         if level != lint::Level::Allow {
232             let unused_externs =
233                 self.unused_externs.iter().map(|ident| ident.to_ident_string()).collect::<Vec<_>>();
234             let unused_externs = unused_externs.iter().map(String::as_str).collect::<Vec<&str>>();
235             tcx.sess.parse_sess.span_diagnostic.emit_unused_externs(
236                 level,
237                 json_unused_externs.is_loud(),
238                 &unused_externs,
239             );
240         }
241     }
242
243     pub fn new(sess: &Session) -> CStore {
244         let mut stable_crate_ids = FxHashMap::default();
245         stable_crate_ids.insert(sess.local_stable_crate_id(), LOCAL_CRATE);
246         CStore {
247             // We add an empty entry for LOCAL_CRATE (which maps to zero) in
248             // order to make array indices in `metas` match with the
249             // corresponding `CrateNum`. This first entry will always remain
250             // `None`.
251             metas: IndexVec::from_elem_n(None, 1),
252             injected_panic_runtime: None,
253             allocator_kind: None,
254             alloc_error_handler_kind: None,
255             has_global_allocator: false,
256             has_alloc_error_handler: false,
257             stable_crate_ids,
258             unused_externs: Vec::new(),
259         }
260     }
261 }
262
263 impl<'a> CrateLoader<'a> {
264     pub fn new(
265         sess: &'a Session,
266         metadata_loader: &'a MetadataLoaderDyn,
267         local_crate_name: Symbol,
268         cstore: &'a mut CStore,
269         definitions: ReadGuard<'a, Definitions>,
270         used_extern_options: &'a mut FxHashSet<Symbol>,
271     ) -> Self {
272         CrateLoader {
273             sess,
274             metadata_loader,
275             local_crate_name,
276             cstore,
277             used_extern_options,
278             definitions,
279         }
280     }
281     pub fn cstore(&self) -> &CStore {
282         &self.cstore
283     }
284
285     fn existing_match(&self, name: Symbol, hash: Option<Svh>, kind: PathKind) -> Option<CrateNum> {
286         for (cnum, data) in self.cstore.iter_crate_data() {
287             if data.name() != name {
288                 trace!("{} did not match {}", data.name(), name);
289                 continue;
290             }
291
292             match hash {
293                 Some(hash) if hash == data.hash() => return Some(cnum),
294                 Some(hash) => {
295                     debug!("actual hash {} did not match expected {}", hash, data.hash());
296                     continue;
297                 }
298                 None => {}
299             }
300
301             // When the hash is None we're dealing with a top-level dependency
302             // in which case we may have a specification on the command line for
303             // this library. Even though an upstream library may have loaded
304             // something of the same name, we have to make sure it was loaded
305             // from the exact same location as well.
306             //
307             // We're also sure to compare *paths*, not actual byte slices. The
308             // `source` stores paths which are normalized which may be different
309             // from the strings on the command line.
310             let source = self.cstore.get_crate_data(cnum).cdata.source();
311             if let Some(entry) = self.sess.opts.externs.get(name.as_str()) {
312                 // Only use `--extern crate_name=path` here, not `--extern crate_name`.
313                 if let Some(mut files) = entry.files() {
314                     if files.any(|l| {
315                         let l = l.canonicalized();
316                         source.dylib.as_ref().map(|(p, _)| p) == Some(l)
317                             || source.rlib.as_ref().map(|(p, _)| p) == Some(l)
318                             || source.rmeta.as_ref().map(|(p, _)| p) == Some(l)
319                     }) {
320                         return Some(cnum);
321                     }
322                 }
323                 continue;
324             }
325
326             // Alright, so we've gotten this far which means that `data` has the
327             // right name, we don't have a hash, and we don't have a --extern
328             // pointing for ourselves. We're still not quite yet done because we
329             // have to make sure that this crate was found in the crate lookup
330             // path (this is a top-level dependency) as we don't want to
331             // implicitly load anything inside the dependency lookup path.
332             let prev_kind = source
333                 .dylib
334                 .as_ref()
335                 .or(source.rlib.as_ref())
336                 .or(source.rmeta.as_ref())
337                 .expect("No sources for crate")
338                 .1;
339             if kind.matches(prev_kind) {
340                 return Some(cnum);
341             } else {
342                 debug!(
343                     "failed to load existing crate {}; kind {:?} did not match prev_kind {:?}",
344                     name, kind, prev_kind
345                 );
346             }
347         }
348
349         None
350     }
351
352     fn verify_no_symbol_conflicts(&self, root: &CrateRoot) -> Result<(), CrateError> {
353         // Check for (potential) conflicts with the local crate
354         if self.sess.local_stable_crate_id() == root.stable_crate_id() {
355             return Err(CrateError::SymbolConflictsCurrent(root.name()));
356         }
357
358         // Check for conflicts with any crate loaded so far
359         for (_, other) in self.cstore.iter_crate_data() {
360             // Same stable crate id but different SVH
361             if other.stable_crate_id() == root.stable_crate_id() && other.hash() != root.hash() {
362                 return Err(CrateError::SymbolConflictsOthers(root.name()));
363             }
364         }
365
366         Ok(())
367     }
368
369     fn verify_no_stable_crate_id_hash_conflicts(
370         &mut self,
371         root: &CrateRoot,
372         cnum: CrateNum,
373     ) -> Result<(), CrateError> {
374         if let Some(existing) = self.cstore.stable_crate_ids.insert(root.stable_crate_id(), cnum) {
375             let crate_name0 = root.name();
376             let crate_name1 = self.cstore.get_crate_data(existing).name();
377             return Err(CrateError::StableCrateIdCollision(crate_name0, crate_name1));
378         }
379
380         Ok(())
381     }
382
383     fn register_crate(
384         &mut self,
385         host_lib: Option<Library>,
386         root: Option<&CratePaths>,
387         lib: Library,
388         dep_kind: CrateDepKind,
389         name: Symbol,
390     ) -> Result<CrateNum, CrateError> {
391         let _prof_timer = self.sess.prof.generic_activity("metadata_register_crate");
392
393         let Library { source, metadata } = lib;
394         let crate_root = metadata.get_root();
395         let host_hash = host_lib.as_ref().map(|lib| lib.metadata.get_root().hash());
396
397         let private_dep =
398             self.sess.opts.externs.get(name.as_str()).map_or(false, |e| e.is_private_dep);
399
400         // Claim this crate number and cache it
401         let cnum = self.cstore.alloc_new_crate_num();
402
403         info!(
404             "register crate `{}` (cnum = {}. private_dep = {})",
405             crate_root.name(),
406             cnum,
407             private_dep
408         );
409
410         // Maintain a reference to the top most crate.
411         // Stash paths for top-most crate locally if necessary.
412         let crate_paths;
413         let root = if let Some(root) = root {
414             root
415         } else {
416             crate_paths = CratePaths::new(crate_root.name(), source.clone());
417             &crate_paths
418         };
419
420         let cnum_map = self.resolve_crate_deps(root, &crate_root, &metadata, cnum, dep_kind)?;
421
422         let raw_proc_macros = if crate_root.is_proc_macro_crate() {
423             let temp_root;
424             let (dlsym_source, dlsym_root) = match &host_lib {
425                 Some(host_lib) => (&host_lib.source, {
426                     temp_root = host_lib.metadata.get_root();
427                     &temp_root
428                 }),
429                 None => (&source, &crate_root),
430             };
431             let dlsym_dylib = dlsym_source.dylib.as_ref().expect("no dylib for a proc-macro crate");
432             Some(self.dlsym_proc_macros(&dlsym_dylib.0, dlsym_root.stable_crate_id())?)
433         } else {
434             None
435         };
436
437         // Perform some verification *after* resolve_crate_deps() above is
438         // known to have been successful. It seems that - in error cases - the
439         // cstore can be in a temporarily invalid state between cnum allocation
440         // and dependency resolution and the verification code would produce
441         // ICEs in that case (see #83045).
442         self.verify_no_symbol_conflicts(&crate_root)?;
443         self.verify_no_stable_crate_id_hash_conflicts(&crate_root, cnum)?;
444
445         let crate_metadata = CrateMetadata::new(
446             self.sess,
447             &self.cstore,
448             metadata,
449             crate_root,
450             raw_proc_macros,
451             cnum,
452             cnum_map,
453             dep_kind,
454             source,
455             private_dep,
456             host_hash,
457         );
458
459         self.cstore.set_crate_data(cnum, crate_metadata);
460
461         Ok(cnum)
462     }
463
464     fn load_proc_macro<'b>(
465         &self,
466         locator: &mut CrateLocator<'b>,
467         path_kind: PathKind,
468         host_hash: Option<Svh>,
469     ) -> Result<Option<(LoadResult, Option<Library>)>, CrateError>
470     where
471         'a: 'b,
472     {
473         // Use a new crate locator so trying to load a proc macro doesn't affect the error
474         // message we emit
475         let mut proc_macro_locator = locator.clone();
476
477         // Try to load a proc macro
478         proc_macro_locator.is_proc_macro = true;
479
480         // Load the proc macro crate for the target
481         let (locator, target_result) = if self.sess.opts.unstable_opts.dual_proc_macros {
482             proc_macro_locator.reset();
483             let result = match self.load(&mut proc_macro_locator)? {
484                 Some(LoadResult::Previous(cnum)) => {
485                     return Ok(Some((LoadResult::Previous(cnum), None)));
486                 }
487                 Some(LoadResult::Loaded(library)) => Some(LoadResult::Loaded(library)),
488                 None => return Ok(None),
489             };
490             locator.hash = host_hash;
491             // Use the locator when looking for the host proc macro crate, as that is required
492             // so we want it to affect the error message
493             (locator, result)
494         } else {
495             (&mut proc_macro_locator, None)
496         };
497
498         // Load the proc macro crate for the host
499
500         locator.reset();
501         locator.is_proc_macro = true;
502         locator.target = &self.sess.host;
503         locator.triple = TargetTriple::from_triple(config::host_triple());
504         locator.filesearch = self.sess.host_filesearch(path_kind);
505
506         let Some(host_result) = self.load(locator)? else {
507             return Ok(None);
508         };
509
510         Ok(Some(if self.sess.opts.unstable_opts.dual_proc_macros {
511             let host_result = match host_result {
512                 LoadResult::Previous(..) => {
513                     panic!("host and target proc macros must be loaded in lock-step")
514                 }
515                 LoadResult::Loaded(library) => library,
516             };
517             (target_result.unwrap(), Some(host_result))
518         } else {
519             (host_result, None)
520         }))
521     }
522
523     fn resolve_crate(
524         &mut self,
525         name: Symbol,
526         span: Span,
527         dep_kind: CrateDepKind,
528     ) -> Option<CrateNum> {
529         self.used_extern_options.insert(name);
530         match self.maybe_resolve_crate(name, dep_kind, None) {
531             Ok(cnum) => Some(cnum),
532             Err(err) => {
533                 let missing_core =
534                     self.maybe_resolve_crate(sym::core, CrateDepKind::Explicit, None).is_err();
535                 err.report(&self.sess, span, missing_core);
536                 None
537             }
538         }
539     }
540
541     fn maybe_resolve_crate<'b>(
542         &'b mut self,
543         name: Symbol,
544         mut dep_kind: CrateDepKind,
545         dep: Option<(&'b CratePaths, &'b CrateDep)>,
546     ) -> Result<CrateNum, CrateError> {
547         info!("resolving crate `{}`", name);
548         if !name.as_str().is_ascii() {
549             return Err(CrateError::NonAsciiName(name));
550         }
551         let (root, hash, host_hash, extra_filename, path_kind) = match dep {
552             Some((root, dep)) => (
553                 Some(root),
554                 Some(dep.hash),
555                 dep.host_hash,
556                 Some(&dep.extra_filename[..]),
557                 PathKind::Dependency,
558             ),
559             None => (None, None, None, None, PathKind::Crate),
560         };
561         let result = if let Some(cnum) = self.existing_match(name, hash, path_kind) {
562             (LoadResult::Previous(cnum), None)
563         } else {
564             info!("falling back to a load");
565             let mut locator = CrateLocator::new(
566                 self.sess,
567                 &*self.metadata_loader,
568                 name,
569                 hash,
570                 extra_filename,
571                 false, // is_host
572                 path_kind,
573             );
574
575             match self.load(&mut locator)? {
576                 Some(res) => (res, None),
577                 None => {
578                     dep_kind = CrateDepKind::MacrosOnly;
579                     match self.load_proc_macro(&mut locator, path_kind, host_hash)? {
580                         Some(res) => res,
581                         None => return Err(locator.into_error(root.cloned())),
582                     }
583                 }
584             }
585         };
586
587         match result {
588             (LoadResult::Previous(cnum), None) => {
589                 let data = self.cstore.get_crate_data(cnum);
590                 if data.is_proc_macro_crate() {
591                     dep_kind = CrateDepKind::MacrosOnly;
592                 }
593                 data.update_dep_kind(|data_dep_kind| cmp::max(data_dep_kind, dep_kind));
594                 Ok(cnum)
595             }
596             (LoadResult::Loaded(library), host_library) => {
597                 self.register_crate(host_library, root, library, dep_kind, name)
598             }
599             _ => panic!(),
600         }
601     }
602
603     fn load(&self, locator: &mut CrateLocator<'_>) -> Result<Option<LoadResult>, CrateError> {
604         let Some(library) = locator.maybe_load_library_crate()? else {
605             return Ok(None);
606         };
607
608         // In the case that we're loading a crate, but not matching
609         // against a hash, we could load a crate which has the same hash
610         // as an already loaded crate. If this is the case prevent
611         // duplicates by just using the first crate.
612         //
613         // Note that we only do this for target triple crates, though, as we
614         // don't want to match a host crate against an equivalent target one
615         // already loaded.
616         let root = library.metadata.get_root();
617         // FIXME: why is this condition necessary? It was adding in #33625 but I
618         // don't know why and the original author doesn't remember ...
619         let can_reuse_cratenum =
620             locator.triple == self.sess.opts.target_triple || locator.is_proc_macro;
621         Ok(Some(if can_reuse_cratenum {
622             let mut result = LoadResult::Loaded(library);
623             for (cnum, data) in self.cstore.iter_crate_data() {
624                 if data.name() == root.name() && root.hash() == data.hash() {
625                     assert!(locator.hash.is_none());
626                     info!("load success, going to previous cnum: {}", cnum);
627                     result = LoadResult::Previous(cnum);
628                     break;
629                 }
630             }
631             result
632         } else {
633             LoadResult::Loaded(library)
634         }))
635     }
636
637     fn update_extern_crate(&self, cnum: CrateNum, extern_crate: ExternCrate) {
638         let cmeta = self.cstore.get_crate_data(cnum);
639         if cmeta.update_extern_crate(extern_crate) {
640             // Propagate the extern crate info to dependencies if it was updated.
641             let extern_crate = ExternCrate { dependency_of: cnum, ..extern_crate };
642             for &dep_cnum in cmeta.dependencies().iter() {
643                 self.update_extern_crate(dep_cnum, extern_crate);
644             }
645         }
646     }
647
648     // Go through the crate metadata and load any crates that it references
649     fn resolve_crate_deps(
650         &mut self,
651         root: &CratePaths,
652         crate_root: &CrateRoot,
653         metadata: &MetadataBlob,
654         krate: CrateNum,
655         dep_kind: CrateDepKind,
656     ) -> Result<CrateNumMap, CrateError> {
657         debug!("resolving deps of external crate");
658         if crate_root.is_proc_macro_crate() {
659             return Ok(CrateNumMap::new());
660         }
661
662         // The map from crate numbers in the crate we're resolving to local crate numbers.
663         // We map 0 and all other holes in the map to our parent crate. The "additional"
664         // self-dependencies should be harmless.
665         let deps = crate_root.decode_crate_deps(metadata);
666         let mut crate_num_map = CrateNumMap::with_capacity(1 + deps.len());
667         crate_num_map.push(krate);
668         for dep in deps {
669             info!(
670                 "resolving dep crate {} hash: `{}` extra filename: `{}`",
671                 dep.name, dep.hash, dep.extra_filename
672             );
673             let dep_kind = match dep_kind {
674                 CrateDepKind::MacrosOnly => CrateDepKind::MacrosOnly,
675                 _ => dep.kind,
676             };
677             let cnum = self.maybe_resolve_crate(dep.name, dep_kind, Some((root, &dep)))?;
678             crate_num_map.push(cnum);
679         }
680
681         debug!("resolve_crate_deps: cnum_map for {:?} is {:?}", krate, crate_num_map);
682         Ok(crate_num_map)
683     }
684
685     fn dlsym_proc_macros(
686         &self,
687         path: &Path,
688         stable_crate_id: StableCrateId,
689     ) -> Result<&'static [ProcMacro], CrateError> {
690         // Make sure the path contains a / or the linker will search for it.
691         let path = env::current_dir().unwrap().join(path);
692         let lib = unsafe { libloading::Library::new(path) }
693             .map_err(|err| CrateError::DlOpen(err.to_string()))?;
694
695         let sym_name = self.sess.generate_proc_macro_decls_symbol(stable_crate_id);
696         let sym = unsafe { lib.get::<*const &[ProcMacro]>(sym_name.as_bytes()) }
697             .map_err(|err| CrateError::DlSym(err.to_string()))?;
698
699         // Intentionally leak the dynamic library. We can't ever unload it
700         // since the library can make things that will live arbitrarily long.
701         let sym = unsafe { sym.into_raw() };
702         std::mem::forget(lib);
703
704         Ok(unsafe { **sym })
705     }
706
707     fn inject_panic_runtime(&mut self, krate: &ast::Crate) {
708         // If we're only compiling an rlib, then there's no need to select a
709         // panic runtime, so we just skip this section entirely.
710         let any_non_rlib = self.sess.crate_types().iter().any(|ct| *ct != CrateType::Rlib);
711         if !any_non_rlib {
712             info!("panic runtime injection skipped, only generating rlib");
713             return;
714         }
715
716         // If we need a panic runtime, we try to find an existing one here. At
717         // the same time we perform some general validation of the DAG we've got
718         // going such as ensuring everything has a compatible panic strategy.
719         //
720         // The logic for finding the panic runtime here is pretty much the same
721         // as the allocator case with the only addition that the panic strategy
722         // compilation mode also comes into play.
723         let desired_strategy = self.sess.panic_strategy();
724         let mut runtime_found = false;
725         let mut needs_panic_runtime =
726             self.sess.contains_name(&krate.attrs, sym::needs_panic_runtime);
727
728         for (cnum, data) in self.cstore.iter_crate_data() {
729             needs_panic_runtime = needs_panic_runtime || data.needs_panic_runtime();
730             if data.is_panic_runtime() {
731                 // Inject a dependency from all #![needs_panic_runtime] to this
732                 // #![panic_runtime] crate.
733                 self.inject_dependency_if(cnum, "a panic runtime", &|data| {
734                     data.needs_panic_runtime()
735                 });
736                 runtime_found = runtime_found || data.dep_kind() == CrateDepKind::Explicit;
737             }
738         }
739
740         // If an explicitly linked and matching panic runtime was found, or if
741         // we just don't need one at all, then we're done here and there's
742         // nothing else to do.
743         if !needs_panic_runtime || runtime_found {
744             return;
745         }
746
747         // By this point we know that we (a) need a panic runtime and (b) no
748         // panic runtime was explicitly linked. Here we just load an appropriate
749         // default runtime for our panic strategy and then inject the
750         // dependencies.
751         //
752         // We may resolve to an already loaded crate (as the crate may not have
753         // been explicitly linked prior to this) and we may re-inject
754         // dependencies again, but both of those situations are fine.
755         //
756         // Also note that we have yet to perform validation of the crate graph
757         // in terms of everyone has a compatible panic runtime format, that's
758         // performed later as part of the `dependency_format` module.
759         let name = match desired_strategy {
760             PanicStrategy::Unwind => sym::panic_unwind,
761             PanicStrategy::Abort => sym::panic_abort,
762         };
763         info!("panic runtime not found -- loading {}", name);
764
765         let Some(cnum) = self.resolve_crate(name, DUMMY_SP, CrateDepKind::Implicit) else { return; };
766         let data = self.cstore.get_crate_data(cnum);
767
768         // Sanity check the loaded crate to ensure it is indeed a panic runtime
769         // and the panic strategy is indeed what we thought it was.
770         if !data.is_panic_runtime() {
771             self.sess.emit_err(CrateNotPanicRuntime { crate_name: name });
772         }
773         if data.required_panic_strategy() != Some(desired_strategy) {
774             self.sess.emit_err(NoPanicStrategy { crate_name: name, strategy: desired_strategy });
775         }
776
777         self.cstore.injected_panic_runtime = Some(cnum);
778         self.inject_dependency_if(cnum, "a panic runtime", &|data| data.needs_panic_runtime());
779     }
780
781     fn inject_profiler_runtime(&mut self, krate: &ast::Crate) {
782         if self.sess.opts.unstable_opts.no_profiler_runtime
783             || !(self.sess.instrument_coverage()
784                 || self.sess.opts.unstable_opts.profile
785                 || self.sess.opts.cg.profile_generate.enabled())
786         {
787             return;
788         }
789
790         info!("loading profiler");
791
792         let name = Symbol::intern(&self.sess.opts.unstable_opts.profiler_runtime);
793         if name == sym::profiler_builtins && self.sess.contains_name(&krate.attrs, sym::no_core) {
794             self.sess.emit_err(ProfilerBuiltinsNeedsCore);
795         }
796
797         let Some(cnum) = self.resolve_crate(name, DUMMY_SP, CrateDepKind::Implicit) else { return; };
798         let data = self.cstore.get_crate_data(cnum);
799
800         // Sanity check the loaded crate to ensure it is indeed a profiler runtime
801         if !data.is_profiler_runtime() {
802             self.sess.emit_err(NotProfilerRuntime { crate_name: name });
803         }
804     }
805
806     fn inject_allocator_crate(&mut self, krate: &ast::Crate) {
807         self.cstore.has_global_allocator = match &*global_allocator_spans(&self.sess, krate) {
808             [span1, span2, ..] => {
809                 self.sess.emit_err(NoMultipleGlobalAlloc { span2: *span2, span1: *span1 });
810                 true
811             }
812             spans => !spans.is_empty(),
813         };
814         self.cstore.has_alloc_error_handler = match &*alloc_error_handler_spans(&self.sess, krate) {
815             [span1, span2, ..] => {
816                 self.sess.emit_err(NoMultipleAllocErrorHandler { span2: *span2, span1: *span1 });
817                 true
818             }
819             spans => !spans.is_empty(),
820         };
821
822         // Check to see if we actually need an allocator. This desire comes
823         // about through the `#![needs_allocator]` attribute and is typically
824         // written down in liballoc.
825         if !self.sess.contains_name(&krate.attrs, sym::needs_allocator)
826             && !self.cstore.iter_crate_data().any(|(_, data)| data.needs_allocator())
827         {
828             return;
829         }
830
831         // At this point we've determined that we need an allocator. Let's see
832         // if our compilation session actually needs an allocator based on what
833         // we're emitting.
834         let all_rlib = self.sess.crate_types().iter().all(|ct| matches!(*ct, CrateType::Rlib));
835         if all_rlib {
836             return;
837         }
838
839         // Ok, we need an allocator. Not only that but we're actually going to
840         // create an artifact that needs one linked in. Let's go find the one
841         // that we're going to link in.
842         //
843         // First up we check for global allocators. Look at the crate graph here
844         // and see what's a global allocator, including if we ourselves are a
845         // global allocator.
846         let mut global_allocator =
847             self.cstore.has_global_allocator.then(|| Symbol::intern("this crate"));
848         for (_, data) in self.cstore.iter_crate_data() {
849             if data.has_global_allocator() {
850                 match global_allocator {
851                     Some(other_crate) => {
852                         self.sess.emit_err(ConflictingGlobalAlloc {
853                             crate_name: data.name(),
854                             other_crate_name: other_crate,
855                         });
856                     }
857                     None => global_allocator = Some(data.name()),
858                 }
859             }
860         }
861         let mut alloc_error_handler =
862             self.cstore.has_alloc_error_handler.then(|| Symbol::intern("this crate"));
863         for (_, data) in self.cstore.iter_crate_data() {
864             if data.has_alloc_error_handler() {
865                 match alloc_error_handler {
866                     Some(other_crate) => {
867                         self.sess.emit_err(ConflictingAllocErrorHandler {
868                             crate_name: data.name(),
869                             other_crate_name: other_crate,
870                         });
871                     }
872                     None => alloc_error_handler = Some(data.name()),
873                 }
874             }
875         }
876
877         if global_allocator.is_some() {
878             self.cstore.allocator_kind = Some(AllocatorKind::Global);
879         } else {
880             // Ok we haven't found a global allocator but we still need an
881             // allocator. At this point our allocator request is typically fulfilled
882             // by the standard library, denoted by the `#![default_lib_allocator]`
883             // attribute.
884             if !self.sess.contains_name(&krate.attrs, sym::default_lib_allocator)
885                 && !self.cstore.iter_crate_data().any(|(_, data)| data.has_default_lib_allocator())
886             {
887                 self.sess.emit_err(GlobalAllocRequired);
888             }
889             self.cstore.allocator_kind = Some(AllocatorKind::Default);
890         }
891
892         if alloc_error_handler.is_some() {
893             self.cstore.alloc_error_handler_kind = Some(AllocatorKind::Global);
894         } else {
895             // The alloc crate provides a default allocation error handler if
896             // one isn't specified.
897             self.cstore.alloc_error_handler_kind = Some(AllocatorKind::Default);
898         }
899     }
900
901     fn inject_dependency_if(
902         &self,
903         krate: CrateNum,
904         what: &str,
905         needs_dep: &dyn Fn(&CrateMetadata) -> bool,
906     ) {
907         // don't perform this validation if the session has errors, as one of
908         // those errors may indicate a circular dependency which could cause
909         // this to stack overflow.
910         if self.sess.has_errors().is_some() {
911             return;
912         }
913
914         // Before we inject any dependencies, make sure we don't inject a
915         // circular dependency by validating that this crate doesn't
916         // transitively depend on any crates satisfying `needs_dep`.
917         for dep in self.cstore.crate_dependencies_in_reverse_postorder(krate) {
918             let data = self.cstore.get_crate_data(dep);
919             if needs_dep(&data) {
920                 self.sess.emit_err(NoTransitiveNeedsDep {
921                     crate_name: self.cstore.get_crate_data(krate).name(),
922                     needs_crate_name: what,
923                     deps_crate_name: data.name(),
924                 });
925             }
926         }
927
928         // All crates satisfying `needs_dep` do not explicitly depend on the
929         // crate provided for this compile, but in order for this compilation to
930         // be successfully linked we need to inject a dependency (to order the
931         // crates on the command line correctly).
932         for (cnum, data) in self.cstore.iter_crate_data() {
933             if needs_dep(data) {
934                 info!("injecting a dep from {} to {}", cnum, krate);
935                 data.add_dependency(krate);
936             }
937         }
938     }
939
940     fn report_unused_deps(&mut self, krate: &ast::Crate) {
941         // Make a point span rather than covering the whole file
942         let span = krate.spans.inner_span.shrink_to_lo();
943         // Complain about anything left over
944         for (name, entry) in self.sess.opts.externs.iter() {
945             if let ExternLocation::FoundInLibrarySearchDirectories = entry.location {
946                 // Don't worry about pathless `--extern foo` sysroot references
947                 continue;
948             }
949             if entry.nounused_dep {
950                 // We're not worried about this one
951                 continue;
952             }
953             let name_interned = Symbol::intern(name);
954             if self.used_extern_options.contains(&name_interned) {
955                 continue;
956             }
957
958             // Got a real unused --extern
959             if self.sess.opts.json_unused_externs.is_enabled() {
960                 self.cstore.unused_externs.push(name_interned);
961                 continue;
962             }
963
964             self.sess.parse_sess.buffer_lint(
965                     lint::builtin::UNUSED_CRATE_DEPENDENCIES,
966                     span,
967                     ast::CRATE_NODE_ID,
968                     &format!(
969                         "external crate `{}` unused in `{}`: remove the dependency or add `use {} as _;`",
970                         name,
971                         self.local_crate_name,
972                         name),
973                 );
974         }
975     }
976
977     pub fn postprocess(&mut self, krate: &ast::Crate) {
978         self.inject_profiler_runtime(krate);
979         self.inject_allocator_crate(krate);
980         self.inject_panic_runtime(krate);
981
982         self.report_unused_deps(krate);
983
984         info!("{:?}", CrateDump(&self.cstore));
985     }
986
987     pub fn process_extern_crate(
988         &mut self,
989         item: &ast::Item,
990         def_id: LocalDefId,
991     ) -> Option<CrateNum> {
992         match item.kind {
993             ast::ItemKind::ExternCrate(orig_name) => {
994                 debug!(
995                     "resolving extern crate stmt. ident: {} orig_name: {:?}",
996                     item.ident, orig_name
997                 );
998                 let name = match orig_name {
999                     Some(orig_name) => {
1000                         validate_crate_name(self.sess, orig_name, Some(item.span));
1001                         orig_name
1002                     }
1003                     None => item.ident.name,
1004                 };
1005                 let dep_kind = if self.sess.contains_name(&item.attrs, sym::no_link) {
1006                     CrateDepKind::MacrosOnly
1007                 } else {
1008                     CrateDepKind::Explicit
1009                 };
1010
1011                 let cnum = self.resolve_crate(name, item.span, dep_kind)?;
1012
1013                 let path_len = self.definitions.def_path(def_id).data.len();
1014                 self.update_extern_crate(
1015                     cnum,
1016                     ExternCrate {
1017                         src: ExternCrateSource::Extern(def_id.to_def_id()),
1018                         span: item.span,
1019                         path_len,
1020                         dependency_of: LOCAL_CRATE,
1021                     },
1022                 );
1023                 Some(cnum)
1024             }
1025             _ => bug!(),
1026         }
1027     }
1028
1029     pub fn process_path_extern(&mut self, name: Symbol, span: Span) -> Option<CrateNum> {
1030         let cnum = self.resolve_crate(name, span, CrateDepKind::Explicit)?;
1031
1032         self.update_extern_crate(
1033             cnum,
1034             ExternCrate {
1035                 src: ExternCrateSource::Path,
1036                 span,
1037                 // to have the least priority in `update_extern_crate`
1038                 path_len: usize::MAX,
1039                 dependency_of: LOCAL_CRATE,
1040             },
1041         );
1042
1043         Some(cnum)
1044     }
1045
1046     pub fn maybe_process_path_extern(&mut self, name: Symbol) -> Option<CrateNum> {
1047         self.maybe_resolve_crate(name, CrateDepKind::Explicit, None).ok()
1048     }
1049 }
1050
1051 fn global_allocator_spans(sess: &Session, krate: &ast::Crate) -> Vec<Span> {
1052     struct Finder<'a> {
1053         sess: &'a Session,
1054         name: Symbol,
1055         spans: Vec<Span>,
1056     }
1057     impl<'ast, 'a> visit::Visitor<'ast> for Finder<'a> {
1058         fn visit_item(&mut self, item: &'ast ast::Item) {
1059             if item.ident.name == self.name
1060                 && self.sess.contains_name(&item.attrs, sym::rustc_std_internal_symbol)
1061             {
1062                 self.spans.push(item.span);
1063             }
1064             visit::walk_item(self, item)
1065         }
1066     }
1067
1068     let name = Symbol::intern(&AllocatorKind::Global.fn_name(sym::alloc));
1069     let mut f = Finder { sess, name, spans: Vec::new() };
1070     visit::walk_crate(&mut f, krate);
1071     f.spans
1072 }
1073
1074 fn alloc_error_handler_spans(sess: &Session, krate: &ast::Crate) -> Vec<Span> {
1075     struct Finder<'a> {
1076         sess: &'a Session,
1077         name: Symbol,
1078         spans: Vec<Span>,
1079     }
1080     impl<'ast, 'a> visit::Visitor<'ast> for Finder<'a> {
1081         fn visit_item(&mut self, item: &'ast ast::Item) {
1082             if item.ident.name == self.name
1083                 && self.sess.contains_name(&item.attrs, sym::rustc_std_internal_symbol)
1084             {
1085                 self.spans.push(item.span);
1086             }
1087             visit::walk_item(self, item)
1088         }
1089     }
1090
1091     let name = Symbol::intern(&AllocatorKind::Global.fn_name(sym::oom));
1092     let mut f = Finder { sess, name, spans: Vec::new() };
1093     visit::walk_crate(&mut f, krate);
1094     f.spans
1095 }