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