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