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