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