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