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