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