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