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