]> git.lizzy.rs Git - rust.git/blob - src/librustc_metadata/creader.rs
Auto merge of #41515 - eddyb:non-static-assoc-const, 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;
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.decode(&metadata).collect();
315
316         let mut cmeta = cstore::CrateMetadata {
317             name: name,
318             extern_crate: Cell::new(None),
319             def_path_table: def_path_table,
320             exported_symbols: exported_symbols,
321             proc_macros: crate_root.macro_derive_registrar.map(|_| {
322                 self.load_derive_macros(&crate_root, dylib.clone().map(|p| p.0), span)
323             }),
324             root: crate_root,
325             blob: metadata,
326             cnum_map: RefCell::new(cnum_map),
327             cnum: cnum,
328             codemap_import_info: RefCell::new(vec![]),
329             attribute_cache: RefCell::new([Vec::new(), Vec::new()]),
330             dep_kind: Cell::new(dep_kind),
331             source: cstore::CrateSource {
332                 dylib: dylib,
333                 rlib: rlib,
334                 rmeta: rmeta,
335             },
336             dllimport_foreign_items: FxHashSet(),
337         };
338
339         let dllimports: Vec<_> = cmeta.get_native_libraries().iter()
340                             .filter(|lib| relevant_lib(self.sess, lib) &&
341                                           lib.kind == cstore::NativeLibraryKind::NativeUnknown)
342                             .flat_map(|lib| &lib.foreign_items)
343                             .map(|id| *id)
344                             .collect();
345         cmeta.dllimport_foreign_items.extend(dllimports);
346
347         let cmeta = Rc::new(cmeta);
348         self.cstore.set_crate_data(cnum, cmeta.clone());
349         (cnum, cmeta)
350     }
351
352     fn resolve_crate(&mut self,
353                      root: &Option<CratePaths>,
354                      ident: Symbol,
355                      name: Symbol,
356                      hash: Option<&Svh>,
357                      span: Span,
358                      path_kind: PathKind,
359                      mut dep_kind: DepKind)
360                      -> (CrateNum, Rc<cstore::CrateMetadata>) {
361         info!("resolving crate `extern crate {} as {}`", name, ident);
362         let result = if let Some(cnum) = self.existing_match(name, hash, path_kind) {
363             LoadResult::Previous(cnum)
364         } else {
365             info!("falling back to a load");
366             let mut locate_ctxt = locator::Context {
367                 sess: self.sess,
368                 span: span,
369                 ident: ident,
370                 crate_name: name,
371                 hash: hash.map(|a| &*a),
372                 filesearch: self.sess.target_filesearch(path_kind),
373                 target: &self.sess.target.target,
374                 triple: &self.sess.opts.target_triple,
375                 root: root,
376                 rejected_via_hash: vec![],
377                 rejected_via_triple: vec![],
378                 rejected_via_kind: vec![],
379                 rejected_via_version: vec![],
380                 rejected_via_filename: vec![],
381                 should_match_name: true,
382                 is_proc_macro: Some(false),
383             };
384
385             self.load(&mut locate_ctxt).or_else(|| {
386                 dep_kind = DepKind::UnexportedMacrosOnly;
387
388                 let mut proc_macro_locator = locator::Context {
389                     target: &self.sess.host,
390                     triple: config::host_triple(),
391                     filesearch: self.sess.host_filesearch(path_kind),
392                     rejected_via_hash: vec![],
393                     rejected_via_triple: vec![],
394                     rejected_via_kind: vec![],
395                     rejected_via_version: vec![],
396                     rejected_via_filename: vec![],
397                     is_proc_macro: Some(true),
398                     ..locate_ctxt
399                 };
400
401                 self.load(&mut proc_macro_locator)
402             }).unwrap_or_else(|| locate_ctxt.report_errs())
403         };
404
405         match result {
406             LoadResult::Previous(cnum) => {
407                 let data = self.cstore.get_crate_data(cnum);
408                 if data.root.macro_derive_registrar.is_some() {
409                     dep_kind = DepKind::UnexportedMacrosOnly;
410                 }
411                 data.dep_kind.set(cmp::max(data.dep_kind.get(), dep_kind));
412                 (cnum, data)
413             }
414             LoadResult::Loaded(library) => {
415                 self.register_crate(root, ident, name, span, library, dep_kind)
416             }
417         }
418     }
419
420     fn load(&mut self, locate_ctxt: &mut locator::Context) -> Option<LoadResult> {
421         let library = match locate_ctxt.maybe_load_library_crate() {
422             Some(lib) => lib,
423             None => return None,
424         };
425
426         // In the case that we're loading a crate, but not matching
427         // against a hash, we could load a crate which has the same hash
428         // as an already loaded crate. If this is the case prevent
429         // duplicates by just using the first crate.
430         //
431         // Note that we only do this for target triple crates, though, as we
432         // don't want to match a host crate against an equivalent target one
433         // already loaded.
434         let root = library.metadata.get_root();
435         if locate_ctxt.triple == self.sess.opts.target_triple {
436             let mut result = LoadResult::Loaded(library);
437             self.cstore.iter_crate_data(|cnum, data| {
438                 if data.name() == root.name && root.hash == data.hash() {
439                     assert!(locate_ctxt.hash.is_none());
440                     info!("load success, going to previous cnum: {}", cnum);
441                     result = LoadResult::Previous(cnum);
442                 }
443             });
444             Some(result)
445         } else {
446             Some(LoadResult::Loaded(library))
447         }
448     }
449
450     fn update_extern_crate(&mut self,
451                            cnum: CrateNum,
452                            mut extern_crate: ExternCrate,
453                            visited: &mut FxHashSet<(CrateNum, bool)>)
454     {
455         if !visited.insert((cnum, extern_crate.direct)) { return }
456
457         let cmeta = self.cstore.get_crate_data(cnum);
458         let old_extern_crate = cmeta.extern_crate.get();
459
460         // Prefer:
461         // - something over nothing (tuple.0);
462         // - direct extern crate to indirect (tuple.1);
463         // - shorter paths to longer (tuple.2).
464         let new_rank = (true, extern_crate.direct, !extern_crate.path_len);
465         let old_rank = match old_extern_crate {
466             None => (false, false, !0),
467             Some(ref c) => (true, c.direct, !c.path_len),
468         };
469
470         if old_rank >= new_rank {
471             return; // no change needed
472         }
473
474         cmeta.extern_crate.set(Some(extern_crate));
475         // Propagate the extern crate info to dependencies.
476         extern_crate.direct = false;
477         for &dep_cnum in cmeta.cnum_map.borrow().iter() {
478             self.update_extern_crate(dep_cnum, extern_crate, visited);
479         }
480     }
481
482     // Go through the crate metadata and load any crates that it references
483     fn resolve_crate_deps(&mut self,
484                           root: &Option<CratePaths>,
485                           crate_root: &CrateRoot,
486                           metadata: &MetadataBlob,
487                           krate: CrateNum,
488                           span: Span,
489                           dep_kind: DepKind)
490                           -> cstore::CrateNumMap {
491         debug!("resolving deps of external crate");
492         if crate_root.macro_derive_registrar.is_some() {
493             return cstore::CrateNumMap::new();
494         }
495
496         // The map from crate numbers in the crate we're resolving to local crate numbers.
497         // We map 0 and all other holes in the map to our parent crate. The "additional"
498         // self-dependencies should be harmless.
499         ::std::iter::once(krate).chain(crate_root.crate_deps.decode(metadata).map(|dep| {
500             debug!("resolving dep crate {} hash: `{}`", dep.name, dep.hash);
501             if dep.kind == DepKind::UnexportedMacrosOnly {
502                 return krate;
503             }
504             let dep_kind = match dep_kind {
505                 DepKind::MacrosOnly => DepKind::MacrosOnly,
506                 _ => dep.kind,
507             };
508             let (local_cnum, ..) = self.resolve_crate(
509                 root, dep.name, dep.name, Some(&dep.hash), span, PathKind::Dependency, dep_kind,
510             );
511             local_cnum
512         })).collect()
513     }
514
515     fn read_extension_crate(&mut self, span: Span, info: &ExternCrateInfo) -> ExtensionCrate {
516         info!("read extension crate {} `extern crate {} as {}` dep_kind={:?}",
517               info.id, info.name, info.ident, info.dep_kind);
518         let target_triple = &self.sess.opts.target_triple[..];
519         let is_cross = target_triple != config::host_triple();
520         let mut target_only = false;
521         let mut locate_ctxt = locator::Context {
522             sess: self.sess,
523             span: span,
524             ident: info.ident,
525             crate_name: info.name,
526             hash: None,
527             filesearch: self.sess.host_filesearch(PathKind::Crate),
528             target: &self.sess.host,
529             triple: config::host_triple(),
530             root: &None,
531             rejected_via_hash: vec![],
532             rejected_via_triple: vec![],
533             rejected_via_kind: vec![],
534             rejected_via_version: vec![],
535             rejected_via_filename: vec![],
536             should_match_name: true,
537             is_proc_macro: None,
538         };
539         let library = self.load(&mut locate_ctxt).or_else(|| {
540             if !is_cross {
541                 return None
542             }
543             // Try loading from target crates. This will abort later if we
544             // try to load a plugin registrar function,
545             target_only = true;
546
547             locate_ctxt.target = &self.sess.target.target;
548             locate_ctxt.triple = target_triple;
549             locate_ctxt.filesearch = self.sess.target_filesearch(PathKind::Crate);
550
551             self.load(&mut locate_ctxt)
552         });
553         let library = match library {
554             Some(l) => l,
555             None => locate_ctxt.report_errs(),
556         };
557
558         let (dylib, metadata) = match library {
559             LoadResult::Previous(cnum) => {
560                 let data = self.cstore.get_crate_data(cnum);
561                 (data.source.dylib.clone(), PMDSource::Registered(data))
562             }
563             LoadResult::Loaded(library) => {
564                 let dylib = library.dylib.clone();
565                 let metadata = PMDSource::Owned(library);
566                 (dylib, metadata)
567             }
568         };
569
570         ExtensionCrate {
571             metadata: metadata,
572             dylib: dylib.map(|p| p.0),
573             target_only: target_only,
574         }
575     }
576
577     /// Load custom derive macros.
578     ///
579     /// Note that this is intentionally similar to how we load plugins today,
580     /// but also intentionally separate. Plugins are likely always going to be
581     /// implemented as dynamic libraries, but we have a possible future where
582     /// custom derive (and other macro-1.1 style features) are implemented via
583     /// executables and custom IPC.
584     fn load_derive_macros(&mut self, root: &CrateRoot, dylib: Option<PathBuf>, span: Span)
585                           -> Vec<(ast::Name, Rc<SyntaxExtension>)> {
586         use std::{env, mem};
587         use proc_macro::TokenStream;
588         use proc_macro::__internal::Registry;
589         use rustc_back::dynamic_lib::DynamicLibrary;
590         use syntax_ext::deriving::custom::ProcMacroDerive;
591         use syntax_ext::proc_macro_impl::{AttrProcMacro, BangProcMacro};
592
593         let path = match dylib {
594             Some(dylib) => dylib,
595             None => span_bug!(span, "proc-macro crate not dylib"),
596         };
597         // Make sure the path contains a / or the linker will search for it.
598         let path = env::current_dir().unwrap().join(path);
599         let lib = match DynamicLibrary::open(Some(&path)) {
600             Ok(lib) => lib,
601             Err(err) => self.sess.span_fatal(span, &err),
602         };
603
604         let sym = self.sess.generate_derive_registrar_symbol(root.disambiguator,
605                                                              root.macro_derive_registrar.unwrap());
606         let registrar = unsafe {
607             let sym = match lib.symbol(&sym) {
608                 Ok(f) => f,
609                 Err(err) => self.sess.span_fatal(span, &err),
610             };
611             mem::transmute::<*mut u8, fn(&mut Registry)>(sym)
612         };
613
614         struct MyRegistrar(Vec<(ast::Name, Rc<SyntaxExtension>)>);
615
616         impl Registry for MyRegistrar {
617             fn register_custom_derive(&mut self,
618                                       trait_name: &str,
619                                       expand: fn(TokenStream) -> TokenStream,
620                                       attributes: &[&'static str]) {
621                 let attrs = attributes.iter().cloned().map(Symbol::intern).collect::<Vec<_>>();
622                 let derive = ProcMacroDerive::new(expand, attrs.clone());
623                 let derive = SyntaxExtension::ProcMacroDerive(Box::new(derive), attrs);
624                 self.0.push((Symbol::intern(trait_name), Rc::new(derive)));
625             }
626
627             fn register_attr_proc_macro(&mut self,
628                                         name: &str,
629                                         expand: fn(TokenStream, TokenStream) -> TokenStream) {
630                 let expand = SyntaxExtension::AttrProcMacro(
631                     Box::new(AttrProcMacro { inner: expand })
632                 );
633                 self.0.push((Symbol::intern(name), Rc::new(expand)));
634             }
635
636             fn register_bang_proc_macro(&mut self,
637                                         name: &str,
638                                         expand: fn(TokenStream) -> TokenStream) {
639                 let expand = SyntaxExtension::ProcMacro(
640                     Box::new(BangProcMacro { inner: expand })
641                 );
642                 self.0.push((Symbol::intern(name), Rc::new(expand)));
643             }
644         }
645
646         let mut my_registrar = MyRegistrar(Vec::new());
647         registrar(&mut my_registrar);
648
649         // Intentionally leak the dynamic library. We can't ever unload it
650         // since the library can make things that will live arbitrarily long.
651         mem::forget(lib);
652         my_registrar.0
653     }
654
655     /// Look for a plugin registrar. Returns library path, crate
656     /// SVH and DefIndex of the registrar function.
657     pub fn find_plugin_registrar(&mut self, span: Span, name: &str)
658                                  -> Option<(PathBuf, Symbol, DefIndex)> {
659         let ekrate = self.read_extension_crate(span, &ExternCrateInfo {
660              name: Symbol::intern(name),
661              ident: Symbol::intern(name),
662              id: ast::DUMMY_NODE_ID,
663              dep_kind: DepKind::UnexportedMacrosOnly,
664         });
665
666         if ekrate.target_only {
667             // Need to abort before syntax expansion.
668             let message = format!("plugin `{}` is not available for triple `{}` \
669                                    (only found {})",
670                                   name,
671                                   config::host_triple(),
672                                   self.sess.opts.target_triple);
673             span_fatal!(self.sess, span, E0456, "{}", &message);
674         }
675
676         let root = ekrate.metadata.get_root();
677         match (ekrate.dylib.as_ref(), root.plugin_registrar_fn) {
678             (Some(dylib), Some(reg)) => {
679                 Some((dylib.to_path_buf(), root.disambiguator, reg))
680             }
681             (None, Some(_)) => {
682                 span_err!(self.sess, span, E0457,
683                           "plugin `{}` only found in rlib format, but must be available \
684                            in dylib format",
685                           name);
686                 // No need to abort because the loading code will just ignore this
687                 // empty dylib.
688                 None
689             }
690             _ => None,
691         }
692     }
693
694     fn get_foreign_items_of_kind(&self, kind: cstore::NativeLibraryKind) -> Vec<DefIndex> {
695         let mut items = vec![];
696         let libs = self.cstore.get_used_libraries();
697         for lib in libs.borrow().iter() {
698             if relevant_lib(self.sess, lib) && lib.kind == kind {
699                 items.extend(&lib.foreign_items);
700             }
701         }
702         items
703     }
704
705     fn register_statically_included_foreign_items(&mut self) {
706         for id in self.get_foreign_items_of_kind(cstore::NativeStatic) {
707             self.cstore.add_statically_included_foreign_item(id);
708         }
709         for id in self.get_foreign_items_of_kind(cstore::NativeStaticNobundle) {
710             self.cstore.add_statically_included_foreign_item(id);
711         }
712     }
713
714     fn register_dllimport_foreign_items(&mut self) {
715         let mut dllimports = self.cstore.dllimport_foreign_items.borrow_mut();
716         for id in self.get_foreign_items_of_kind(cstore::NativeUnknown) {
717             dllimports.insert(id);
718         }
719     }
720
721     fn inject_panic_runtime(&mut self, krate: &ast::Crate) {
722         // If we're only compiling an rlib, then there's no need to select a
723         // panic runtime, so we just skip this section entirely.
724         let any_non_rlib = self.sess.crate_types.borrow().iter().any(|ct| {
725             *ct != config::CrateTypeRlib
726         });
727         if !any_non_rlib {
728             info!("panic runtime injection skipped, only generating rlib");
729             return
730         }
731
732         // If we need a panic runtime, we try to find an existing one here. At
733         // the same time we perform some general validation of the DAG we've got
734         // going such as ensuring everything has a compatible panic strategy.
735         //
736         // The logic for finding the panic runtime here is pretty much the same
737         // as the allocator case with the only addition that the panic strategy
738         // compilation mode also comes into play.
739         let desired_strategy = self.sess.panic_strategy();
740         let mut runtime_found = false;
741         let mut needs_panic_runtime = attr::contains_name(&krate.attrs,
742                                                           "needs_panic_runtime");
743         self.cstore.iter_crate_data(|cnum, data| {
744             needs_panic_runtime = needs_panic_runtime || data.needs_panic_runtime();
745             if data.is_panic_runtime() {
746                 // Inject a dependency from all #![needs_panic_runtime] to this
747                 // #![panic_runtime] crate.
748                 self.inject_dependency_if(cnum, "a panic runtime",
749                                           &|data| data.needs_panic_runtime());
750                 runtime_found = runtime_found || data.dep_kind.get() == DepKind::Explicit;
751             }
752         });
753
754         // If an explicitly linked and matching panic runtime was found, or if
755         // we just don't need one at all, then we're done here and there's
756         // nothing else to do.
757         if !needs_panic_runtime || runtime_found {
758             return
759         }
760
761         // By this point we know that we (a) need a panic runtime and (b) no
762         // panic runtime was explicitly linked. Here we just load an appropriate
763         // default runtime for our panic strategy and then inject the
764         // dependencies.
765         //
766         // We may resolve to an already loaded crate (as the crate may not have
767         // been explicitly linked prior to this) and we may re-inject
768         // dependencies again, but both of those situations are fine.
769         //
770         // Also note that we have yet to perform validation of the crate graph
771         // in terms of everyone has a compatible panic runtime format, that's
772         // performed later as part of the `dependency_format` module.
773         let name = match desired_strategy {
774             PanicStrategy::Unwind => Symbol::intern("panic_unwind"),
775             PanicStrategy::Abort => Symbol::intern("panic_abort"),
776         };
777         info!("panic runtime not found -- loading {}", name);
778
779         let dep_kind = DepKind::Implicit;
780         let (cnum, data) =
781             self.resolve_crate(&None, name, name, None, DUMMY_SP, PathKind::Crate, dep_kind);
782
783         // Sanity check the loaded crate to ensure it is indeed a panic runtime
784         // and the panic strategy is indeed what we thought it was.
785         if !data.is_panic_runtime() {
786             self.sess.err(&format!("the crate `{}` is not a panic runtime",
787                                    name));
788         }
789         if data.panic_strategy() != desired_strategy {
790             self.sess.err(&format!("the crate `{}` does not have the panic \
791                                     strategy `{}`",
792                                    name, desired_strategy.desc()));
793         }
794
795         self.sess.injected_panic_runtime.set(Some(cnum));
796         self.inject_dependency_if(cnum, "a panic runtime",
797                                   &|data| data.needs_panic_runtime());
798     }
799
800     fn inject_sanitizer_runtime(&mut self) {
801         if let Some(ref sanitizer) = self.sess.opts.debugging_opts.sanitizer {
802             // Sanitizers can only be used on some tested platforms with
803             // executables linked to `std`
804             const ASAN_SUPPORTED_TARGETS: &[&str] = &["x86_64-unknown-linux-gnu",
805                                                       "x86_64-apple-darwin"];
806             const TSAN_SUPPORTED_TARGETS: &[&str] = &["x86_64-unknown-linux-gnu",
807                                                       "x86_64-apple-darwin"];
808             const LSAN_SUPPORTED_TARGETS: &[&str] = &["x86_64-unknown-linux-gnu"];
809             const MSAN_SUPPORTED_TARGETS: &[&str] = &["x86_64-unknown-linux-gnu"];
810
811             let supported_targets = match *sanitizer {
812                 Sanitizer::Address => ASAN_SUPPORTED_TARGETS,
813                 Sanitizer::Thread => TSAN_SUPPORTED_TARGETS,
814                 Sanitizer::Leak => LSAN_SUPPORTED_TARGETS,
815                 Sanitizer::Memory => MSAN_SUPPORTED_TARGETS,
816             };
817             if !supported_targets.contains(&&*self.sess.target.target.llvm_target) {
818                 self.sess.err(&format!("{:?}Sanitizer only works with the `{}` target",
819                     sanitizer,
820                     supported_targets.join("` or `")
821                 ));
822                 return
823             }
824
825             if !self.sess.crate_types.borrow().iter().all(|ct| {
826                 match *ct {
827                     // Link the runtime
828                     config::CrateTypeExecutable => true,
829                     // This crate will be compiled with the required
830                     // instrumentation pass
831                     config::CrateTypeRlib => false,
832                     _ => {
833                         self.sess.err(&format!("Only executables and rlibs can be \
834                                                 compiled with `-Z sanitizer`"));
835                         false
836                     }
837                 }
838             }) {
839                 return
840             }
841
842             let mut uses_std = false;
843             self.cstore.iter_crate_data(|_, data| {
844                 if data.name == "std" {
845                     uses_std = true;
846                 }
847             });
848
849             if uses_std {
850                 let name = match *sanitizer {
851                     Sanitizer::Address => "rustc_asan",
852                     Sanitizer::Leak => "rustc_lsan",
853                     Sanitizer::Memory => "rustc_msan",
854                     Sanitizer::Thread => "rustc_tsan",
855                 };
856                 info!("loading sanitizer: {}", name);
857
858                 let symbol = Symbol::intern(name);
859                 let dep_kind = DepKind::Implicit;
860                 let (_, data) =
861                     self.resolve_crate(&None, symbol, symbol, None, DUMMY_SP,
862                                        PathKind::Crate, dep_kind);
863
864                 // Sanity check the loaded crate to ensure it is indeed a sanitizer runtime
865                 if !data.is_sanitizer_runtime() {
866                     self.sess.err(&format!("the crate `{}` is not a sanitizer runtime",
867                                            name));
868                 }
869             }
870         }
871     }
872
873     fn inject_allocator_crate(&mut self) {
874         // Make sure that we actually need an allocator, if none of our
875         // dependencies need one then we definitely don't!
876         //
877         // Also, if one of our dependencies has an explicit allocator, then we
878         // also bail out as we don't need to implicitly inject one.
879         let mut needs_allocator = false;
880         let mut found_required_allocator = false;
881         self.cstore.iter_crate_data(|cnum, data| {
882             needs_allocator = needs_allocator || data.needs_allocator();
883             if data.is_allocator() {
884                 info!("{} required by rlib and is an allocator", data.name());
885                 self.inject_dependency_if(cnum, "an allocator",
886                                           &|data| data.needs_allocator());
887                 found_required_allocator = found_required_allocator ||
888                     data.dep_kind.get() == DepKind::Explicit;
889             }
890         });
891         if !needs_allocator || found_required_allocator { return }
892
893         // At this point we've determined that we need an allocator and no
894         // previous allocator has been activated. We look through our outputs of
895         // crate types to see what kind of allocator types we may need.
896         //
897         // The main special output type here is that rlibs do **not** need an
898         // allocator linked in (they're just object files), only final products
899         // (exes, dylibs, staticlibs) need allocators.
900         let mut need_lib_alloc = false;
901         let mut need_exe_alloc = false;
902         for ct in self.sess.crate_types.borrow().iter() {
903             match *ct {
904                 config::CrateTypeExecutable => need_exe_alloc = true,
905                 config::CrateTypeDylib |
906                 config::CrateTypeProcMacro |
907                 config::CrateTypeCdylib |
908                 config::CrateTypeStaticlib => need_lib_alloc = true,
909                 config::CrateTypeRlib => {}
910             }
911         }
912         if !need_lib_alloc && !need_exe_alloc { return }
913
914         // The default allocator crate comes from the custom target spec, and we
915         // choose between the standard library allocator or exe allocator. This
916         // distinction exists because the default allocator for binaries (where
917         // the world is Rust) is different than library (where the world is
918         // likely *not* Rust).
919         //
920         // If a library is being produced, but we're also flagged with `-C
921         // prefer-dynamic`, then we interpret this as a *Rust* dynamic library
922         // is being produced so we use the exe allocator instead.
923         //
924         // What this boils down to is:
925         //
926         // * Binaries use jemalloc
927         // * Staticlibs and Rust dylibs use system malloc
928         // * Rust dylibs used as dependencies to rust use jemalloc
929         let name = if need_lib_alloc && !self.sess.opts.cg.prefer_dynamic {
930             Symbol::intern(&self.sess.target.target.options.lib_allocation_crate)
931         } else {
932             Symbol::intern(&self.sess.target.target.options.exe_allocation_crate)
933         };
934         let dep_kind = DepKind::Implicit;
935         let (cnum, data) =
936             self.resolve_crate(&None, name, name, None, DUMMY_SP, PathKind::Crate, dep_kind);
937
938         // Sanity check the crate we loaded to ensure that it is indeed an
939         // allocator.
940         if !data.is_allocator() {
941             self.sess.err(&format!("the allocator crate `{}` is not tagged \
942                                     with #![allocator]", data.name()));
943         }
944
945         self.sess.injected_allocator.set(Some(cnum));
946         self.inject_dependency_if(cnum, "an allocator",
947                                   &|data| data.needs_allocator());
948     }
949
950     fn inject_dependency_if(&self,
951                             krate: CrateNum,
952                             what: &str,
953                             needs_dep: &Fn(&cstore::CrateMetadata) -> bool) {
954         // don't perform this validation if the session has errors, as one of
955         // those errors may indicate a circular dependency which could cause
956         // this to stack overflow.
957         if self.sess.has_errors() {
958             return
959         }
960
961         // Before we inject any dependencies, make sure we don't inject a
962         // circular dependency by validating that this crate doesn't
963         // transitively depend on any crates satisfying `needs_dep`.
964         for dep in self.cstore.crate_dependencies_in_rpo(krate) {
965             let data = self.cstore.get_crate_data(dep);
966             if needs_dep(&data) {
967                 self.sess.err(&format!("the crate `{}` cannot depend \
968                                         on a crate that needs {}, but \
969                                         it depends on `{}`",
970                                        self.cstore.get_crate_data(krate).name(),
971                                        what,
972                                        data.name()));
973             }
974         }
975
976         // All crates satisfying `needs_dep` do not explicitly depend on the
977         // crate provided for this compile, but in order for this compilation to
978         // be successfully linked we need to inject a dependency (to order the
979         // crates on the command line correctly).
980         self.cstore.iter_crate_data(|cnum, data| {
981             if !needs_dep(data) {
982                 return
983             }
984
985             info!("injecting a dep from {} to {}", cnum, krate);
986             data.cnum_map.borrow_mut().push(krate);
987         });
988     }
989 }
990
991 impl<'a> CrateLoader<'a> {
992     pub fn preprocess(&mut self, krate: &ast::Crate) {
993         for attr in &krate.attrs {
994             if attr.path == "link_args" {
995                 if let Some(linkarg) = attr.value_str() {
996                     self.cstore.add_used_link_args(&linkarg.as_str());
997                 }
998             }
999         }
1000     }
1001
1002     fn process_foreign_mod(&mut self, i: &ast::Item, fm: &ast::ForeignMod,
1003                            definitions: &Definitions) {
1004         if fm.abi == Abi::Rust || fm.abi == Abi::RustIntrinsic || fm.abi == Abi::PlatformIntrinsic {
1005             return;
1006         }
1007
1008         // First, add all of the custom #[link_args] attributes
1009         for m in i.attrs.iter().filter(|a| a.check_name("link_args")) {
1010             if let Some(linkarg) = m.value_str() {
1011                 self.cstore.add_used_link_args(&linkarg.as_str());
1012             }
1013         }
1014
1015         // Next, process all of the #[link(..)]-style arguments
1016         for m in i.attrs.iter().filter(|a| a.check_name("link")) {
1017             let items = match m.meta_item_list() {
1018                 Some(item) => item,
1019                 None => continue,
1020             };
1021             let kind = items.iter().find(|k| {
1022                 k.check_name("kind")
1023             }).and_then(|a| a.value_str()).map(Symbol::as_str);
1024             let kind = match kind.as_ref().map(|s| &s[..]) {
1025                 Some("static") => cstore::NativeStatic,
1026                 Some("static-nobundle") => cstore::NativeStaticNobundle,
1027                 Some("dylib") => cstore::NativeUnknown,
1028                 Some("framework") => cstore::NativeFramework,
1029                 Some(k) => {
1030                     struct_span_err!(self.sess, m.span, E0458,
1031                               "unknown kind: `{}`", k)
1032                         .span_label(m.span, "unknown kind").emit();
1033                     cstore::NativeUnknown
1034                 }
1035                 None => cstore::NativeUnknown
1036             };
1037             let n = items.iter().find(|n| {
1038                 n.check_name("name")
1039             }).and_then(|a| a.value_str());
1040             let n = match n {
1041                 Some(n) => n,
1042                 None => {
1043                     struct_span_err!(self.sess, m.span, E0459,
1044                                      "#[link(...)] specified without `name = \"foo\"`")
1045                         .span_label(m.span, "missing `name` argument").emit();
1046                     Symbol::intern("foo")
1047                 }
1048             };
1049             let cfg = items.iter().find(|k| {
1050                 k.check_name("cfg")
1051             }).and_then(|a| a.meta_item_list());
1052             let cfg = cfg.map(|list| {
1053                 list[0].meta_item().unwrap().clone()
1054             });
1055             let foreign_items = fm.items.iter()
1056                 .map(|it| definitions.opt_def_index(it.id).unwrap())
1057                 .collect();
1058             let lib = NativeLibrary {
1059                 name: n,
1060                 kind: kind,
1061                 cfg: cfg,
1062                 foreign_items: foreign_items,
1063             };
1064             register_native_lib(self.sess, self.cstore, Some(m.span), lib);
1065         }
1066     }
1067 }
1068
1069 impl<'a> middle::cstore::CrateLoader for CrateLoader<'a> {
1070     fn postprocess(&mut self, krate: &ast::Crate) {
1071         // inject the sanitizer runtime before the allocator runtime because all
1072         // sanitizers force the use of the `alloc_system` allocator
1073         self.inject_sanitizer_runtime();
1074         self.inject_allocator_crate();
1075         self.inject_panic_runtime(krate);
1076
1077         if log_enabled!(log::LogLevel::Info) {
1078             dump_crates(&self.cstore);
1079         }
1080
1081         // Process libs passed on the command line
1082         // First, check for errors
1083         let mut renames = FxHashSet();
1084         for &(ref name, ref new_name, _) in &self.sess.opts.libs {
1085             if let &Some(ref new_name) = new_name {
1086                 if new_name.is_empty() {
1087                     self.sess.err(
1088                         &format!("an empty renaming target was specified for library `{}`",name));
1089                 } else if !self.cstore.get_used_libraries().borrow().iter()
1090                                                            .any(|lib| lib.name == name as &str) {
1091                     self.sess.err(&format!("renaming of the library `{}` was specified, \
1092                                             however this crate contains no #[link(...)] \
1093                                             attributes referencing this library.", name));
1094                 } else if renames.contains(name) {
1095                     self.sess.err(&format!("multiple renamings were specified for library `{}` .",
1096                                             name));
1097                 } else {
1098                     renames.insert(name);
1099                 }
1100             }
1101         }
1102         // Update kind and, optionally, the name of all native libaries
1103         // (there may be more than one) with the specified name.
1104         for &(ref name, ref new_name, kind) in &self.sess.opts.libs {
1105             let mut found = false;
1106             for lib in self.cstore.get_used_libraries().borrow_mut().iter_mut() {
1107                 if lib.name == name as &str {
1108                     let mut changed = false;
1109                     if let Some(k) = kind {
1110                         lib.kind = k;
1111                         changed = true;
1112                     }
1113                     if let &Some(ref new_name) = new_name {
1114                         lib.name = Symbol::intern(new_name);
1115                         changed = true;
1116                     }
1117                     if !changed {
1118                         self.sess.warn(&format!("redundant linker flag specified for library `{}`",
1119                                                 name));
1120                     }
1121
1122                     found = true;
1123                 }
1124             }
1125             if !found {
1126                 // Add if not found
1127                 let new_name = new_name.as_ref().map(|s| &**s); // &Option<String> -> Option<&str>
1128                 let lib = NativeLibrary {
1129                     name: Symbol::intern(new_name.unwrap_or(name)),
1130                     kind: if let Some(k) = kind { k } else { cstore::NativeUnknown },
1131                     cfg: None,
1132                     foreign_items: Vec::new(),
1133                 };
1134                 register_native_lib(self.sess, self.cstore, None, lib);
1135             }
1136         }
1137         self.register_statically_included_foreign_items();
1138         self.register_dllimport_foreign_items();
1139     }
1140
1141     fn process_item(&mut self, item: &ast::Item, definitions: &Definitions) {
1142         match item.node {
1143             ast::ItemKind::ForeignMod(ref fm) => {
1144                 self.process_foreign_mod(item, fm, definitions)
1145             },
1146             ast::ItemKind::ExternCrate(_) => {
1147                 let info = self.extract_crate_info(item).unwrap();
1148                 let (cnum, ..) = self.resolve_crate(
1149                     &None, info.ident, info.name, None, item.span, PathKind::Crate, info.dep_kind,
1150                 );
1151
1152                 let def_id = definitions.opt_local_def_id(item.id).unwrap();
1153                 let len = definitions.def_path(def_id.index).data.len();
1154
1155                 let extern_crate =
1156                     ExternCrate { def_id: def_id, span: item.span, direct: true, path_len: len };
1157                 self.update_extern_crate(cnum, extern_crate, &mut FxHashSet());
1158                 self.cstore.add_extern_mod_stmt_cnum(info.id, cnum);
1159             }
1160             _ => {}
1161         }
1162     }
1163 }