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