]>
Commit | Line | Data |
---|---|---|
223e47cc | 1 | //! Finds crate binaries and loads their metadata |
1a4d82fc JJ |
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 | |
9fa01778 | 30 | //! that we can always type-check/translate any function, we have to have |
1a4d82fc JJ |
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 | //! | |
476ff2be SL |
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 | //! | |
1a4d82fc JJ |
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 | //! | |
064997fb | 70 | //! This is a pretty tricky area of loading crates. Given a file, how do we know |
1a4d82fc JJ |
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? | |
83c7162d XL |
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. | |
1a4d82fc JJ |
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 | //! | |
041b39d2 | 146 | //! ```compile_fail,E0463 |
1a4d82fc JJ |
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 | |
4b012472 | 215 | use crate::creader::{Library, MetadataLoader}; |
9ffffee4 | 216 | use crate::errors; |
dfeec247 | 217 | use crate::rmeta::{rustc_version, MetadataBlob, METADATA_HEADER}; |
92a42be0 | 218 | |
dfeec247 | 219 | use rustc_data_structures::fx::{FxHashMap, FxHashSet}; |
cdc7bbd5 | 220 | use rustc_data_structures::memmap::Mmap; |
353b0b11 | 221 | use rustc_data_structures::owned_slice::slice_owned; |
dfeec247 | 222 | use rustc_data_structures::svh::Svh; |
ed00b5ec | 223 | use rustc_errors::{DiagnosticArgValue, IntoDiagnosticArg}; |
353b0b11 | 224 | use rustc_fs_util::try_canonicalize; |
add651ee | 225 | use rustc_session::config; |
4b012472 | 226 | use rustc_session::cstore::CrateSource; |
5099ac24 | 227 | use rustc_session::filesearch::FileSearch; |
ba9703b0 | 228 | use rustc_session::search_paths::PathKind; |
5869c6ff | 229 | use rustc_session::utils::CanonicalizedPath; |
94222f64 | 230 | use rustc_session::Session; |
f2b60f7d | 231 | use rustc_span::symbol::Symbol; |
dfeec247 | 232 | use rustc_span::Span; |
83c7162d | 233 | use rustc_target::spec::{Target, TargetTriple}; |
1a4d82fc | 234 | |
1b1a35ee | 235 | use snap::read::FrameDecoder; |
f2b60f7d | 236 | use std::borrow::Cow; |
3dfed10e | 237 | use std::io::{Read, Result as IoResult, Write}; |
353b0b11 | 238 | use std::ops::Deref; |
c34b1796 | 239 | use std::path::{Path, PathBuf}; |
353b0b11 | 240 | use std::{cmp, fmt}; |
223e47cc | 241 | |
532ac7d7 | 242 | #[derive(Clone)] |
923072b8 | 243 | pub(crate) struct CrateLocator<'a> { |
60c5eb7d | 244 | // Immutable per-session configuration. |
c295e0f8 XL |
245 | only_needs_metadata: bool, |
246 | sysroot: &'a Path, | |
60c5eb7d | 247 | metadata_loader: &'a dyn MetadataLoader, |
49aad941 | 248 | cfg_version: &'static str, |
60c5eb7d XL |
249 | |
250 | // Immutable per-search configuration. | |
251 | crate_name: Symbol, | |
5869c6ff | 252 | exact_paths: Vec<CanonicalizedPath>, |
60c5eb7d | 253 | pub hash: Option<Svh>, |
60c5eb7d | 254 | extra_filename: Option<&'a str>, |
85aaf69f | 255 | pub target: &'a Target, |
532ac7d7 | 256 | pub triple: TargetTriple, |
1a4d82fc | 257 | pub filesearch: FileSearch<'a>, |
c295e0f8 | 258 | pub is_proc_macro: bool, |
60c5eb7d XL |
259 | |
260 | // Mutable in-progress state or output. | |
c295e0f8 | 261 | crate_rejections: CrateRejections, |
223e47cc LB |
262 | } |
263 | ||
3dfed10e | 264 | #[derive(Clone)] |
923072b8 | 265 | pub(crate) struct CratePaths { |
60c5eb7d XL |
266 | name: Symbol, |
267 | source: CrateSource, | |
268 | } | |
269 | ||
270 | impl CratePaths { | |
923072b8 | 271 | pub(crate) fn new(name: Symbol, source: CrateSource) -> CratePaths { |
60c5eb7d XL |
272 | CratePaths { name, source } |
273 | } | |
223e47cc LB |
274 | } |
275 | ||
a7813a04 | 276 | #[derive(Copy, Clone, PartialEq)] |
923072b8 | 277 | pub(crate) enum CrateFlavor { |
a7813a04 | 278 | Rlib, |
476ff2be | 279 | Rmeta, |
c30ab7b3 | 280 | Dylib, |
a7813a04 XL |
281 | } |
282 | ||
283 | impl fmt::Display for CrateFlavor { | |
9fa01778 | 284 | fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { |
a7813a04 XL |
285 | f.write_str(match *self { |
286 | CrateFlavor::Rlib => "rlib", | |
476ff2be | 287 | CrateFlavor::Rmeta => "rmeta", |
c30ab7b3 | 288 | CrateFlavor::Dylib => "dylib", |
a7813a04 XL |
289 | }) |
290 | } | |
291 | } | |
292 | ||
f2b60f7d FG |
293 | impl IntoDiagnosticArg for CrateFlavor { |
294 | fn into_diagnostic_arg(self) -> rustc_errors::DiagnosticArgValue<'static> { | |
295 | match self { | |
296 | CrateFlavor::Rlib => DiagnosticArgValue::Str(Cow::Borrowed("rlib")), | |
297 | CrateFlavor::Rmeta => DiagnosticArgValue::Str(Cow::Borrowed("rmeta")), | |
298 | CrateFlavor::Dylib => DiagnosticArgValue::Str(Cow::Borrowed("dylib")), | |
299 | } | |
300 | } | |
301 | } | |
302 | ||
60c5eb7d | 303 | impl<'a> CrateLocator<'a> { |
923072b8 | 304 | pub(crate) fn new( |
60c5eb7d XL |
305 | sess: &'a Session, |
306 | metadata_loader: &'a dyn MetadataLoader, | |
307 | crate_name: Symbol, | |
add651ee | 308 | is_rlib: bool, |
60c5eb7d | 309 | hash: Option<Svh>, |
60c5eb7d XL |
310 | extra_filename: Option<&'a str>, |
311 | is_host: bool, | |
312 | path_kind: PathKind, | |
60c5eb7d | 313 | ) -> CrateLocator<'a> { |
c295e0f8 XL |
314 | let needs_object_code = sess.opts.output_types.should_codegen(); |
315 | // If we're producing an rlib, then we don't need object code. | |
316 | // Or, if we're not producing object code, then we don't need it either | |
317 | // (e.g., if we're a cdylib but emitting just metadata). | |
318 | let only_needs_metadata = is_rlib || !needs_object_code; | |
319 | ||
60c5eb7d | 320 | CrateLocator { |
c295e0f8 XL |
321 | only_needs_metadata, |
322 | sysroot: &sess.sysroot, | |
60c5eb7d | 323 | metadata_loader, |
49aad941 | 324 | cfg_version: sess.cfg_version, |
60c5eb7d XL |
325 | crate_name, |
326 | exact_paths: if hash.is_none() { | |
dfeec247 XL |
327 | sess.opts |
328 | .externs | |
a2a8927a | 329 | .get(crate_name.as_str()) |
dfeec247 | 330 | .into_iter() |
60c5eb7d XL |
331 | .filter_map(|entry| entry.files()) |
332 | .flatten() | |
5869c6ff | 333 | .cloned() |
dfeec247 | 334 | .collect() |
60c5eb7d XL |
335 | } else { |
336 | // SVH being specified means this is a transitive dependency, | |
337 | // so `--extern` options do not apply. | |
338 | Vec::new() | |
339 | }, | |
340 | hash, | |
60c5eb7d | 341 | extra_filename, |
29967ef6 | 342 | target: if is_host { &sess.host } else { &sess.target }, |
60c5eb7d XL |
343 | triple: if is_host { |
344 | TargetTriple::from_triple(config::host_triple()) | |
345 | } else { | |
346 | sess.opts.target_triple.clone() | |
347 | }, | |
348 | filesearch: if is_host { | |
349 | sess.host_filesearch(path_kind) | |
350 | } else { | |
351 | sess.target_filesearch(path_kind) | |
352 | }, | |
c295e0f8 XL |
353 | is_proc_macro: false, |
354 | crate_rejections: CrateRejections::default(), | |
60c5eb7d XL |
355 | } |
356 | } | |
357 | ||
923072b8 | 358 | pub(crate) fn reset(&mut self) { |
c295e0f8 XL |
359 | self.crate_rejections.via_hash.clear(); |
360 | self.crate_rejections.via_triple.clear(); | |
361 | self.crate_rejections.via_kind.clear(); | |
362 | self.crate_rejections.via_version.clear(); | |
363 | self.crate_rejections.via_filename.clear(); | |
3c0e092e | 364 | self.crate_rejections.via_invalid.clear(); |
532ac7d7 XL |
365 | } |
366 | ||
923072b8 | 367 | pub(crate) fn maybe_load_library_crate(&mut self) -> Result<Option<Library>, CrateError> { |
60c5eb7d XL |
368 | if !self.exact_paths.is_empty() { |
369 | return self.find_commandline_library(); | |
370 | } | |
b7449926 | 371 | let mut seen_paths = FxHashSet::default(); |
3dfed10e XL |
372 | if let Some(extra_filename) = self.extra_filename { |
373 | if let library @ Some(_) = self.find_library_crate(extra_filename, &mut seen_paths)? { | |
374 | return Ok(library); | |
476ff2be SL |
375 | } |
376 | } | |
3dfed10e | 377 | self.find_library_crate("", &mut seen_paths) |
1a4d82fc JJ |
378 | } |
379 | ||
dfeec247 XL |
380 | fn find_library_crate( |
381 | &mut self, | |
382 | extra_prefix: &str, | |
383 | seen_paths: &mut FxHashSet<PathBuf>, | |
3dfed10e | 384 | ) -> Result<Option<Library>, CrateError> { |
5099ac24 FG |
385 | let rmeta_prefix = &format!("lib{}{}", self.crate_name, extra_prefix); |
386 | let rlib_prefix = rmeta_prefix; | |
387 | let dylib_prefix = | |
388 | &format!("{}{}{}", self.target.dll_prefix, self.crate_name, extra_prefix); | |
3dfed10e | 389 | let staticlib_prefix = |
5099ac24 FG |
390 | &format!("{}{}{}", self.target.staticlib_prefix, self.crate_name, extra_prefix); |
391 | ||
392 | let rmeta_suffix = ".rmeta"; | |
393 | let rlib_suffix = ".rlib"; | |
394 | let dylib_suffix = &self.target.dll_suffix; | |
395 | let staticlib_suffix = &self.target.staticlib_suffix; | |
1a4d82fc | 396 | |
dfeec247 XL |
397 | let mut candidates: FxHashMap<_, (FxHashMap<_, _>, FxHashMap<_, _>, FxHashMap<_, _>)> = |
398 | Default::default(); | |
1a4d82fc JJ |
399 | |
400 | // First, find all possible candidate rlibs and dylibs purely based on | |
401 | // the name of the files themselves. We're trying to match against an | |
402 | // exact crate name and a possibly an exact hash. | |
403 | // | |
404 | // During this step, we can filter all found libraries based on the | |
405 | // name and id found in the crate id (we ignore the path portion for | |
406 | // filename matching), as well as the exact hash (if specified). If we | |
407 | // end up having many candidates, we must look at the metadata to | |
408 | // perform exact matches against hashes/crate ids. Note that opening up | |
409 | // the metadata is where we do an exact match against the full contents | |
410 | // of the crate id (path/name/id). | |
411 | // | |
412 | // The goal of this step is to look at as little metadata as possible. | |
5099ac24 FG |
413 | // Unfortunately, the prefix-based matching sometimes is over-eager. |
414 | // E.g. if `rlib_suffix` is `libstd` it'll match the file | |
415 | // `libstd_detect-8d6701fb958915ad.rlib` (incorrect) as well as | |
416 | // `libstd-f3ab5b1dea981f17.rlib` (correct). But this is hard to avoid | |
417 | // given that `extra_filename` comes from the `-C extra-filename` | |
418 | // option and thus can be anything, and the incorrect match will be | |
419 | // handled safely in `extract_one`. | |
420 | for search_path in self.filesearch.search_paths() { | |
421 | debug!("searching {}", search_path.dir.display()); | |
422 | for spf in search_path.files.iter() { | |
423 | debug!("testing {}", spf.path.display()); | |
424 | ||
425 | let f = &spf.file_name_str; | |
426 | let (hash, kind) = if f.starts_with(rlib_prefix) && f.ends_with(rlib_suffix) { | |
427 | (&f[rlib_prefix.len()..(f.len() - rlib_suffix.len())], CrateFlavor::Rlib) | |
428 | } else if f.starts_with(rmeta_prefix) && f.ends_with(rmeta_suffix) { | |
429 | (&f[rmeta_prefix.len()..(f.len() - rmeta_suffix.len())], CrateFlavor::Rmeta) | |
5e7ed085 | 430 | } else if f.starts_with(dylib_prefix) && f.ends_with(dylib_suffix.as_ref()) { |
5099ac24 FG |
431 | (&f[dylib_prefix.len()..(f.len() - dylib_suffix.len())], CrateFlavor::Dylib) |
432 | } else { | |
5e7ed085 | 433 | if f.starts_with(staticlib_prefix) && f.ends_with(staticlib_suffix.as_ref()) { |
5099ac24 FG |
434 | self.crate_rejections.via_kind.push(CrateMismatch { |
435 | path: spf.path.clone(), | |
436 | got: "static".to_string(), | |
437 | }); | |
438 | } | |
439 | continue; | |
440 | }; | |
83c7162d | 441 | |
5099ac24 | 442 | info!("lib candidate: {}", spf.path.display()); |
1a4d82fc | 443 | |
5099ac24 | 444 | let (rlibs, rmetas, dylibs) = candidates.entry(hash.to_string()).or_default(); |
353b0b11 | 445 | let path = try_canonicalize(&spf.path).unwrap_or_else(|_| spf.path.clone()); |
5099ac24 FG |
446 | if seen_paths.contains(&path) { |
447 | continue; | |
448 | }; | |
449 | seen_paths.insert(path.clone()); | |
450 | match kind { | |
451 | CrateFlavor::Rlib => rlibs.insert(path, search_path.kind), | |
452 | CrateFlavor::Rmeta => rmetas.insert(path, search_path.kind), | |
453 | CrateFlavor::Dylib => dylibs.insert(path, search_path.kind), | |
454 | }; | |
455 | } | |
456 | } | |
1a4d82fc JJ |
457 | |
458 | // We have now collected all known libraries into a set of candidates | |
459 | // keyed of the filename hash listed. For each filename, we also have a | |
460 | // list of rlibs/dylibs that apply. Here, we map each of these lists | |
461 | // (per hash), to a Library candidate for returning. | |
462 | // | |
463 | // A Library candidate is created if the metadata for the set of | |
464 | // libraries corresponds to the crate id and hash criteria that this | |
465 | // search is being performed for. | |
0bf4aa26 | 466 | let mut libraries = FxHashMap::default(); |
476ff2be | 467 | for (_hash, (rlibs, rmetas, dylibs)) in candidates { |
3dfed10e | 468 | if let Some((svh, lib)) = self.extract_lib(rlibs, rmetas, dylibs)? { |
e74abb32 | 469 | libraries.insert(svh, lib); |
1a4d82fc JJ |
470 | } |
471 | } | |
472 | ||
473 | // Having now translated all relevant found hashes into libraries, see | |
474 | // what we've got and figure out if we found multiple candidates for | |
475 | // libraries or not. | |
476 | match libraries.len() { | |
3dfed10e XL |
477 | 0 => Ok(None), |
478 | 1 => Ok(Some(libraries.into_iter().next().unwrap().1)), | |
9c376795 FG |
479 | _ => { |
480 | let mut libraries: Vec<_> = libraries.into_values().collect(); | |
481 | ||
482 | libraries.sort_by_cached_key(|lib| lib.source.paths().next().unwrap().clone()); | |
483 | let candidates = libraries | |
484 | .iter() | |
485 | .map(|lib| lib.source.paths().next().unwrap().clone()) | |
486 | .collect::<Vec<_>>(); | |
487 | ||
488 | Err(CrateError::MultipleCandidates( | |
489 | self.crate_name, | |
490 | // these are the same for all candidates | |
491 | get_flavor_from_path(candidates.first().unwrap()), | |
492 | candidates, | |
493 | )) | |
494 | } | |
1a4d82fc JJ |
495 | } |
496 | } | |
497 | ||
e74abb32 XL |
498 | fn extract_lib( |
499 | &mut self, | |
500 | rlibs: FxHashMap<PathBuf, PathKind>, | |
501 | rmetas: FxHashMap<PathBuf, PathKind>, | |
502 | dylibs: FxHashMap<PathBuf, PathKind>, | |
3dfed10e | 503 | ) -> Result<Option<(Svh, Library)>, CrateError> { |
e74abb32 | 504 | let mut slot = None; |
dfeec247 XL |
505 | // Order here matters, rmeta should come first. See comment in |
506 | // `extract_one` below. | |
e74abb32 | 507 | let source = CrateSource { |
3dfed10e XL |
508 | rmeta: self.extract_one(rmetas, CrateFlavor::Rmeta, &mut slot)?, |
509 | rlib: self.extract_one(rlibs, CrateFlavor::Rlib, &mut slot)?, | |
510 | dylib: self.extract_one(dylibs, CrateFlavor::Dylib, &mut slot)?, | |
e74abb32 | 511 | }; |
add651ee | 512 | Ok(slot.map(|(svh, metadata, _)| (svh, Library { source, metadata }))) |
e74abb32 XL |
513 | } |
514 | ||
dfeec247 | 515 | fn needs_crate_flavor(&self, flavor: CrateFlavor) -> bool { |
c295e0f8 | 516 | if flavor == CrateFlavor::Dylib && self.is_proc_macro { |
dfeec247 XL |
517 | return true; |
518 | } | |
519 | ||
c295e0f8 | 520 | if self.only_needs_metadata { |
dfeec247 XL |
521 | flavor == CrateFlavor::Rmeta |
522 | } else { | |
523 | // we need all flavors (perhaps not true, but what we do for now) | |
524 | true | |
525 | } | |
526 | } | |
527 | ||
1a4d82fc JJ |
528 | // Attempts to extract *one* library from the set `m`. If the set has no |
529 | // elements, `None` is returned. If the set has more than one element, then | |
530 | // the errors and notes are emitted about the set of libraries. | |
531 | // | |
532 | // With only one library in the set, this function will extract it, and then | |
533 | // read the metadata from it if `*slot` is `None`. If the metadata couldn't | |
534 | // be read, it is assumed that the file isn't a valid rust library (no | |
535 | // errors are emitted). | |
add651ee FG |
536 | // |
537 | // The `PathBuf` in `slot` will only be used for diagnostic purposes. | |
dfeec247 XL |
538 | fn extract_one( |
539 | &mut self, | |
540 | m: FxHashMap<PathBuf, PathKind>, | |
541 | flavor: CrateFlavor, | |
add651ee | 542 | slot: &mut Option<(Svh, MetadataBlob, PathBuf)>, |
3dfed10e | 543 | ) -> Result<Option<(PathBuf, PathKind)>, CrateError> { |
dfeec247 XL |
544 | // If we are producing an rlib, and we've already loaded metadata, then |
545 | // we should not attempt to discover further crate sources (unless we're | |
546 | // locating a proc macro; exact logic is in needs_crate_flavor). This means | |
547 | // that under -Zbinary-dep-depinfo we will not emit a dependency edge on | |
548 | // the *unused* rlib, and by returning `None` here immediately we | |
549 | // guarantee that we do indeed not use it. | |
550 | // | |
551 | // See also #68149 which provides more detail on why emitting the | |
552 | // dependency on the rlib is a bad thing. | |
1a4d82fc | 553 | if slot.is_some() { |
dfeec247 | 554 | if m.is_empty() || !self.needs_crate_flavor(flavor) { |
3dfed10e | 555 | return Ok(None); |
1a4d82fc JJ |
556 | } |
557 | } | |
558 | ||
3dfed10e XL |
559 | let mut ret: Option<(PathBuf, PathKind)> = None; |
560 | let mut err_data: Option<Vec<PathBuf>> = None; | |
85aaf69f | 561 | for (lib, kind) in m { |
1a4d82fc | 562 | info!("{} reading metadata from: {}", flavor, lib.display()); |
49aad941 | 563 | if flavor == CrateFlavor::Rmeta && lib.metadata().is_ok_and(|m| m.len() == 0) { |
c295e0f8 XL |
564 | // Empty files will cause get_metadata_section to fail. Rmeta |
565 | // files can be empty, for example with binaries (which can | |
566 | // often appear with `cargo check` when checking a library as | |
567 | // a unittest). We don't want to emit a user-visible warning | |
568 | // in this case as it is not a real problem. | |
569 | debug!("skipping empty file"); | |
570 | continue; | |
571 | } | |
7cac9316 XL |
572 | let (hash, metadata) = |
573 | match get_metadata_section(self.target, flavor, &lib, self.metadata_loader) { | |
574 | Ok(blob) => { | |
575 | if let Some(h) = self.crate_matches(&blob, &lib) { | |
576 | (h, blob) | |
577 | } else { | |
578 | info!("metadata mismatch"); | |
579 | continue; | |
580 | } | |
581 | } | |
3c0e092e XL |
582 | Err(MetadataError::LoadFailure(err)) => { |
583 | info!("no metadata found: {}", err); | |
584 | // The file was present and created by the same compiler version, but we | |
9c376795 | 585 | // couldn't load it for some reason. Give a hard error instead of silently |
3c0e092e XL |
586 | // ignoring it, but only if we would have given an error anyway. |
587 | self.crate_rejections | |
588 | .via_invalid | |
589 | .push(CrateMismatch { path: lib, got: err }); | |
590 | continue; | |
591 | } | |
592 | Err(err @ MetadataError::NotPresent(_)) => { | |
593 | info!("no metadata found: {}", err); | |
c30ab7b3 | 594 | continue; |
1a4d82fc | 595 | } |
7cac9316 | 596 | }; |
a7813a04 | 597 | // If we see multiple hashes, emit an error about duplicate candidates. |
49aad941 | 598 | if slot.as_ref().is_some_and(|s| s.0 != hash) { |
3dfed10e XL |
599 | if let Some(candidates) = err_data { |
600 | return Err(CrateError::MultipleCandidates( | |
601 | self.crate_name, | |
602 | flavor, | |
603 | candidates, | |
604 | )); | |
9cc50fc6 | 605 | } |
add651ee | 606 | err_data = Some(vec![slot.take().unwrap().2]); |
1a4d82fc | 607 | } |
3dfed10e XL |
608 | if let Some(candidates) = &mut err_data { |
609 | candidates.push(lib); | |
c30ab7b3 | 610 | continue; |
970d7e83 | 611 | } |
8bb4bdeb XL |
612 | |
613 | // Ok so at this point we've determined that `(lib, kind)` above is | |
614 | // a candidate crate to load, and that `slot` is either none (this | |
615 | // is the first crate of its kind) or if some the previous path has | |
0731742a | 616 | // the exact same hash (e.g., it's the exact same crate). |
8bb4bdeb XL |
617 | // |
618 | // In principle these two candidate crates are exactly the same so | |
619 | // we can choose either of them to link. As a stupidly gross hack, | |
620 | // however, we favor crate in the sysroot. | |
621 | // | |
622 | // You can find more info in rust-lang/rust#39518 and various linked | |
623 | // issues, but the general gist is that during testing libstd the | |
624 | // compilers has two candidates to choose from: one in the sysroot | |
625 | // and one in the deps folder. These two crates are the exact same | |
626 | // crate but if the compiler chooses the one in the deps folder | |
627 | // it'll cause spurious errors on Windows. | |
628 | // | |
629 | // As a result, we favor the sysroot crate here. Note that the | |
630 | // candidates are all canonicalized, so we canonicalize the sysroot | |
631 | // as well. | |
3dfed10e | 632 | if let Some((prev, _)) = &ret { |
c295e0f8 | 633 | let sysroot = self.sysroot; |
353b0b11 | 634 | let sysroot = try_canonicalize(sysroot).unwrap_or_else(|_| sysroot.to_path_buf()); |
8bb4bdeb | 635 | if prev.starts_with(&sysroot) { |
dfeec247 | 636 | continue; |
8bb4bdeb XL |
637 | } |
638 | } | |
add651ee | 639 | *slot = Some((hash, metadata, lib.clone())); |
85aaf69f | 640 | ret = Some((lib, kind)); |
1a4d82fc | 641 | } |
9cc50fc6 | 642 | |
3dfed10e XL |
643 | if let Some(candidates) = err_data { |
644 | Err(CrateError::MultipleCandidates(self.crate_name, flavor, candidates)) | |
9cc50fc6 | 645 | } else { |
3dfed10e | 646 | Ok(ret) |
9cc50fc6 | 647 | } |
1a4d82fc JJ |
648 | } |
649 | ||
9e0c209e | 650 | fn crate_matches(&mut self, metadata: &MetadataBlob, libpath: &Path) -> Option<Svh> { |
49aad941 | 651 | let rustc_version = rustc_version(self.cfg_version); |
476ff2be SL |
652 | let found_version = metadata.get_rustc_version(); |
653 | if found_version != rustc_version { | |
dfeec247 | 654 | info!("Rejecting via version: expected {} got {}", rustc_version, found_version); |
c295e0f8 XL |
655 | self.crate_rejections |
656 | .via_version | |
dfeec247 | 657 | .push(CrateMismatch { path: libpath.to_path_buf(), got: found_version }); |
a7813a04 XL |
658 | return None; |
659 | } | |
660 | ||
fe692bf9 FG |
661 | let header = metadata.get_header(); |
662 | if header.is_proc_macro_crate != self.is_proc_macro { | |
c295e0f8 XL |
663 | info!( |
664 | "Rejecting via proc macro: expected {} got {}", | |
fe692bf9 | 665 | self.is_proc_macro, header.is_proc_macro_crate, |
c295e0f8 XL |
666 | ); |
667 | return None; | |
476ff2be SL |
668 | } |
669 | ||
fe692bf9 | 670 | if self.exact_paths.is_empty() && self.crate_name != header.name { |
29967ef6 XL |
671 | info!("Rejecting via crate name"); |
672 | return None; | |
1a4d82fc | 673 | } |
1a4d82fc | 674 | |
fe692bf9 FG |
675 | if header.triple != self.triple { |
676 | info!("Rejecting via crate triple: expected {} got {}", self.triple, header.triple); | |
c295e0f8 | 677 | self.crate_rejections.via_triple.push(CrateMismatch { |
c34b1796 | 678 | path: libpath.to_path_buf(), |
fe692bf9 | 679 | got: header.triple.to_string(), |
1a4d82fc | 680 | }); |
a7813a04 | 681 | return None; |
223e47cc | 682 | } |
223e47cc | 683 | |
fe692bf9 | 684 | let hash = header.hash; |
60c5eb7d XL |
685 | if let Some(expected_hash) = self.hash { |
686 | if hash != expected_hash { | |
687 | info!("Rejecting via hash: expected {} got {}", expected_hash, hash); | |
c295e0f8 XL |
688 | self.crate_rejections |
689 | .via_hash | |
dfeec247 | 690 | .push(CrateMismatch { path: libpath.to_path_buf(), got: hash.to_string() }); |
a7813a04 | 691 | return None; |
1a4d82fc | 692 | } |
223e47cc | 693 | } |
a7813a04 | 694 | |
60c5eb7d | 695 | Some(hash) |
223e47cc | 696 | } |
223e47cc | 697 | |
3dfed10e | 698 | fn find_commandline_library(&mut self) -> Result<Option<Library>, CrateError> { |
1a4d82fc JJ |
699 | // First, filter out all libraries that look suspicious. We only accept |
700 | // files which actually exist that have the correct naming scheme for | |
701 | // rlibs/dylibs. | |
0bf4aa26 XL |
702 | let mut rlibs = FxHashMap::default(); |
703 | let mut rmetas = FxHashMap::default(); | |
704 | let mut dylibs = FxHashMap::default(); | |
3dfed10e | 705 | for loc in &self.exact_paths { |
5869c6ff XL |
706 | if !loc.canonicalized().exists() { |
707 | return Err(CrateError::ExternLocationNotExist( | |
708 | self.crate_name, | |
709 | loc.original().clone(), | |
710 | )); | |
3dfed10e | 711 | } |
487cf647 FG |
712 | if !loc.original().is_file() { |
713 | return Err(CrateError::ExternLocationNotFile( | |
714 | self.crate_name, | |
715 | loc.original().clone(), | |
716 | )); | |
717 | } | |
5e7ed085 FG |
718 | let Some(file) = loc.original().file_name().and_then(|s| s.to_str()) else { |
719 | return Err(CrateError::ExternLocationNotFile( | |
720 | self.crate_name, | |
721 | loc.original().clone(), | |
722 | )); | |
3dfed10e | 723 | }; |
476ff2be | 724 | |
3dfed10e | 725 | if file.starts_with("lib") && (file.ends_with(".rlib") || file.ends_with(".rmeta")) |
5e7ed085 FG |
726 | || file.starts_with(self.target.dll_prefix.as_ref()) |
727 | && file.ends_with(self.target.dll_suffix.as_ref()) | |
3dfed10e XL |
728 | { |
729 | // Make sure there's at most one rlib and at most one dylib. | |
730 | // Note to take care and match against the non-canonicalized name: | |
731 | // some systems save build artifacts into content-addressed stores | |
732 | // that do not preserve extensions, and then link to them using | |
733 | // e.g. symbolic links. If we canonicalize too early, we resolve | |
734 | // the symlink, the file type is lost and we might treat rlibs and | |
735 | // rmetas as dylibs. | |
5869c6ff XL |
736 | let loc_canon = loc.canonicalized().clone(); |
737 | let loc = loc.original(); | |
c34b1796 | 738 | if loc.file_name().unwrap().to_str().unwrap().ends_with(".rlib") { |
3dfed10e | 739 | rlibs.insert(loc_canon, PathKind::ExternFlag); |
476ff2be | 740 | } else if loc.file_name().unwrap().to_str().unwrap().ends_with(".rmeta") { |
3dfed10e | 741 | rmetas.insert(loc_canon, PathKind::ExternFlag); |
1a4d82fc | 742 | } else { |
3dfed10e | 743 | dylibs.insert(loc_canon, PathKind::ExternFlag); |
1a4d82fc | 744 | } |
3dfed10e | 745 | } else { |
c295e0f8 XL |
746 | self.crate_rejections |
747 | .via_filename | |
5869c6ff | 748 | .push(CrateMismatch { path: loc.original().clone(), got: String::new() }); |
1a4d82fc | 749 | } |
3dfed10e | 750 | } |
1a4d82fc | 751 | |
e74abb32 | 752 | // Extract the dylib/rlib/rmeta triple. |
3dfed10e | 753 | Ok(self.extract_lib(rlibs, rmetas, dylibs)?.map(|(_, lib)| lib)) |
223e47cc | 754 | } |
223e47cc | 755 | |
923072b8 | 756 | pub(crate) fn into_error(self, root: Option<CratePaths>) -> CrateError { |
353b0b11 | 757 | CrateError::LocatorCombined(Box::new(CombinedLocatorError { |
3dfed10e | 758 | crate_name: self.crate_name, |
c295e0f8 | 759 | root, |
3dfed10e | 760 | triple: self.triple, |
5e7ed085 FG |
761 | dll_prefix: self.target.dll_prefix.to_string(), |
762 | dll_suffix: self.target.dll_suffix.to_string(), | |
c295e0f8 | 763 | crate_rejections: self.crate_rejections, |
353b0b11 | 764 | })) |
3dfed10e | 765 | } |
223e47cc LB |
766 | } |
767 | ||
a2a8927a | 768 | fn get_metadata_section<'p>( |
dfeec247 XL |
769 | target: &Target, |
770 | flavor: CrateFlavor, | |
3c0e092e | 771 | filename: &'p Path, |
dfeec247 | 772 | loader: &dyn MetadataLoader, |
3c0e092e | 773 | ) -> Result<MetadataBlob, MetadataError<'p>> { |
1a4d82fc | 774 | if !filename.exists() { |
3c0e092e | 775 | return Err(MetadataError::NotPresent(filename)); |
1a4d82fc | 776 | } |
49aad941 | 777 | let raw_bytes = match flavor { |
3c0e092e XL |
778 | CrateFlavor::Rlib => { |
779 | loader.get_rlib_metadata(target, filename).map_err(MetadataError::LoadFailure)? | |
780 | } | |
7cac9316 | 781 | CrateFlavor::Dylib => { |
3c0e092e XL |
782 | let buf = |
783 | loader.get_dylib_metadata(target, filename).map_err(MetadataError::LoadFailure)?; | |
7cac9316 XL |
784 | // The header is uncompressed |
785 | let header_len = METADATA_HEADER.len(); | |
4b012472 FG |
786 | // header + u64 length of data |
787 | let data_start = header_len + 8; | |
353b0b11 | 788 | |
7cac9316 XL |
789 | debug!("checking {} bytes of metadata-version stamp", header_len); |
790 | let header = &buf[..cmp::min(header_len, buf.len())]; | |
791 | if header != METADATA_HEADER { | |
3c0e092e XL |
792 | return Err(MetadataError::LoadFailure(format!( |
793 | "invalid metadata version found: {}", | |
dfeec247 | 794 | filename.display() |
3c0e092e | 795 | ))); |
1a4d82fc | 796 | } |
223e47cc | 797 | |
353b0b11 | 798 | // Length of the compressed stream - this allows linkers to pad the section if they want |
add651ee | 799 | let Ok(len_bytes) = |
4b012472 | 800 | <[u8; 8]>::try_from(&buf[header_len..cmp::min(data_start, buf.len())]) |
add651ee FG |
801 | else { |
802 | return Err(MetadataError::LoadFailure( | |
803 | "invalid metadata length found".to_string(), | |
804 | )); | |
353b0b11 | 805 | }; |
4b012472 | 806 | let compressed_len = u64::from_le_bytes(len_bytes) as usize; |
353b0b11 | 807 | |
7cac9316 | 808 | // Header is okay -> inflate the actual metadata |
add651ee FG |
809 | let compressed_bytes = buf.slice(|buf| &buf[data_start..(data_start + compressed_len)]); |
810 | if &compressed_bytes[..cmp::min(METADATA_HEADER.len(), compressed_bytes.len())] | |
811 | == METADATA_HEADER | |
812 | { | |
813 | // The metadata was not actually compressed. | |
814 | compressed_bytes | |
815 | } else { | |
816 | debug!("inflating {} bytes of compressed metadata", compressed_bytes.len()); | |
817 | // Assume the decompressed data will be at least the size of the compressed data, so we | |
818 | // don't have to grow the buffer as much. | |
819 | let mut inflated = Vec::with_capacity(compressed_bytes.len()); | |
820 | FrameDecoder::new(&*compressed_bytes).read_to_end(&mut inflated).map_err(|_| { | |
821 | MetadataError::LoadFailure(format!( | |
822 | "failed to decompress metadata: {}", | |
823 | filename.display() | |
824 | )) | |
825 | })?; | |
353b0b11 | 826 | |
add651ee FG |
827 | slice_owned(inflated, Deref::deref) |
828 | } | |
223e47cc | 829 | } |
7cac9316 | 830 | CrateFlavor::Rmeta => { |
a1dfa0c6 | 831 | // mmap the file, because only a small fraction of it is read. |
3c0e092e XL |
832 | let file = std::fs::File::open(filename).map_err(|_| { |
833 | MetadataError::LoadFailure(format!( | |
834 | "failed to open rmeta metadata: '{}'", | |
835 | filename.display() | |
836 | )) | |
837 | })?; | |
cdc7bbd5 | 838 | let mmap = unsafe { Mmap::map(file) }; |
3c0e092e XL |
839 | let mmap = mmap.map_err(|_| { |
840 | MetadataError::LoadFailure(format!( | |
841 | "failed to mmap rmeta metadata: '{}'", | |
842 | filename.display() | |
843 | )) | |
844 | })?; | |
a1dfa0c6 | 845 | |
353b0b11 | 846 | slice_owned(mmap, Deref::deref) |
7cac9316 XL |
847 | } |
848 | }; | |
49aad941 | 849 | let blob = MetadataBlob(raw_bytes); |
7cac9316 XL |
850 | if blob.is_compatible() { |
851 | Ok(blob) | |
1a4d82fc | 852 | } else { |
3c0e092e XL |
853 | Err(MetadataError::LoadFailure(format!( |
854 | "invalid metadata version found: {}", | |
855 | filename.display() | |
856 | ))) | |
223e47cc LB |
857 | } |
858 | } | |
859 | ||
9fa01778 | 860 | /// A diagnostic function for dumping crate metadata to an output stream. |
dfeec247 XL |
861 | pub fn list_file_metadata( |
862 | target: &Target, | |
863 | path: &Path, | |
864 | metadata_loader: &dyn MetadataLoader, | |
3dfed10e | 865 | out: &mut dyn Write, |
781aab86 | 866 | ls_kinds: &[String], |
3dfed10e | 867 | ) -> IoResult<()> { |
9c376795 FG |
868 | let flavor = get_flavor_from_path(path); |
869 | match get_metadata_section(target, flavor, path, metadata_loader) { | |
781aab86 | 870 | Ok(metadata) => metadata.list_crate_metadata(out, ls_kinds), |
add651ee | 871 | Err(msg) => write!(out, "{msg}\n"), |
9c376795 FG |
872 | } |
873 | } | |
874 | ||
875 | fn get_flavor_from_path(path: &Path) -> CrateFlavor { | |
a7813a04 | 876 | let filename = path.file_name().unwrap().to_str().unwrap(); |
9c376795 FG |
877 | |
878 | if filename.ends_with(".rlib") { | |
c30ab7b3 | 879 | CrateFlavor::Rlib |
476ff2be SL |
880 | } else if filename.ends_with(".rmeta") { |
881 | CrateFlavor::Rmeta | |
c30ab7b3 SL |
882 | } else { |
883 | CrateFlavor::Dylib | |
223e47cc LB |
884 | } |
885 | } | |
3dfed10e XL |
886 | |
887 | // ------------------------------------------ Error reporting ------------------------------------- | |
888 | ||
889 | #[derive(Clone)] | |
890 | struct CrateMismatch { | |
891 | path: PathBuf, | |
892 | got: String, | |
893 | } | |
894 | ||
c295e0f8 XL |
895 | #[derive(Clone, Default)] |
896 | struct CrateRejections { | |
897 | via_hash: Vec<CrateMismatch>, | |
898 | via_triple: Vec<CrateMismatch>, | |
899 | via_kind: Vec<CrateMismatch>, | |
900 | via_version: Vec<CrateMismatch>, | |
901 | via_filename: Vec<CrateMismatch>, | |
3c0e092e | 902 | via_invalid: Vec<CrateMismatch>, |
c295e0f8 XL |
903 | } |
904 | ||
3dfed10e XL |
905 | /// Candidate rejection reasons collected during crate search. |
906 | /// If no candidate is accepted, then these reasons are presented to the user, | |
907 | /// otherwise they are ignored. | |
923072b8 | 908 | pub(crate) struct CombinedLocatorError { |
3dfed10e XL |
909 | crate_name: Symbol, |
910 | root: Option<CratePaths>, | |
911 | triple: TargetTriple, | |
912 | dll_prefix: String, | |
913 | dll_suffix: String, | |
c295e0f8 | 914 | crate_rejections: CrateRejections, |
3dfed10e XL |
915 | } |
916 | ||
923072b8 | 917 | pub(crate) enum CrateError { |
3dfed10e XL |
918 | NonAsciiName(Symbol), |
919 | ExternLocationNotExist(Symbol, PathBuf), | |
920 | ExternLocationNotFile(Symbol, PathBuf), | |
921 | MultipleCandidates(Symbol, CrateFlavor, Vec<PathBuf>), | |
3dfed10e | 922 | SymbolConflictsCurrent(Symbol), |
6a06907d | 923 | StableCrateIdCollision(Symbol, Symbol), |
3dfed10e XL |
924 | DlOpen(String), |
925 | DlSym(String), | |
353b0b11 | 926 | LocatorCombined(Box<CombinedLocatorError>), |
49aad941 | 927 | NotFound(Symbol), |
3dfed10e XL |
928 | } |
929 | ||
3c0e092e XL |
930 | enum MetadataError<'a> { |
931 | /// The file was missing. | |
932 | NotPresent(&'a Path), | |
933 | /// The file was present and invalid. | |
934 | LoadFailure(String), | |
935 | } | |
936 | ||
937 | impl fmt::Display for MetadataError<'_> { | |
938 | fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { | |
939 | match self { | |
940 | MetadataError::NotPresent(filename) => { | |
941 | f.write_str(&format!("no such file: '{}'", filename.display())) | |
942 | } | |
943 | MetadataError::LoadFailure(msg) => f.write_str(msg), | |
944 | } | |
945 | } | |
946 | } | |
947 | ||
3dfed10e | 948 | impl CrateError { |
923072b8 | 949 | pub(crate) fn report(self, sess: &Session, span: Span, missing_core: bool) { |
f2b60f7d FG |
950 | match self { |
951 | CrateError::NonAsciiName(crate_name) => { | |
9ffffee4 | 952 | sess.emit_err(errors::NonAsciiName { span, crate_name }); |
f2b60f7d FG |
953 | } |
954 | CrateError::ExternLocationNotExist(crate_name, loc) => { | |
9ffffee4 | 955 | sess.emit_err(errors::ExternLocationNotExist { span, crate_name, location: &loc }); |
f2b60f7d FG |
956 | } |
957 | CrateError::ExternLocationNotFile(crate_name, loc) => { | |
9ffffee4 | 958 | sess.emit_err(errors::ExternLocationNotFile { span, crate_name, location: &loc }); |
f2b60f7d | 959 | } |
3dfed10e | 960 | CrateError::MultipleCandidates(crate_name, flavor, candidates) => { |
9ffffee4 | 961 | sess.emit_err(errors::MultipleCandidates { span, crate_name, flavor, candidates }); |
f2b60f7d FG |
962 | } |
963 | CrateError::SymbolConflictsCurrent(root_name) => { | |
9ffffee4 | 964 | sess.emit_err(errors::SymbolConflictsCurrent { span, crate_name: root_name }); |
3dfed10e | 965 | } |
6a06907d | 966 | CrateError::StableCrateIdCollision(crate_name0, crate_name1) => { |
9ffffee4 | 967 | sess.emit_err(errors::StableCrateIdCollision { span, crate_name0, crate_name1 }); |
f2b60f7d FG |
968 | } |
969 | CrateError::DlOpen(s) | CrateError::DlSym(s) => { | |
9ffffee4 | 970 | sess.emit_err(errors::DlError { span, err: s }); |
6a06907d | 971 | } |
3dfed10e XL |
972 | CrateError::LocatorCombined(locator) => { |
973 | let crate_name = locator.crate_name; | |
f2b60f7d | 974 | let add_info = match &locator.root { |
3dfed10e XL |
975 | None => String::new(), |
976 | Some(r) => format!(" which `{}` depends on", r.name), | |
977 | }; | |
f2b60f7d FG |
978 | if !locator.crate_rejections.via_filename.is_empty() { |
979 | let mismatches = locator.crate_rejections.via_filename.iter(); | |
980 | for CrateMismatch { path, .. } in mismatches { | |
9ffffee4 FG |
981 | sess.emit_err(errors::CrateLocationUnknownType { |
982 | span, | |
4b012472 | 983 | path: path, |
9ffffee4 FG |
984 | crate_name, |
985 | }); | |
986 | sess.emit_err(errors::LibFilenameForm { | |
f2b60f7d FG |
987 | span, |
988 | dll_prefix: &locator.dll_prefix, | |
989 | dll_suffix: &locator.dll_suffix, | |
990 | }); | |
991 | } | |
992 | } | |
993 | let mut found_crates = String::new(); | |
994 | if !locator.crate_rejections.via_hash.is_empty() { | |
c295e0f8 | 995 | let mismatches = locator.crate_rejections.via_hash.iter(); |
3dfed10e | 996 | for CrateMismatch { path, .. } in mismatches { |
f2b60f7d FG |
997 | found_crates.push_str(&format!( |
998 | "\ncrate `{}`: {}", | |
999 | crate_name, | |
1000 | path.display() | |
1001 | )); | |
3dfed10e XL |
1002 | } |
1003 | if let Some(r) = locator.root { | |
1004 | for path in r.source.paths() { | |
f2b60f7d FG |
1005 | found_crates.push_str(&format!( |
1006 | "\ncrate `{}`: {}", | |
1007 | r.name, | |
1008 | path.display() | |
1009 | )); | |
3dfed10e XL |
1010 | } |
1011 | } | |
9ffffee4 | 1012 | sess.emit_err(errors::NewerCrateVersion { |
3dfed10e | 1013 | span, |
f2b60f7d FG |
1014 | crate_name: crate_name, |
1015 | add_info, | |
1016 | found_crates, | |
1017 | }); | |
1018 | } else if !locator.crate_rejections.via_triple.is_empty() { | |
c295e0f8 | 1019 | let mismatches = locator.crate_rejections.via_triple.iter(); |
3dfed10e | 1020 | for CrateMismatch { path, got } in mismatches { |
f2b60f7d | 1021 | found_crates.push_str(&format!( |
3dfed10e XL |
1022 | "\ncrate `{}`, target triple {}: {}", |
1023 | crate_name, | |
1024 | got, | |
1025 | path.display(), | |
1026 | )); | |
1027 | } | |
9ffffee4 | 1028 | sess.emit_err(errors::NoCrateWithTriple { |
3dfed10e | 1029 | span, |
9c376795 | 1030 | crate_name, |
f2b60f7d FG |
1031 | locator_triple: locator.triple.triple(), |
1032 | add_info, | |
1033 | found_crates, | |
1034 | }); | |
1035 | } else if !locator.crate_rejections.via_kind.is_empty() { | |
c295e0f8 | 1036 | let mismatches = locator.crate_rejections.via_kind.iter(); |
3dfed10e | 1037 | for CrateMismatch { path, .. } in mismatches { |
f2b60f7d FG |
1038 | found_crates.push_str(&format!( |
1039 | "\ncrate `{}`: {}", | |
1040 | crate_name, | |
1041 | path.display() | |
1042 | )); | |
3dfed10e | 1043 | } |
9ffffee4 FG |
1044 | sess.emit_err(errors::FoundStaticlib { |
1045 | span, | |
1046 | crate_name, | |
1047 | add_info, | |
1048 | found_crates, | |
1049 | }); | |
c295e0f8 | 1050 | } else if !locator.crate_rejections.via_version.is_empty() { |
c295e0f8 | 1051 | let mismatches = locator.crate_rejections.via_version.iter(); |
3dfed10e | 1052 | for CrateMismatch { path, got } in mismatches { |
f2b60f7d | 1053 | found_crates.push_str(&format!( |
3dfed10e XL |
1054 | "\ncrate `{}` compiled by {}: {}", |
1055 | crate_name, | |
1056 | got, | |
1057 | path.display(), | |
1058 | )); | |
1059 | } | |
9ffffee4 | 1060 | sess.emit_err(errors::IncompatibleRustc { |
3c0e092e | 1061 | span, |
3c0e092e | 1062 | crate_name, |
f2b60f7d FG |
1063 | add_info, |
1064 | found_crates, | |
49aad941 | 1065 | rustc_version: rustc_version(sess.cfg_version), |
f2b60f7d FG |
1066 | }); |
1067 | } else if !locator.crate_rejections.via_invalid.is_empty() { | |
1068 | let mut crate_rejections = Vec::new(); | |
3c0e092e | 1069 | for CrateMismatch { path: _, got } in locator.crate_rejections.via_invalid { |
f2b60f7d | 1070 | crate_rejections.push(got); |
3c0e092e | 1071 | } |
9ffffee4 | 1072 | sess.emit_err(errors::InvalidMetadataFiles { |
f2b60f7d FG |
1073 | span, |
1074 | crate_name, | |
1075 | add_info, | |
1076 | crate_rejections, | |
1077 | }); | |
3dfed10e | 1078 | } else { |
9ffffee4 | 1079 | sess.emit_err(errors::CannotFindCrate { |
3dfed10e | 1080 | span, |
3dfed10e | 1081 | crate_name, |
f2b60f7d FG |
1082 | add_info, |
1083 | missing_core, | |
1084 | current_crate: sess | |
1085 | .opts | |
1086 | .crate_name | |
1087 | .clone() | |
1088 | .unwrap_or("<unknown>".to_string()), | |
1089 | is_nightly_build: sess.is_nightly_build(), | |
1090 | profiler_runtime: Symbol::intern(&sess.opts.unstable_opts.profiler_runtime), | |
1091 | locator_triple: locator.triple, | |
add651ee | 1092 | is_ui_testing: sess.opts.unstable_opts.ui_testing, |
f2b60f7d | 1093 | }); |
3dfed10e | 1094 | } |
3dfed10e | 1095 | } |
49aad941 FG |
1096 | CrateError::NotFound(crate_name) => { |
1097 | sess.emit_err(errors::CannotFindCrate { | |
1098 | span, | |
1099 | crate_name, | |
1100 | add_info: String::new(), | |
1101 | missing_core, | |
1102 | current_crate: sess.opts.crate_name.clone().unwrap_or("<unknown>".to_string()), | |
1103 | is_nightly_build: sess.is_nightly_build(), | |
1104 | profiler_runtime: Symbol::intern(&sess.opts.unstable_opts.profiler_runtime), | |
1105 | locator_triple: sess.opts.target_triple.clone(), | |
add651ee | 1106 | is_ui_testing: sess.opts.unstable_opts.ui_testing, |
49aad941 FG |
1107 | }); |
1108 | } | |
f2b60f7d | 1109 | } |
3dfed10e XL |
1110 | } |
1111 | } |