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