]> git.lizzy.rs Git - rust.git/blob - src/librustc_metadata/creader.rs
32548081e62997a36e6fcf5bae93872416b7b397
[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         if cmeta.update_extern_crate(extern_crate) {
404             // Propagate the extern crate info to dependencies.
405             extern_crate.dependency_of = cnum;
406             for &dep_cnum in cmeta.dependencies().iter() {
407                 self.update_extern_crate(dep_cnum, extern_crate, visited);
408             }
409         }
410     }
411
412     // Go through the crate metadata and load any crates that it references
413     fn resolve_crate_deps(&mut self,
414                           root: &CratePaths,
415                           crate_root: &CrateRoot<'_>,
416                           metadata: &MetadataBlob,
417                           krate: CrateNum,
418                           span: Span,
419                           dep_kind: DepKind)
420                           -> CrateNumMap {
421         debug!("resolving deps of external crate");
422         if crate_root.is_proc_macro_crate() {
423             return CrateNumMap::new();
424         }
425
426         // The map from crate numbers in the crate we're resolving to local crate numbers.
427         // We map 0 and all other holes in the map to our parent crate. The "additional"
428         // self-dependencies should be harmless.
429         std::iter::once(krate).chain(crate_root.decode_crate_deps(metadata).map(|dep| {
430             info!("resolving dep crate {} hash: `{}` extra filename: `{}`", dep.name, dep.hash,
431                   dep.extra_filename);
432             if dep.kind == DepKind::UnexportedMacrosOnly {
433                 return krate;
434             }
435             let dep_kind = match dep_kind {
436                 DepKind::MacrosOnly => DepKind::MacrosOnly,
437                 _ => dep.kind,
438             };
439             self.resolve_crate(dep.name, span, dep_kind, Some((root, &dep)))
440         })).collect()
441     }
442
443     fn dlsym_proc_macros(&self,
444                          path: &Path,
445                          disambiguator: CrateDisambiguator,
446                          span: Span
447     ) -> &'static [ProcMacro] {
448         use std::env;
449         use crate::dynamic_lib::DynamicLibrary;
450
451         // Make sure the path contains a / or the linker will search for it.
452         let path = env::current_dir().unwrap().join(path);
453         let lib = match DynamicLibrary::open(Some(&path)) {
454             Ok(lib) => lib,
455             Err(err) => self.sess.span_fatal(span, &err),
456         };
457
458         let sym = self.sess.generate_proc_macro_decls_symbol(disambiguator);
459         let decls = unsafe {
460             let sym = match lib.symbol(&sym) {
461                 Ok(f) => f,
462                 Err(err) => self.sess.span_fatal(span, &err),
463             };
464             *(sym as *const &[ProcMacro])
465         };
466
467         // Intentionally leak the dynamic library. We can't ever unload it
468         // since the library can make things that will live arbitrarily long.
469         std::mem::forget(lib);
470
471         decls
472     }
473
474     fn inject_panic_runtime(&mut self, krate: &ast::Crate) {
475         // If we're only compiling an rlib, then there's no need to select a
476         // panic runtime, so we just skip this section entirely.
477         let any_non_rlib = self.sess.crate_types.borrow().iter().any(|ct| {
478             *ct != config::CrateType::Rlib
479         });
480         if !any_non_rlib {
481             info!("panic runtime injection skipped, only generating rlib");
482             self.cstore.injected_panic_runtime = None;
483             return
484         }
485
486         // If we need a panic runtime, we try to find an existing one here. At
487         // the same time we perform some general validation of the DAG we've got
488         // going such as ensuring everything has a compatible panic strategy.
489         //
490         // The logic for finding the panic runtime here is pretty much the same
491         // as the allocator case with the only addition that the panic strategy
492         // compilation mode also comes into play.
493         let desired_strategy = self.sess.panic_strategy();
494         let mut runtime_found = false;
495         let mut needs_panic_runtime = attr::contains_name(&krate.attrs,
496                                                           sym::needs_panic_runtime);
497
498         self.cstore.iter_crate_data(|cnum, data| {
499             needs_panic_runtime = needs_panic_runtime ||
500                                   data.root.needs_panic_runtime;
501             if data.root.panic_runtime {
502                 // Inject a dependency from all #![needs_panic_runtime] to this
503                 // #![panic_runtime] crate.
504                 self.inject_dependency_if(cnum, "a panic runtime",
505                                           &|data| data.root.needs_panic_runtime);
506                 runtime_found = runtime_found || *data.dep_kind.lock() == DepKind::Explicit;
507             }
508         });
509
510         // If an explicitly linked and matching panic runtime was found, or if
511         // we just don't need one at all, then we're done here and there's
512         // nothing else to do.
513         if !needs_panic_runtime || runtime_found {
514             self.cstore.injected_panic_runtime = None;
515             return
516         }
517
518         // By this point we know that we (a) need a panic runtime and (b) no
519         // panic runtime was explicitly linked. Here we just load an appropriate
520         // default runtime for our panic strategy and then inject the
521         // dependencies.
522         //
523         // We may resolve to an already loaded crate (as the crate may not have
524         // been explicitly linked prior to this) and we may re-inject
525         // dependencies again, but both of those situations are fine.
526         //
527         // Also note that we have yet to perform validation of the crate graph
528         // in terms of everyone has a compatible panic runtime format, that's
529         // performed later as part of the `dependency_format` module.
530         let name = match desired_strategy {
531             PanicStrategy::Unwind => Symbol::intern("panic_unwind"),
532             PanicStrategy::Abort => Symbol::intern("panic_abort"),
533         };
534         info!("panic runtime not found -- loading {}", name);
535
536         let cnum = self.resolve_crate(name, DUMMY_SP, DepKind::Implicit, None);
537         let data = self.cstore.get_crate_data(cnum);
538
539         // Sanity check the loaded crate to ensure it is indeed a panic runtime
540         // and the panic strategy is indeed what we thought it was.
541         if !data.root.panic_runtime {
542             self.sess.err(&format!("the crate `{}` is not a panic runtime",
543                                    name));
544         }
545         if data.root.panic_strategy != desired_strategy {
546             self.sess.err(&format!("the crate `{}` does not have the panic \
547                                     strategy `{}`",
548                                    name, desired_strategy.desc()));
549         }
550
551         self.cstore.injected_panic_runtime = Some(cnum);
552         self.inject_dependency_if(cnum, "a panic runtime",
553                                   &|data| data.root.needs_panic_runtime);
554     }
555
556     fn inject_sanitizer_runtime(&mut self) {
557         if let Some(ref sanitizer) = self.sess.opts.debugging_opts.sanitizer {
558             // Sanitizers can only be used on some tested platforms with
559             // executables linked to `std`
560             const ASAN_SUPPORTED_TARGETS: &[&str] = &["x86_64-unknown-linux-gnu",
561                                                       "x86_64-apple-darwin"];
562             const TSAN_SUPPORTED_TARGETS: &[&str] = &["x86_64-unknown-linux-gnu",
563                                                       "x86_64-apple-darwin"];
564             const LSAN_SUPPORTED_TARGETS: &[&str] = &["x86_64-unknown-linux-gnu"];
565             const MSAN_SUPPORTED_TARGETS: &[&str] = &["x86_64-unknown-linux-gnu"];
566
567             let supported_targets = match *sanitizer {
568                 Sanitizer::Address => ASAN_SUPPORTED_TARGETS,
569                 Sanitizer::Thread => TSAN_SUPPORTED_TARGETS,
570                 Sanitizer::Leak => LSAN_SUPPORTED_TARGETS,
571                 Sanitizer::Memory => MSAN_SUPPORTED_TARGETS,
572             };
573             if !supported_targets.contains(&&*self.sess.opts.target_triple.triple()) {
574                 self.sess.err(&format!("{:?}Sanitizer only works with the `{}` target",
575                     sanitizer,
576                     supported_targets.join("` or `")
577                 ));
578                 return
579             }
580
581             // firstyear 2017 - during testing I was unable to access an OSX machine
582             // to make this work on different crate types. As a result, today I have
583             // only been able to test and support linux as a target.
584             if self.sess.opts.target_triple.triple() == "x86_64-unknown-linux-gnu" {
585                 if !self.sess.crate_types.borrow().iter().all(|ct| {
586                     match *ct {
587                         // Link the runtime
588                         config::CrateType::Executable => true,
589                         // This crate will be compiled with the required
590                         // instrumentation pass
591                         config::CrateType::Staticlib |
592                         config::CrateType::Rlib |
593                         config::CrateType::Dylib |
594                         config::CrateType::Cdylib =>
595                             false,
596                         _ => {
597                             self.sess.err(&format!("Only executables, staticlibs, \
598                                 cdylibs, dylibs and rlibs can be compiled with \
599                                 `-Z sanitizer`"));
600                             false
601                         }
602                     }
603                 }) {
604                     return
605                 }
606             } else {
607                 if !self.sess.crate_types.borrow().iter().all(|ct| {
608                     match *ct {
609                         // Link the runtime
610                         config::CrateType::Executable => true,
611                         // This crate will be compiled with the required
612                         // instrumentation pass
613                         config::CrateType::Rlib => false,
614                         _ => {
615                             self.sess.err(&format!("Only executables and rlibs can be \
616                                                     compiled with `-Z sanitizer`"));
617                             false
618                         }
619                     }
620                 }) {
621                     return
622                 }
623             }
624
625             let mut uses_std = false;
626             self.cstore.iter_crate_data(|_, data| {
627                 if data.root.name == sym::std {
628                     uses_std = true;
629                 }
630             });
631
632             if uses_std {
633                 let name = Symbol::intern(match sanitizer {
634                     Sanitizer::Address => "rustc_asan",
635                     Sanitizer::Leak => "rustc_lsan",
636                     Sanitizer::Memory => "rustc_msan",
637                     Sanitizer::Thread => "rustc_tsan",
638                 });
639                 info!("loading sanitizer: {}", name);
640
641                 let cnum = self.resolve_crate(name, DUMMY_SP, DepKind::Explicit, None);
642                 let data = self.cstore.get_crate_data(cnum);
643
644                 // Sanity check the loaded crate to ensure it is indeed a sanitizer runtime
645                 if !data.root.sanitizer_runtime {
646                     self.sess.err(&format!("the crate `{}` is not a sanitizer runtime",
647                                            name));
648                 }
649             } else {
650                 self.sess.err("Must link std to be compiled with `-Z sanitizer`");
651             }
652         }
653     }
654
655     fn inject_profiler_runtime(&mut self) {
656         if self.sess.opts.debugging_opts.profile ||
657            self.sess.opts.cg.profile_generate.enabled()
658         {
659             info!("loading profiler");
660
661             let name = Symbol::intern("profiler_builtins");
662             let cnum = self.resolve_crate(name, DUMMY_SP, DepKind::Implicit, None);
663             let data = self.cstore.get_crate_data(cnum);
664
665             // Sanity check the loaded crate to ensure it is indeed a profiler runtime
666             if !data.root.profiler_runtime {
667                 self.sess.err(&format!("the crate `profiler_builtins` is not \
668                                         a profiler runtime"));
669             }
670         }
671     }
672
673     fn inject_allocator_crate(&mut self, krate: &ast::Crate) {
674         let has_global_allocator = match &*global_allocator_spans(krate) {
675             [span1, span2, ..] => {
676                 self.sess.struct_span_err(*span2, "cannot define multiple global allocators")
677                     .span_label(*span2, "cannot define a new global allocator")
678                     .span_label(*span1, "previous global allocator is defined here")
679                     .emit();
680                 true
681             }
682             spans => !spans.is_empty()
683         };
684         self.sess.has_global_allocator.set(has_global_allocator);
685
686         // Check to see if we actually need an allocator. This desire comes
687         // about through the `#![needs_allocator]` attribute and is typically
688         // written down in liballoc.
689         let mut needs_allocator = attr::contains_name(&krate.attrs,
690                                                       sym::needs_allocator);
691         self.cstore.iter_crate_data(|_, data| {
692             needs_allocator = needs_allocator || data.root.needs_allocator;
693         });
694         if !needs_allocator {
695             self.cstore.allocator_kind = None;
696             return
697         }
698
699         // At this point we've determined that we need an allocator. Let's see
700         // if our compilation session actually needs an allocator based on what
701         // we're emitting.
702         let all_rlib = self.sess.crate_types.borrow()
703             .iter()
704             .all(|ct| {
705                 match *ct {
706                     config::CrateType::Rlib => true,
707                     _ => false,
708                 }
709             });
710         if all_rlib {
711             self.cstore.allocator_kind = None;
712             return
713         }
714
715         // Ok, we need an allocator. Not only that but we're actually going to
716         // create an artifact that needs one linked in. Let's go find the one
717         // that we're going to link in.
718         //
719         // First up we check for global allocators. Look at the crate graph here
720         // and see what's a global allocator, including if we ourselves are a
721         // global allocator.
722         let mut global_allocator = if has_global_allocator {
723             Some(None)
724         } else {
725             None
726         };
727         self.cstore.iter_crate_data(|_, data| {
728             if !data.root.has_global_allocator {
729                 return
730             }
731             match global_allocator {
732                 Some(Some(other_crate)) => {
733                     self.sess.err(&format!("the `#[global_allocator]` in {} \
734                                             conflicts with this global \
735                                             allocator in: {}",
736                                            other_crate,
737                                            data.root.name));
738                 }
739                 Some(None) => {
740                     self.sess.err(&format!("the `#[global_allocator]` in this \
741                                             crate conflicts with global \
742                                             allocator in: {}", data.root.name));
743                 }
744                 None => global_allocator = Some(Some(data.root.name)),
745             }
746         });
747         if global_allocator.is_some() {
748             self.cstore.allocator_kind = Some(AllocatorKind::Global);
749             return
750         }
751
752         // Ok we haven't found a global allocator but we still need an
753         // allocator. At this point our allocator request is typically fulfilled
754         // by the standard library, denoted by the `#![default_lib_allocator]`
755         // attribute.
756         let mut has_default = attr::contains_name(&krate.attrs, sym::default_lib_allocator);
757         self.cstore.iter_crate_data(|_, data| {
758             if data.root.has_default_lib_allocator {
759                 has_default = true;
760             }
761         });
762
763         if !has_default {
764             self.sess.err("no global memory allocator found but one is \
765                            required; link to std or \
766                            add `#[global_allocator]` to a static item \
767                            that implements the GlobalAlloc trait.");
768         }
769         self.cstore.allocator_kind = Some(AllocatorKind::DefaultLib);
770     }
771
772     fn inject_dependency_if(&self,
773                             krate: CrateNum,
774                             what: &str,
775                             needs_dep: &dyn Fn(&CrateMetadata) -> bool) {
776         // don't perform this validation if the session has errors, as one of
777         // those errors may indicate a circular dependency which could cause
778         // this to stack overflow.
779         if self.sess.has_errors() {
780             return
781         }
782
783         // Before we inject any dependencies, make sure we don't inject a
784         // circular dependency by validating that this crate doesn't
785         // transitively depend on any crates satisfying `needs_dep`.
786         for dep in self.cstore.crate_dependencies_in_reverse_postorder(krate) {
787             let data = self.cstore.get_crate_data(dep);
788             if needs_dep(&data) {
789                 self.sess.err(&format!("the crate `{}` cannot depend \
790                                         on a crate that needs {}, but \
791                                         it depends on `{}`",
792                                        self.cstore.get_crate_data(krate).root.name,
793                                        what,
794                                        data.root.name));
795             }
796         }
797
798         // All crates satisfying `needs_dep` do not explicitly depend on the
799         // crate provided for this compile, but in order for this compilation to
800         // be successfully linked we need to inject a dependency (to order the
801         // crates on the command line correctly).
802         self.cstore.iter_crate_data(|cnum, data| {
803             if !needs_dep(data) {
804                 return
805             }
806
807             info!("injecting a dep from {} to {}", cnum, krate);
808             data.add_dependency(krate);
809         });
810     }
811
812     pub fn postprocess(&mut self, krate: &ast::Crate) {
813         self.inject_sanitizer_runtime();
814         self.inject_profiler_runtime();
815         self.inject_allocator_crate(krate);
816         self.inject_panic_runtime(krate);
817
818         if log_enabled!(log::Level::Info) {
819             dump_crates(&self.cstore);
820         }
821     }
822
823     pub fn process_extern_crate(
824         &mut self,
825         item: &ast::Item,
826         definitions: &Definitions,
827     ) -> CrateNum {
828         match item.kind {
829             ast::ItemKind::ExternCrate(orig_name) => {
830                 debug!("resolving extern crate stmt. ident: {} orig_name: {:?}",
831                        item.ident, orig_name);
832                 let name = match orig_name {
833                     Some(orig_name) => {
834                         crate::validate_crate_name(Some(self.sess), &orig_name.as_str(),
835                                             Some(item.span));
836                         orig_name
837                     }
838                     None => item.ident.name,
839                 };
840                 let dep_kind = if attr::contains_name(&item.attrs, sym::no_link) {
841                     DepKind::UnexportedMacrosOnly
842                 } else {
843                     DepKind::Explicit
844                 };
845
846                 let cnum = self.resolve_crate(name, item.span, dep_kind, None);
847
848                 let def_id = definitions.opt_local_def_id(item.id).unwrap();
849                 let path_len = definitions.def_path(def_id.index).data.len();
850                 self.update_extern_crate(
851                     cnum,
852                     ExternCrate {
853                         src: ExternCrateSource::Extern(def_id),
854                         span: item.span,
855                         path_len,
856                         dependency_of: LOCAL_CRATE,
857                     },
858                     &mut FxHashSet::default(),
859                 );
860                 cnum
861             }
862             _ => bug!(),
863         }
864     }
865
866     pub fn process_path_extern(&mut self, name: Symbol, span: Span) -> CrateNum {
867         let cnum = self.resolve_crate(name, span, DepKind::Explicit, None);
868
869         self.update_extern_crate(
870             cnum,
871             ExternCrate {
872                 src: ExternCrateSource::Path,
873                 span,
874                 // to have the least priority in `update_extern_crate`
875                 path_len: usize::max_value(),
876                 dependency_of: LOCAL_CRATE,
877             },
878             &mut FxHashSet::default(),
879         );
880
881         cnum
882     }
883
884     pub fn maybe_process_path_extern(&mut self, name: Symbol, span: Span) -> Option<CrateNum> {
885         let cnum = self.maybe_resolve_crate(name, span, DepKind::Explicit, None).ok()?;
886
887         self.update_extern_crate(
888             cnum,
889             ExternCrate {
890                 src: ExternCrateSource::Path,
891                 span,
892                 // to have the least priority in `update_extern_crate`
893                 path_len: usize::max_value(),
894                 dependency_of: LOCAL_CRATE,
895             },
896             &mut FxHashSet::default(),
897         );
898
899         Some(cnum)
900     }
901 }