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;
24 use std::path::PathBuf;
31 use syntax::attr::AttrMetaMethods;
32 use syntax::codemap::{self, Span, mk_sp, Pos};
34 use syntax::parse::token::InternedString;
35 use syntax::parse::token;
39 pub struct CrateReader<'a> {
41 next_crate_num: ast::CrateNum,
44 impl<'a, 'v> visit::Visitor<'v> for CrateReader<'a> {
45 fn visit_item(&mut self, a: &ast::Item) {
47 visit::walk_item(self, a);
51 fn dump_crates(cstore: &CStore) {
52 debug!("resolved crates:");
53 cstore.iter_crate_data_origins(|_, data, opt_source| {
54 debug!(" name: {}", data.name());
55 debug!(" cnum: {}", data.cnum);
56 debug!(" hash: {}", data.hash());
58 let CrateSource { dylib, rlib, cnum: _ } = cs;
59 dylib.map(|dl| debug!(" dylib: {}", dl.0.display()));
60 rlib.map(|rl| debug!(" rlib: {}", rl.0.display()));
65 fn should_link(i: &ast::Item) -> bool {
66 !attr::contains_name(&i.attrs, "no_link")
76 pub fn validate_crate_name(sess: Option<&Session>, s: &str, sp: Option<Span>) {
79 (_, None) => panic!("{}", s),
80 (Some(sp), Some(sess)) => sess.span_err(sp, s),
81 (None, Some(sess)) => sess.err(s),
85 say("crate name must not be empty");
88 if c.is_alphanumeric() { continue }
89 if c == '_' { continue }
90 say(&format!("invalid character `{}` in crate name: `{}`", c, s));
93 Some(sess) => sess.abort_if_errors(),
99 fn register_native_lib(sess: &Session,
102 kind: cstore::NativeLibraryKind) {
106 sess.span_err(span, "#[link(name = \"\")] given with \
110 sess.err("empty library name given via `-l`");
115 let is_osx = sess.target.target.options.is_like_osx;
116 if kind == cstore::NativeFramework && !is_osx {
117 let msg = "native frameworks are only available on OSX targets";
119 Some(span) => sess.span_err(span, msg),
120 None => sess.err(msg),
123 sess.cstore.add_used_library(name, kind);
126 // Extra info about a crate loaded for plugins or exported macros.
127 struct ExtensionCrate {
129 dylib: Option<PathBuf>,
134 Registered(Rc<cstore::crate_metadata>),
139 pub fn as_slice<'a>(&'a self) -> &'a [u8] {
141 PMDSource::Registered(ref cmd) => cmd.data(),
142 PMDSource::Owned(ref mdb) => mdb.as_slice(),
147 impl<'a> CrateReader<'a> {
148 pub fn new(sess: &'a Session) -> CrateReader<'a> {
151 next_crate_num: sess.cstore.next_crate_num(),
155 // Traverses an AST, reading all the information about use'd crates and
156 // extern libraries necessary for later resolving, typechecking, linking,
158 pub fn read_crates(&mut self, krate: &ast::Crate) {
159 self.process_crate(krate);
160 visit::walk_crate(self, krate);
162 if log_enabled!(log::DEBUG) {
163 dump_crates(&self.sess.cstore);
166 for &(ref name, kind) in &self.sess.opts.libs {
167 register_native_lib(self.sess, None, name.clone(), kind);
171 fn process_crate(&self, c: &ast::Crate) {
172 for a in c.attrs.iter().filter(|m| m.name() == "link_args") {
173 match a.value_str() {
174 Some(ref linkarg) => self.sess.cstore.add_used_link_args(&linkarg),
175 None => { /* fallthrough */ }
180 fn extract_crate_info(&self, i: &ast::Item) -> Option<CrateInfo> {
182 ast::ItemExternCrate(ref path_opt) => {
183 let ident = token::get_ident(i.ident);
184 debug!("resolving extern crate stmt. ident: {} path_opt: {:?}",
186 let name = match *path_opt {
188 validate_crate_name(Some(self.sess), name.as_str(),
190 name.as_str().to_string()
192 None => ident.to_string(),
195 ident: ident.to_string(),
198 should_link: should_link(i),
205 fn process_item(&mut self, i: &ast::Item) {
207 ast::ItemExternCrate(_) => {
212 match self.extract_crate_info(i) {
214 let (cnum, _, _) = self.resolve_crate(&None,
220 self.sess.cstore.add_extern_mod_stmt_cnum(info.id, cnum);
225 ast::ItemForeignMod(ref fm) => {
226 if fm.abi == abi::Rust || fm.abi == abi::RustIntrinsic {
230 // First, add all of the custom link_args attributes
231 let link_args = i.attrs.iter()
232 .filter_map(|at| if at.name() == "link_args" {
237 .collect::<Vec<&ast::Attribute>>();
238 for m in &link_args {
239 match m.value_str() {
240 Some(linkarg) => self.sess.cstore.add_used_link_args(&linkarg),
241 None => { /* fallthrough */ }
245 // Next, process all of the #[link(..)]-style arguments
246 let link_args = i.attrs.iter()
247 .filter_map(|at| if at.name() == "link" {
252 .collect::<Vec<&ast::Attribute>>();
253 for m in &link_args {
254 match m.meta_item_list() {
256 let kind = items.iter().find(|k| {
258 }).and_then(|a| a.value_str());
259 let kind = match kind {
263 } else if self.sess.target.target.options.is_like_osx
264 && k == "framework" {
265 cstore::NativeFramework
266 } else if k == "framework" {
267 cstore::NativeFramework
268 } else if k == "dylib" {
269 cstore::NativeUnknown
271 self.sess.span_err(m.span,
272 &format!("unknown kind: `{}`",
274 cstore::NativeUnknown
277 None => cstore::NativeUnknown
279 let n = items.iter().find(|n| {
281 }).and_then(|a| a.value_str());
285 self.sess.span_err(m.span,
286 "#[link(...)] specified without \
288 InternedString::new("foo")
291 register_native_lib(self.sess, Some(m.span),
292 n.to_string(), kind);
302 fn existing_match(&self, name: &str, hash: Option<&Svh>, kind: PathKind)
303 -> Option<ast::CrateNum> {
305 self.sess.cstore.iter_crate_data(|cnum, data| {
306 if data.name != name { return }
309 Some(hash) if *hash == data.hash() => { ret = Some(cnum); return }
314 // When the hash is None we're dealing with a top-level dependency
315 // in which case we may have a specification on the command line for
316 // this library. Even though an upstream library may have loaded
317 // something of the same name, we have to make sure it was loaded
318 // from the exact same location as well.
320 // We're also sure to compare *paths*, not actual byte slices. The
321 // `source` stores paths which are normalized which may be different
322 // from the strings on the command line.
323 let source = self.sess.cstore.get_used_crate_source(cnum).unwrap();
324 if let Some(locs) = self.sess.opts.externs.get(name) {
325 let found = locs.iter().any(|l| {
326 let l = fs::canonicalize(l).ok();
327 source.dylib.as_ref().map(|p| &p.0) == l.as_ref() ||
328 source.rlib.as_ref().map(|p| &p.0) == l.as_ref()
336 // Alright, so we've gotten this far which means that `data` has the
337 // right name, we don't have a hash, and we don't have a --extern
338 // pointing for ourselves. We're still not quite yet done because we
339 // have to make sure that this crate was found in the crate lookup
340 // path (this is a top-level dependency) as we don't want to
341 // implicitly load anything inside the dependency lookup path.
342 let prev_kind = source.dylib.as_ref().or(source.rlib.as_ref())
344 if ret.is_none() && (prev_kind == kind || prev_kind == PathKind::All) {
351 fn register_crate(&mut self,
352 root: &Option<CratePaths>,
356 lib: loader::Library)
357 -> (ast::CrateNum, Rc<cstore::crate_metadata>,
358 cstore::CrateSource) {
359 // Claim this crate number and cache it
360 let cnum = self.next_crate_num;
361 self.next_crate_num += 1;
363 // Stash paths for top-most crate locally if necessary.
364 let crate_paths = if root.is_none() {
366 ident: ident.to_string(),
367 dylib: lib.dylib.clone().map(|p| p.0),
368 rlib: lib.rlib.clone().map(|p| p.0),
373 // Maintain a reference to the top most crate.
374 let root = if root.is_some() { root } else { &crate_paths };
376 let loader::Library { dylib, rlib, metadata } = lib;
378 let cnum_map = self.resolve_crate_deps(root, metadata.as_slice(), span);
379 let codemap_import_info = import_codemap(self.sess.codemap(), &metadata);
381 let cmeta = Rc::new( cstore::crate_metadata {
382 name: name.to_string(),
386 codemap_import_info: codemap_import_info,
390 let source = cstore::CrateSource {
396 self.sess.cstore.set_crate_data(cnum, cmeta.clone());
397 self.sess.cstore.add_used_crate_source(source.clone());
398 (cnum, cmeta, source)
401 fn resolve_crate(&mut self,
402 root: &Option<CratePaths>,
408 -> (ast::CrateNum, Rc<cstore::crate_metadata>,
409 cstore::CrateSource) {
410 match self.existing_match(name, hash, kind) {
412 let mut load_ctxt = loader::Context {
417 hash: hash.map(|a| &*a),
418 filesearch: self.sess.target_filesearch(kind),
419 target: &self.sess.target.target,
420 triple: &self.sess.opts.target_triple,
422 rejected_via_hash: vec!(),
423 rejected_via_triple: vec!(),
424 rejected_via_kind: vec!(),
425 should_match_name: true,
427 let library = load_ctxt.load_library_crate();
428 self.register_crate(root, ident, name, span, library)
431 self.sess.cstore.get_crate_data(cnum),
432 self.sess.cstore.get_used_crate_source(cnum).unwrap())
436 // Go through the crate metadata and load any crates that it references
437 fn resolve_crate_deps(&mut self,
438 root: &Option<CratePaths>,
439 cdata: &[u8], span : Span)
440 -> cstore::cnum_map {
441 debug!("resolving deps of external crate");
442 // The map from crate numbers in the crate we're resolving to local crate
444 decoder::get_crate_deps(cdata).iter().map(|dep| {
445 debug!("resolving dep crate {} hash: `{}`", dep.name, dep.hash);
446 let (local_cnum, _, _) = self.resolve_crate(root,
451 PathKind::Dependency);
452 (dep.cnum, local_cnum)
456 fn read_extension_crate(&mut self, span: Span, info: &CrateInfo) -> ExtensionCrate {
457 let target_triple = &self.sess.opts.target_triple[..];
458 let is_cross = target_triple != config::host_triple();
459 let mut should_link = info.should_link && !is_cross;
460 let mut target_only = false;
461 let ident = info.ident.clone();
462 let name = info.name.clone();
463 let mut load_ctxt = loader::Context {
467 crate_name: &name[..],
469 filesearch: self.sess.host_filesearch(PathKind::Crate),
470 target: &self.sess.host,
471 triple: config::host_triple(),
473 rejected_via_hash: vec!(),
474 rejected_via_triple: vec!(),
475 rejected_via_kind: vec!(),
476 should_match_name: true,
478 let library = match load_ctxt.maybe_load_library_crate() {
480 None if is_cross => {
481 // Try loading from target crates. This will abort later if we
482 // try to load a plugin registrar function,
484 should_link = info.should_link;
486 load_ctxt.target = &self.sess.target.target;
487 load_ctxt.triple = target_triple;
488 load_ctxt.filesearch = self.sess.target_filesearch(PathKind::Crate);
489 load_ctxt.load_library_crate()
491 None => { load_ctxt.report_load_errs(); unreachable!() },
494 let dylib = library.dylib.clone();
495 let register = should_link && self.existing_match(&info.name,
497 PathKind::Crate).is_none();
498 let metadata = if register {
499 // Register crate now to avoid double-reading metadata
500 let (_, cmd, _) = self.register_crate(&None, &info.ident,
501 &info.name, span, library);
502 PMDSource::Registered(cmd)
504 // Not registering the crate; just hold on to the metadata
505 PMDSource::Owned(library.metadata)
510 dylib: dylib.map(|p| p.0),
511 target_only: target_only,
515 /// Read exported macros.
516 pub fn read_exported_macros(&mut self, krate: &ast::Item) -> Vec<ast::MacroDef> {
517 let ci = self.extract_crate_info(krate).unwrap();
518 let ekrate = self.read_extension_crate(krate.span, &ci);
520 let source_name = format!("<{} macros>", krate.ident);
521 let mut macros = vec![];
522 decoder::each_exported_macro(ekrate.metadata.as_slice(),
523 &*self.sess.cstore.intr,
524 |name, attrs, body| {
525 // NB: Don't use parse::parse_tts_from_source_str because it parses with
527 let mut p = parse::new_parser_from_source_str(&self.sess.parse_sess,
528 self.sess.opts.cfg.clone(),
532 let body = match p.parse_all_token_trees() {
534 Err(err) => panic!(err),
536 let span = mk_sp(lo, p.last_span.hi);
538 macros.push(ast::MacroDef {
541 id: ast::DUMMY_NODE_ID,
543 imported_from: Some(krate.ident),
544 // overridden in plugin/load.rs
547 allow_internal_unstable: false,
557 /// Look for a plugin registrar. Returns library path and symbol name.
558 pub fn find_plugin_registrar(&mut self, span: Span, name: &str)
559 -> Option<(PathBuf, String)> {
560 let ekrate = self.read_extension_crate(span, &CrateInfo {
561 name: name.to_string(),
562 ident: name.to_string(),
563 id: ast::DUMMY_NODE_ID,
567 if ekrate.target_only {
568 // Need to abort before syntax expansion.
569 let message = format!("plugin `{}` is not available for triple `{}` \
572 config::host_triple(),
573 self.sess.opts.target_triple);
574 self.sess.span_err(span, &message[..]);
575 self.sess.abort_if_errors();
578 let registrar = decoder::get_plugin_registrar_fn(ekrate.metadata.as_slice())
579 .map(|id| decoder::get_symbol(ekrate.metadata.as_slice(), id));
581 match (ekrate.dylib.as_ref(), registrar) {
582 (Some(dylib), Some(reg)) => Some((dylib.to_path_buf(), reg)),
584 let message = format!("plugin `{}` only found in rlib format, \
585 but must be available in dylib format",
587 self.sess.span_err(span, &message[..]);
588 // No need to abort because the loading code will just ignore this
597 /// Imports the codemap from an external crate into the codemap of the crate
598 /// currently being compiled (the "local crate").
600 /// The import algorithm works analogous to how AST items are inlined from an
601 /// external crate's metadata:
602 /// For every FileMap in the external codemap an 'inline' copy is created in the
603 /// local codemap. The correspondence relation between external and local
604 /// FileMaps is recorded in the `ImportedFileMap` objects returned from this
605 /// function. When an item from an external crate is later inlined into this
606 /// crate, this correspondence information is used to translate the span
607 /// information of the inlined item so that it refers the correct positions in
608 /// the local codemap (see `astencode::DecodeContext::tr_span()`).
610 /// The import algorithm in the function below will reuse FileMaps already
611 /// existing in the local codemap. For example, even if the FileMap of some
612 /// source file of libstd gets imported many times, there will only ever be
613 /// one FileMap object for the corresponding file in the local codemap.
615 /// Note that imported FileMaps do not actually contain the source code of the
616 /// file they represent, just information about length, line breaks, and
617 /// multibyte characters. This information is enough to generate valid debuginfo
618 /// for items inlined from other crates.
619 fn import_codemap(local_codemap: &codemap::CodeMap,
620 metadata: &MetadataBlob)
621 -> Vec<cstore::ImportedFileMap> {
622 let external_codemap = decoder::get_imported_filemaps(metadata.as_slice());
624 let imported_filemaps = external_codemap.into_iter().map(|filemap_to_import| {
625 // Try to find an existing FileMap that can be reused for the filemap to
626 // be imported. A FileMap is reusable if it is exactly the same, just
627 // positioned at a different offset within the codemap.
628 let reusable_filemap = {
632 .find(|fm| are_equal_modulo_startpos(&fm, &filemap_to_import))
633 .map(|rc| rc.clone())
636 match reusable_filemap {
638 cstore::ImportedFileMap {
639 original_start_pos: filemap_to_import.start_pos,
640 original_end_pos: filemap_to_import.end_pos,
641 translated_filemap: fm
645 // We can't reuse an existing FileMap, so allocate a new one
646 // containing the information we need.
647 let codemap::FileMap {
654 } = filemap_to_import;
656 let source_length = (end_pos - start_pos).to_usize();
658 // Translate line-start positions and multibyte character
659 // position into frame of reference local to file.
660 // `CodeMap::new_imported_filemap()` will then translate those
661 // coordinates to their new global frame of reference when the
662 // offset of the FileMap is known.
663 let lines = lines.into_inner().map_in_place(|pos| pos - start_pos);
664 let multibyte_chars = multibyte_chars
667 codemap::MultiByteChar {
668 pos: mbc.pos - start_pos,
672 let local_version = local_codemap.new_imported_filemap(name,
676 cstore::ImportedFileMap {
677 original_start_pos: start_pos,
678 original_end_pos: end_pos,
679 translated_filemap: local_version
685 return imported_filemaps;
687 fn are_equal_modulo_startpos(fm1: &codemap::FileMap,
688 fm2: &codemap::FileMap)
690 if fm1.name != fm2.name {
694 let lines1 = fm1.lines.borrow();
695 let lines2 = fm2.lines.borrow();
697 if lines1.len() != lines2.len() {
701 for (&line1, &line2) in lines1.iter().zip(lines2.iter()) {
702 if (line1 - fm1.start_pos) != (line2 - fm2.start_pos) {
707 let multibytes1 = fm1.multibyte_chars.borrow();
708 let multibytes2 = fm2.multibyte_chars.borrow();
710 if multibytes1.len() != multibytes2.len() {
714 for (mb1, mb2) in multibytes1.iter().zip(multibytes2.iter()) {
715 if (mb1.bytes != mb2.bytes) ||
716 ((mb1.pos - fm1.start_pos) != (mb2.pos - fm2.start_pos)) {