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