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