]>
Commit | Line | Data |
---|---|---|
85aaf69f | 1 | // Copyright 2012-2015 The Rust Project Developers. See the COPYRIGHT |
223e47cc LB |
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 | ||
223e47cc | 11 | //! Finds crate binaries and loads their metadata |
1a4d82fc JJ |
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 | |
9346a6ac | 132 | //! > would like you to assume that the library is located at |
1a4d82fc JJ |
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 | |
c30ab7b3 | 213 | //! metadata::locator or metadata::creader for all the juicy details! |
223e47cc | 214 | |
9e0c209e | 215 | use cstore::MetadataBlob; |
c30ab7b3 SL |
216 | use creader::Library; |
217 | use schema::{METADATA_HEADER, rustc_version}; | |
92a42be0 | 218 | |
54a0048b | 219 | use rustc::hir::svh::Svh; |
92a42be0 SL |
220 | use rustc::session::Session; |
221 | use rustc::session::filesearch::{FileSearch, FileMatches, FileDoesntMatch}; | |
222 | use rustc::session::search_paths::PathKind; | |
223 | use rustc::util::common; | |
9e0c209e | 224 | use rustc::util::nodemap::FnvHashMap; |
92a42be0 SL |
225 | |
226 | use rustc_llvm as llvm; | |
227 | use rustc_llvm::{False, ObjectFile, mk_section_iter}; | |
228 | use rustc_llvm::archive_ro::ArchiveRO; | |
3157f602 XL |
229 | use errors::DiagnosticBuilder; |
230 | use syntax_pos::Span; | |
85aaf69f | 231 | use rustc_back::target::Target; |
1a4d82fc | 232 | |
1a4d82fc | 233 | use std::cmp; |
a7813a04 | 234 | use std::fmt; |
d9579d0f | 235 | use std::fs; |
c34b1796 AL |
236 | use std::io; |
237 | use std::path::{Path, PathBuf}; | |
970d7e83 | 238 | use std::ptr; |
1a4d82fc | 239 | use std::slice; |
92a42be0 | 240 | use std::time::Instant; |
1a4d82fc JJ |
241 | |
242 | use flate; | |
243 | ||
244 | pub struct CrateMismatch { | |
c34b1796 | 245 | path: PathBuf, |
1a4d82fc | 246 | got: String, |
223e47cc LB |
247 | } |
248 | ||
1a4d82fc JJ |
249 | pub struct Context<'a> { |
250 | pub sess: &'a Session, | |
251 | pub span: Span, | |
252 | pub ident: &'a str, | |
253 | pub crate_name: &'a str, | |
254 | pub hash: Option<&'a Svh>, | |
85aaf69f SL |
255 | // points to either self.sess.target.target or self.sess.host, must match triple |
256 | pub target: &'a Target, | |
1a4d82fc JJ |
257 | pub triple: &'a str, |
258 | pub filesearch: FileSearch<'a>, | |
259 | pub root: &'a Option<CratePaths>, | |
260 | pub rejected_via_hash: Vec<CrateMismatch>, | |
261 | pub rejected_via_triple: Vec<CrateMismatch>, | |
85aaf69f | 262 | pub rejected_via_kind: Vec<CrateMismatch>, |
a7813a04 | 263 | pub rejected_via_version: Vec<CrateMismatch>, |
1a4d82fc | 264 | pub should_match_name: bool, |
223e47cc LB |
265 | } |
266 | ||
1a4d82fc JJ |
267 | pub struct ArchiveMetadata { |
268 | _archive: ArchiveRO, | |
269 | // points into self._archive | |
270 | data: *const [u8], | |
223e47cc LB |
271 | } |
272 | ||
1a4d82fc JJ |
273 | pub struct CratePaths { |
274 | pub ident: String, | |
c34b1796 | 275 | pub dylib: Option<PathBuf>, |
c30ab7b3 | 276 | pub rlib: Option<PathBuf>, |
223e47cc LB |
277 | } |
278 | ||
c1a9b12d SL |
279 | pub const METADATA_FILENAME: &'static str = "rust.metadata.bin"; |
280 | ||
a7813a04 XL |
281 | #[derive(Copy, Clone, PartialEq)] |
282 | enum CrateFlavor { | |
283 | Rlib, | |
c30ab7b3 | 284 | Dylib, |
a7813a04 XL |
285 | } |
286 | ||
287 | impl fmt::Display for CrateFlavor { | |
288 | fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { | |
289 | f.write_str(match *self { | |
290 | CrateFlavor::Rlib => "rlib", | |
c30ab7b3 | 291 | CrateFlavor::Dylib => "dylib", |
a7813a04 XL |
292 | }) |
293 | } | |
294 | } | |
295 | ||
1a4d82fc | 296 | impl CratePaths { |
c34b1796 | 297 | fn paths(&self) -> Vec<PathBuf> { |
1a4d82fc | 298 | match (&self.dylib, &self.rlib) { |
c30ab7b3 | 299 | (&None, &None) => vec![], |
1a4d82fc | 300 | (&Some(ref p), &None) | |
c30ab7b3 SL |
301 | (&None, &Some(ref p)) => vec![p.clone()], |
302 | (&Some(ref p1), &Some(ref p2)) => vec![p1.clone(), p2.clone()], | |
1a4d82fc JJ |
303 | } |
304 | } | |
305 | } | |
306 | ||
307 | impl<'a> Context<'a> { | |
308 | pub fn maybe_load_library_crate(&mut self) -> Option<Library> { | |
309 | self.find_library_crate() | |
310 | } | |
311 | ||
312 | pub fn load_library_crate(&mut self) -> Library { | |
c30ab7b3 | 313 | self.find_library_crate().unwrap_or_else(|| self.report_errs()) |
1a4d82fc JJ |
314 | } |
315 | ||
c30ab7b3 | 316 | pub fn report_errs(&mut self) -> ! { |
b039eaaf SL |
317 | let add = match self.root { |
318 | &None => String::new(), | |
c30ab7b3 | 319 | &Some(ref r) => format!(" which `{}` depends on", r.ident), |
b039eaaf | 320 | }; |
9cc50fc6 | 321 | let mut err = if !self.rejected_via_hash.is_empty() { |
c30ab7b3 SL |
322 | struct_span_err!(self.sess, |
323 | self.span, | |
324 | E0460, | |
9cc50fc6 | 325 | "found possibly newer version of crate `{}`{}", |
c30ab7b3 SL |
326 | self.ident, |
327 | add) | |
9346a6ac | 328 | } else if !self.rejected_via_triple.is_empty() { |
c30ab7b3 SL |
329 | struct_span_err!(self.sess, |
330 | self.span, | |
331 | E0461, | |
9cc50fc6 | 332 | "couldn't find crate `{}` with expected target triple {}{}", |
c30ab7b3 SL |
333 | self.ident, |
334 | self.triple, | |
335 | add) | |
9346a6ac | 336 | } else if !self.rejected_via_kind.is_empty() { |
c30ab7b3 SL |
337 | struct_span_err!(self.sess, |
338 | self.span, | |
339 | E0462, | |
9cc50fc6 | 340 | "found staticlib `{}` instead of rlib or dylib{}", |
c30ab7b3 SL |
341 | self.ident, |
342 | add) | |
a7813a04 | 343 | } else if !self.rejected_via_version.is_empty() { |
c30ab7b3 SL |
344 | struct_span_err!(self.sess, |
345 | self.span, | |
346 | E0514, | |
a7813a04 | 347 | "found crate `{}` compiled by an incompatible version of rustc{}", |
c30ab7b3 SL |
348 | self.ident, |
349 | add) | |
1a4d82fc | 350 | } else { |
c30ab7b3 SL |
351 | let mut err = struct_span_err!(self.sess, |
352 | self.span, | |
353 | E0463, | |
9e0c209e | 354 | "can't find crate for `{}`{}", |
c30ab7b3 SL |
355 | self.ident, |
356 | add); | |
9e0c209e SL |
357 | err.span_label(self.span, &format!("can't find crate")); |
358 | err | |
9cc50fc6 | 359 | }; |
1a4d82fc | 360 | |
9346a6ac | 361 | if !self.rejected_via_triple.is_empty() { |
1a4d82fc | 362 | let mismatches = self.rejected_via_triple.iter(); |
c30ab7b3 | 363 | for (i, &CrateMismatch { ref path, ref got }) in mismatches.enumerate() { |
a7813a04 | 364 | err.note(&format!("crate `{}`, path #{}, triple {}: {}", |
c30ab7b3 SL |
365 | self.ident, |
366 | i + 1, | |
367 | got, | |
368 | path.display())); | |
1a4d82fc JJ |
369 | } |
370 | } | |
9346a6ac | 371 | if !self.rejected_via_hash.is_empty() { |
a7813a04 | 372 | err.note("perhaps that crate needs to be recompiled?"); |
1a4d82fc | 373 | let mismatches = self.rejected_via_hash.iter(); |
c30ab7b3 SL |
374 | for (i, &CrateMismatch { ref path, .. }) in mismatches.enumerate() { |
375 | err.note(&format!("crate `{}` path #{}: {}", self.ident, i + 1, path.display())); | |
1a4d82fc JJ |
376 | } |
377 | match self.root { | |
378 | &None => {} | |
379 | &Some(ref r) => { | |
380 | for (i, path) in r.paths().iter().enumerate() { | |
a7813a04 | 381 | err.note(&format!("crate `{}` path #{}: {}", |
c30ab7b3 SL |
382 | r.ident, |
383 | i + 1, | |
384 | path.display())); | |
970d7e83 | 385 | } |
223e47cc | 386 | } |
223e47cc | 387 | } |
1a4d82fc | 388 | } |
9346a6ac | 389 | if !self.rejected_via_kind.is_empty() { |
a7813a04 | 390 | err.help("please recompile that crate using --crate-type lib"); |
85aaf69f SL |
391 | let mismatches = self.rejected_via_kind.iter(); |
392 | for (i, &CrateMismatch { ref path, .. }) in mismatches.enumerate() { | |
c30ab7b3 | 393 | err.note(&format!("crate `{}` path #{}: {}", self.ident, i + 1, path.display())); |
a7813a04 XL |
394 | } |
395 | } | |
396 | if !self.rejected_via_version.is_empty() { | |
397 | err.help(&format!("please recompile that crate using this compiler ({})", | |
c30ab7b3 | 398 | rustc_version())); |
a7813a04 XL |
399 | let mismatches = self.rejected_via_version.iter(); |
400 | for (i, &CrateMismatch { ref path, ref got }) in mismatches.enumerate() { | |
401 | err.note(&format!("crate `{}` path #{}: {} compiled by {:?}", | |
c30ab7b3 SL |
402 | self.ident, |
403 | i + 1, | |
404 | path.display(), | |
405 | got)); | |
85aaf69f SL |
406 | } |
407 | } | |
9cc50fc6 SL |
408 | |
409 | err.emit(); | |
1a4d82fc | 410 | self.sess.abort_if_errors(); |
54a0048b | 411 | unreachable!(); |
1a4d82fc JJ |
412 | } |
413 | ||
414 | fn find_library_crate(&mut self) -> Option<Library> { | |
415 | // If an SVH is specified, then this is a transitive dependency that | |
416 | // must be loaded via -L plus some filtering. | |
417 | if self.hash.is_none() { | |
418 | self.should_match_name = false; | |
85aaf69f | 419 | if let Some(s) = self.sess.opts.externs.get(self.crate_name) { |
5bcae85e | 420 | return self.find_commandline_library(s.iter()); |
1a4d82fc JJ |
421 | } |
422 | self.should_match_name = true; | |
423 | } | |
424 | ||
425 | let dypair = self.dylibname(); | |
7453a54e | 426 | let staticpair = self.staticlibname(); |
1a4d82fc JJ |
427 | |
428 | // want: crate_name.dir_part() + prefix + crate_name.file_part + "-" | |
429 | let dylib_prefix = format!("{}{}", dypair.0, self.crate_name); | |
430 | let rlib_prefix = format!("lib{}", self.crate_name); | |
7453a54e | 431 | let staticlib_prefix = format!("{}{}", staticpair.0, self.crate_name); |
1a4d82fc | 432 | |
9e0c209e | 433 | let mut candidates = FnvHashMap(); |
c30ab7b3 | 434 | let mut staticlibs = vec![]; |
1a4d82fc JJ |
435 | |
436 | // First, find all possible candidate rlibs and dylibs purely based on | |
437 | // the name of the files themselves. We're trying to match against an | |
438 | // exact crate name and a possibly an exact hash. | |
439 | // | |
440 | // During this step, we can filter all found libraries based on the | |
441 | // name and id found in the crate id (we ignore the path portion for | |
442 | // filename matching), as well as the exact hash (if specified). If we | |
443 | // end up having many candidates, we must look at the metadata to | |
444 | // perform exact matches against hashes/crate ids. Note that opening up | |
445 | // the metadata is where we do an exact match against the full contents | |
446 | // of the crate id (path/name/id). | |
447 | // | |
448 | // The goal of this step is to look at as little metadata as possible. | |
85aaf69f | 449 | self.filesearch.search(|path, kind| { |
c34b1796 | 450 | let file = match path.file_name().and_then(|s| s.to_str()) { |
1a4d82fc JJ |
451 | None => return FileDoesntMatch, |
452 | Some(file) => file, | |
453 | }; | |
c30ab7b3 SL |
454 | let (hash, rlib) = if file.starts_with(&rlib_prefix[..]) && file.ends_with(".rlib") { |
455 | (&file[(rlib_prefix.len())..(file.len() - ".rlib".len())], true) | |
85aaf69f | 456 | } else if file.starts_with(&dylib_prefix) && |
c30ab7b3 SL |
457 | file.ends_with(&dypair.1) { |
458 | (&file[(dylib_prefix.len())..(file.len() - dypair.1.len())], false) | |
1a4d82fc | 459 | } else { |
c30ab7b3 | 460 | if file.starts_with(&staticlib_prefix[..]) && file.ends_with(&staticpair.1) { |
85aaf69f | 461 | staticlibs.push(CrateMismatch { |
c34b1796 | 462 | path: path.to_path_buf(), |
c30ab7b3 | 463 | got: "static".to_string(), |
85aaf69f SL |
464 | }); |
465 | } | |
c30ab7b3 | 466 | return FileDoesntMatch; |
1a4d82fc JJ |
467 | }; |
468 | info!("lib candidate: {}", path.display()); | |
469 | ||
470 | let hash_str = hash.to_string(); | |
c34b1796 | 471 | let slot = candidates.entry(hash_str) |
c30ab7b3 | 472 | .or_insert_with(|| (FnvHashMap(), FnvHashMap())); |
1a4d82fc | 473 | let (ref mut rlibs, ref mut dylibs) = *slot; |
c30ab7b3 SL |
474 | fs::canonicalize(path) |
475 | .map(|p| { | |
476 | if rlib { | |
477 | rlibs.insert(p, kind); | |
478 | } else { | |
479 | dylibs.insert(p, kind); | |
480 | } | |
481 | FileMatches | |
482 | }) | |
483 | .unwrap_or(FileDoesntMatch) | |
1a4d82fc | 484 | }); |
62682a34 | 485 | self.rejected_via_kind.extend(staticlibs); |
1a4d82fc JJ |
486 | |
487 | // We have now collected all known libraries into a set of candidates | |
488 | // keyed of the filename hash listed. For each filename, we also have a | |
489 | // list of rlibs/dylibs that apply. Here, we map each of these lists | |
490 | // (per hash), to a Library candidate for returning. | |
491 | // | |
492 | // A Library candidate is created if the metadata for the set of | |
493 | // libraries corresponds to the crate id and hash criteria that this | |
494 | // search is being performed for. | |
9e0c209e | 495 | let mut libraries = FnvHashMap(); |
85aaf69f | 496 | for (_hash, (rlibs, dylibs)) in candidates { |
a7813a04 XL |
497 | let mut slot = None; |
498 | let rlib = self.extract_one(rlibs, CrateFlavor::Rlib, &mut slot); | |
499 | let dylib = self.extract_one(dylibs, CrateFlavor::Dylib, &mut slot); | |
500 | if let Some((h, m)) = slot { | |
c30ab7b3 SL |
501 | libraries.insert(h, |
502 | Library { | |
503 | dylib: dylib, | |
504 | rlib: rlib, | |
505 | metadata: m, | |
506 | }); | |
1a4d82fc JJ |
507 | } |
508 | } | |
509 | ||
510 | // Having now translated all relevant found hashes into libraries, see | |
511 | // what we've got and figure out if we found multiple candidates for | |
512 | // libraries or not. | |
513 | match libraries.len() { | |
514 | 0 => None, | |
a7813a04 | 515 | 1 => Some(libraries.into_iter().next().unwrap().1), |
970d7e83 | 516 | _ => { |
c30ab7b3 SL |
517 | let mut err = struct_span_err!(self.sess, |
518 | self.span, | |
519 | E0464, | |
9cc50fc6 SL |
520 | "multiple matching crates for `{}`", |
521 | self.crate_name); | |
522 | err.note("candidates:"); | |
a7813a04 | 523 | for (_, lib) in libraries { |
3157f602 XL |
524 | if let Some((ref p, _)) = lib.dylib { |
525 | err.note(&format!("path: {}", p.display())); | |
1a4d82fc | 526 | } |
3157f602 XL |
527 | if let Some((ref p, _)) = lib.rlib { |
528 | err.note(&format!("path: {}", p.display())); | |
1a4d82fc | 529 | } |
9e0c209e | 530 | note_crate_name(&mut err, &lib.metadata.get_root().name); |
1a4d82fc | 531 | } |
9cc50fc6 | 532 | err.emit(); |
970d7e83 LB |
533 | None |
534 | } | |
1a4d82fc JJ |
535 | } |
536 | } | |
537 | ||
538 | // Attempts to extract *one* library from the set `m`. If the set has no | |
539 | // elements, `None` is returned. If the set has more than one element, then | |
540 | // the errors and notes are emitted about the set of libraries. | |
541 | // | |
542 | // With only one library in the set, this function will extract it, and then | |
543 | // read the metadata from it if `*slot` is `None`. If the metadata couldn't | |
544 | // be read, it is assumed that the file isn't a valid rust library (no | |
545 | // errors are emitted). | |
c30ab7b3 SL |
546 | fn extract_one(&mut self, |
547 | m: FnvHashMap<PathBuf, PathKind>, | |
548 | flavor: CrateFlavor, | |
549 | slot: &mut Option<(Svh, MetadataBlob)>) | |
550 | -> Option<(PathBuf, PathKind)> { | |
a7813a04 | 551 | let mut ret: Option<(PathBuf, PathKind)> = None; |
85aaf69f | 552 | let mut error = 0; |
1a4d82fc JJ |
553 | |
554 | if slot.is_some() { | |
555 | // FIXME(#10786): for an optimization, we only read one of the | |
a7813a04 | 556 | // libraries' metadata sections. In theory we should |
1a4d82fc JJ |
557 | // read both, but reading dylib metadata is quite |
558 | // slow. | |
9346a6ac | 559 | if m.is_empty() { |
c30ab7b3 | 560 | return None; |
1a4d82fc | 561 | } else if m.len() == 1 { |
c30ab7b3 | 562 | return Some(m.into_iter().next().unwrap()); |
1a4d82fc JJ |
563 | } |
564 | } | |
565 | ||
9cc50fc6 | 566 | let mut err: Option<DiagnosticBuilder> = None; |
85aaf69f | 567 | for (lib, kind) in m { |
1a4d82fc | 568 | info!("{} reading metadata from: {}", flavor, lib.display()); |
a7813a04 | 569 | let (hash, metadata) = match get_metadata_section(self.target, flavor, &lib) { |
1a4d82fc | 570 | Ok(blob) => { |
9e0c209e | 571 | if let Some(h) = self.crate_matches(&blob, &lib) { |
a7813a04 | 572 | (h, blob) |
1a4d82fc JJ |
573 | } else { |
574 | info!("metadata mismatch"); | |
c30ab7b3 | 575 | continue; |
1a4d82fc | 576 | } |
970d7e83 | 577 | } |
92a42be0 SL |
578 | Err(err) => { |
579 | info!("no metadata found: {}", err); | |
c30ab7b3 | 580 | continue; |
1a4d82fc JJ |
581 | } |
582 | }; | |
a7813a04 XL |
583 | // If we see multiple hashes, emit an error about duplicate candidates. |
584 | if slot.as_ref().map_or(false, |s| s.0 != hash) { | |
c30ab7b3 SL |
585 | let mut e = struct_span_err!(self.sess, |
586 | self.span, | |
587 | E0465, | |
9cc50fc6 | 588 | "multiple {} candidates for `{}` found", |
c30ab7b3 SL |
589 | flavor, |
590 | self.crate_name); | |
9cc50fc6 SL |
591 | e.span_note(self.span, |
592 | &format!(r"candidate #1: {}", | |
c30ab7b3 SL |
593 | ret.as_ref() |
594 | .unwrap() | |
595 | .0 | |
596 | .display())); | |
9cc50fc6 SL |
597 | if let Some(ref mut e) = err { |
598 | e.emit(); | |
599 | } | |
600 | err = Some(e); | |
1a4d82fc | 601 | error = 1; |
a7813a04 | 602 | *slot = None; |
1a4d82fc JJ |
603 | } |
604 | if error > 0 { | |
605 | error += 1; | |
9cc50fc6 | 606 | err.as_mut().unwrap().span_note(self.span, |
c30ab7b3 SL |
607 | &format!(r"candidate #{}: {}", |
608 | error, | |
9cc50fc6 | 609 | lib.display())); |
c30ab7b3 | 610 | continue; |
970d7e83 | 611 | } |
a7813a04 | 612 | *slot = Some((hash, metadata)); |
85aaf69f | 613 | ret = Some((lib, kind)); |
1a4d82fc | 614 | } |
9cc50fc6 SL |
615 | |
616 | if error > 0 { | |
617 | err.unwrap().emit(); | |
618 | None | |
619 | } else { | |
620 | ret | |
621 | } | |
1a4d82fc JJ |
622 | } |
623 | ||
9e0c209e SL |
624 | fn crate_matches(&mut self, metadata: &MetadataBlob, libpath: &Path) -> Option<Svh> { |
625 | let root = metadata.get_root(); | |
c30ab7b3 SL |
626 | let rustc_version = rustc_version(); |
627 | if root.rustc_version != rustc_version { | |
9e0c209e | 628 | info!("Rejecting via version: expected {} got {}", |
c30ab7b3 SL |
629 | rustc_version, |
630 | root.rustc_version); | |
a7813a04 XL |
631 | self.rejected_via_version.push(CrateMismatch { |
632 | path: libpath.to_path_buf(), | |
c30ab7b3 | 633 | got: root.rustc_version, |
a7813a04 XL |
634 | }); |
635 | return None; | |
636 | } | |
637 | ||
1a4d82fc | 638 | if self.should_match_name { |
9e0c209e | 639 | if self.crate_name != root.name { |
c30ab7b3 SL |
640 | info!("Rejecting via crate name"); |
641 | return None; | |
1a4d82fc JJ |
642 | } |
643 | } | |
1a4d82fc | 644 | |
9e0c209e SL |
645 | if root.triple != self.triple { |
646 | info!("Rejecting via crate triple: expected {} got {}", | |
c30ab7b3 SL |
647 | self.triple, |
648 | root.triple); | |
1a4d82fc | 649 | self.rejected_via_triple.push(CrateMismatch { |
c34b1796 | 650 | path: libpath.to_path_buf(), |
c30ab7b3 | 651 | got: root.triple, |
1a4d82fc | 652 | }); |
a7813a04 | 653 | return None; |
223e47cc | 654 | } |
223e47cc | 655 | |
a7813a04 | 656 | if let Some(myhash) = self.hash { |
9e0c209e | 657 | if *myhash != root.hash { |
c30ab7b3 | 658 | info!("Rejecting via hash: expected {} got {}", *myhash, root.hash); |
a7813a04 XL |
659 | self.rejected_via_hash.push(CrateMismatch { |
660 | path: libpath.to_path_buf(), | |
c30ab7b3 | 661 | got: myhash.to_string(), |
a7813a04 XL |
662 | }); |
663 | return None; | |
1a4d82fc | 664 | } |
223e47cc | 665 | } |
a7813a04 | 666 | |
9e0c209e | 667 | Some(root.hash) |
223e47cc | 668 | } |
223e47cc | 669 | |
1a4d82fc JJ |
670 | |
671 | // Returns the corresponding (prefix, suffix) that files need to have for | |
672 | // dynamic libraries | |
673 | fn dylibname(&self) -> (String, String) { | |
85aaf69f | 674 | let t = &self.target; |
1a4d82fc | 675 | (t.options.dll_prefix.clone(), t.options.dll_suffix.clone()) |
223e47cc | 676 | } |
223e47cc | 677 | |
7453a54e SL |
678 | // Returns the corresponding (prefix, suffix) that files need to have for |
679 | // static libraries | |
680 | fn staticlibname(&self) -> (String, String) { | |
681 | let t = &self.target; | |
682 | (t.options.staticlib_prefix.clone(), t.options.staticlib_suffix.clone()) | |
683 | } | |
684 | ||
c30ab7b3 SL |
685 | fn find_commandline_library<'b, LOCS>(&mut self, locs: LOCS) -> Option<Library> |
686 | where LOCS: Iterator<Item = &'b String> | |
5bcae85e | 687 | { |
1a4d82fc JJ |
688 | // First, filter out all libraries that look suspicious. We only accept |
689 | // files which actually exist that have the correct naming scheme for | |
690 | // rlibs/dylibs. | |
691 | let sess = self.sess; | |
692 | let dylibname = self.dylibname(); | |
9e0c209e SL |
693 | let mut rlibs = FnvHashMap(); |
694 | let mut dylibs = FnvHashMap(); | |
1a4d82fc | 695 | { |
5bcae85e | 696 | let locs = locs.map(|l| PathBuf::from(l)).filter(|loc| { |
1a4d82fc JJ |
697 | if !loc.exists() { |
698 | sess.err(&format!("extern location for {} does not exist: {}", | |
c30ab7b3 SL |
699 | self.crate_name, |
700 | loc.display())); | |
1a4d82fc JJ |
701 | return false; |
702 | } | |
c34b1796 | 703 | let file = match loc.file_name().and_then(|s| s.to_str()) { |
1a4d82fc JJ |
704 | Some(file) => file, |
705 | None => { | |
706 | sess.err(&format!("extern location for {} is not a file: {}", | |
c30ab7b3 SL |
707 | self.crate_name, |
708 | loc.display())); | |
1a4d82fc JJ |
709 | return false; |
710 | } | |
711 | }; | |
712 | if file.starts_with("lib") && file.ends_with(".rlib") { | |
c30ab7b3 | 713 | return true; |
1a4d82fc JJ |
714 | } else { |
715 | let (ref prefix, ref suffix) = dylibname; | |
c30ab7b3 SL |
716 | if file.starts_with(&prefix[..]) && file.ends_with(&suffix[..]) { |
717 | return true; | |
1a4d82fc JJ |
718 | } |
719 | } | |
9cc50fc6 | 720 | sess.struct_err(&format!("extern location for {} is of an unknown type: {}", |
c30ab7b3 SL |
721 | self.crate_name, |
722 | loc.display())) | |
9cc50fc6 | 723 | .help(&format!("file name should be lib*.rlib or {}*.{}", |
c30ab7b3 SL |
724 | dylibname.0, |
725 | dylibname.1)) | |
9cc50fc6 | 726 | .emit(); |
1a4d82fc JJ |
727 | false |
728 | }); | |
729 | ||
85aaf69f SL |
730 | // Now that we have an iterator of good candidates, make sure |
731 | // there's at most one rlib and at most one dylib. | |
1a4d82fc | 732 | for loc in locs { |
c34b1796 | 733 | if loc.file_name().unwrap().to_str().unwrap().ends_with(".rlib") { |
c30ab7b3 | 734 | rlibs.insert(fs::canonicalize(&loc).unwrap(), PathKind::ExternFlag); |
1a4d82fc | 735 | } else { |
c30ab7b3 | 736 | dylibs.insert(fs::canonicalize(&loc).unwrap(), PathKind::ExternFlag); |
1a4d82fc JJ |
737 | } |
738 | } | |
739 | }; | |
740 | ||
741 | // Extract the rlib/dylib pair. | |
a7813a04 XL |
742 | let mut slot = None; |
743 | let rlib = self.extract_one(rlibs, CrateFlavor::Rlib, &mut slot); | |
744 | let dylib = self.extract_one(dylibs, CrateFlavor::Dylib, &mut slot); | |
1a4d82fc | 745 | |
c30ab7b3 SL |
746 | if rlib.is_none() && dylib.is_none() { |
747 | return None; | |
748 | } | |
a7813a04 | 749 | match slot { |
c30ab7b3 SL |
750 | Some((_, metadata)) => { |
751 | Some(Library { | |
752 | dylib: dylib, | |
753 | rlib: rlib, | |
754 | metadata: metadata, | |
755 | }) | |
756 | } | |
1a4d82fc JJ |
757 | None => None, |
758 | } | |
223e47cc | 759 | } |
223e47cc LB |
760 | } |
761 | ||
9cc50fc6 SL |
762 | pub fn note_crate_name(err: &mut DiagnosticBuilder, name: &str) { |
763 | err.note(&format!("crate name: {}", name)); | |
1a4d82fc | 764 | } |
223e47cc | 765 | |
1a4d82fc JJ |
766 | impl ArchiveMetadata { |
767 | fn new(ar: ArchiveRO) -> Option<ArchiveMetadata> { | |
d9579d0f | 768 | let data = { |
c30ab7b3 SL |
769 | let section = ar.iter() |
770 | .filter_map(|s| s.ok()) | |
771 | .find(|sect| sect.name() == Some(METADATA_FILENAME)); | |
d9579d0f AL |
772 | match section { |
773 | Some(s) => s.data() as *const [u8], | |
774 | None => { | |
775 | debug!("didn't find '{}' in the archive", METADATA_FILENAME); | |
776 | return None; | |
777 | } | |
1a4d82fc JJ |
778 | } |
779 | }; | |
223e47cc | 780 | |
1a4d82fc JJ |
781 | Some(ArchiveMetadata { |
782 | _archive: ar, | |
783 | data: data, | |
784 | }) | |
223e47cc | 785 | } |
1a4d82fc | 786 | |
c30ab7b3 SL |
787 | pub fn as_slice<'a>(&'a self) -> &'a [u8] { |
788 | unsafe { &*self.data } | |
789 | } | |
1a4d82fc JJ |
790 | } |
791 | ||
c30ab7b3 SL |
792 | fn verify_decompressed_encoding_version(blob: &MetadataBlob, |
793 | filename: &Path) | |
794 | -> Result<(), String> { | |
9e0c209e | 795 | if !blob.is_compatible() { |
a7813a04 XL |
796 | Err((format!("incompatible metadata version found: '{}'", |
797 | filename.display()))) | |
798 | } else { | |
799 | Ok(()) | |
800 | } | |
801 | } | |
802 | ||
1a4d82fc | 803 | // Just a small wrapper to time how long reading metadata takes. |
c30ab7b3 SL |
804 | fn get_metadata_section(target: &Target, |
805 | flavor: CrateFlavor, | |
806 | filename: &Path) | |
62682a34 | 807 | -> Result<MetadataBlob, String> { |
92a42be0 | 808 | let start = Instant::now(); |
a7813a04 | 809 | let ret = get_metadata_section_imp(target, flavor, filename); |
c30ab7b3 SL |
810 | info!("reading {:?} => {:?}", |
811 | filename.file_name().unwrap(), | |
92a42be0 | 812 | start.elapsed()); |
c30ab7b3 | 813 | return ret; |
223e47cc LB |
814 | } |
815 | ||
c30ab7b3 SL |
816 | fn get_metadata_section_imp(target: &Target, |
817 | flavor: CrateFlavor, | |
818 | filename: &Path) | |
62682a34 | 819 | -> Result<MetadataBlob, String> { |
1a4d82fc JJ |
820 | if !filename.exists() { |
821 | return Err(format!("no such file: '{}'", filename.display())); | |
822 | } | |
a7813a04 | 823 | if flavor == CrateFlavor::Rlib { |
1a4d82fc JJ |
824 | // Use ArchiveRO for speed here, it's backed by LLVM and uses mmap |
825 | // internally to read the file. We also avoid even using a memcpy by | |
826 | // just keeping the archive along while the metadata is in use. | |
827 | let archive = match ArchiveRO::open(filename) { | |
828 | Some(ar) => ar, | |
829 | None => { | |
830 | debug!("llvm didn't like `{}`", filename.display()); | |
c30ab7b3 | 831 | return Err(format!("failed to read rlib metadata: '{}'", filename.display())); |
1a4d82fc JJ |
832 | } |
833 | }; | |
9e0c209e | 834 | return match ArchiveMetadata::new(archive).map(|ar| MetadataBlob::Archive(ar)) { |
c30ab7b3 | 835 | None => Err(format!("failed to read rlib metadata: '{}'", filename.display())), |
a7813a04 | 836 | Some(blob) => { |
9e0c209e | 837 | verify_decompressed_encoding_version(&blob, filename)?; |
a7813a04 XL |
838 | Ok(blob) |
839 | } | |
c34b1796 | 840 | }; |
1a4d82fc | 841 | } |
223e47cc | 842 | unsafe { |
c34b1796 | 843 | let buf = common::path2cstr(filename); |
1a4d82fc | 844 | let mb = llvm::LLVMRustCreateMemoryBufferWithContentsOfFile(buf.as_ptr()); |
c34b1796 | 845 | if mb as isize == 0 { |
c30ab7b3 | 846 | return Err(format!("error reading library: '{}'", filename.display())); |
1a4d82fc JJ |
847 | } |
848 | let of = match ObjectFile::new(mb) { | |
849 | Some(of) => of, | |
850 | _ => { | |
c30ab7b3 | 851 | return Err((format!("provided path not an object file: '{}'", filename.display()))) |
1a4d82fc | 852 | } |
223e47cc LB |
853 | }; |
854 | let si = mk_section_iter(of.llof); | |
855 | while llvm::LLVMIsSectionIteratorAtEnd(of.llof, si.llsi) == False { | |
1a4d82fc JJ |
856 | let mut name_buf = ptr::null(); |
857 | let name_len = llvm::LLVMRustGetSectionName(si.llsi, &mut name_buf); | |
c30ab7b3 | 858 | let name = slice::from_raw_parts(name_buf as *const u8, name_len as usize).to_vec(); |
1a4d82fc JJ |
859 | let name = String::from_utf8(name).unwrap(); |
860 | debug!("get_metadata_section: name {}", name); | |
62682a34 | 861 | if read_meta_section_name(target) == name { |
223e47cc | 862 | let cbuf = llvm::LLVMGetSectionContents(si.llsi); |
c34b1796 | 863 | let csz = llvm::LLVMGetSectionSize(si.llsi) as usize; |
1a4d82fc | 864 | let cvbuf: *const u8 = cbuf as *const u8; |
9e0c209e | 865 | let vlen = METADATA_HEADER.len(); |
c30ab7b3 | 866 | debug!("checking {} bytes of metadata-version stamp", vlen); |
1a4d82fc | 867 | let minsz = cmp::min(vlen, csz); |
85aaf69f | 868 | let buf0 = slice::from_raw_parts(cvbuf, minsz); |
9e0c209e | 869 | let version_ok = buf0 == METADATA_HEADER; |
1a4d82fc JJ |
870 | if !version_ok { |
871 | return Err((format!("incompatible metadata version found: '{}'", | |
872 | filename.display()))); | |
970d7e83 | 873 | } |
223e47cc | 874 | |
c34b1796 | 875 | let cvbuf1 = cvbuf.offset(vlen as isize); |
c30ab7b3 | 876 | debug!("inflating {} bytes of compressed metadata", csz - vlen); |
85aaf69f | 877 | let bytes = slice::from_raw_parts(cvbuf1, csz - vlen); |
1a4d82fc | 878 | match flate::inflate_bytes(bytes) { |
a7813a04 | 879 | Ok(inflated) => { |
9e0c209e SL |
880 | let blob = MetadataBlob::Inflated(inflated); |
881 | verify_decompressed_encoding_version(&blob, filename)?; | |
a7813a04 XL |
882 | return Ok(blob); |
883 | } | |
c34b1796 | 884 | Err(_) => {} |
223e47cc LB |
885 | } |
886 | } | |
887 | llvm::LLVMMoveToNextSection(si.llsi); | |
888 | } | |
c34b1796 | 889 | Err(format!("metadata not found: '{}'", filename.display())) |
223e47cc LB |
890 | } |
891 | } | |
892 | ||
62682a34 | 893 | pub fn meta_section_name(target: &Target) -> &'static str { |
5bcae85e SL |
894 | // Historical note: |
895 | // | |
896 | // When using link.exe it was seen that the section name `.note.rustc` | |
897 | // was getting shortened to `.note.ru`, and according to the PE and COFF | |
898 | // specification: | |
899 | // | |
900 | // > Executable images do not use a string table and do not support | |
901 | // > section names longer than 8 characters | |
902 | // | |
903 | // https://msdn.microsoft.com/en-us/library/windows/hardware/gg463119.aspx | |
904 | // | |
905 | // As a result, we choose a slightly shorter name! As to why | |
906 | // `.note.rustc` works on MinGW, that's another good question... | |
907 | ||
62682a34 | 908 | if target.options.is_like_osx { |
5bcae85e | 909 | "__DATA,.rustc" |
1a4d82fc | 910 | } else { |
5bcae85e | 911 | ".rustc" |
223e47cc LB |
912 | } |
913 | } | |
914 | ||
5bcae85e SL |
915 | pub fn read_meta_section_name(_target: &Target) -> &'static str { |
916 | ".rustc" | |
970d7e83 LB |
917 | } |
918 | ||
223e47cc | 919 | // A diagnostic function for dumping crate metadata to an output stream |
c30ab7b3 | 920 | pub fn list_file_metadata(target: &Target, path: &Path, out: &mut io::Write) -> io::Result<()> { |
a7813a04 | 921 | let filename = path.file_name().unwrap().to_str().unwrap(); |
c30ab7b3 SL |
922 | let flavor = if filename.ends_with(".rlib") { |
923 | CrateFlavor::Rlib | |
924 | } else { | |
925 | CrateFlavor::Dylib | |
926 | }; | |
a7813a04 | 927 | match get_metadata_section(target, flavor, path) { |
9e0c209e | 928 | Ok(metadata) => metadata.list_crate_metadata(out), |
c30ab7b3 | 929 | Err(msg) => write!(out, "{}\n", msg), |
223e47cc LB |
930 | } |
931 | } |