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