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