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.
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.
11 #![allow(non_camel_case_types)]
13 //! Validates all used crates and extern libraries and loads their metadata
16 use session::{config, Session};
17 use session::search_paths::PathKind;
19 use metadata::cstore::{CStore, CrateSource, MetadataBlob};
20 use metadata::decoder;
22 use metadata::loader::CratePaths;
28 use syntax::attr::AttrMetaMethods;
29 use syntax::codemap::{Span, mk_sp};
31 use syntax::parse::token::InternedString;
32 use syntax::parse::token;
37 pub struct CrateReader<'a> {
39 next_crate_num: ast::CrateNum,
42 impl<'a, 'v> visit::Visitor<'v> for CrateReader<'a> {
43 fn visit_item(&mut self, a: &ast::Item) {
45 visit::walk_item(self, a);
49 fn dump_crates(cstore: &CStore) {
50 debug!("resolved crates:");
51 cstore.iter_crate_data_origins(|_, data, opt_source| {
52 debug!(" name: {}", data.name());
53 debug!(" cnum: {}", data.cnum);
54 debug!(" hash: {}", data.hash());
56 let CrateSource { dylib, rlib, cnum: _ } = cs;
57 dylib.map(|dl| debug!(" dylib: {}", dl.0.display()));
58 rlib.map(|rl| debug!(" rlib: {}", rl.0.display()));
63 fn should_link(i: &ast::Item) -> bool {
64 !attr::contains_name(&i.attrs[], "no_link")
74 pub fn validate_crate_name(sess: Option<&Session>, s: &str, sp: Option<Span>) {
77 (_, None) => panic!("{}", s),
78 (Some(sp), Some(sess)) => sess.span_err(sp, s),
79 (None, Some(sess)) => sess.err(s),
83 err("crate name must not be empty");
86 if c.is_alphanumeric() { continue }
87 if c == '_' || c == '-' { continue }
88 err(&format!("invalid character `{}` in crate name: `{}`", c, s)[]);
91 Some(sess) => sess.abort_if_errors(),
97 fn register_native_lib(sess: &Session,
100 kind: cstore::NativeLibraryKind) {
104 sess.span_err(span, "#[link(name = \"\")] given with \
108 sess.err("empty library name given via `-l`");
113 let is_osx = sess.target.target.options.is_like_osx;
114 if kind == cstore::NativeFramework && !is_osx {
115 let msg = "native frameworks are only available on OSX targets";
117 Some(span) => sess.span_err(span, msg),
118 None => sess.err(msg),
121 sess.cstore.add_used_library(name, kind);
124 // Extra info about a crate loaded for plugins or exported macros.
125 struct ExtensionCrate {
132 Registered(Rc<cstore::crate_metadata>),
137 pub fn as_slice<'a>(&'a self) -> &'a [u8] {
139 PMDSource::Registered(ref cmd) => cmd.data(),
140 PMDSource::Owned(ref mdb) => mdb.as_slice(),
145 impl<'a> CrateReader<'a> {
146 pub fn new(sess: &'a Session) -> CrateReader<'a> {
149 next_crate_num: sess.cstore.next_crate_num(),
153 // Traverses an AST, reading all the information about use'd crates and extern
154 // libraries necessary for later resolving, typechecking, linking, etc.
155 pub fn read_crates(&mut self, krate: &ast::Crate) {
156 self.process_crate(krate);
157 visit::walk_crate(self, krate);
159 if log_enabled!(log::DEBUG) {
160 dump_crates(&self.sess.cstore);
163 for &(ref name, kind) in &self.sess.opts.libs {
164 register_native_lib(self.sess, None, name.clone(), kind);
168 fn process_crate(&self, c: &ast::Crate) {
169 for a in c.attrs.iter().filter(|m| m.name() == "link_args") {
170 match a.value_str() {
171 Some(ref linkarg) => self.sess.cstore.add_used_link_args(&linkarg),
172 None => { /* fallthrough */ }
177 fn extract_crate_info(&self, i: &ast::Item) -> Option<CrateInfo> {
179 ast::ItemExternCrate(ref path_opt) => {
180 let ident = token::get_ident(i.ident);
181 debug!("resolving extern crate stmt. ident: {} path_opt: {:?}",
183 let name = match *path_opt {
184 Some((ref path_str, _)) => {
185 let name = path_str.to_string();
186 validate_crate_name(Some(self.sess), &name[..],
190 None => ident.to_string(),
193 ident: ident.to_string(),
196 should_link: should_link(i),
203 fn process_item(&mut self, i: &ast::Item) {
205 ast::ItemExternCrate(_) => {
210 match self.extract_crate_info(i) {
212 let (cnum, _, _) = self.resolve_crate(&None,
218 self.sess.cstore.add_extern_mod_stmt_cnum(info.id, cnum);
223 ast::ItemForeignMod(ref fm) => {
224 if fm.abi == abi::Rust || fm.abi == abi::RustIntrinsic {
228 // First, add all of the custom link_args attributes
229 let link_args = i.attrs.iter()
230 .filter_map(|at| if at.name() == "link_args" {
235 .collect::<Vec<&ast::Attribute>>();
236 for m in &link_args {
237 match m.value_str() {
238 Some(linkarg) => self.sess.cstore.add_used_link_args(&linkarg),
239 None => { /* fallthrough */ }
243 // Next, process all of the #[link(..)]-style arguments
244 let link_args = i.attrs.iter()
245 .filter_map(|at| if at.name() == "link" {
250 .collect::<Vec<&ast::Attribute>>();
251 for m in &link_args {
252 match m.meta_item_list() {
254 let kind = items.iter().find(|k| {
256 }).and_then(|a| a.value_str());
257 let kind = match kind {
261 } else if self.sess.target.target.options.is_like_osx
262 && k == "framework" {
263 cstore::NativeFramework
264 } else if k == "framework" {
265 cstore::NativeFramework
266 } else if k == "dylib" {
267 cstore::NativeUnknown
269 self.sess.span_err(m.span,
270 &format!("unknown kind: `{}`",
272 cstore::NativeUnknown
275 None => cstore::NativeUnknown
277 let n = items.iter().find(|n| {
279 }).and_then(|a| a.value_str());
283 self.sess.span_err(m.span,
284 "#[link(...)] specified without \
286 InternedString::new("foo")
289 register_native_lib(self.sess, Some(m.span),
290 n.to_string(), kind);
300 fn existing_match(&self, name: &str, hash: Option<&Svh>, kind: PathKind)
301 -> Option<ast::CrateNum> {
303 self.sess.cstore.iter_crate_data(|cnum, data| {
304 if data.name != name { return }
307 Some(hash) if *hash == data.hash() => { ret = Some(cnum); return }
312 // When the hash is None we're dealing with a top-level dependency
313 // in which case we may have a specification on the command line for
314 // this library. Even though an upstream library may have loaded
315 // something of the same name, we have to make sure it was loaded
316 // from the exact same location as well.
318 // We're also sure to compare *paths*, not actual byte slices. The
319 // `source` stores paths which are normalized which may be different
320 // from the strings on the command line.
321 let source = self.sess.cstore.get_used_crate_source(cnum).unwrap();
322 if let Some(locs) = self.sess.opts.externs.get(name) {
323 let found = locs.iter().any(|l| {
324 let l = fs::realpath(&Path::new(&l[..])).ok();
325 source.dylib.as_ref().map(|p| &p.0) == l.as_ref() ||
326 source.rlib.as_ref().map(|p| &p.0) == l.as_ref()
334 // Alright, so we've gotten this far which means that `data` has the
335 // right name, we don't have a hash, and we don't have a --extern
336 // pointing for ourselves. We're still not quite yet done because we
337 // have to make sure that this crate was found in the crate lookup
338 // path (this is a top-level dependency) as we don't want to
339 // implicitly load anything inside the dependency lookup path.
340 let prev_kind = source.dylib.as_ref().or(source.rlib.as_ref())
342 if ret.is_none() && (prev_kind == kind || prev_kind == PathKind::All) {
349 fn register_crate(&mut self,
350 root: &Option<CratePaths>,
354 lib: loader::Library)
355 -> (ast::CrateNum, Rc<cstore::crate_metadata>,
356 cstore::CrateSource) {
357 // Claim this crate number and cache it
358 let cnum = self.next_crate_num;
359 self.next_crate_num += 1;
361 // Stash paths for top-most crate locally if necessary.
362 let crate_paths = if root.is_none() {
364 ident: ident.to_string(),
365 dylib: lib.dylib.clone().map(|p| p.0),
366 rlib: lib.rlib.clone().map(|p| p.0),
371 // Maintain a reference to the top most crate.
372 let root = if root.is_some() { root } else { &crate_paths };
374 let cnum_map = self.resolve_crate_deps(root, lib.metadata.as_slice(), span);
376 let loader::Library{ dylib, rlib, metadata } = lib;
378 let cmeta = Rc::new( cstore::crate_metadata {
379 name: name.to_string(),
386 let source = cstore::CrateSource {
392 self.sess.cstore.set_crate_data(cnum, cmeta.clone());
393 self.sess.cstore.add_used_crate_source(source.clone());
394 (cnum, cmeta, source)
397 fn resolve_crate(&mut self,
398 root: &Option<CratePaths>,
404 -> (ast::CrateNum, Rc<cstore::crate_metadata>,
405 cstore::CrateSource) {
406 match self.existing_match(name, hash, kind) {
408 let mut load_ctxt = loader::Context {
413 hash: hash.map(|a| &*a),
414 filesearch: self.sess.target_filesearch(kind),
415 target: &self.sess.target.target,
416 triple: &self.sess.opts.target_triple[],
418 rejected_via_hash: vec!(),
419 rejected_via_triple: vec!(),
420 rejected_via_kind: vec!(),
421 should_match_name: true,
423 let library = load_ctxt.load_library_crate();
424 self.register_crate(root, ident, name, span, library)
427 self.sess.cstore.get_crate_data(cnum),
428 self.sess.cstore.get_used_crate_source(cnum).unwrap())
432 // Go through the crate metadata and load any crates that it references
433 fn resolve_crate_deps(&mut self,
434 root: &Option<CratePaths>,
435 cdata: &[u8], span : Span)
436 -> cstore::cnum_map {
437 debug!("resolving deps of external crate");
438 // The map from crate numbers in the crate we're resolving to local crate
440 decoder::get_crate_deps(cdata).iter().map(|dep| {
441 debug!("resolving dep crate {} hash: `{}`", dep.name, dep.hash);
442 let (local_cnum, _, _) = self.resolve_crate(root,
447 PathKind::Dependency);
448 (dep.cnum, local_cnum)
452 fn read_extension_crate(&mut self, span: Span, info: &CrateInfo) -> ExtensionCrate {
453 let target_triple = &self.sess.opts.target_triple[];
454 let is_cross = target_triple != config::host_triple();
455 let mut should_link = info.should_link && !is_cross;
456 let mut target_only = false;
457 let ident = info.ident.clone();
458 let name = info.name.clone();
459 let mut load_ctxt = loader::Context {
463 crate_name: &name[..],
465 filesearch: self.sess.host_filesearch(PathKind::Crate),
466 target: &self.sess.host,
467 triple: config::host_triple(),
469 rejected_via_hash: vec!(),
470 rejected_via_triple: vec!(),
471 rejected_via_kind: vec!(),
472 should_match_name: true,
474 let library = match load_ctxt.maybe_load_library_crate() {
476 None if is_cross => {
477 // Try loading from target crates. This will abort later if we
478 // try to load a plugin registrar function,
480 should_link = info.should_link;
482 load_ctxt.target = &self.sess.target.target;
483 load_ctxt.triple = target_triple;
484 load_ctxt.filesearch = self.sess.target_filesearch(PathKind::Crate);
485 load_ctxt.load_library_crate()
487 None => { load_ctxt.report_load_errs(); unreachable!() },
490 let dylib = library.dylib.clone();
491 let register = should_link && self.existing_match(info.name.as_slice(),
493 PathKind::Crate).is_none();
494 let metadata = if register {
495 // Register crate now to avoid double-reading metadata
496 let (_, cmd, _) = self.register_crate(&None, &info.ident[],
497 &info.name[], span, library);
498 PMDSource::Registered(cmd)
500 // Not registering the crate; just hold on to the metadata
501 PMDSource::Owned(library.metadata)
506 dylib: dylib.map(|p| p.0),
507 target_only: target_only,
511 /// Read exported macros.
512 pub fn read_exported_macros(&mut self, krate: &ast::Item) -> Vec<ast::MacroDef> {
513 let ci = self.extract_crate_info(krate).unwrap();
514 let ekrate = self.read_extension_crate(krate.span, &ci);
516 let source_name = format!("<{} macros>", krate.ident);
517 let mut macros = vec![];
518 decoder::each_exported_macro(ekrate.metadata.as_slice(),
519 &*self.sess.cstore.intr,
520 |name, attrs, body| {
521 // NB: Don't use parse::parse_tts_from_source_str because it parses with
523 let mut p = parse::new_parser_from_source_str(&self.sess.parse_sess,
524 self.sess.opts.cfg.clone(),
528 let body = p.parse_all_token_trees();
529 let span = mk_sp(lo, p.last_span.hi);
531 macros.push(ast::MacroDef {
534 id: ast::DUMMY_NODE_ID,
536 imported_from: Some(krate.ident),
537 // overridden in plugin/load.rs
549 /// Look for a plugin registrar. Returns library path and symbol name.
550 pub fn find_plugin_registrar(&mut self, span: Span, name: &str) -> Option<(Path, String)> {
551 let ekrate = self.read_extension_crate(span, &CrateInfo {
552 name: name.to_string(),
553 ident: name.to_string(),
554 id: ast::DUMMY_NODE_ID,
558 if ekrate.target_only {
559 // Need to abort before syntax expansion.
560 let message = format!("plugin `{}` is not available for triple `{}` \
563 config::host_triple(),
564 self.sess.opts.target_triple);
565 self.sess.span_err(span, &message[..]);
566 self.sess.abort_if_errors();
569 let registrar = decoder::get_plugin_registrar_fn(ekrate.metadata.as_slice())
570 .map(|id| decoder::get_symbol(ekrate.metadata.as_slice(), id));
572 match (ekrate.dylib.as_ref(), registrar) {
573 (Some(dylib), Some(reg)) => Some((dylib.clone(), reg)),
575 let message = format!("plugin `{}` only found in rlib format, \
576 but must be available in dylib format",
578 self.sess.span_err(span, &message[..]);
579 // No need to abort because the loading code will just ignore this