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