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