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