]> git.lizzy.rs Git - rust.git/blob - src/librustc/metadata/loader.rs
auto merge of #14832 : alexcrichton/rust/no-rpath, r=brson
[rust.git] / src / librustc / metadata / loader.rs
1 // Copyright 2012 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, conficting 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 answeres `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 //! ```notrust
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 too 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 //! ```notrust
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 dependences. 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 //! ```notrust
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::archive::{ArchiveRO, METADATA_FILENAME};
216 use back::svh::Svh;
217 use driver::session::Session;
218 use lib::llvm::{False, llvm, ObjectFile, mk_section_iter};
219 use metadata::cstore::{MetadataBlob, MetadataVec, MetadataArchive};
220 use metadata::decoder;
221 use metadata::encoder;
222 use metadata::filesearch::{FileSearch, FileMatches, FileDoesntMatch};
223 use syntax::abi;
224 use syntax::codemap::Span;
225 use syntax::diagnostic::SpanHandler;
226 use util::fs;
227
228 use std::c_str::ToCStr;
229 use std::cmp;
230 use std::io;
231 use std::mem;
232 use std::ptr;
233 use std::slice;
234 use std::str;
235
236 use std::collections::{HashMap, HashSet};
237 use flate;
238 use time;
239
240 pub static MACOS_DLL_PREFIX: &'static str = "lib";
241 pub static MACOS_DLL_SUFFIX: &'static str = ".dylib";
242
243 pub static WIN32_DLL_PREFIX: &'static str = "";
244 pub static WIN32_DLL_SUFFIX: &'static str = ".dll";
245
246 pub static LINUX_DLL_PREFIX: &'static str = "lib";
247 pub static LINUX_DLL_SUFFIX: &'static str = ".so";
248
249 pub static FREEBSD_DLL_PREFIX: &'static str = "lib";
250 pub static FREEBSD_DLL_SUFFIX: &'static str = ".so";
251
252 pub static ANDROID_DLL_PREFIX: &'static str = "lib";
253 pub static ANDROID_DLL_SUFFIX: &'static str = ".so";
254
255 pub struct CrateMismatch {
256     path: Path,
257     got: String,
258 }
259
260 pub struct Context<'a> {
261     pub sess: &'a Session,
262     pub span: Span,
263     pub ident: &'a str,
264     pub crate_name: &'a str,
265     pub hash: Option<&'a Svh>,
266     pub triple: &'a str,
267     pub os: abi::Os,
268     pub filesearch: FileSearch<'a>,
269     pub root: &'a Option<CratePaths>,
270     pub rejected_via_hash: Vec<CrateMismatch>,
271     pub rejected_via_triple: Vec<CrateMismatch>,
272     pub should_match_name: bool,
273 }
274
275 pub struct Library {
276     pub dylib: Option<Path>,
277     pub rlib: Option<Path>,
278     pub metadata: MetadataBlob,
279 }
280
281 pub struct ArchiveMetadata {
282     _archive: ArchiveRO,
283     // See comments in ArchiveMetadata::new for why this is static
284     data: &'static [u8],
285 }
286
287 pub struct CratePaths {
288     pub ident: String,
289     pub dylib: Option<Path>,
290     pub rlib: Option<Path>
291 }
292
293 impl CratePaths {
294     fn paths(&self) -> Vec<Path> {
295         match (&self.dylib, &self.rlib) {
296             (&None,    &None)              => vec!(),
297             (&Some(ref p), &None) |
298             (&None, &Some(ref p))          => vec!(p.clone()),
299             (&Some(ref p1), &Some(ref p2)) => vec!(p1.clone(), p2.clone()),
300         }
301     }
302 }
303
304 impl<'a> Context<'a> {
305     pub fn maybe_load_library_crate(&mut self) -> Option<Library> {
306         self.find_library_crate()
307     }
308
309     pub fn load_library_crate(&mut self) -> Library {
310         match self.find_library_crate() {
311             Some(t) => t,
312             None => {
313                 self.report_load_errs();
314                 unreachable!()
315             }
316         }
317     }
318
319     pub fn report_load_errs(&mut self) {
320         let message = if self.rejected_via_hash.len() > 0 {
321             format!("found possibly newer version of crate `{}`",
322                     self.ident)
323         } else if self.rejected_via_triple.len() > 0 {
324             format!("found incorrect triple for crate `{}`", self.ident)
325         } else {
326             format!("can't find crate for `{}`", self.ident)
327         };
328         let message = match self.root {
329             &None => message,
330             &Some(ref r) => format!("{} which `{}` depends on",
331                                     message, r.ident)
332         };
333         self.sess.span_err(self.span, message.as_slice());
334
335         let mismatches = self.rejected_via_triple.iter();
336         if self.rejected_via_triple.len() > 0 {
337             self.sess.span_note(self.span,
338                                 format!("expected triple of {}",
339                                         self.triple).as_slice());
340             for (i, &CrateMismatch{ ref path, ref got }) in mismatches.enumerate() {
341                 self.sess.fileline_note(self.span,
342                     format!("crate `{}` path {}{}, triple {}: {}",
343                             self.ident, "#", i+1, got, path.display()).as_slice());
344             }
345         }
346         if self.rejected_via_hash.len() > 0 {
347             self.sess.span_note(self.span, "perhaps this crate needs \
348                                             to be recompiled?");
349             let mismatches = self.rejected_via_hash.iter();
350             for (i, &CrateMismatch{ ref path, .. }) in mismatches.enumerate() {
351                 self.sess.fileline_note(self.span,
352                     format!("crate `{}` path {}{}: {}",
353                             self.ident, "#", i+1, path.display()).as_slice());
354             }
355             match self.root {
356                 &None => {}
357                 &Some(ref r) => {
358                     for (i, path) in r.paths().iter().enumerate() {
359                         self.sess.fileline_note(self.span,
360                             format!("crate `{}` path #{}: {}",
361                                     r.ident, i+1, path.display()).as_slice());
362                     }
363                 }
364             }
365         }
366         self.sess.abort_if_errors();
367     }
368
369     fn find_library_crate(&mut self) -> Option<Library> {
370         // If an SVH is specified, then this is a transitive dependency that
371         // must be loaded via -L plus some filtering.
372         if self.hash.is_none() {
373             self.should_match_name = false;
374             match self.find_commandline_library() {
375                 Some(l) => return Some(l),
376                 None => {}
377             }
378             self.should_match_name = true;
379         }
380
381         let dypair = self.dylibname();
382
383         // want: crate_name.dir_part() + prefix + crate_name.file_part + "-"
384         let dylib_prefix = dypair.map(|(prefix, _)| {
385             format!("{}{}", prefix, self.crate_name)
386         });
387         let rlib_prefix = format!("lib{}", self.crate_name);
388
389         let mut candidates = HashMap::new();
390
391         // First, find all possible candidate rlibs and dylibs purely based on
392         // the name of the files themselves. We're trying to match against an
393         // exact crate name and a possibly an exact hash.
394         //
395         // During this step, we can filter all found libraries based on the
396         // name and id found in the crate id (we ignore the path portion for
397         // filename matching), as well as the exact hash (if specified). If we
398         // end up having many candidates, we must look at the metadata to
399         // perform exact matches against hashes/crate ids. Note that opening up
400         // the metadata is where we do an exact match against the full contents
401         // of the crate id (path/name/id).
402         //
403         // The goal of this step is to look at as little metadata as possible.
404         self.filesearch.search(|path| {
405             let file = match path.filename_str() {
406                 None => return FileDoesntMatch,
407                 Some(file) => file,
408             };
409             let (hash, rlib) = if file.starts_with(rlib_prefix.as_slice()) &&
410                     file.ends_with(".rlib") {
411                 (file.slice(rlib_prefix.len(), file.len() - ".rlib".len()),
412                  true)
413             } else if dypair.map_or(false, |(_, suffix)| {
414                 file.starts_with(dylib_prefix.get_ref().as_slice()) &&
415                 file.ends_with(suffix)
416             }) {
417                 let (_, suffix) = dypair.unwrap();
418                 let dylib_prefix = dylib_prefix.get_ref().as_slice();
419                 (file.slice(dylib_prefix.len(), file.len() - suffix.len()),
420                  false)
421             } else {
422                 return FileDoesntMatch
423             };
424             info!("lib candidate: {}", path.display());
425             let slot = candidates.find_or_insert_with(hash.to_string(), |_| {
426                 (HashSet::new(), HashSet::new())
427             });
428             let (ref mut rlibs, ref mut dylibs) = *slot;
429             if rlib {
430                 rlibs.insert(fs::realpath(path).unwrap());
431             } else {
432                 dylibs.insert(fs::realpath(path).unwrap());
433             }
434             FileMatches
435         });
436
437         // We have now collected all known libraries into a set of candidates
438         // keyed of the filename hash listed. For each filename, we also have a
439         // list of rlibs/dylibs that apply. Here, we map each of these lists
440         // (per hash), to a Library candidate for returning.
441         //
442         // A Library candidate is created if the metadata for the set of
443         // libraries corresponds to the crate id and hash criteria that this
444         // search is being performed for.
445         let mut libraries = Vec::new();
446         for (_hash, (rlibs, dylibs)) in candidates.move_iter() {
447             let mut metadata = None;
448             let rlib = self.extract_one(rlibs, "rlib", &mut metadata);
449             let dylib = self.extract_one(dylibs, "dylib", &mut metadata);
450             match metadata {
451                 Some(metadata) => {
452                     libraries.push(Library {
453                         dylib: dylib,
454                         rlib: rlib,
455                         metadata: metadata,
456                     })
457                 }
458                 None => {}
459             }
460         }
461
462         // Having now translated all relevant found hashes into libraries, see
463         // what we've got and figure out if we found multiple candidates for
464         // libraries or not.
465         match libraries.len() {
466             0 => None,
467             1 => Some(libraries.move_iter().next().unwrap()),
468             _ => {
469                 self.sess.span_err(self.span,
470                     format!("multiple matching crates for `{}`",
471                             self.crate_name).as_slice());
472                 self.sess.note("candidates:");
473                 for lib in libraries.iter() {
474                     match lib.dylib {
475                         Some(ref p) => {
476                             self.sess.note(format!("path: {}",
477                                                    p.display()).as_slice());
478                         }
479                         None => {}
480                     }
481                     match lib.rlib {
482                         Some(ref p) => {
483                             self.sess.note(format!("path: {}",
484                                                    p.display()).as_slice());
485                         }
486                         None => {}
487                     }
488                     let data = lib.metadata.as_slice();
489                     let name = decoder::get_crate_name(data);
490                     note_crate_name(self.sess.diagnostic(), name.as_slice());
491                 }
492                 None
493             }
494         }
495     }
496
497     // Attempts to extract *one* library from the set `m`. If the set has no
498     // elements, `None` is returned. If the set has more than one element, then
499     // the errors and notes are emitted about the set of libraries.
500     //
501     // With only one library in the set, this function will extract it, and then
502     // read the metadata from it if `*slot` is `None`. If the metadata couldn't
503     // be read, it is assumed that the file isn't a valid rust library (no
504     // errors are emitted).
505     fn extract_one(&mut self, m: HashSet<Path>, flavor: &str,
506                    slot: &mut Option<MetadataBlob>) -> Option<Path> {
507         let mut ret = None::<Path>;
508         let mut error = 0u;
509
510         if slot.is_some() {
511             // FIXME(#10786): for an optimization, we only read one of the
512             //                library's metadata sections. In theory we should
513             //                read both, but reading dylib metadata is quite
514             //                slow.
515             if m.len() == 0 {
516                 return None
517             } else if m.len() == 1 {
518                 return Some(m.move_iter().next().unwrap())
519             }
520         }
521
522         for lib in m.move_iter() {
523             info!("{} reading metadata from: {}", flavor, lib.display());
524             let metadata = match get_metadata_section(self.os, &lib) {
525                 Ok(blob) => {
526                     if self.crate_matches(blob.as_slice(), &lib) {
527                         blob
528                     } else {
529                         info!("metadata mismatch");
530                         continue
531                     }
532                 }
533                 Err(_) => {
534                     info!("no metadata found");
535                     continue
536                 }
537             };
538             if ret.is_some() {
539                 self.sess.span_err(self.span,
540                                    format!("multiple {} candidates for `{}` \
541                                             found",
542                                            flavor,
543                                            self.crate_name).as_slice());
544                 self.sess.span_note(self.span,
545                                     format!(r"candidate #1: {}",
546                                             ret.get_ref()
547                                                .display()).as_slice());
548                 error = 1;
549                 ret = None;
550             }
551             if error > 0 {
552                 error += 1;
553                 self.sess.span_note(self.span,
554                                     format!(r"candidate #{}: {}", error,
555                                             lib.display()).as_slice());
556                 continue
557             }
558             *slot = Some(metadata);
559             ret = Some(lib);
560         }
561         return if error > 0 {None} else {ret}
562     }
563
564     fn crate_matches(&mut self, crate_data: &[u8], libpath: &Path) -> bool {
565         if self.should_match_name {
566             match decoder::maybe_get_crate_name(crate_data) {
567                 Some(ref name) if self.crate_name == name.as_slice() => {}
568                 _ => { info!("Rejecting via crate name"); return false }
569             }
570         }
571         let hash = match decoder::maybe_get_crate_hash(crate_data) {
572             Some(hash) => hash, None => {
573                 info!("Rejecting via lack of crate hash");
574                 return false;
575             }
576         };
577
578         let triple = match decoder::get_crate_triple(crate_data) {
579             None => { debug!("triple not present"); return false }
580             Some(t) => t,
581         };
582         if triple.as_slice() != self.triple {
583             info!("Rejecting via crate triple: expected {} got {}", self.triple, triple);
584             self.rejected_via_triple.push(CrateMismatch {
585                 path: libpath.clone(),
586                 got: triple.to_string()
587             });
588             return false;
589         }
590
591         match self.hash {
592             None => true,
593             Some(myhash) => {
594                 if *myhash != hash {
595                     info!("Rejecting via hash: expected {} got {}", *myhash, hash);
596                     self.rejected_via_hash.push(CrateMismatch {
597                         path: libpath.clone(),
598                         got: myhash.as_str().to_string()
599                     });
600                     false
601                 } else {
602                     true
603                 }
604             }
605         }
606     }
607
608
609     // Returns the corresponding (prefix, suffix) that files need to have for
610     // dynamic libraries
611     fn dylibname(&self) -> Option<(&'static str, &'static str)> {
612         match self.os {
613             abi::OsWin32 => Some((WIN32_DLL_PREFIX, WIN32_DLL_SUFFIX)),
614             abi::OsMacos => Some((MACOS_DLL_PREFIX, MACOS_DLL_SUFFIX)),
615             abi::OsLinux => Some((LINUX_DLL_PREFIX, LINUX_DLL_SUFFIX)),
616             abi::OsAndroid => Some((ANDROID_DLL_PREFIX, ANDROID_DLL_SUFFIX)),
617             abi::OsFreebsd => Some((FREEBSD_DLL_PREFIX, FREEBSD_DLL_SUFFIX)),
618             abi::OsiOS => None,
619         }
620     }
621
622     fn find_commandline_library(&mut self) -> Option<Library> {
623         let locs = match self.sess.opts.externs.find_equiv(&self.crate_name) {
624             Some(s) => s,
625             None => return None,
626         };
627
628         // First, filter out all libraries that look suspicious. We only accept
629         // files which actually exist that have the correct naming scheme for
630         // rlibs/dylibs.
631         let sess = self.sess;
632         let dylibname = self.dylibname();
633         let mut locs = locs.iter().map(|l| Path::new(l.as_slice())).filter(|loc| {
634             if !loc.exists() {
635                 sess.err(format!("extern location does not exist: {}",
636                                  loc.display()).as_slice());
637                 return false;
638             }
639             let file = loc.filename_str().unwrap();
640             if file.starts_with("lib") && file.ends_with(".rlib") {
641                 return true
642             } else {
643                 match dylibname {
644                     Some((prefix, suffix)) => {
645                         if file.starts_with(prefix) && file.ends_with(suffix) {
646                             return true
647                         }
648                     }
649                     None => {}
650                 }
651             }
652             sess.err(format!("extern location is of an unknown type: {}",
653                              loc.display()).as_slice());
654             false
655         });
656
657         // Now that we have an itertor of good candidates, make sure there's at
658         // most one rlib and at most one dylib.
659         let mut rlibs = HashSet::new();
660         let mut dylibs = HashSet::new();
661         for loc in locs {
662             if loc.filename_str().unwrap().ends_with(".rlib") {
663                 rlibs.insert(loc.clone());
664             } else {
665                 dylibs.insert(loc.clone());
666             }
667         }
668
669         // Extract the rlib/dylib pair.
670         let mut metadata = None;
671         let rlib = self.extract_one(rlibs, "rlib", &mut metadata);
672         let dylib = self.extract_one(dylibs, "dylib", &mut metadata);
673
674         if rlib.is_none() && dylib.is_none() { return None }
675         match metadata {
676             Some(metadata) => Some(Library {
677                 dylib: dylib,
678                 rlib: rlib,
679                 metadata: metadata,
680             }),
681             None => None,
682         }
683     }
684 }
685
686 pub fn note_crate_name(diag: &SpanHandler, name: &str) {
687     diag.handler().note(format!("crate name: {}", name).as_slice());
688 }
689
690 impl ArchiveMetadata {
691     fn new(ar: ArchiveRO) -> Option<ArchiveMetadata> {
692         let data: &'static [u8] = {
693             let data = match ar.read(METADATA_FILENAME) {
694                 Some(data) => data,
695                 None => {
696                     debug!("didn't find '{}' in the archive", METADATA_FILENAME);
697                     return None;
698                 }
699             };
700             // This data is actually a pointer inside of the archive itself, but
701             // we essentially want to cache it because the lookup inside the
702             // archive is a fairly expensive operation (and it's queried for
703             // *very* frequently). For this reason, we transmute it to the
704             // static lifetime to put into the struct. Note that the buffer is
705             // never actually handed out with a static lifetime, but rather the
706             // buffer is loaned with the lifetime of this containing object.
707             // Hence, we're guaranteed that the buffer will never be used after
708             // this object is dead, so this is a safe operation to transmute and
709             // store the data as a static buffer.
710             unsafe { mem::transmute(data) }
711         };
712         Some(ArchiveMetadata {
713             _archive: ar,
714             data: data,
715         })
716     }
717
718     pub fn as_slice<'a>(&'a self) -> &'a [u8] { self.data }
719 }
720
721 // Just a small wrapper to time how long reading metadata takes.
722 fn get_metadata_section(os: abi::Os, filename: &Path) -> Result<MetadataBlob, String> {
723     let start = time::precise_time_ns();
724     let ret = get_metadata_section_imp(os, filename);
725     info!("reading {} => {}ms", filename.filename_display(),
726            (time::precise_time_ns() - start) / 1000000);
727     return ret;
728 }
729
730 fn get_metadata_section_imp(os: abi::Os, filename: &Path) -> Result<MetadataBlob, String> {
731     if !filename.exists() {
732         return Err(format!("no such file: '{}'", filename.display()));
733     }
734     if filename.filename_str().unwrap().ends_with(".rlib") {
735         // Use ArchiveRO for speed here, it's backed by LLVM and uses mmap
736         // internally to read the file. We also avoid even using a memcpy by
737         // just keeping the archive along while the metadata is in use.
738         let archive = match ArchiveRO::open(filename) {
739             Some(ar) => ar,
740             None => {
741                 debug!("llvm didn't like `{}`", filename.display());
742                 return Err(format!("failed to read rlib metadata: '{}'",
743                                    filename.display()));
744             }
745         };
746         return match ArchiveMetadata::new(archive).map(|ar| MetadataArchive(ar)) {
747             None => {
748                 return Err((format!("failed to read rlib metadata: '{}'",
749                                     filename.display())))
750             }
751             Some(blob) => return Ok(blob)
752         }
753     }
754     unsafe {
755         let mb = filename.with_c_str(|buf| {
756             llvm::LLVMRustCreateMemoryBufferWithContentsOfFile(buf)
757         });
758         if mb as int == 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 = str::raw::from_buf_len(name_buf as *const u8,
774                                               name_len as uint);
775             debug!("get_metadata_section: name {}", name);
776             if read_meta_section_name(os).as_slice() == name.as_slice() {
777                 let cbuf = llvm::LLVMGetSectionContents(si.llsi);
778                 let csz = llvm::LLVMGetSectionSize(si.llsi) as uint;
779                 let mut found =
780                     Err(format!("metadata not found: '{}'", filename.display()));
781                 let cvbuf: *const u8 = mem::transmute(cbuf);
782                 let vlen = encoder::metadata_encoding_version.len();
783                 debug!("checking {} bytes of metadata-version stamp",
784                        vlen);
785                 let minsz = cmp::min(vlen, csz);
786                 let version_ok = slice::raw::buf_as_slice(cvbuf, minsz,
787                     |buf0| buf0 == encoder::metadata_encoding_version);
788                 if !version_ok {
789                     return Err((format!("incompatible metadata version found: '{}'",
790                                         filename.display())));
791                 }
792
793                 let cvbuf1 = cvbuf.offset(vlen as int);
794                 debug!("inflating {} bytes of compressed metadata",
795                        csz - vlen);
796                 slice::raw::buf_as_slice(cvbuf1, csz-vlen, |bytes| {
797                     match flate::inflate_bytes(bytes) {
798                         Some(inflated) => found = Ok(MetadataVec(inflated)),
799                         None => {
800                             found =
801                                 Err(format!("failed to decompress \
802                                              metadata for: '{}'",
803                                             filename.display()))
804                         }
805                     }
806                 });
807                 if found.is_ok() {
808                     return found;
809                 }
810             }
811             llvm::LLVMMoveToNextSection(si.llsi);
812         }
813         return Err(format!("metadata not found: '{}'", filename.display()));
814     }
815 }
816
817 pub fn meta_section_name(os: abi::Os) -> Option<&'static str> {
818     match os {
819         abi::OsMacos => Some("__DATA,__note.rustc"),
820         abi::OsiOS => Some("__DATA,__note.rustc"),
821         abi::OsWin32 => Some(".note.rustc"),
822         abi::OsLinux => Some(".note.rustc"),
823         abi::OsAndroid => Some(".note.rustc"),
824         abi::OsFreebsd => Some(".note.rustc")
825     }
826 }
827
828 pub fn read_meta_section_name(os: abi::Os) -> &'static str {
829     match os {
830         abi::OsMacos => "__note.rustc",
831         abi::OsiOS => unreachable!(),
832         abi::OsWin32 => ".note.rustc",
833         abi::OsLinux => ".note.rustc",
834         abi::OsAndroid => ".note.rustc",
835         abi::OsFreebsd => ".note.rustc"
836     }
837 }
838
839 // A diagnostic function for dumping crate metadata to an output stream
840 pub fn list_file_metadata(os: abi::Os, path: &Path,
841                           out: &mut io::Writer) -> io::IoResult<()> {
842     match get_metadata_section(os, path) {
843         Ok(bytes) => decoder::list_crate_metadata(bytes.as_slice(), out),
844         Err(msg) => {
845             write!(out, "{}\n", msg)
846         }
847     }
848 }