]> git.proxmox.com Git - rustc.git/blob - src/librustc/metadata/loader.rs
Imported Upstream version 1.5.0+dfsg1
[rustc.git] / src / librustc / metadata / loader.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 //! Finds crate binaries and loads their metadata
12 //!
13 //! Might I be the first to welcome you to a world of platform differences,
14 //! version requirements, dependency graphs, conflicting desires, and fun! This
15 //! is the major guts (along with metadata::creader) of the compiler for loading
16 //! crates and resolving dependencies. Let's take a tour!
17 //!
18 //! # The problem
19 //!
20 //! Each invocation of the compiler is immediately concerned with one primary
21 //! problem, to connect a set of crates to resolved crates on the filesystem.
22 //! Concretely speaking, the compiler follows roughly these steps to get here:
23 //!
24 //! 1. Discover a set of `extern crate` statements.
25 //! 2. Transform these directives into crate names. If the directive does not
26 //! have an explicit name, then the identifier is the name.
27 //! 3. For each of these crate names, find a corresponding crate on the
28 //! filesystem.
29 //!
30 //! Sounds easy, right? Let's walk into some of the nuances.
31 //!
32 //! ## Transitive Dependencies
33 //!
34 //! Let's say we've got three crates: A, B, and C. A depends on B, and B depends
35 //! on C. When we're compiling A, we primarily need to find and locate B, but we
36 //! also end up needing to find and locate C as well.
37 //!
38 //! The reason for this is that any of B's types could be composed of C's types,
39 //! any function in B could return a type from C, etc. To be able to guarantee
40 //! that we can always typecheck/translate any function, we have to have
41 //! complete knowledge of the whole ecosystem, not just our immediate
42 //! dependencies.
43 //!
44 //! So now as part of the "find a corresponding crate on the filesystem" step
45 //! above, this involves also finding all crates for *all upstream
46 //! dependencies*. This includes all dependencies transitively.
47 //!
48 //! ## Rlibs and Dylibs
49 //!
50 //! The compiler has two forms of intermediate dependencies. These are dubbed
51 //! rlibs and dylibs for the static and dynamic variants, respectively. An rlib
52 //! is a rustc-defined file format (currently just an ar archive) while a dylib
53 //! is a platform-defined dynamic library. Each library has a metadata somewhere
54 //! inside of it.
55 //!
56 //! When translating a crate name to a crate on the filesystem, we all of a
57 //! sudden need to take into account both rlibs and dylibs! Linkage later on may
58 //! use either one of these files, as each has their pros/cons. The job of crate
59 //! loading is to discover what's possible by finding all candidates.
60 //!
61 //! Most parts of this loading systems keep the dylib/rlib as just separate
62 //! variables.
63 //!
64 //! ## Where to look?
65 //!
66 //! We can't exactly scan your whole hard drive when looking for dependencies,
67 //! so we need to places to look. Currently the compiler will implicitly add the
68 //! target lib search path ($prefix/lib/rustlib/$target/lib) to any compilation,
69 //! and otherwise all -L flags are added to the search paths.
70 //!
71 //! ## What criterion to select on?
72 //!
73 //! This a pretty tricky area of loading crates. Given a file, how do we know
74 //! whether it's the right crate? Currently, the rules look along these lines:
75 //!
76 //! 1. Does the filename match an rlib/dylib pattern? That is to say, does the
77 //! filename have the right prefix/suffix?
78 //! 2. Does the filename have the right prefix for the crate name being queried?
79 //! This is filtering for files like `libfoo*.rlib` and such.
80 //! 3. Is the file an actual rust library? This is done by loading the metadata
81 //! from the library and making sure it's actually there.
82 //! 4. Does the name in the metadata agree with the name of the library?
83 //! 5. Does the target in the metadata agree with the current target?
84 //! 6. Does the SVH match? (more on this later)
85 //!
86 //! If the file answers `yes` to all these questions, then the file is
87 //! considered as being *candidate* for being accepted. It is illegal to have
88 //! more than two candidates as the compiler has no method by which to resolve
89 //! this conflict. Additionally, rlib/dylib candidates are considered
90 //! separately.
91 //!
92 //! After all this has happened, we have 1 or two files as candidates. These
93 //! represent the rlib/dylib file found for a library, and they're returned as
94 //! being found.
95 //!
96 //! ### What about versions?
97 //!
98 //! A lot of effort has been put forth to remove versioning from the compiler.
99 //! There have been forays in the past to have versioning baked in, but it was
100 //! largely always deemed insufficient to the point that it was recognized that
101 //! it's probably something the compiler shouldn't do anyway due to its
102 //! complicated nature and the state of the half-baked solutions.
103 //!
104 //! With a departure from versioning, the primary criterion for loading crates
105 //! is just the name of a crate. If we stopped here, it would imply that you
106 //! could never link two crates of the same name from different sources
107 //! together, which is clearly a bad state to be in.
108 //!
109 //! To resolve this problem, we come to the next section!
110 //!
111 //! # Expert Mode
112 //!
113 //! A number of flags have been added to the compiler to solve the "version
114 //! problem" in the previous section, as well as generally enabling more
115 //! powerful usage of the crate loading system of the compiler. The goal of
116 //! these flags and options are to enable third-party tools to drive the
117 //! compiler with prior knowledge about how the world should look.
118 //!
119 //! ## The `--extern` flag
120 //!
121 //! The compiler accepts a flag of this form a number of times:
122 //!
123 //! ```text
124 //! --extern crate-name=path/to/the/crate.rlib
125 //! ```
126 //!
127 //! This flag is basically the following letter to the compiler:
128 //!
129 //! > Dear rustc,
130 //! >
131 //! > When you are attempting to load the immediate dependency `crate-name`, I
132 //! > would like you to assume that the library is located at
133 //! > `path/to/the/crate.rlib`, and look nowhere else. Also, please do not
134 //! > assume that the path I specified has the name `crate-name`.
135 //!
136 //! This flag basically overrides most matching logic except for validating that
137 //! the file is indeed a rust library. The same `crate-name` can be specified
138 //! twice to specify the rlib/dylib pair.
139 //!
140 //! ## Enabling "multiple versions"
141 //!
142 //! This basically boils down to the ability to specify arbitrary packages to
143 //! the compiler. For example, if crate A wanted to use Bv1 and Bv2, then it
144 //! would look something like:
145 //!
146 //! ```ignore
147 //! extern crate b1;
148 //! extern crate b2;
149 //!
150 //! fn main() {}
151 //! ```
152 //!
153 //! and the compiler would be invoked as:
154 //!
155 //! ```text
156 //! rustc a.rs --extern b1=path/to/libb1.rlib --extern b2=path/to/libb2.rlib
157 //! ```
158 //!
159 //! In this scenario there are two crates named `b` and the compiler must be
160 //! manually driven to be informed where each crate is.
161 //!
162 //! ## Frobbing symbols
163 //!
164 //! One of the immediate problems with linking the same library together twice
165 //! in the same problem is dealing with duplicate symbols. The primary way to
166 //! deal with this in rustc is to add hashes to the end of each symbol.
167 //!
168 //! In order to force hashes to change between versions of a library, if
169 //! desired, the compiler exposes an option `-C metadata=foo`, which is used to
170 //! initially seed each symbol hash. The string `foo` is prepended to each
171 //! string-to-hash to ensure that symbols change over time.
172 //!
173 //! ## Loading transitive dependencies
174 //!
175 //! Dealing with same-named-but-distinct crates is not just a local problem, but
176 //! one that also needs to be dealt with for transitive dependencies. Note that
177 //! in the letter above `--extern` flags only apply to the *local* set of
178 //! dependencies, not the upstream transitive dependencies. Consider this
179 //! dependency graph:
180 //!
181 //! ```text
182 //! A.1 A.2
183 //! | |
184 //! | |
185 //! B C
186 //! \ /
187 //! \ /
188 //! D
189 //! ```
190 //!
191 //! In this scenario, when we compile `D`, we need to be able to distinctly
192 //! resolve `A.1` and `A.2`, but an `--extern` flag cannot apply to these
193 //! transitive dependencies.
194 //!
195 //! Note that the key idea here is that `B` and `C` are both *already compiled*.
196 //! That is, they have already resolved their dependencies. Due to unrelated
197 //! technical reasons, when a library is compiled, it is only compatible with
198 //! the *exact same* version of the upstream libraries it was compiled against.
199 //! We use the "Strict Version Hash" to identify the exact copy of an upstream
200 //! library.
201 //!
202 //! With this knowledge, we know that `B` and `C` will depend on `A` with
203 //! different SVH values, so we crawl the normal `-L` paths looking for
204 //! `liba*.rlib` and filter based on the contained SVH.
205 //!
206 //! In the end, this ends up not needing `--extern` to specify upstream
207 //! transitive dependencies.
208 //!
209 //! # Wrapping up
210 //!
211 //! That's the general overview of loading crates in the compiler, but it's by
212 //! no means all of the necessary details. Take a look at the rest of
213 //! metadata::loader or metadata::creader for all the juicy details!
214
215 use back::svh::Svh;
216 use session::Session;
217 use session::search_paths::PathKind;
218 use llvm;
219 use llvm::{False, ObjectFile, mk_section_iter};
220 use llvm::archive_ro::ArchiveRO;
221 use metadata::cstore::{MetadataBlob, MetadataVec, MetadataArchive};
222 use metadata::decoder;
223 use metadata::encoder;
224 use metadata::filesearch::{FileSearch, FileMatches, FileDoesntMatch};
225 use syntax::codemap::Span;
226 use syntax::diagnostic::SpanHandler;
227 use util::common;
228 use rustc_back::target::Target;
229
230 use std::cmp;
231 use std::collections::HashMap;
232 use std::fs;
233 use std::io::prelude::*;
234 use std::io;
235 use std::path::{Path, PathBuf};
236 use std::ptr;
237 use std::slice;
238 use std::time::Duration;
239
240 use flate;
241
242 pub struct CrateMismatch {
243 path: PathBuf,
244 got: String,
245 }
246
247 pub struct Context<'a> {
248 pub sess: &'a Session,
249 pub span: Span,
250 pub ident: &'a str,
251 pub crate_name: &'a str,
252 pub hash: Option<&'a Svh>,
253 // points to either self.sess.target.target or self.sess.host, must match triple
254 pub target: &'a Target,
255 pub triple: &'a str,
256 pub filesearch: FileSearch<'a>,
257 pub root: &'a Option<CratePaths>,
258 pub rejected_via_hash: Vec<CrateMismatch>,
259 pub rejected_via_triple: Vec<CrateMismatch>,
260 pub rejected_via_kind: Vec<CrateMismatch>,
261 pub should_match_name: bool,
262 }
263
264 pub struct Library {
265 pub dylib: Option<(PathBuf, PathKind)>,
266 pub rlib: Option<(PathBuf, PathKind)>,
267 pub metadata: MetadataBlob,
268 }
269
270 pub struct ArchiveMetadata {
271 _archive: ArchiveRO,
272 // points into self._archive
273 data: *const [u8],
274 }
275
276 pub struct CratePaths {
277 pub ident: String,
278 pub dylib: Option<PathBuf>,
279 pub rlib: Option<PathBuf>
280 }
281
282 pub const METADATA_FILENAME: &'static str = "rust.metadata.bin";
283
284 impl CratePaths {
285 fn paths(&self) -> Vec<PathBuf> {
286 match (&self.dylib, &self.rlib) {
287 (&None, &None) => vec!(),
288 (&Some(ref p), &None) |
289 (&None, &Some(ref p)) => vec!(p.clone()),
290 (&Some(ref p1), &Some(ref p2)) => vec!(p1.clone(), p2.clone()),
291 }
292 }
293 }
294
295 impl<'a> Context<'a> {
296 pub fn maybe_load_library_crate(&mut self) -> Option<Library> {
297 self.find_library_crate()
298 }
299
300 pub fn load_library_crate(&mut self) -> Library {
301 match self.find_library_crate() {
302 Some(t) => t,
303 None => {
304 self.report_load_errs();
305 unreachable!()
306 }
307 }
308 }
309
310 pub fn report_load_errs(&mut self) {
311 let add = match self.root {
312 &None => String::new(),
313 &Some(ref r) => format!(" which `{}` depends on",
314 r.ident)
315 };
316 if !self.rejected_via_hash.is_empty() {
317 span_err!(self.sess, self.span, E0460,
318 "found possibly newer version of crate `{}`{}",
319 self.ident, add);
320 } else if !self.rejected_via_triple.is_empty() {
321 span_err!(self.sess, self.span, E0461,
322 "couldn't find crate `{}` with expected target triple {}{}",
323 self.ident, self.triple, add);
324 } else if !self.rejected_via_kind.is_empty() {
325 span_err!(self.sess, self.span, E0462,
326 "found staticlib `{}` instead of rlib or dylib{}",
327 self.ident, add);
328 } else {
329 span_err!(self.sess, self.span, E0463,
330 "can't find crate for `{}`{}",
331 self.ident, add);
332 }
333
334 if !self.rejected_via_triple.is_empty() {
335 let mismatches = self.rejected_via_triple.iter();
336 for (i, &CrateMismatch{ ref path, ref got }) in mismatches.enumerate() {
337 self.sess.fileline_note(self.span,
338 &format!("crate `{}`, path #{}, triple {}: {}",
339 self.ident, i+1, got, path.display()));
340 }
341 }
342 if !self.rejected_via_hash.is_empty() {
343 self.sess.span_note(self.span, "perhaps this crate needs \
344 to be recompiled?");
345 let mismatches = self.rejected_via_hash.iter();
346 for (i, &CrateMismatch{ ref path, .. }) in mismatches.enumerate() {
347 self.sess.fileline_note(self.span,
348 &format!("crate `{}` path #{}: {}",
349 self.ident, i+1, path.display()));
350 }
351 match self.root {
352 &None => {}
353 &Some(ref r) => {
354 for (i, path) in r.paths().iter().enumerate() {
355 self.sess.fileline_note(self.span,
356 &format!("crate `{}` path #{}: {}",
357 r.ident, i+1, path.display()));
358 }
359 }
360 }
361 }
362 if !self.rejected_via_kind.is_empty() {
363 self.sess.fileline_help(self.span, "please recompile this crate using \
364 --crate-type lib");
365 let mismatches = self.rejected_via_kind.iter();
366 for (i, &CrateMismatch { ref path, .. }) in mismatches.enumerate() {
367 self.sess.fileline_note(self.span,
368 &format!("crate `{}` path #{}: {}",
369 self.ident, i+1, path.display()));
370 }
371 }
372 self.sess.abort_if_errors();
373 }
374
375 fn find_library_crate(&mut self) -> Option<Library> {
376 // If an SVH is specified, then this is a transitive dependency that
377 // must be loaded via -L plus some filtering.
378 if self.hash.is_none() {
379 self.should_match_name = false;
380 if let Some(s) = self.sess.opts.externs.get(self.crate_name) {
381 return self.find_commandline_library(s);
382 }
383 self.should_match_name = true;
384 }
385
386 let dypair = self.dylibname();
387
388 // want: crate_name.dir_part() + prefix + crate_name.file_part + "-"
389 let dylib_prefix = format!("{}{}", dypair.0, self.crate_name);
390 let rlib_prefix = format!("lib{}", self.crate_name);
391 let staticlib_prefix = format!("lib{}", self.crate_name);
392
393 let mut candidates = HashMap::new();
394 let mut staticlibs = vec!();
395
396 // First, find all possible candidate rlibs and dylibs purely based on
397 // the name of the files themselves. We're trying to match against an
398 // exact crate name and a possibly an exact hash.
399 //
400 // During this step, we can filter all found libraries based on the
401 // name and id found in the crate id (we ignore the path portion for
402 // filename matching), as well as the exact hash (if specified). If we
403 // end up having many candidates, we must look at the metadata to
404 // perform exact matches against hashes/crate ids. Note that opening up
405 // the metadata is where we do an exact match against the full contents
406 // of the crate id (path/name/id).
407 //
408 // The goal of this step is to look at as little metadata as possible.
409 self.filesearch.search(|path, kind| {
410 let file = match path.file_name().and_then(|s| s.to_str()) {
411 None => return FileDoesntMatch,
412 Some(file) => file,
413 };
414 let (hash, rlib) = if file.starts_with(&rlib_prefix[..]) &&
415 file.ends_with(".rlib") {
416 (&file[(rlib_prefix.len()) .. (file.len() - ".rlib".len())],
417 true)
418 } else if file.starts_with(&dylib_prefix) &&
419 file.ends_with(&dypair.1) {
420 (&file[(dylib_prefix.len()) .. (file.len() - dypair.1.len())],
421 false)
422 } else {
423 if file.starts_with(&staticlib_prefix[..]) &&
424 file.ends_with(".a") {
425 staticlibs.push(CrateMismatch {
426 path: path.to_path_buf(),
427 got: "static".to_string()
428 });
429 }
430 return FileDoesntMatch
431 };
432 info!("lib candidate: {}", path.display());
433
434 let hash_str = hash.to_string();
435 let slot = candidates.entry(hash_str)
436 .or_insert_with(|| (HashMap::new(), HashMap::new()));
437 let (ref mut rlibs, ref mut dylibs) = *slot;
438 fs::canonicalize(path).map(|p| {
439 if rlib {
440 rlibs.insert(p, kind);
441 } else {
442 dylibs.insert(p, kind);
443 }
444 FileMatches
445 }).unwrap_or(FileDoesntMatch)
446 });
447 self.rejected_via_kind.extend(staticlibs);
448
449 // We have now collected all known libraries into a set of candidates
450 // keyed of the filename hash listed. For each filename, we also have a
451 // list of rlibs/dylibs that apply. Here, we map each of these lists
452 // (per hash), to a Library candidate for returning.
453 //
454 // A Library candidate is created if the metadata for the set of
455 // libraries corresponds to the crate id and hash criteria that this
456 // search is being performed for.
457 let mut libraries = Vec::new();
458 for (_hash, (rlibs, dylibs)) in candidates {
459 let mut metadata = None;
460 let rlib = self.extract_one(rlibs, "rlib", &mut metadata);
461 let dylib = self.extract_one(dylibs, "dylib", &mut metadata);
462 match metadata {
463 Some(metadata) => {
464 libraries.push(Library {
465 dylib: dylib,
466 rlib: rlib,
467 metadata: metadata,
468 })
469 }
470 None => {}
471 }
472 }
473
474 // Having now translated all relevant found hashes into libraries, see
475 // what we've got and figure out if we found multiple candidates for
476 // libraries or not.
477 match libraries.len() {
478 0 => None,
479 1 => Some(libraries.into_iter().next().unwrap()),
480 _ => {
481 span_err!(self.sess, self.span, E0464,
482 "multiple matching crates for `{}`",
483 self.crate_name);
484 self.sess.note("candidates:");
485 for lib in &libraries {
486 match lib.dylib {
487 Some((ref p, _)) => {
488 self.sess.note(&format!("path: {}",
489 p.display()));
490 }
491 None => {}
492 }
493 match lib.rlib {
494 Some((ref p, _)) => {
495 self.sess.note(&format!("path: {}",
496 p.display()));
497 }
498 None => {}
499 }
500 let data = lib.metadata.as_slice();
501 let name = decoder::get_crate_name(data);
502 note_crate_name(self.sess.diagnostic(), &name);
503 }
504 None
505 }
506 }
507 }
508
509 // Attempts to extract *one* library from the set `m`. If the set has no
510 // elements, `None` is returned. If the set has more than one element, then
511 // the errors and notes are emitted about the set of libraries.
512 //
513 // With only one library in the set, this function will extract it, and then
514 // read the metadata from it if `*slot` is `None`. If the metadata couldn't
515 // be read, it is assumed that the file isn't a valid rust library (no
516 // errors are emitted).
517 fn extract_one(&mut self, m: HashMap<PathBuf, PathKind>, flavor: &str,
518 slot: &mut Option<MetadataBlob>) -> Option<(PathBuf, PathKind)> {
519 let mut ret = None::<(PathBuf, PathKind)>;
520 let mut error = 0;
521
522 if slot.is_some() {
523 // FIXME(#10786): for an optimization, we only read one of the
524 // library's metadata sections. In theory we should
525 // read both, but reading dylib metadata is quite
526 // slow.
527 if m.is_empty() {
528 return None
529 } else if m.len() == 1 {
530 return Some(m.into_iter().next().unwrap())
531 }
532 }
533
534 for (lib, kind) in m {
535 info!("{} reading metadata from: {}", flavor, lib.display());
536 let metadata = match get_metadata_section(self.target, &lib) {
537 Ok(blob) => {
538 if self.crate_matches(blob.as_slice(), &lib) {
539 blob
540 } else {
541 info!("metadata mismatch");
542 continue
543 }
544 }
545 Err(_) => {
546 info!("no metadata found");
547 continue
548 }
549 };
550 if ret.is_some() {
551 span_err!(self.sess, self.span, E0465,
552 "multiple {} candidates for `{}` found",
553 flavor, self.crate_name);
554 self.sess.span_note(self.span,
555 &format!(r"candidate #1: {}",
556 ret.as_ref().unwrap().0
557 .display()));
558 error = 1;
559 ret = None;
560 }
561 if error > 0 {
562 error += 1;
563 self.sess.span_note(self.span,
564 &format!(r"candidate #{}: {}", error,
565 lib.display()));
566 continue
567 }
568 *slot = Some(metadata);
569 ret = Some((lib, kind));
570 }
571 return if error > 0 {None} else {ret}
572 }
573
574 fn crate_matches(&mut self, crate_data: &[u8], libpath: &Path) -> bool {
575 if self.should_match_name {
576 match decoder::maybe_get_crate_name(crate_data) {
577 Some(ref name) if self.crate_name == *name => {}
578 _ => { info!("Rejecting via crate name"); return false }
579 }
580 }
581 let hash = match decoder::maybe_get_crate_hash(crate_data) {
582 Some(hash) => hash, None => {
583 info!("Rejecting via lack of crate hash");
584 return false;
585 }
586 };
587
588 let triple = match decoder::get_crate_triple(crate_data) {
589 None => { debug!("triple not present"); return false }
590 Some(t) => t,
591 };
592 if triple != self.triple {
593 info!("Rejecting via crate triple: expected {} got {}", self.triple, triple);
594 self.rejected_via_triple.push(CrateMismatch {
595 path: libpath.to_path_buf(),
596 got: triple.to_string()
597 });
598 return false;
599 }
600
601 match self.hash {
602 None => true,
603 Some(myhash) => {
604 if *myhash != hash {
605 info!("Rejecting via hash: expected {} got {}", *myhash, hash);
606 self.rejected_via_hash.push(CrateMismatch {
607 path: libpath.to_path_buf(),
608 got: myhash.as_str().to_string()
609 });
610 false
611 } else {
612 true
613 }
614 }
615 }
616 }
617
618
619 // Returns the corresponding (prefix, suffix) that files need to have for
620 // dynamic libraries
621 fn dylibname(&self) -> (String, String) {
622 let t = &self.target;
623 (t.options.dll_prefix.clone(), t.options.dll_suffix.clone())
624 }
625
626 fn find_commandline_library(&mut self, locs: &[String]) -> Option<Library> {
627 // First, filter out all libraries that look suspicious. We only accept
628 // files which actually exist that have the correct naming scheme for
629 // rlibs/dylibs.
630 let sess = self.sess;
631 let dylibname = self.dylibname();
632 let mut rlibs = HashMap::new();
633 let mut dylibs = HashMap::new();
634 {
635 let locs = locs.iter().map(|l| PathBuf::from(l)).filter(|loc| {
636 if !loc.exists() {
637 sess.err(&format!("extern location for {} does not exist: {}",
638 self.crate_name, loc.display()));
639 return false;
640 }
641 let file = match loc.file_name().and_then(|s| s.to_str()) {
642 Some(file) => file,
643 None => {
644 sess.err(&format!("extern location for {} is not a file: {}",
645 self.crate_name, loc.display()));
646 return false;
647 }
648 };
649 if file.starts_with("lib") && file.ends_with(".rlib") {
650 return true
651 } else {
652 let (ref prefix, ref suffix) = dylibname;
653 if file.starts_with(&prefix[..]) &&
654 file.ends_with(&suffix[..]) {
655 return true
656 }
657 }
658 sess.err(&format!("extern location for {} is of an unknown type: {}",
659 self.crate_name, loc.display()));
660 false
661 });
662
663 // Now that we have an iterator of good candidates, make sure
664 // there's at most one rlib and at most one dylib.
665 for loc in locs {
666 if loc.file_name().unwrap().to_str().unwrap().ends_with(".rlib") {
667 rlibs.insert(fs::canonicalize(&loc).unwrap(),
668 PathKind::ExternFlag);
669 } else {
670 dylibs.insert(fs::canonicalize(&loc).unwrap(),
671 PathKind::ExternFlag);
672 }
673 }
674 };
675
676 // Extract the rlib/dylib pair.
677 let mut metadata = None;
678 let rlib = self.extract_one(rlibs, "rlib", &mut metadata);
679 let dylib = self.extract_one(dylibs, "dylib", &mut metadata);
680
681 if rlib.is_none() && dylib.is_none() { return None }
682 match metadata {
683 Some(metadata) => Some(Library {
684 dylib: dylib,
685 rlib: rlib,
686 metadata: metadata,
687 }),
688 None => None,
689 }
690 }
691 }
692
693 pub fn note_crate_name(diag: &SpanHandler, name: &str) {
694 diag.handler().note(&format!("crate name: {}", name));
695 }
696
697 impl ArchiveMetadata {
698 fn new(ar: ArchiveRO) -> Option<ArchiveMetadata> {
699 let data = {
700 let section = ar.iter().find(|sect| {
701 sect.name() == Some(METADATA_FILENAME)
702 });
703 match section {
704 Some(s) => s.data() as *const [u8],
705 None => {
706 debug!("didn't find '{}' in the archive", METADATA_FILENAME);
707 return None;
708 }
709 }
710 };
711
712 Some(ArchiveMetadata {
713 _archive: ar,
714 data: data,
715 })
716 }
717
718 pub fn as_slice<'a>(&'a self) -> &'a [u8] { unsafe { &*self.data } }
719 }
720
721 // Just a small wrapper to time how long reading metadata takes.
722 fn get_metadata_section(target: &Target, filename: &Path)
723 -> Result<MetadataBlob, String> {
724 let mut ret = None;
725 let dur = Duration::span(|| {
726 ret = Some(get_metadata_section_imp(target, filename));
727 });
728 info!("reading {:?} => {:?}", filename.file_name().unwrap(), dur);
729 ret.unwrap()
730 }
731
732 fn get_metadata_section_imp(target: &Target, filename: &Path)
733 -> Result<MetadataBlob, String> {
734 if !filename.exists() {
735 return Err(format!("no such file: '{}'", filename.display()));
736 }
737 if filename.file_name().unwrap().to_str().unwrap().ends_with(".rlib") {
738 // Use ArchiveRO for speed here, it's backed by LLVM and uses mmap
739 // internally to read the file. We also avoid even using a memcpy by
740 // just keeping the archive along while the metadata is in use.
741 let archive = match ArchiveRO::open(filename) {
742 Some(ar) => ar,
743 None => {
744 debug!("llvm didn't like `{}`", filename.display());
745 return Err(format!("failed to read rlib metadata: '{}'",
746 filename.display()));
747 }
748 };
749 return match ArchiveMetadata::new(archive).map(|ar| MetadataArchive(ar)) {
750 None => Err(format!("failed to read rlib metadata: '{}'",
751 filename.display())),
752 Some(blob) => Ok(blob)
753 };
754 }
755 unsafe {
756 let buf = common::path2cstr(filename);
757 let mb = llvm::LLVMRustCreateMemoryBufferWithContentsOfFile(buf.as_ptr());
758 if mb as isize == 0 {
759 return Err(format!("error reading library: '{}'",
760 filename.display()))
761 }
762 let of = match ObjectFile::new(mb) {
763 Some(of) => of,
764 _ => {
765 return Err((format!("provided path not an object file: '{}'",
766 filename.display())))
767 }
768 };
769 let si = mk_section_iter(of.llof);
770 while llvm::LLVMIsSectionIteratorAtEnd(of.llof, si.llsi) == False {
771 let mut name_buf = ptr::null();
772 let name_len = llvm::LLVMRustGetSectionName(si.llsi, &mut name_buf);
773 let name = slice::from_raw_parts(name_buf as *const u8,
774 name_len as usize).to_vec();
775 let name = String::from_utf8(name).unwrap();
776 debug!("get_metadata_section: name {}", name);
777 if read_meta_section_name(target) == name {
778 let cbuf = llvm::LLVMGetSectionContents(si.llsi);
779 let csz = llvm::LLVMGetSectionSize(si.llsi) as usize;
780 let cvbuf: *const u8 = cbuf as *const u8;
781 let vlen = encoder::metadata_encoding_version.len();
782 debug!("checking {} bytes of metadata-version stamp",
783 vlen);
784 let minsz = cmp::min(vlen, csz);
785 let buf0 = slice::from_raw_parts(cvbuf, minsz);
786 let version_ok = buf0 == encoder::metadata_encoding_version;
787 if !version_ok {
788 return Err((format!("incompatible metadata version found: '{}'",
789 filename.display())));
790 }
791
792 let cvbuf1 = cvbuf.offset(vlen as isize);
793 debug!("inflating {} bytes of compressed metadata",
794 csz - vlen);
795 let bytes = slice::from_raw_parts(cvbuf1, csz - vlen);
796 match flate::inflate_bytes(bytes) {
797 Ok(inflated) => return Ok(MetadataVec(inflated)),
798 Err(_) => {}
799 }
800 }
801 llvm::LLVMMoveToNextSection(si.llsi);
802 }
803 Err(format!("metadata not found: '{}'", filename.display()))
804 }
805 }
806
807 pub fn meta_section_name(target: &Target) -> &'static str {
808 if target.options.is_like_osx {
809 "__DATA,__note.rustc"
810 } else if target.options.is_like_msvc {
811 // When using link.exe it was seen that the section name `.note.rustc`
812 // was getting shortened to `.note.ru`, and according to the PE and COFF
813 // specification:
814 //
815 // > Executable images do not use a string table and do not support
816 // > section names longer than 8 characters
817 //
818 // https://msdn.microsoft.com/en-us/library/windows/hardware/gg463119.aspx
819 //
820 // As a result, we choose a slightly shorter name! As to why
821 // `.note.rustc` works on MinGW, that's another good question...
822 ".rustc"
823 } else {
824 ".note.rustc"
825 }
826 }
827
828 pub fn read_meta_section_name(target: &Target) -> &'static str {
829 if target.options.is_like_osx {
830 "__note.rustc"
831 } else if target.options.is_like_msvc {
832 ".rustc"
833 } else {
834 ".note.rustc"
835 }
836 }
837
838 // A diagnostic function for dumping crate metadata to an output stream
839 pub fn list_file_metadata(target: &Target, path: &Path,
840 out: &mut io::Write) -> io::Result<()> {
841 match get_metadata_section(target, path) {
842 Ok(bytes) => decoder::list_crate_metadata(bytes.as_slice(), out),
843 Err(msg) => {
844 write!(out, "{}\n", msg)
845 }
846 }
847 }