]> git.lizzy.rs Git - rust.git/blob - src/librustc_metadata/locator.rs
Auto merge of #66384 - cjgillot:typefoldable, r=Zoxc
[rust.git] / src / librustc_metadata / locator.rs
1 //! Finds crate binaries and loads their metadata
2 //!
3 //! Might I be the first to welcome you to a world of platform differences,
4 //! version requirements, dependency graphs, conflicting desires, and fun! This
5 //! is the major guts (along with metadata::creader) of the compiler for loading
6 //! crates and resolving dependencies. Let's take a tour!
7 //!
8 //! # The problem
9 //!
10 //! Each invocation of the compiler is immediately concerned with one primary
11 //! problem, to connect a set of crates to resolved crates on the filesystem.
12 //! Concretely speaking, the compiler follows roughly these steps to get here:
13 //!
14 //! 1. Discover a set of `extern crate` statements.
15 //! 2. Transform these directives into crate names. If the directive does not
16 //!    have an explicit name, then the identifier is the name.
17 //! 3. For each of these crate names, find a corresponding crate on the
18 //!    filesystem.
19 //!
20 //! Sounds easy, right? Let's walk into some of the nuances.
21 //!
22 //! ## Transitive Dependencies
23 //!
24 //! Let's say we've got three crates: A, B, and C. A depends on B, and B depends
25 //! on C. When we're compiling A, we primarily need to find and locate B, but we
26 //! also end up needing to find and locate C as well.
27 //!
28 //! The reason for this is that any of B's types could be composed of C's types,
29 //! any function in B could return a type from C, etc. To be able to guarantee
30 //! that we can always type-check/translate any function, we have to have
31 //! complete knowledge of the whole ecosystem, not just our immediate
32 //! dependencies.
33 //!
34 //! So now as part of the "find a corresponding crate on the filesystem" step
35 //! above, this involves also finding all crates for *all upstream
36 //! dependencies*. This includes all dependencies transitively.
37 //!
38 //! ## Rlibs and Dylibs
39 //!
40 //! The compiler has two forms of intermediate dependencies. These are dubbed
41 //! rlibs and dylibs for the static and dynamic variants, respectively. An rlib
42 //! is a rustc-defined file format (currently just an ar archive) while a dylib
43 //! is a platform-defined dynamic library. Each library has a metadata somewhere
44 //! inside of it.
45 //!
46 //! A third kind of dependency is an rmeta file. These are metadata files and do
47 //! not contain any code, etc. To a first approximation, these are treated in the
48 //! same way as rlibs. Where there is both an rlib and an rmeta file, the rlib
49 //! gets priority (even if the rmeta file is newer). An rmeta file is only
50 //! useful for checking a downstream crate, attempting to link one will cause an
51 //! error.
52 //!
53 //! When translating a crate name to a crate on the filesystem, we all of a
54 //! sudden need to take into account both rlibs and dylibs! Linkage later on may
55 //! use either one of these files, as each has their pros/cons. The job of crate
56 //! loading is to discover what's possible by finding all candidates.
57 //!
58 //! Most parts of this loading systems keep the dylib/rlib as just separate
59 //! variables.
60 //!
61 //! ## Where to look?
62 //!
63 //! We can't exactly scan your whole hard drive when looking for dependencies,
64 //! so we need to places to look. Currently the compiler will implicitly add the
65 //! target lib search path ($prefix/lib/rustlib/$target/lib) to any compilation,
66 //! and otherwise all -L flags are added to the search paths.
67 //!
68 //! ## What criterion to select on?
69 //!
70 //! This a pretty tricky area of loading crates. Given a file, how do we know
71 //! whether it's the right crate? Currently, the rules look along these lines:
72 //!
73 //! 1. Does the filename match an rlib/dylib pattern? That is to say, does the
74 //!    filename have the right prefix/suffix?
75 //! 2. Does the filename have the right prefix for the crate name being queried?
76 //!    This is filtering for files like `libfoo*.rlib` and such. If the crate
77 //!    we're looking for was originally compiled with -C extra-filename, the
78 //!    extra filename will be included in this prefix to reduce reading
79 //!    metadata from crates that would otherwise share our prefix.
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 //! ```compile_fail,E0463
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::locator or metadata::creader for all the juicy details!
214
215 use crate::cstore::MetadataBlob;
216 use crate::creader::Library;
217 use crate::rmeta::{METADATA_HEADER, rustc_version};
218
219 use rustc_data_structures::fx::FxHashSet;
220 use rustc_data_structures::svh::Svh;
221 use rustc_data_structures::sync::MetadataRef;
222 use rustc::middle::cstore::{CrateSource, MetadataLoader};
223 use rustc::session::{config, Session, CrateDisambiguator};
224 use rustc::session::filesearch::{FileSearch, FileMatches, FileDoesntMatch};
225 use rustc::session::search_paths::PathKind;
226 use rustc::util::nodemap::FxHashMap;
227
228 use errors::DiagnosticBuilder;
229 use syntax::{span_err, span_fatal};
230 use syntax::symbol::{Symbol, sym};
231 use syntax::struct_span_err;
232 use syntax_pos::Span;
233 use rustc_target::spec::{Target, TargetTriple};
234
235 use std::cmp;
236 use std::fmt;
237 use std::fs;
238 use std::io::{self, Read};
239 use std::ops::Deref;
240 use std::path::{Path, PathBuf};
241 use std::time::Instant;
242
243 use flate2::read::DeflateDecoder;
244
245 use rustc_data_structures::owning_ref::OwningRef;
246
247 use log::{debug, info, warn};
248
249 use rustc_error_codes::*;
250
251 #[derive(Clone)]
252 crate struct CrateMismatch {
253     path: PathBuf,
254     got: String,
255 }
256
257 #[derive(Clone)]
258 crate struct Context<'a> {
259     pub sess: &'a Session,
260     pub span: Span,
261     pub crate_name: Symbol,
262     pub hash: Option<&'a Svh>,
263     pub host_hash: Option<&'a Svh>,
264     pub extra_filename: Option<&'a str>,
265     // points to either self.sess.target.target or self.sess.host, must match triple
266     pub target: &'a Target,
267     pub triple: TargetTriple,
268     pub filesearch: FileSearch<'a>,
269     pub root: Option<&'a CratePaths>,
270     pub rejected_via_hash: Vec<CrateMismatch>,
271     pub rejected_via_triple: Vec<CrateMismatch>,
272     pub rejected_via_kind: Vec<CrateMismatch>,
273     pub rejected_via_version: Vec<CrateMismatch>,
274     pub rejected_via_filename: Vec<CrateMismatch>,
275     pub should_match_name: bool,
276     pub is_proc_macro: Option<bool>,
277     pub metadata_loader: &'a dyn MetadataLoader,
278 }
279
280 crate struct CratePaths {
281     pub name: Symbol,
282     pub source: CrateSource,
283 }
284
285 #[derive(Copy, Clone, PartialEq)]
286 enum CrateFlavor {
287     Rlib,
288     Rmeta,
289     Dylib,
290 }
291
292 impl fmt::Display for CrateFlavor {
293     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
294         f.write_str(match *self {
295             CrateFlavor::Rlib => "rlib",
296             CrateFlavor::Rmeta => "rmeta",
297             CrateFlavor::Dylib => "dylib",
298         })
299     }
300 }
301
302 impl<'a> Context<'a> {
303     crate fn reset(&mut self) {
304         self.rejected_via_hash.clear();
305         self.rejected_via_triple.clear();
306         self.rejected_via_kind.clear();
307         self.rejected_via_version.clear();
308         self.rejected_via_filename.clear();
309     }
310
311     crate fn maybe_load_library_crate(&mut self) -> Option<Library> {
312         let mut seen_paths = FxHashSet::default();
313         match self.extra_filename {
314             Some(s) => self.find_library_crate(s, &mut seen_paths)
315                 .or_else(|| self.find_library_crate("", &mut seen_paths)),
316             None => self.find_library_crate("", &mut seen_paths)
317         }
318     }
319
320     crate fn report_errs(self) -> ! {
321         let add = match self.root {
322             None => String::new(),
323             Some(r) => format!(" which `{}` depends on", r.name),
324         };
325         let mut msg = "the following crate versions were found:".to_string();
326         let mut err = if !self.rejected_via_hash.is_empty() {
327             let mut err = struct_span_err!(self.sess,
328                                            self.span,
329                                            E0460,
330                                            "found possibly newer version of crate `{}`{}",
331                                            self.crate_name,
332                                            add);
333             err.note("perhaps that crate needs to be recompiled?");
334             let mismatches = self.rejected_via_hash.iter();
335             for &CrateMismatch { ref path, .. } in mismatches {
336                 msg.push_str(&format!("\ncrate `{}`: {}", self.crate_name, path.display()));
337             }
338             match self.root {
339                 None => {}
340                 Some(r) => {
341                     for path in r.source.paths() {
342                         msg.push_str(&format!("\ncrate `{}`: {}", r.name, path.display()));
343                     }
344                 }
345             }
346             err.note(&msg);
347             err
348         } else if !self.rejected_via_triple.is_empty() {
349             let mut err = struct_span_err!(self.sess,
350                                            self.span,
351                                            E0461,
352                                            "couldn't find crate `{}` \
353                                             with expected target triple {}{}",
354                                            self.crate_name,
355                                            self.triple,
356                                            add);
357             let mismatches = self.rejected_via_triple.iter();
358             for &CrateMismatch { ref path, ref got } in mismatches {
359                 msg.push_str(&format!("\ncrate `{}`, target triple {}: {}",
360                                       self.crate_name,
361                                       got,
362                                       path.display()));
363             }
364             err.note(&msg);
365             err
366         } else if !self.rejected_via_kind.is_empty() {
367             let mut err = struct_span_err!(self.sess,
368                                            self.span,
369                                            E0462,
370                                            "found staticlib `{}` instead of rlib or dylib{}",
371                                            self.crate_name,
372                                            add);
373             err.help("please recompile that crate using --crate-type lib");
374             let mismatches = self.rejected_via_kind.iter();
375             for &CrateMismatch { ref path, .. } in mismatches {
376                 msg.push_str(&format!("\ncrate `{}`: {}", self.crate_name, path.display()));
377             }
378             err.note(&msg);
379             err
380         } else if !self.rejected_via_version.is_empty() {
381             let mut err = struct_span_err!(self.sess,
382                                            self.span,
383                                            E0514,
384                                            "found crate `{}` compiled by an incompatible version \
385                                             of rustc{}",
386                                            self.crate_name,
387                                            add);
388             err.help(&format!("please recompile that crate using this compiler ({})",
389                               rustc_version()));
390             let mismatches = self.rejected_via_version.iter();
391             for &CrateMismatch { ref path, ref got } in mismatches {
392                 msg.push_str(&format!("\ncrate `{}` compiled by {}: {}",
393                                       self.crate_name,
394                                       got,
395                                       path.display()));
396             }
397             err.note(&msg);
398             err
399         } else {
400             let mut err = struct_span_err!(self.sess,
401                                            self.span,
402                                            E0463,
403                                            "can't find crate for `{}`{}",
404                                            self.crate_name,
405                                            add);
406
407             if (self.crate_name == sym::std || self.crate_name == sym::core)
408                 && self.triple != TargetTriple::from_triple(config::host_triple()) {
409                 err.note(&format!("the `{}` target may not be installed", self.triple));
410             }
411             err.span_label(self.span, "can't find crate");
412             err
413         };
414
415         if !self.rejected_via_filename.is_empty() {
416             let dylibname = self.dylibname();
417             let mismatches = self.rejected_via_filename.iter();
418             for &CrateMismatch { ref path, .. } in mismatches {
419                 err.note(&format!("extern location for {} is of an unknown type: {}",
420                                   self.crate_name,
421                                   path.display()))
422                    .help(&format!("file name should be lib*.rlib or {}*.{}",
423                                   dylibname.0,
424                                   dylibname.1));
425             }
426         }
427
428         err.emit();
429         self.sess.abort_if_errors();
430         unreachable!();
431     }
432
433     fn find_library_crate(&mut self,
434                           extra_prefix: &str,
435                           seen_paths: &mut FxHashSet<PathBuf>)
436                           -> Option<Library> {
437         // If an SVH is specified, then this is a transitive dependency that
438         // must be loaded via -L plus some filtering.
439         if self.hash.is_none() {
440             self.should_match_name = false;
441             if let Some(entry) = self.sess.opts.externs.get(&self.crate_name.as_str()) {
442                 // Only use `--extern crate_name=path` here, not `--extern crate_name`.
443                 if entry.locations.iter().any(|l| l.is_some()) {
444                     return self.find_commandline_library(
445                         entry.locations.iter().filter_map(|l| l.as_ref()),
446                     );
447                 }
448             }
449             self.should_match_name = true;
450         }
451
452         let dypair = self.dylibname();
453         let staticpair = self.staticlibname();
454
455         // want: crate_name.dir_part() + prefix + crate_name.file_part + "-"
456         let dylib_prefix = format!("{}{}{}", dypair.0, self.crate_name, extra_prefix);
457         let rlib_prefix = format!("lib{}{}", self.crate_name, extra_prefix);
458         let staticlib_prefix = format!("{}{}{}", staticpair.0, self.crate_name, extra_prefix);
459
460         let mut candidates: FxHashMap<
461             _,
462             (FxHashMap<_, _>, FxHashMap<_, _>, FxHashMap<_, _>),
463         > = Default::default();
464         let mut staticlibs = vec![];
465
466         // First, find all possible candidate rlibs and dylibs purely based on
467         // the name of the files themselves. We're trying to match against an
468         // exact crate name and a possibly an exact hash.
469         //
470         // During this step, we can filter all found libraries based on the
471         // name and id found in the crate id (we ignore the path portion for
472         // filename matching), as well as the exact hash (if specified). If we
473         // end up having many candidates, we must look at the metadata to
474         // perform exact matches against hashes/crate ids. Note that opening up
475         // the metadata is where we do an exact match against the full contents
476         // of the crate id (path/name/id).
477         //
478         // The goal of this step is to look at as little metadata as possible.
479         self.filesearch.search(|path, kind| {
480             let file = match path.file_name().and_then(|s| s.to_str()) {
481                 None => return FileDoesntMatch,
482                 Some(file) => file,
483             };
484             let (hash, found_kind) =
485                 if file.starts_with(&rlib_prefix) && file.ends_with(".rlib") {
486                     (&file[(rlib_prefix.len())..(file.len() - ".rlib".len())], CrateFlavor::Rlib)
487                 } else if file.starts_with(&rlib_prefix) && file.ends_with(".rmeta") {
488                     (&file[(rlib_prefix.len())..(file.len() - ".rmeta".len())], CrateFlavor::Rmeta)
489                 } else if file.starts_with(&dylib_prefix) &&
490                                              file.ends_with(&dypair.1) {
491                     (&file[(dylib_prefix.len())..(file.len() - dypair.1.len())], CrateFlavor::Dylib)
492                 } else {
493                     if file.starts_with(&staticlib_prefix) && file.ends_with(&staticpair.1) {
494                         staticlibs.push(CrateMismatch {
495                             path: path.to_path_buf(),
496                             got: "static".to_string(),
497                         });
498                     }
499                     return FileDoesntMatch;
500                 };
501
502             info!("lib candidate: {}", path.display());
503
504             let hash_str = hash.to_string();
505             let slot = candidates.entry(hash_str).or_default();
506             let (ref mut rlibs, ref mut rmetas, ref mut dylibs) = *slot;
507             fs::canonicalize(path)
508                 .map(|p| {
509                     if seen_paths.contains(&p) {
510                         return FileDoesntMatch
511                     };
512                     seen_paths.insert(p.clone());
513                     match found_kind {
514                         CrateFlavor::Rlib => { rlibs.insert(p, kind); }
515                         CrateFlavor::Rmeta => { rmetas.insert(p, kind); }
516                         CrateFlavor::Dylib => { dylibs.insert(p, kind); }
517                     }
518                     FileMatches
519                 })
520                 .unwrap_or(FileDoesntMatch)
521         });
522         self.rejected_via_kind.extend(staticlibs);
523
524         // We have now collected all known libraries into a set of candidates
525         // keyed of the filename hash listed. For each filename, we also have a
526         // list of rlibs/dylibs that apply. Here, we map each of these lists
527         // (per hash), to a Library candidate for returning.
528         //
529         // A Library candidate is created if the metadata for the set of
530         // libraries corresponds to the crate id and hash criteria that this
531         // search is being performed for.
532         let mut libraries = FxHashMap::default();
533         for (_hash, (rlibs, rmetas, dylibs)) in candidates {
534             if let Some((svh, lib)) = self.extract_lib(rlibs, rmetas, dylibs) {
535                 libraries.insert(svh, lib);
536             }
537         }
538
539         // Having now translated all relevant found hashes into libraries, see
540         // what we've got and figure out if we found multiple candidates for
541         // libraries or not.
542         match libraries.len() {
543             0 => None,
544             1 => Some(libraries.into_iter().next().unwrap().1),
545             _ => {
546                 let mut err = struct_span_err!(self.sess,
547                                                self.span,
548                                                E0464,
549                                                "multiple matching crates for `{}`",
550                                                self.crate_name);
551                 let candidates = libraries.iter().filter_map(|(_, lib)| {
552                     let crate_name = &lib.metadata.get_root().name.as_str();
553                     match &(&lib.source.dylib, &lib.source.rlib) {
554                         &(&Some((ref pd, _)), &Some((ref pr, _))) => {
555                             Some(format!("\ncrate `{}`: {}\n{:>padding$}",
556                                          crate_name,
557                                          pd.display(),
558                                          pr.display(),
559                                          padding=8 + crate_name.len()))
560                         }
561                         &(&Some((ref p, _)), &None) | &(&None, &Some((ref p, _))) => {
562                             Some(format!("\ncrate `{}`: {}", crate_name, p.display()))
563                         }
564                         &(&None, &None) => None,
565                     }
566                 }).collect::<String>();
567                 err.note(&format!("candidates:{}", candidates));
568                 err.emit();
569                 None
570             }
571         }
572     }
573
574     fn extract_lib(
575         &mut self,
576         rlibs: FxHashMap<PathBuf, PathKind>,
577         rmetas: FxHashMap<PathBuf, PathKind>,
578         dylibs: FxHashMap<PathBuf, PathKind>,
579     ) -> Option<(Svh, Library)> {
580         let mut slot = None;
581         let source = CrateSource {
582             rlib: self.extract_one(rlibs, CrateFlavor::Rlib, &mut slot),
583             rmeta: self.extract_one(rmetas, CrateFlavor::Rmeta, &mut slot),
584             dylib: self.extract_one(dylibs, CrateFlavor::Dylib, &mut slot),
585         };
586         slot.map(|(svh, metadata)| (svh, Library { source, metadata }))
587     }
588
589     // Attempts to extract *one* library from the set `m`. If the set has no
590     // elements, `None` is returned. If the set has more than one element, then
591     // the errors and notes are emitted about the set of libraries.
592     //
593     // With only one library in the set, this function will extract it, and then
594     // read the metadata from it if `*slot` is `None`. If the metadata couldn't
595     // be read, it is assumed that the file isn't a valid rust library (no
596     // errors are emitted).
597     fn extract_one(&mut self,
598                    m: FxHashMap<PathBuf, PathKind>,
599                    flavor: CrateFlavor,
600                    slot: &mut Option<(Svh, MetadataBlob)>)
601                    -> Option<(PathBuf, PathKind)> {
602         let mut ret: Option<(PathBuf, PathKind)> = None;
603         let mut error = 0;
604
605         if slot.is_some() {
606             // FIXME(#10786): for an optimization, we only read one of the
607             //                libraries' metadata sections. In theory we should
608             //                read both, but reading dylib metadata is quite
609             //                slow.
610             if m.is_empty() {
611                 return None;
612             } else if m.len() == 1 {
613                 return Some(m.into_iter().next().unwrap());
614             }
615         }
616
617         let mut err: Option<DiagnosticBuilder<'_>> = None;
618         for (lib, kind) in m {
619             info!("{} reading metadata from: {}", flavor, lib.display());
620             let (hash, metadata) =
621                 match get_metadata_section(self.target, flavor, &lib, self.metadata_loader) {
622                     Ok(blob) => {
623                         if let Some(h) = self.crate_matches(&blob, &lib) {
624                             (h, blob)
625                         } else {
626                             info!("metadata mismatch");
627                             continue;
628                         }
629                     }
630                     Err(err) => {
631                         warn!("no metadata found: {}", err);
632                         continue;
633                     }
634                 };
635             // If we see multiple hashes, emit an error about duplicate candidates.
636             if slot.as_ref().map_or(false, |s| s.0 != hash) {
637                 let mut e = struct_span_err!(self.sess,
638                                              self.span,
639                                              E0465,
640                                              "multiple {} candidates for `{}` found",
641                                              flavor,
642                                              self.crate_name);
643                 e.span_note(self.span,
644                             &format!(r"candidate #1: {}",
645                                      ret.as_ref()
646                                          .unwrap()
647                                          .0
648                                          .display()));
649                 if let Some(ref mut e) = err {
650                     e.emit();
651                 }
652                 err = Some(e);
653                 error = 1;
654                 *slot = None;
655             }
656             if error > 0 {
657                 error += 1;
658                 err.as_mut().unwrap().span_note(self.span,
659                                                 &format!(r"candidate #{}: {}",
660                                                          error,
661                                                          lib.display()));
662                 continue;
663             }
664
665             // Ok so at this point we've determined that `(lib, kind)` above is
666             // a candidate crate to load, and that `slot` is either none (this
667             // is the first crate of its kind) or if some the previous path has
668             // the exact same hash (e.g., it's the exact same crate).
669             //
670             // In principle these two candidate crates are exactly the same so
671             // we can choose either of them to link. As a stupidly gross hack,
672             // however, we favor crate in the sysroot.
673             //
674             // You can find more info in rust-lang/rust#39518 and various linked
675             // issues, but the general gist is that during testing libstd the
676             // compilers has two candidates to choose from: one in the sysroot
677             // and one in the deps folder. These two crates are the exact same
678             // crate but if the compiler chooses the one in the deps folder
679             // it'll cause spurious errors on Windows.
680             //
681             // As a result, we favor the sysroot crate here. Note that the
682             // candidates are all canonicalized, so we canonicalize the sysroot
683             // as well.
684             if let Some((ref prev, _)) = ret {
685                 let sysroot = &self.sess.sysroot;
686                 let sysroot = sysroot.canonicalize()
687                                      .unwrap_or_else(|_| sysroot.to_path_buf());
688                 if prev.starts_with(&sysroot) {
689                     continue
690                 }
691             }
692             *slot = Some((hash, metadata));
693             ret = Some((lib, kind));
694         }
695
696         if error > 0 {
697             err.unwrap().emit();
698             None
699         } else {
700             ret
701         }
702     }
703
704     fn crate_matches(&mut self, metadata: &MetadataBlob, libpath: &Path) -> Option<Svh> {
705         let rustc_version = rustc_version();
706         let found_version = metadata.get_rustc_version();
707         if found_version != rustc_version {
708             info!("Rejecting via version: expected {} got {}",
709                   rustc_version,
710                   found_version);
711             self.rejected_via_version.push(CrateMismatch {
712                 path: libpath.to_path_buf(),
713                 got: found_version,
714             });
715             return None;
716         }
717
718         let root = metadata.get_root();
719         if let Some(is_proc_macro) = self.is_proc_macro {
720             if root.proc_macro_data.is_some() != is_proc_macro {
721                 info!("Rejecting via proc macro: expected {} got {}",
722                       is_proc_macro, root.proc_macro_data.is_some());
723                 return None;
724             }
725         }
726
727         if self.should_match_name {
728             if self.crate_name != root.name {
729                 info!("Rejecting via crate name");
730                 return None;
731             }
732         }
733
734         if root.triple != self.triple {
735             info!("Rejecting via crate triple: expected {} got {}",
736                   self.triple,
737                   root.triple);
738             self.rejected_via_triple.push(CrateMismatch {
739                 path: libpath.to_path_buf(),
740                 got: root.triple.to_string(),
741             });
742             return None;
743         }
744
745         if let Some(myhash) = self.hash {
746             if *myhash != root.hash {
747                 info!("Rejecting via hash: expected {} got {}", *myhash, root.hash);
748                 self.rejected_via_hash.push(CrateMismatch {
749                     path: libpath.to_path_buf(),
750                     got: myhash.to_string(),
751                 });
752                 return None;
753             }
754         }
755
756         Some(root.hash)
757     }
758
759
760     // Returns the corresponding (prefix, suffix) that files need to have for
761     // dynamic libraries
762     fn dylibname(&self) -> (String, String) {
763         let t = &self.target;
764         (t.options.dll_prefix.clone(), t.options.dll_suffix.clone())
765     }
766
767     // Returns the corresponding (prefix, suffix) that files need to have for
768     // static libraries
769     fn staticlibname(&self) -> (String, String) {
770         let t = &self.target;
771         (t.options.staticlib_prefix.clone(), t.options.staticlib_suffix.clone())
772     }
773
774     fn find_commandline_library<'b, LOCS>(&mut self, locs: LOCS) -> Option<Library>
775         where LOCS: Iterator<Item = &'b String>
776     {
777         // First, filter out all libraries that look suspicious. We only accept
778         // files which actually exist that have the correct naming scheme for
779         // rlibs/dylibs.
780         let sess = self.sess;
781         let dylibname = self.dylibname();
782         let mut rlibs = FxHashMap::default();
783         let mut rmetas = FxHashMap::default();
784         let mut dylibs = FxHashMap::default();
785         {
786             let locs = locs.map(|l| PathBuf::from(l)).filter(|loc| {
787                 if !loc.exists() {
788                     sess.err(&format!("extern location for {} does not exist: {}",
789                                       self.crate_name,
790                                       loc.display()));
791                     return false;
792                 }
793                 let file = match loc.file_name().and_then(|s| s.to_str()) {
794                     Some(file) => file,
795                     None => {
796                         sess.err(&format!("extern location for {} is not a file: {}",
797                                           self.crate_name,
798                                           loc.display()));
799                         return false;
800                     }
801                 };
802                 if file.starts_with("lib") &&
803                    (file.ends_with(".rlib") || file.ends_with(".rmeta")) {
804                     return true;
805                 } else {
806                     let (ref prefix, ref suffix) = dylibname;
807                     if file.starts_with(&prefix[..]) && file.ends_with(&suffix[..]) {
808                         return true;
809                     }
810                 }
811
812                 self.rejected_via_filename.push(CrateMismatch {
813                     path: loc.clone(),
814                     got: String::new(),
815                 });
816
817                 false
818             });
819
820             // Now that we have an iterator of good candidates, make sure
821             // there's at most one rlib and at most one dylib.
822             for loc in locs {
823                 if loc.file_name().unwrap().to_str().unwrap().ends_with(".rlib") {
824                     rlibs.insert(fs::canonicalize(&loc).unwrap(), PathKind::ExternFlag);
825                 } else if loc.file_name().unwrap().to_str().unwrap().ends_with(".rmeta") {
826                     rmetas.insert(fs::canonicalize(&loc).unwrap(), PathKind::ExternFlag);
827                 } else {
828                     dylibs.insert(fs::canonicalize(&loc).unwrap(), PathKind::ExternFlag);
829                 }
830             }
831         };
832
833         // Extract the dylib/rlib/rmeta triple.
834         self.extract_lib(rlibs, rmetas, dylibs).map(|(_, lib)| lib)
835     }
836 }
837
838 // Just a small wrapper to time how long reading metadata takes.
839 fn get_metadata_section(target: &Target,
840                         flavor: CrateFlavor,
841                         filename: &Path,
842                         loader: &dyn MetadataLoader)
843                         -> Result<MetadataBlob, String> {
844     let start = Instant::now();
845     let ret = get_metadata_section_imp(target, flavor, filename, loader);
846     info!("reading {:?} => {:?}",
847           filename.file_name().unwrap(),
848           start.elapsed());
849     return ret;
850 }
851
852 /// A trivial wrapper for `Mmap` that implements `StableDeref`.
853 struct StableDerefMmap(memmap::Mmap);
854
855 impl Deref for StableDerefMmap {
856     type Target = [u8];
857
858     fn deref(&self) -> &[u8] {
859         self.0.deref()
860     }
861 }
862
863 unsafe impl stable_deref_trait::StableDeref for StableDerefMmap {}
864
865 fn get_metadata_section_imp(target: &Target,
866                             flavor: CrateFlavor,
867                             filename: &Path,
868                             loader: &dyn MetadataLoader)
869                             -> Result<MetadataBlob, String> {
870     if !filename.exists() {
871         return Err(format!("no such file: '{}'", filename.display()));
872     }
873     let raw_bytes: MetadataRef = match flavor {
874         CrateFlavor::Rlib => loader.get_rlib_metadata(target, filename)?,
875         CrateFlavor::Dylib => {
876             let buf = loader.get_dylib_metadata(target, filename)?;
877             // The header is uncompressed
878             let header_len = METADATA_HEADER.len();
879             debug!("checking {} bytes of metadata-version stamp", header_len);
880             let header = &buf[..cmp::min(header_len, buf.len())];
881             if header != METADATA_HEADER {
882                 return Err(format!("incompatible metadata version found: '{}'",
883                                    filename.display()));
884             }
885
886             // Header is okay -> inflate the actual metadata
887             let compressed_bytes = &buf[header_len..];
888             debug!("inflating {} bytes of compressed metadata", compressed_bytes.len());
889             let mut inflated = Vec::new();
890             match DeflateDecoder::new(compressed_bytes).read_to_end(&mut inflated) {
891                 Ok(_) => {
892                     rustc_erase_owner!(OwningRef::new(inflated).map_owner_box())
893                 }
894                 Err(_) => {
895                     return Err(format!("failed to decompress metadata: {}", filename.display()));
896                 }
897             }
898         }
899         CrateFlavor::Rmeta => {
900             // mmap the file, because only a small fraction of it is read.
901             let file = std::fs::File::open(filename).map_err(|_|
902                 format!("failed to open rmeta metadata: '{}'", filename.display()))?;
903             let mmap = unsafe { memmap::Mmap::map(&file) };
904             let mmap = mmap.map_err(|_|
905                 format!("failed to mmap rmeta metadata: '{}'", filename.display()))?;
906
907             rustc_erase_owner!(OwningRef::new(StableDerefMmap(mmap)).map_owner_box())
908         }
909     };
910     let blob = MetadataBlob(raw_bytes);
911     if blob.is_compatible() {
912         Ok(blob)
913     } else {
914         Err(format!("incompatible metadata version found: '{}'", filename.display()))
915     }
916 }
917
918 /// Look for a plugin registrar. Returns its library path and crate disambiguator.
919 pub fn find_plugin_registrar(
920     sess: &Session,
921     metadata_loader: &dyn MetadataLoader,
922     span: Span,
923     name: Symbol,
924 ) -> Option<(PathBuf, CrateDisambiguator)> {
925     info!("find plugin registrar `{}`", name);
926     let target_triple = sess.opts.target_triple.clone();
927     let host_triple = TargetTriple::from_triple(config::host_triple());
928     let is_cross = target_triple != host_triple;
929     let mut target_only = false;
930     let mut locate_ctxt = Context {
931         sess,
932         span,
933         crate_name: name,
934         hash: None,
935         host_hash: None,
936         extra_filename: None,
937         filesearch: sess.host_filesearch(PathKind::Crate),
938         target: &sess.host,
939         triple: host_triple,
940         root: None,
941         rejected_via_hash: vec![],
942         rejected_via_triple: vec![],
943         rejected_via_kind: vec![],
944         rejected_via_version: vec![],
945         rejected_via_filename: vec![],
946         should_match_name: true,
947         is_proc_macro: None,
948         metadata_loader,
949     };
950
951     let library = locate_ctxt.maybe_load_library_crate().or_else(|| {
952         if !is_cross {
953             return None
954         }
955         // Try loading from target crates. This will abort later if we
956         // try to load a plugin registrar function,
957         target_only = true;
958
959         locate_ctxt.target = &sess.target.target;
960         locate_ctxt.triple = target_triple;
961         locate_ctxt.filesearch = sess.target_filesearch(PathKind::Crate);
962
963         locate_ctxt.maybe_load_library_crate()
964     });
965     let library = match library {
966         Some(l) => l,
967         None => locate_ctxt.report_errs(),
968     };
969
970     if target_only {
971         // Need to abort before syntax expansion.
972         let message = format!("plugin `{}` is not available for triple `{}` \
973                                 (only found {})",
974                                 name,
975                                 config::host_triple(),
976                                 sess.opts.target_triple);
977         span_fatal!(sess, span, E0456, "{}", &message);
978     }
979
980     match library.source.dylib {
981         Some(dylib) => {
982             Some((dylib.0, library.metadata.get_root().disambiguator))
983         }
984         None => {
985             span_err!(sess, span, E0457,
986                         "plugin `{}` only found in rlib format, but must be available \
987                         in dylib format",
988                         name);
989             // No need to abort because the loading code will just ignore this
990             // empty dylib.
991             None
992         }
993     }
994 }
995
996 /// A diagnostic function for dumping crate metadata to an output stream.
997 pub fn list_file_metadata(target: &Target,
998                           path: &Path,
999                           metadata_loader: &dyn MetadataLoader,
1000                           out: &mut dyn io::Write)
1001                           -> io::Result<()> {
1002     let filename = path.file_name().unwrap().to_str().unwrap();
1003     let flavor = if filename.ends_with(".rlib") {
1004         CrateFlavor::Rlib
1005     } else if filename.ends_with(".rmeta") {
1006         CrateFlavor::Rmeta
1007     } else {
1008         CrateFlavor::Dylib
1009     };
1010     match get_metadata_section(target, flavor, path, metadata_loader) {
1011         Ok(metadata) => metadata.list_crate_metadata(out),
1012         Err(msg) => write!(out, "{}\n", msg),
1013     }
1014 }