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