]> git.lizzy.rs Git - rust.git/blob - src/librustc_metadata/creader.rs
Revert a few changes
[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, Tracked};
16
17 use rustc::hir::def_id::{CrateNum, DefIndex};
18 use rustc::hir::svh::Svh;
19 use rustc::middle::cstore::DepKind;
20 use rustc::session::Session;
21 use rustc::session::config::{Sanitizer, self};
22 use rustc_back::PanicStrategy;
23 use rustc::session::search_paths::PathKind;
24 use rustc::middle;
25 use rustc::middle::cstore::{CrateStore, validate_crate_name, ExternCrate};
26 use rustc::util::common::record_time;
27 use rustc::util::nodemap::FxHashSet;
28 use rustc::middle::cstore::NativeLibrary;
29 use rustc::hir::map::Definitions;
30
31 use std::cell::{RefCell, Cell};
32 use std::ops::Deref;
33 use std::path::PathBuf;
34 use std::rc::Rc;
35 use std::{cmp, fs};
36
37 use syntax::ast;
38 use syntax::abi::Abi;
39 use syntax::attr;
40 use syntax::ext::base::SyntaxExtension;
41 use syntax::feature_gate::{self, GateIssue};
42 use syntax::symbol::Symbol;
43 use syntax_pos::{Span, DUMMY_SP};
44 use log;
45
46 pub struct Library {
47     pub dylib: Option<(PathBuf, PathKind)>,
48     pub rlib: Option<(PathBuf, PathKind)>,
49     pub rmeta: Option<(PathBuf, PathKind)>,
50     pub metadata: MetadataBlob,
51 }
52
53 pub struct CrateLoader<'a> {
54     pub sess: &'a Session,
55     cstore: &'a CStore,
56     next_crate_num: CrateNum,
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.name());
64         info!("  cnum: {}", data.cnum);
65         info!("  hash: {}", data.hash());
66         info!("  reqd: {:?}", data.dep_kind.get());
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 #[derive(Debug)]
75 struct ExternCrateInfo {
76     ident: Symbol,
77     name: Symbol,
78     id: ast::NodeId,
79     dep_kind: DepKind,
80 }
81
82 fn register_native_lib(sess: &Session,
83                        cstore: &CStore,
84                        span: Option<Span>,
85                        lib: NativeLibrary) {
86     if lib.name.as_str().is_empty() {
87         match span {
88             Some(span) => {
89                 struct_span_err!(sess, span, E0454,
90                                  "#[link(name = \"\")] given with empty name")
91                     .span_label(span, "empty name given")
92                     .emit();
93             }
94             None => {
95                 sess.err("empty library name given via `-l`");
96             }
97         }
98         return
99     }
100     let is_osx = sess.target.target.options.is_like_osx;
101     if lib.kind == cstore::NativeFramework && !is_osx {
102         let msg = "native frameworks are only available on macOS targets";
103         match span {
104             Some(span) => span_err!(sess, span, E0455, "{}", msg),
105             None => sess.err(msg),
106         }
107     }
108     if lib.cfg.is_some() && !sess.features.borrow().link_cfg {
109         feature_gate::emit_feature_err(&sess.parse_sess,
110                                        "link_cfg",
111                                        span.unwrap(),
112                                        GateIssue::Language,
113                                        "is feature gated");
114     }
115     if lib.kind == cstore::NativeStaticNobundle && !sess.features.borrow().static_nobundle {
116         feature_gate::emit_feature_err(&sess.parse_sess,
117                                        "static_nobundle",
118                                        span.unwrap(),
119                                        GateIssue::Language,
120                                        "kind=\"static-nobundle\" is feature gated");
121     }
122     cstore.add_used_library(lib);
123 }
124
125 fn relevant_lib(sess: &Session, lib: &NativeLibrary) -> bool {
126     match lib.cfg {
127         Some(ref cfg) => attr::cfg_matches(cfg, &sess.parse_sess, None),
128         None => true,
129     }
130 }
131
132 // Extra info about a crate loaded for plugins or exported macros.
133 struct ExtensionCrate {
134     metadata: PMDSource,
135     dylib: Option<PathBuf>,
136     target_only: bool,
137 }
138
139 enum PMDSource {
140     Registered(Rc<cstore::CrateMetadata>),
141     Owned(Library),
142 }
143
144 impl Deref for PMDSource {
145     type Target = MetadataBlob;
146
147     fn deref(&self) -> &MetadataBlob {
148         match *self {
149             PMDSource::Registered(ref cmd) => &cmd.blob,
150             PMDSource::Owned(ref lib) => &lib.metadata
151         }
152     }
153 }
154
155 enum LoadResult {
156     Previous(CrateNum),
157     Loaded(Library),
158 }
159
160 impl<'a> CrateLoader<'a> {
161     pub fn new(sess: &'a Session, cstore: &'a CStore, local_crate_name: &str) -> Self {
162         CrateLoader {
163             sess: sess,
164             cstore: cstore,
165             next_crate_num: cstore.next_crate_num(),
166             local_crate_name: Symbol::intern(local_crate_name),
167         }
168     }
169
170     fn extract_crate_info(&self, i: &ast::Item) -> Option<ExternCrateInfo> {
171         match i.node {
172             ast::ItemKind::ExternCrate(ref path_opt) => {
173                 debug!("resolving extern crate stmt. ident: {} path_opt: {:?}",
174                        i.ident, path_opt);
175                 let name = match *path_opt {
176                     Some(name) => {
177                         validate_crate_name(Some(self.sess), &name.as_str(),
178                                             Some(i.span));
179                         name
180                     }
181                     None => i.ident.name,
182                 };
183                 Some(ExternCrateInfo {
184                     ident: i.ident.name,
185                     name: name,
186                     id: i.id,
187                     dep_kind: if attr::contains_name(&i.attrs, "no_link") {
188                         DepKind::UnexportedMacrosOnly
189                     } else {
190                         DepKind::Explicit
191                     },
192                 })
193             }
194             _ => None
195         }
196     }
197
198     fn existing_match(&self, name: Symbol, hash: Option<&Svh>, kind: PathKind)
199                       -> Option<CrateNum> {
200         let mut ret = None;
201         self.cstore.iter_crate_data(|cnum, data| {
202             if data.name != name { return }
203
204             match hash {
205                 Some(hash) if *hash == data.hash() => { ret = Some(cnum); return }
206                 Some(..) => return,
207                 None => {}
208             }
209
210             // When the hash is None we're dealing with a top-level dependency
211             // in which case we may have a specification on the command line for
212             // this library. Even though an upstream library may have loaded
213             // something of the same name, we have to make sure it was loaded
214             // from the exact same location as well.
215             //
216             // We're also sure to compare *paths*, not actual byte slices. The
217             // `source` stores paths which are normalized which may be different
218             // from the strings on the command line.
219             let source = self.cstore.used_crate_source(cnum);
220             if let Some(locs) = self.sess.opts.externs.get(&*name.as_str()) {
221                 let found = locs.iter().any(|l| {
222                     let l = fs::canonicalize(l).ok();
223                     source.dylib.as_ref().map(|p| &p.0) == l.as_ref() ||
224                     source.rlib.as_ref().map(|p| &p.0) == l.as_ref()
225                 });
226                 if found {
227                     ret = Some(cnum);
228                 }
229                 return
230             }
231
232             // Alright, so we've gotten this far which means that `data` has the
233             // right name, we don't have a hash, and we don't have a --extern
234             // pointing for ourselves. We're still not quite yet done because we
235             // have to make sure that this crate was found in the crate lookup
236             // path (this is a top-level dependency) as we don't want to
237             // implicitly load anything inside the dependency lookup path.
238             let prev_kind = source.dylib.as_ref().or(source.rlib.as_ref())
239                                   .or(source.rmeta.as_ref())
240                                   .expect("No sources for crate").1;
241             if ret.is_none() && (prev_kind == kind || prev_kind == PathKind::All) {
242                 ret = Some(cnum);
243             }
244         });
245         return ret;
246     }
247
248     fn verify_no_symbol_conflicts(&self,
249                                   span: Span,
250                                   root: &CrateRoot) {
251         // Check for (potential) conflicts with the local crate
252         if self.local_crate_name == root.name &&
253            self.sess.local_crate_disambiguator() == root.disambiguator {
254             span_fatal!(self.sess, span, E0519,
255                         "the current crate is indistinguishable from one of its \
256                          dependencies: it has the same crate-name `{}` and was \
257                          compiled with the same `-C metadata` arguments. This \
258                          will result in symbol conflicts between the two.",
259                         root.name)
260         }
261
262         // Check for conflicts with any crate loaded so far
263         self.cstore.iter_crate_data(|_, other| {
264             if other.name() == root.name && // same crate-name
265                other.disambiguator() == root.disambiguator &&  // same crate-disambiguator
266                other.hash() != root.hash { // but different SVH
267                 span_fatal!(self.sess, span, E0523,
268                         "found two different crates with name `{}` that are \
269                          not distinguished by differing `-C metadata`. This \
270                          will result in symbol conflicts between the two.",
271                         root.name)
272             }
273         });
274     }
275
276     fn register_crate(&mut self,
277                       root: &Option<CratePaths>,
278                       ident: Symbol,
279                       name: Symbol,
280                       span: Span,
281                       lib: Library,
282                       dep_kind: DepKind)
283                       -> (CrateNum, Rc<cstore::CrateMetadata>) {
284         info!("register crate `extern crate {} as {}`", name, ident);
285         let crate_root = lib.metadata.get_root();
286         self.verify_no_symbol_conflicts(span, &crate_root);
287
288         // Claim this crate number and cache it
289         let cnum = self.next_crate_num;
290         self.next_crate_num = CrateNum::from_u32(cnum.as_u32() + 1);
291
292         // Stash paths for top-most crate locally if necessary.
293         let crate_paths = if root.is_none() {
294             Some(CratePaths {
295                 ident: ident.to_string(),
296                 dylib: lib.dylib.clone().map(|p| p.0),
297                 rlib:  lib.rlib.clone().map(|p| p.0),
298                 rmeta: lib.rmeta.clone().map(|p| p.0),
299             })
300         } else {
301             None
302         };
303         // Maintain a reference to the top most crate.
304         let root = if root.is_some() { root } else { &crate_paths };
305
306         let Library { dylib, rlib, rmeta, metadata } = lib;
307
308         let cnum_map = self.resolve_crate_deps(root, &crate_root, &metadata, cnum, span, dep_kind);
309
310         let def_path_table = record_time(&self.sess.perf_stats.decode_def_path_tables_time, || {
311             crate_root.def_path_table.decode(&metadata)
312         });
313
314         let exported_symbols = crate_root.exported_symbols
315                                          .map(|x| x.decode(&metadata).collect());
316
317         let trait_impls = crate_root
318             .impls
319             .map(|impls| {
320                 impls.decode(&metadata)
321                      .map(|trait_impls| (trait_impls.trait_id, trait_impls.impls))
322                      .collect()
323             });
324
325         let mut cmeta = cstore::CrateMetadata {
326             name: name,
327             extern_crate: Cell::new(None),
328             def_path_table: Rc::new(def_path_table),
329             exported_symbols: exported_symbols,
330             trait_impls: trait_impls,
331             proc_macros: crate_root.macro_derive_registrar.map(|_| {
332                 self.load_derive_macros(&crate_root, dylib.clone().map(|p| p.0), span)
333             }),
334             root: crate_root,
335             blob: metadata,
336             cnum_map: RefCell::new(cnum_map),
337             cnum: cnum,
338             codemap_import_info: RefCell::new(vec![]),
339             attribute_cache: RefCell::new([Vec::new(), Vec::new()]),
340             dep_kind: Cell::new(dep_kind),
341             source: cstore::CrateSource {
342                 dylib: dylib,
343                 rlib: rlib,
344                 rmeta: rmeta,
345             },
346             // Initialize this with an empty set. The field is populated below
347             // after we were able to deserialize its contents.
348             dllimport_foreign_items: Tracked::new(FxHashSet()),
349         };
350
351         let dllimports: Tracked<FxHashSet<_>> = cmeta
352             .root
353             .native_libraries
354             .map(|native_libraries| {
355                 let native_libraries: Vec<_> = native_libraries.decode(&cmeta)
356                                                                .collect();
357                 native_libraries
358                     .iter()
359                     .filter(|lib| relevant_lib(self.sess, lib) &&
360                                   lib.kind == cstore::NativeLibraryKind::NativeUnknown)
361                     .flat_map(|lib| lib.foreign_items.iter())
362                     .map(|id| *id)
363                     .collect()
364             });
365
366         cmeta.dllimport_foreign_items = dllimports;
367
368         let cmeta = Rc::new(cmeta);
369         self.cstore.set_crate_data(cnum, cmeta.clone());
370         (cnum, cmeta)
371     }
372
373     fn resolve_crate(&mut self,
374                      root: &Option<CratePaths>,
375                      ident: Symbol,
376                      name: Symbol,
377                      hash: Option<&Svh>,
378                      span: Span,
379                      path_kind: PathKind,
380                      mut dep_kind: DepKind)
381                      -> (CrateNum, Rc<cstore::CrateMetadata>) {
382         info!("resolving crate `extern crate {} as {}`", name, ident);
383         let result = if let Some(cnum) = self.existing_match(name, hash, path_kind) {
384             LoadResult::Previous(cnum)
385         } else {
386             info!("falling back to a load");
387             let mut locate_ctxt = locator::Context {
388                 sess: self.sess,
389                 span: span,
390                 ident: ident,
391                 crate_name: name,
392                 hash: hash.map(|a| &*a),
393                 filesearch: self.sess.target_filesearch(path_kind),
394                 target: &self.sess.target.target,
395                 triple: &self.sess.opts.target_triple,
396                 root: root,
397                 rejected_via_hash: vec![],
398                 rejected_via_triple: vec![],
399                 rejected_via_kind: vec![],
400                 rejected_via_version: vec![],
401                 rejected_via_filename: vec![],
402                 should_match_name: true,
403                 is_proc_macro: Some(false),
404                 metadata_loader: &*self.cstore.metadata_loader,
405             };
406
407             self.load(&mut locate_ctxt).or_else(|| {
408                 dep_kind = DepKind::UnexportedMacrosOnly;
409
410                 let mut proc_macro_locator = locator::Context {
411                     target: &self.sess.host,
412                     triple: config::host_triple(),
413                     filesearch: self.sess.host_filesearch(path_kind),
414                     rejected_via_hash: vec![],
415                     rejected_via_triple: vec![],
416                     rejected_via_kind: vec![],
417                     rejected_via_version: vec![],
418                     rejected_via_filename: vec![],
419                     is_proc_macro: Some(true),
420                     ..locate_ctxt
421                 };
422
423                 self.load(&mut proc_macro_locator)
424             }).unwrap_or_else(|| locate_ctxt.report_errs())
425         };
426
427         match result {
428             LoadResult::Previous(cnum) => {
429                 let data = self.cstore.get_crate_data(cnum);
430                 if data.root.macro_derive_registrar.is_some() {
431                     dep_kind = DepKind::UnexportedMacrosOnly;
432                 }
433                 data.dep_kind.set(cmp::max(data.dep_kind.get(), dep_kind));
434                 (cnum, data)
435             }
436             LoadResult::Loaded(library) => {
437                 self.register_crate(root, ident, name, span, library, dep_kind)
438             }
439         }
440     }
441
442     fn load(&mut self, locate_ctxt: &mut locator::Context) -> Option<LoadResult> {
443         let library = match locate_ctxt.maybe_load_library_crate() {
444             Some(lib) => lib,
445             None => return None,
446         };
447
448         // In the case that we're loading a crate, but not matching
449         // against a hash, we could load a crate which has the same hash
450         // as an already loaded crate. If this is the case prevent
451         // duplicates by just using the first crate.
452         //
453         // Note that we only do this for target triple crates, though, as we
454         // don't want to match a host crate against an equivalent target one
455         // already loaded.
456         let root = library.metadata.get_root();
457         if locate_ctxt.triple == self.sess.opts.target_triple {
458             let mut result = LoadResult::Loaded(library);
459             self.cstore.iter_crate_data(|cnum, data| {
460                 if data.name() == root.name && root.hash == data.hash() {
461                     assert!(locate_ctxt.hash.is_none());
462                     info!("load success, going to previous cnum: {}", cnum);
463                     result = LoadResult::Previous(cnum);
464                 }
465             });
466             Some(result)
467         } else {
468             Some(LoadResult::Loaded(library))
469         }
470     }
471
472     fn update_extern_crate(&mut self,
473                            cnum: CrateNum,
474                            mut extern_crate: ExternCrate,
475                            visited: &mut FxHashSet<(CrateNum, bool)>)
476     {
477         if !visited.insert((cnum, extern_crate.direct)) { return }
478
479         let cmeta = self.cstore.get_crate_data(cnum);
480         let old_extern_crate = cmeta.extern_crate.get();
481
482         // Prefer:
483         // - something over nothing (tuple.0);
484         // - direct extern crate to indirect (tuple.1);
485         // - shorter paths to longer (tuple.2).
486         let new_rank = (true, extern_crate.direct, !extern_crate.path_len);
487         let old_rank = match old_extern_crate {
488             None => (false, false, !0),
489             Some(ref c) => (true, c.direct, !c.path_len),
490         };
491
492         if old_rank >= new_rank {
493             return; // no change needed
494         }
495
496         cmeta.extern_crate.set(Some(extern_crate));
497         // Propagate the extern crate info to dependencies.
498         extern_crate.direct = false;
499         for &dep_cnum in cmeta.cnum_map.borrow().iter() {
500             self.update_extern_crate(dep_cnum, extern_crate, visited);
501         }
502     }
503
504     // Go through the crate metadata and load any crates that it references
505     fn resolve_crate_deps(&mut self,
506                           root: &Option<CratePaths>,
507                           crate_root: &CrateRoot,
508                           metadata: &MetadataBlob,
509                           krate: CrateNum,
510                           span: Span,
511                           dep_kind: DepKind)
512                           -> cstore::CrateNumMap {
513         debug!("resolving deps of external crate");
514         if crate_root.macro_derive_registrar.is_some() {
515             return cstore::CrateNumMap::new();
516         }
517
518         // The map from crate numbers in the crate we're resolving to local crate numbers.
519         // We map 0 and all other holes in the map to our parent crate. The "additional"
520         // self-dependencies should be harmless.
521         ::std::iter::once(krate).chain(crate_root.crate_deps
522                                                  .get_untracked()
523                                                  .decode(metadata)
524                                                  .map(|dep| {
525             debug!("resolving dep crate {} hash: `{}`", dep.name, dep.hash);
526             if dep.kind == DepKind::UnexportedMacrosOnly {
527                 return krate;
528             }
529             let dep_kind = match dep_kind {
530                 DepKind::MacrosOnly => DepKind::MacrosOnly,
531                 _ => dep.kind,
532             };
533             let (local_cnum, ..) = self.resolve_crate(
534                 root, dep.name, dep.name, Some(&dep.hash), span, PathKind::Dependency, dep_kind,
535             );
536             local_cnum
537         })).collect()
538     }
539
540     fn read_extension_crate(&mut self, span: Span, info: &ExternCrateInfo) -> ExtensionCrate {
541         info!("read extension crate {} `extern crate {} as {}` dep_kind={:?}",
542               info.id, info.name, info.ident, info.dep_kind);
543         let target_triple = &self.sess.opts.target_triple[..];
544         let is_cross = target_triple != config::host_triple();
545         let mut target_only = false;
546         let mut locate_ctxt = locator::Context {
547             sess: self.sess,
548             span: span,
549             ident: info.ident,
550             crate_name: info.name,
551             hash: None,
552             filesearch: self.sess.host_filesearch(PathKind::Crate),
553             target: &self.sess.host,
554             triple: config::host_triple(),
555             root: &None,
556             rejected_via_hash: vec![],
557             rejected_via_triple: vec![],
558             rejected_via_kind: vec![],
559             rejected_via_version: vec![],
560             rejected_via_filename: vec![],
561             should_match_name: true,
562             is_proc_macro: None,
563             metadata_loader: &*self.cstore.metadata_loader,
564         };
565         let library = self.load(&mut locate_ctxt).or_else(|| {
566             if !is_cross {
567                 return None
568             }
569             // Try loading from target crates. This will abort later if we
570             // try to load a plugin registrar function,
571             target_only = true;
572
573             locate_ctxt.target = &self.sess.target.target;
574             locate_ctxt.triple = target_triple;
575             locate_ctxt.filesearch = self.sess.target_filesearch(PathKind::Crate);
576
577             self.load(&mut locate_ctxt)
578         });
579         let library = match library {
580             Some(l) => l,
581             None => locate_ctxt.report_errs(),
582         };
583
584         let (dylib, metadata) = match library {
585             LoadResult::Previous(cnum) => {
586                 let data = self.cstore.get_crate_data(cnum);
587                 (data.source.dylib.clone(), PMDSource::Registered(data))
588             }
589             LoadResult::Loaded(library) => {
590                 let dylib = library.dylib.clone();
591                 let metadata = PMDSource::Owned(library);
592                 (dylib, metadata)
593             }
594         };
595
596         ExtensionCrate {
597             metadata: metadata,
598             dylib: dylib.map(|p| p.0),
599             target_only: target_only,
600         }
601     }
602
603     /// Load custom derive macros.
604     ///
605     /// Note that this is intentionally similar to how we load plugins today,
606     /// but also intentionally separate. Plugins are likely always going to be
607     /// implemented as dynamic libraries, but we have a possible future where
608     /// custom derive (and other macro-1.1 style features) are implemented via
609     /// executables and custom IPC.
610     fn load_derive_macros(&mut self, root: &CrateRoot, dylib: Option<PathBuf>, span: Span)
611                           -> Vec<(ast::Name, Rc<SyntaxExtension>)> {
612         use std::{env, mem};
613         use proc_macro::TokenStream;
614         use proc_macro::__internal::Registry;
615         use rustc_back::dynamic_lib::DynamicLibrary;
616         use syntax_ext::deriving::custom::ProcMacroDerive;
617         use syntax_ext::proc_macro_impl::{AttrProcMacro, BangProcMacro};
618
619         let path = match dylib {
620             Some(dylib) => dylib,
621             None => span_bug!(span, "proc-macro crate not dylib"),
622         };
623         // Make sure the path contains a / or the linker will search for it.
624         let path = env::current_dir().unwrap().join(path);
625         let lib = match DynamicLibrary::open(Some(&path)) {
626             Ok(lib) => lib,
627             Err(err) => self.sess.span_fatal(span, &err),
628         };
629
630         let sym = self.sess.generate_derive_registrar_symbol(root.disambiguator,
631                                                              root.macro_derive_registrar.unwrap());
632         let registrar = unsafe {
633             let sym = match lib.symbol(&sym) {
634                 Ok(f) => f,
635                 Err(err) => self.sess.span_fatal(span, &err),
636             };
637             mem::transmute::<*mut u8, fn(&mut Registry)>(sym)
638         };
639
640         struct MyRegistrar(Vec<(ast::Name, Rc<SyntaxExtension>)>);
641
642         impl Registry for MyRegistrar {
643             fn register_custom_derive(&mut self,
644                                       trait_name: &str,
645                                       expand: fn(TokenStream) -> TokenStream,
646                                       attributes: &[&'static str]) {
647                 let attrs = attributes.iter().cloned().map(Symbol::intern).collect::<Vec<_>>();
648                 let derive = ProcMacroDerive::new(expand, attrs.clone());
649                 let derive = SyntaxExtension::ProcMacroDerive(Box::new(derive), attrs);
650                 self.0.push((Symbol::intern(trait_name), Rc::new(derive)));
651             }
652
653             fn register_attr_proc_macro(&mut self,
654                                         name: &str,
655                                         expand: fn(TokenStream, TokenStream) -> TokenStream) {
656                 let expand = SyntaxExtension::AttrProcMacro(
657                     Box::new(AttrProcMacro { inner: expand })
658                 );
659                 self.0.push((Symbol::intern(name), Rc::new(expand)));
660             }
661
662             fn register_bang_proc_macro(&mut self,
663                                         name: &str,
664                                         expand: fn(TokenStream) -> TokenStream) {
665                 let expand = SyntaxExtension::ProcMacro(
666                     Box::new(BangProcMacro { inner: expand })
667                 );
668                 self.0.push((Symbol::intern(name), Rc::new(expand)));
669             }
670         }
671
672         let mut my_registrar = MyRegistrar(Vec::new());
673         registrar(&mut my_registrar);
674
675         // Intentionally leak the dynamic library. We can't ever unload it
676         // since the library can make things that will live arbitrarily long.
677         mem::forget(lib);
678         my_registrar.0
679     }
680
681     /// Look for a plugin registrar. Returns library path, crate
682     /// SVH and DefIndex of the registrar function.
683     pub fn find_plugin_registrar(&mut self,
684                                  span: Span,
685                                  name: &str)
686                                  -> Option<(PathBuf, Symbol, DefIndex)> {
687         let ekrate = self.read_extension_crate(span, &ExternCrateInfo {
688              name: Symbol::intern(name),
689              ident: Symbol::intern(name),
690              id: ast::DUMMY_NODE_ID,
691              dep_kind: DepKind::UnexportedMacrosOnly,
692         });
693
694         if ekrate.target_only {
695             // Need to abort before syntax expansion.
696             let message = format!("plugin `{}` is not available for triple `{}` \
697                                    (only found {})",
698                                   name,
699                                   config::host_triple(),
700                                   self.sess.opts.target_triple);
701             span_fatal!(self.sess, span, E0456, "{}", &message);
702         }
703
704         let root = ekrate.metadata.get_root();
705         match (ekrate.dylib.as_ref(), root.plugin_registrar_fn) {
706             (Some(dylib), Some(reg)) => {
707                 Some((dylib.to_path_buf(), root.disambiguator, reg))
708             }
709             (None, Some(_)) => {
710                 span_err!(self.sess, span, E0457,
711                           "plugin `{}` only found in rlib format, but must be available \
712                            in dylib format",
713                           name);
714                 // No need to abort because the loading code will just ignore this
715                 // empty dylib.
716                 None
717             }
718             _ => None,
719         }
720     }
721
722     fn get_foreign_items_of_kind(&self, kind: cstore::NativeLibraryKind) -> Vec<DefIndex> {
723         let mut items = vec![];
724         let libs = self.cstore.get_used_libraries();
725         for lib in libs.borrow().iter() {
726             if relevant_lib(self.sess, lib) && lib.kind == kind {
727                 items.extend(&lib.foreign_items);
728             }
729         }
730         items
731     }
732
733     fn register_statically_included_foreign_items(&mut self) {
734         for id in self.get_foreign_items_of_kind(cstore::NativeStatic) {
735             self.cstore.add_statically_included_foreign_item(id);
736         }
737         for id in self.get_foreign_items_of_kind(cstore::NativeStaticNobundle) {
738             self.cstore.add_statically_included_foreign_item(id);
739         }
740     }
741
742     fn register_dllimport_foreign_items(&mut self) {
743         let mut dllimports = self.cstore.dllimport_foreign_items.borrow_mut();
744         for id in self.get_foreign_items_of_kind(cstore::NativeUnknown) {
745             dllimports.insert(id);
746         }
747     }
748
749     fn inject_panic_runtime(&mut self, krate: &ast::Crate) {
750         // If we're only compiling an rlib, then there's no need to select a
751         // panic runtime, so we just skip this section entirely.
752         let any_non_rlib = self.sess.crate_types.borrow().iter().any(|ct| {
753             *ct != config::CrateTypeRlib
754         });
755         if !any_non_rlib {
756             info!("panic runtime injection skipped, only generating rlib");
757             return
758         }
759
760         // If we need a panic runtime, we try to find an existing one here. At
761         // the same time we perform some general validation of the DAG we've got
762         // going such as ensuring everything has a compatible panic strategy.
763         //
764         // The logic for finding the panic runtime here is pretty much the same
765         // as the allocator case with the only addition that the panic strategy
766         // compilation mode also comes into play.
767         let desired_strategy = self.sess.panic_strategy();
768         let mut runtime_found = false;
769         let mut needs_panic_runtime = attr::contains_name(&krate.attrs,
770                                                           "needs_panic_runtime");
771
772         let dep_graph = &self.sess.dep_graph;
773
774         self.cstore.iter_crate_data(|cnum, data| {
775             needs_panic_runtime = needs_panic_runtime ||
776                                   data.needs_panic_runtime(dep_graph);
777             if data.is_panic_runtime(dep_graph) {
778                 // Inject a dependency from all #![needs_panic_runtime] to this
779                 // #![panic_runtime] crate.
780                 self.inject_dependency_if(cnum, "a panic runtime",
781                                           &|data| data.needs_panic_runtime(dep_graph));
782                 runtime_found = runtime_found || data.dep_kind.get() == DepKind::Explicit;
783             }
784         });
785
786         // If an explicitly linked and matching panic runtime was found, or if
787         // we just don't need one at all, then we're done here and there's
788         // nothing else to do.
789         if !needs_panic_runtime || runtime_found {
790             return
791         }
792
793         // By this point we know that we (a) need a panic runtime and (b) no
794         // panic runtime was explicitly linked. Here we just load an appropriate
795         // default runtime for our panic strategy and then inject the
796         // dependencies.
797         //
798         // We may resolve to an already loaded crate (as the crate may not have
799         // been explicitly linked prior to this) and we may re-inject
800         // dependencies again, but both of those situations are fine.
801         //
802         // Also note that we have yet to perform validation of the crate graph
803         // in terms of everyone has a compatible panic runtime format, that's
804         // performed later as part of the `dependency_format` module.
805         let name = match desired_strategy {
806             PanicStrategy::Unwind => Symbol::intern("panic_unwind"),
807             PanicStrategy::Abort => Symbol::intern("panic_abort"),
808         };
809         info!("panic runtime not found -- loading {}", name);
810
811         let dep_kind = DepKind::Implicit;
812         let (cnum, data) =
813             self.resolve_crate(&None, name, name, None, DUMMY_SP, PathKind::Crate, dep_kind);
814
815         // Sanity check the loaded crate to ensure it is indeed a panic runtime
816         // and the panic strategy is indeed what we thought it was.
817         if !data.is_panic_runtime(dep_graph) {
818             self.sess.err(&format!("the crate `{}` is not a panic runtime",
819                                    name));
820         }
821         if data.panic_strategy(dep_graph) != desired_strategy {
822             self.sess.err(&format!("the crate `{}` does not have the panic \
823                                     strategy `{}`",
824                                    name, desired_strategy.desc()));
825         }
826
827         self.sess.injected_panic_runtime.set(Some(cnum));
828         self.inject_dependency_if(cnum, "a panic runtime",
829                                   &|data| data.needs_panic_runtime(dep_graph));
830     }
831
832     fn inject_sanitizer_runtime(&mut self) {
833         if let Some(ref sanitizer) = self.sess.opts.debugging_opts.sanitizer {
834             // Sanitizers can only be used on some tested platforms with
835             // executables linked to `std`
836             const ASAN_SUPPORTED_TARGETS: &[&str] = &["x86_64-unknown-linux-gnu",
837                                                       "x86_64-apple-darwin"];
838             const TSAN_SUPPORTED_TARGETS: &[&str] = &["x86_64-unknown-linux-gnu",
839                                                       "x86_64-apple-darwin"];
840             const LSAN_SUPPORTED_TARGETS: &[&str] = &["x86_64-unknown-linux-gnu"];
841             const MSAN_SUPPORTED_TARGETS: &[&str] = &["x86_64-unknown-linux-gnu"];
842
843             let supported_targets = match *sanitizer {
844                 Sanitizer::Address => ASAN_SUPPORTED_TARGETS,
845                 Sanitizer::Thread => TSAN_SUPPORTED_TARGETS,
846                 Sanitizer::Leak => LSAN_SUPPORTED_TARGETS,
847                 Sanitizer::Memory => MSAN_SUPPORTED_TARGETS,
848             };
849             if !supported_targets.contains(&&*self.sess.target.target.llvm_target) {
850                 self.sess.err(&format!("{:?}Sanitizer only works with the `{}` target",
851                     sanitizer,
852                     supported_targets.join("` or `")
853                 ));
854                 return
855             }
856
857             if !self.sess.crate_types.borrow().iter().all(|ct| {
858                 match *ct {
859                     // Link the runtime
860                     config::CrateTypeExecutable => true,
861                     // This crate will be compiled with the required
862                     // instrumentation pass
863                     config::CrateTypeRlib => false,
864                     _ => {
865                         self.sess.err(&format!("Only executables and rlibs can be \
866                                                 compiled with `-Z sanitizer`"));
867                         false
868                     }
869                 }
870             }) {
871                 return
872             }
873
874             let mut uses_std = false;
875             self.cstore.iter_crate_data(|_, data| {
876                 if data.name == "std" {
877                     uses_std = true;
878                 }
879             });
880
881             if uses_std {
882                 let name = match *sanitizer {
883                     Sanitizer::Address => "rustc_asan",
884                     Sanitizer::Leak => "rustc_lsan",
885                     Sanitizer::Memory => "rustc_msan",
886                     Sanitizer::Thread => "rustc_tsan",
887                 };
888                 info!("loading sanitizer: {}", name);
889
890                 let symbol = Symbol::intern(name);
891                 let dep_kind = DepKind::Implicit;
892                 let (_, data) =
893                     self.resolve_crate(&None, symbol, symbol, None, DUMMY_SP,
894                                        PathKind::Crate, dep_kind);
895
896                 // Sanity check the loaded crate to ensure it is indeed a sanitizer runtime
897                 if !data.is_sanitizer_runtime(&self.sess.dep_graph) {
898                     self.sess.err(&format!("the crate `{}` is not a sanitizer runtime",
899                                            name));
900                 }
901             }
902         }
903     }
904
905     fn inject_profiler_runtime(&mut self) {
906         if self.sess.opts.debugging_opts.profile {
907             info!("loading profiler");
908
909             let symbol = Symbol::intern("profiler_builtins");
910             let dep_kind = DepKind::Implicit;
911             let (_, data) =
912                 self.resolve_crate(&None, symbol, symbol, None, DUMMY_SP,
913                                    PathKind::Crate, dep_kind);
914
915             // Sanity check the loaded crate to ensure it is indeed a profiler runtime
916             if !data.is_profiler_runtime(&self.sess.dep_graph) {
917                 self.sess.err(&format!("the crate `profiler_builtins` is not \
918                                         a profiler runtime"));
919             }
920         }
921     }
922
923     fn inject_allocator_crate(&mut self) {
924         // Make sure that we actually need an allocator, if none of our
925         // dependencies need one then we definitely don't!
926         //
927         // Also, if one of our dependencies has an explicit allocator, then we
928         // also bail out as we don't need to implicitly inject one.
929         let mut needs_allocator = false;
930         let mut found_required_allocator = false;
931         let dep_graph = &self.sess.dep_graph;
932         self.cstore.iter_crate_data(|cnum, data| {
933             needs_allocator = needs_allocator || data.needs_allocator(dep_graph);
934             if data.is_allocator(dep_graph) {
935                 info!("{} required by rlib and is an allocator", data.name());
936                 self.inject_dependency_if(cnum, "an allocator",
937                                           &|data| data.needs_allocator(dep_graph));
938                 found_required_allocator = found_required_allocator ||
939                     data.dep_kind.get() == DepKind::Explicit;
940             }
941         });
942         if !needs_allocator || found_required_allocator { return }
943
944         // At this point we've determined that we need an allocator and no
945         // previous allocator has been activated. We look through our outputs of
946         // crate types to see what kind of allocator types we may need.
947         //
948         // The main special output type here is that rlibs do **not** need an
949         // allocator linked in (they're just object files), only final products
950         // (exes, dylibs, staticlibs) need allocators.
951         let mut need_lib_alloc = false;
952         let mut need_exe_alloc = false;
953         for ct in self.sess.crate_types.borrow().iter() {
954             match *ct {
955                 config::CrateTypeExecutable => need_exe_alloc = true,
956                 config::CrateTypeDylib |
957                 config::CrateTypeProcMacro |
958                 config::CrateTypeCdylib |
959                 config::CrateTypeStaticlib => need_lib_alloc = true,
960                 config::CrateTypeRlib => {}
961             }
962         }
963         if !need_lib_alloc && !need_exe_alloc { return }
964
965         // The default allocator crate comes from the custom target spec, and we
966         // choose between the standard library allocator or exe allocator. This
967         // distinction exists because the default allocator for binaries (where
968         // the world is Rust) is different than library (where the world is
969         // likely *not* Rust).
970         //
971         // If a library is being produced, but we're also flagged with `-C
972         // prefer-dynamic`, then we interpret this as a *Rust* dynamic library
973         // is being produced so we use the exe allocator instead.
974         //
975         // What this boils down to is:
976         //
977         // * Binaries use jemalloc
978         // * Staticlibs and Rust dylibs use system malloc
979         // * Rust dylibs used as dependencies to rust use jemalloc
980         let name = if need_lib_alloc && !self.sess.opts.cg.prefer_dynamic {
981             Symbol::intern(&self.sess.target.target.options.lib_allocation_crate)
982         } else {
983             Symbol::intern(&self.sess.target.target.options.exe_allocation_crate)
984         };
985         let dep_kind = DepKind::Implicit;
986         let (cnum, data) =
987             self.resolve_crate(&None, name, name, None, DUMMY_SP, PathKind::Crate, dep_kind);
988
989         // Sanity check the crate we loaded to ensure that it is indeed an
990         // allocator.
991         if !data.is_allocator(dep_graph) {
992             self.sess.err(&format!("the allocator crate `{}` is not tagged \
993                                     with #![allocator]", data.name()));
994         }
995
996         self.sess.injected_allocator.set(Some(cnum));
997         self.inject_dependency_if(cnum, "an allocator",
998                                   &|data| data.needs_allocator(dep_graph));
999     }
1000
1001     fn inject_dependency_if(&self,
1002                             krate: CrateNum,
1003                             what: &str,
1004                             needs_dep: &Fn(&cstore::CrateMetadata) -> bool) {
1005         // don't perform this validation if the session has errors, as one of
1006         // those errors may indicate a circular dependency which could cause
1007         // this to stack overflow.
1008         if self.sess.has_errors() {
1009             return
1010         }
1011
1012         // Before we inject any dependencies, make sure we don't inject a
1013         // circular dependency by validating that this crate doesn't
1014         // transitively depend on any crates satisfying `needs_dep`.
1015         for dep in self.cstore.crate_dependencies_in_rpo(krate) {
1016             let data = self.cstore.get_crate_data(dep);
1017             if needs_dep(&data) {
1018                 self.sess.err(&format!("the crate `{}` cannot depend \
1019                                         on a crate that needs {}, but \
1020                                         it depends on `{}`",
1021                                        self.cstore.get_crate_data(krate).name(),
1022                                        what,
1023                                        data.name()));
1024             }
1025         }
1026
1027         // All crates satisfying `needs_dep` do not explicitly depend on the
1028         // crate provided for this compile, but in order for this compilation to
1029         // be successfully linked we need to inject a dependency (to order the
1030         // crates on the command line correctly).
1031         self.cstore.iter_crate_data(|cnum, data| {
1032             if !needs_dep(data) {
1033                 return
1034             }
1035
1036             info!("injecting a dep from {} to {}", cnum, krate);
1037             data.cnum_map.borrow_mut().push(krate);
1038         });
1039     }
1040 }
1041
1042 impl<'a> CrateLoader<'a> {
1043     pub fn preprocess(&mut self, krate: &ast::Crate) {
1044         for attr in &krate.attrs {
1045             if attr.path == "link_args" {
1046                 if let Some(linkarg) = attr.value_str() {
1047                     self.cstore.add_used_link_args(&linkarg.as_str());
1048                 }
1049             }
1050         }
1051     }
1052
1053     fn process_foreign_mod(&mut self, i: &ast::Item, fm: &ast::ForeignMod,
1054                            definitions: &Definitions) {
1055         if fm.abi == Abi::Rust || fm.abi == Abi::RustIntrinsic || fm.abi == Abi::PlatformIntrinsic {
1056             return;
1057         }
1058
1059         // First, add all of the custom #[link_args] attributes
1060         for m in i.attrs.iter().filter(|a| a.check_name("link_args")) {
1061             if let Some(linkarg) = m.value_str() {
1062                 self.cstore.add_used_link_args(&linkarg.as_str());
1063             }
1064         }
1065
1066         // Next, process all of the #[link(..)]-style arguments
1067         for m in i.attrs.iter().filter(|a| a.check_name("link")) {
1068             let items = match m.meta_item_list() {
1069                 Some(item) => item,
1070                 None => continue,
1071             };
1072             let kind = items.iter().find(|k| {
1073                 k.check_name("kind")
1074             }).and_then(|a| a.value_str()).map(Symbol::as_str);
1075             let kind = match kind.as_ref().map(|s| &s[..]) {
1076                 Some("static") => cstore::NativeStatic,
1077                 Some("static-nobundle") => cstore::NativeStaticNobundle,
1078                 Some("dylib") => cstore::NativeUnknown,
1079                 Some("framework") => cstore::NativeFramework,
1080                 Some(k) => {
1081                     struct_span_err!(self.sess, m.span, E0458,
1082                               "unknown kind: `{}`", k)
1083                         .span_label(m.span, "unknown kind").emit();
1084                     cstore::NativeUnknown
1085                 }
1086                 None => cstore::NativeUnknown
1087             };
1088             let n = items.iter().find(|n| {
1089                 n.check_name("name")
1090             }).and_then(|a| a.value_str());
1091             let n = match n {
1092                 Some(n) => n,
1093                 None => {
1094                     struct_span_err!(self.sess, m.span, E0459,
1095                                      "#[link(...)] specified without `name = \"foo\"`")
1096                         .span_label(m.span, "missing `name` argument").emit();
1097                     Symbol::intern("foo")
1098                 }
1099             };
1100             let cfg = items.iter().find(|k| {
1101                 k.check_name("cfg")
1102             }).and_then(|a| a.meta_item_list());
1103             let cfg = cfg.map(|list| {
1104                 list[0].meta_item().unwrap().clone()
1105             });
1106             let foreign_items = fm.items.iter()
1107                 .map(|it| definitions.opt_def_index(it.id).unwrap())
1108                 .collect();
1109             let lib = NativeLibrary {
1110                 name: n,
1111                 kind: kind,
1112                 cfg: cfg,
1113                 foreign_items: foreign_items,
1114             };
1115             register_native_lib(self.sess, self.cstore, Some(m.span), lib);
1116         }
1117     }
1118 }
1119
1120 impl<'a> middle::cstore::CrateLoader for CrateLoader<'a> {
1121     fn postprocess(&mut self, krate: &ast::Crate) {
1122         // inject the sanitizer runtime before the allocator runtime because all
1123         // sanitizers force the use of the `alloc_system` allocator
1124         self.inject_sanitizer_runtime();
1125         self.inject_profiler_runtime();
1126         self.inject_allocator_crate();
1127         self.inject_panic_runtime(krate);
1128
1129         if log_enabled!(log::LogLevel::Info) {
1130             dump_crates(&self.cstore);
1131         }
1132
1133         // Process libs passed on the command line
1134         // First, check for errors
1135         let mut renames = FxHashSet();
1136         for &(ref name, ref new_name, _) in &self.sess.opts.libs {
1137             if let &Some(ref new_name) = new_name {
1138                 if new_name.is_empty() {
1139                     self.sess.err(
1140                         &format!("an empty renaming target was specified for library `{}`",name));
1141                 } else if !self.cstore.get_used_libraries().borrow().iter()
1142                                                            .any(|lib| lib.name == name as &str) {
1143                     self.sess.err(&format!("renaming of the library `{}` was specified, \
1144                                             however this crate contains no #[link(...)] \
1145                                             attributes referencing this library.", name));
1146                 } else if renames.contains(name) {
1147                     self.sess.err(&format!("multiple renamings were specified for library `{}` .",
1148                                             name));
1149                 } else {
1150                     renames.insert(name);
1151                 }
1152             }
1153         }
1154         // Update kind and, optionally, the name of all native libaries
1155         // (there may be more than one) with the specified name.
1156         for &(ref name, ref new_name, kind) in &self.sess.opts.libs {
1157             let mut found = false;
1158             for lib in self.cstore.get_used_libraries().borrow_mut().iter_mut() {
1159                 if lib.name == name as &str {
1160                     let mut changed = false;
1161                     if let Some(k) = kind {
1162                         lib.kind = k;
1163                         changed = true;
1164                     }
1165                     if let &Some(ref new_name) = new_name {
1166                         lib.name = Symbol::intern(new_name);
1167                         changed = true;
1168                     }
1169                     if !changed {
1170                         self.sess.warn(&format!("redundant linker flag specified for library `{}`",
1171                                                 name));
1172                     }
1173
1174                     found = true;
1175                 }
1176             }
1177             if !found {
1178                 // Add if not found
1179                 let new_name = new_name.as_ref().map(|s| &**s); // &Option<String> -> Option<&str>
1180                 let lib = NativeLibrary {
1181                     name: Symbol::intern(new_name.unwrap_or(name)),
1182                     kind: if let Some(k) = kind { k } else { cstore::NativeUnknown },
1183                     cfg: None,
1184                     foreign_items: Vec::new(),
1185                 };
1186                 register_native_lib(self.sess, self.cstore, None, lib);
1187             }
1188         }
1189         self.register_statically_included_foreign_items();
1190         self.register_dllimport_foreign_items();
1191     }
1192
1193     fn process_item(&mut self, item: &ast::Item, definitions: &Definitions) {
1194         match item.node {
1195             ast::ItemKind::ForeignMod(ref fm) => {
1196                 self.process_foreign_mod(item, fm, definitions)
1197             },
1198             ast::ItemKind::ExternCrate(_) => {
1199                 let info = self.extract_crate_info(item).unwrap();
1200                 let (cnum, ..) = self.resolve_crate(
1201                     &None, info.ident, info.name, None, item.span, PathKind::Crate, info.dep_kind,
1202                 );
1203
1204                 let def_id = definitions.opt_local_def_id(item.id).unwrap();
1205                 let len = definitions.def_path(def_id.index).data.len();
1206
1207                 let extern_crate =
1208                     ExternCrate { def_id: def_id, span: item.span, direct: true, path_len: len };
1209                 self.update_extern_crate(cnum, extern_crate, &mut FxHashSet());
1210                 self.cstore.add_extern_mod_stmt_cnum(info.id, cnum);
1211             }
1212             _ => {}
1213         }
1214     }
1215 }