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