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