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 is 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!
214215use std::borrow::Cow;
216use std::io::{self, Erroras IoError, ErrorKindas IoErrorKind, Resultas IoResult, Write};
217use std::ops::Deref;
218use std::path::{Path, PathBuf};
219use std::{cmp, fmt};
220221use rustc_data_structures::fx::{FxHashSet, FxIndexMap, FxIndexSet};
222use rustc_data_structures::memmap::Mmap;
223use rustc_data_structures::owned_slice::{OwnedSlice, slice_owned};
224use rustc_data_structures::svh::Svh;
225use rustc_errors::{DiagArgValue, IntoDiagArg};
226use rustc_fs_util::try_canonicalize;
227use rustc_proc_macro::bridge::client::Clientas ProcMacroClient;
228use rustc_session::cstore::CrateSource;
229use rustc_session::filesearch::FileSearch;
230use rustc_session::search_paths::PathKind;
231use rustc_session::utils::CanonicalizedPath;
232use rustc_session::{Session, config};
233use rustc_span::{Span, Symbol};
234use rustc_target::spec::{Target, TargetTuple};
235use tempfile::Builderas TempFileBuilder;
236use tracing::{debug, info};
237238use crate::creader::{Library, MetadataLoader};
239use crate::diagnostics;
240use crate::rmeta::{METADATA_HEADER, MetadataBlob, ProcMacroKind, rustc_version};
241242#[derive(#[automatically_derived]
impl<'a> ::core::clone::Clone for CrateLocator<'a> {
#[inline]
fn clone(&self) -> CrateLocator<'a> {
CrateLocator {
only_needs_metadata: ::core::clone::Clone::clone(&self.only_needs_metadata),
metadata_loader: ::core::clone::Clone::clone(&self.metadata_loader),
cfg_version: ::core::clone::Clone::clone(&self.cfg_version),
crate_name: ::core::clone::Clone::clone(&self.crate_name),
exact_paths: ::core::clone::Clone::clone(&self.exact_paths),
hash: ::core::clone::Clone::clone(&self.hash),
extra_filename: ::core::clone::Clone::clone(&self.extra_filename),
target: ::core::clone::Clone::clone(&self.target),
tuple: ::core::clone::Clone::clone(&self.tuple),
filesearch: ::core::clone::Clone::clone(&self.filesearch),
is_proc_macro: ::core::clone::Clone::clone(&self.is_proc_macro),
path_kind: ::core::clone::Clone::clone(&self.path_kind),
}
}
}Clone)]
243pub(crate) struct CrateLocator<'a> {
244// Immutable per-session configuration.
245only_needs_metadata: bool,
246 metadata_loader: &'a dyn MetadataLoader,
247 cfg_version: &'static str,
248249// Immutable per-search configuration.
250crate_name: Symbol,
251 exact_paths: Vec<CanonicalizedPath>,
252pub hash: Option<Svh>,
253 extra_filename: Option<&'a str>,
254 target: &'a Target,
255 tuple: TargetTuple,
256 filesearch: &'a FileSearch,
257 is_proc_macro: bool,
258 path_kind: PathKind,
259}
260261#[derive(#[automatically_derived]
impl ::core::clone::Clone for CratePaths {
#[inline]
fn clone(&self) -> CratePaths {
CratePaths {
name: ::core::clone::Clone::clone(&self.name),
source: ::core::clone::Clone::clone(&self.source),
}
}
}Clone, #[automatically_derived]
impl ::core::fmt::Debug for CratePaths {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
::core::fmt::Formatter::debug_struct_field2_finish(f, "CratePaths",
"name", &self.name, "source", &&self.source)
}
}Debug)]
262pub(crate) struct CratePaths {
263pub(crate) name: Symbol,
264 source: CrateSource,
265}
266267impl CratePaths {
268pub(crate) fn new(name: Symbol, source: CrateSource) -> CratePaths {
269CratePaths { name, source }
270 }
271}
272273#[derive(#[automatically_derived]
impl ::core::marker::Copy for CrateFlavor { }Copy, #[automatically_derived]
impl ::core::clone::Clone for CrateFlavor {
#[inline]
fn clone(&self) -> CrateFlavor { *self }
}Clone, #[automatically_derived]
impl ::core::fmt::Debug for CrateFlavor {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
::core::fmt::Formatter::write_str(f,
match self {
CrateFlavor::Rlib => "Rlib",
CrateFlavor::Rmeta => "Rmeta",
CrateFlavor::Dylib => "Dylib",
CrateFlavor::SDylib => "SDylib",
})
}
}Debug, #[automatically_derived]
impl ::core::cmp::PartialEq for CrateFlavor {
#[inline]
fn eq(&self, other: &CrateFlavor) -> bool {
let __self_discr = ::core::intrinsics::discriminant_value(self);
let __arg1_discr = ::core::intrinsics::discriminant_value(other);
__self_discr == __arg1_discr
}
}PartialEq)]
274pub(crate) enum CrateFlavor {
275 Rlib,
276 Rmeta,
277 Dylib,
278 SDylib,
279}
280281impl fmt::Displayfor CrateFlavor {
282fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
283f.write_str(match *self {
284 CrateFlavor::Rlib => "rlib",
285 CrateFlavor::Rmeta => "rmeta",
286 CrateFlavor::Dylib => "dylib",
287 CrateFlavor::SDylib => "sdylib",
288 })
289 }
290}
291292impl IntoDiagArgfor CrateFlavor {
293fn into_diag_arg(self, _: &mut Option<std::path::PathBuf>) -> rustc_errors::DiagArgValue {
294match self {
295 CrateFlavor::Rlib => DiagArgValue::Str(Cow::Borrowed("rlib")),
296 CrateFlavor::Rmeta => DiagArgValue::Str(Cow::Borrowed("rmeta")),
297 CrateFlavor::Dylib => DiagArgValue::Str(Cow::Borrowed("dylib")),
298 CrateFlavor::SDylib => DiagArgValue::Str(Cow::Borrowed("sdylib")),
299 }
300 }
301}
302303impl<'a> CrateLocator<'a> {
304pub(crate) fn new(
305 sess: &'a Session,
306 metadata_loader: &'a dyn MetadataLoader,
307 crate_name: Symbol,
308 is_rlib: bool,
309 hash: Option<Svh>,
310 extra_filename: Option<&'a str>,
311 path_kind: PathKind,
312 ) -> CrateLocator<'a> {
313let needs_object_code = sess.opts.output_types.should_codegen();
314// If we're producing an rlib, then we don't need object code.
315 // Or, if we're not producing object code, then we don't need it either
316 // (e.g., if we're a cdylib but emitting just metadata).
317let only_needs_metadata = is_rlib || !needs_object_code;
318319CrateLocator {
320only_needs_metadata,
321metadata_loader,
322 cfg_version: sess.cfg_version,
323crate_name,
324 exact_paths: if hash.is_none() {
325sess.opts
326 .externs
327 .get(crate_name.as_str())
328 .and_then(|entry| entry.files())
329 .into_flat_iter()
330 .cloned()
331 .collect()
332 } else {
333// SVH being specified means this is a transitive dependency,
334 // so `--extern` options do not apply.
335Vec::new()
336 },
337hash,
338extra_filename,
339 target: &sess.target,
340 tuple: sess.opts.target_triple.clone(),
341 filesearch: sess.target_filesearch(),
342path_kind,
343 is_proc_macro: false,
344 }
345 }
346347pub(crate) fn for_proc_macro(&mut self, sess: &'a Session, path_kind: PathKind) {
348self.is_proc_macro = true;
349self.target = &sess.host;
350self.tuple = TargetTuple::from_tuple(config::host_tuple());
351self.filesearch = sess.host_filesearch();
352self.path_kind = path_kind;
353 }
354355pub(crate) fn for_target_proc_macro(&mut self, sess: &'a Session, path_kind: PathKind) {
356self.is_proc_macro = true;
357self.target = &sess.target;
358self.tuple = sess.opts.target_triple.clone();
359self.filesearch = sess.target_filesearch();
360self.path_kind = path_kind;
361 }
362363pub(crate) fn maybe_load_library_crate(
364&self,
365 crate_rejections: &mut CrateRejections,
366 ) -> Result<Option<Library>, CrateError> {
367if !self.exact_paths.is_empty() {
368return self.find_commandline_library(crate_rejections);
369 }
370let mut seen_paths = FxHashSet::default();
371if let Some(extra_filename) = self.extra_filename
372 && let library @ Some(_) =
373self.find_library_crate(crate_rejections, extra_filename, &mut seen_paths)?
374{
375return Ok(library);
376 }
377self.find_library_crate(crate_rejections, "", &mut seen_paths)
378 }
379380fn find_library_crate(
381&self,
382 crate_rejections: &mut CrateRejections,
383 extra_prefix: &str,
384 seen_paths: &mut FxHashSet<PathBuf>,
385 ) -> Result<Option<Library>, CrateError> {
386let rmeta_prefix = &::alloc::__export::must_use({
::alloc::fmt::format(format_args!("lib{0}{1}", self.crate_name,
extra_prefix))
})format!("lib{}{}", self.crate_name, extra_prefix);
387let rlib_prefix = rmeta_prefix;
388let dylib_prefix =
389&::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0}{1}{2}", self.target.dll_prefix,
self.crate_name, extra_prefix))
})format!("{}{}{}", self.target.dll_prefix, self.crate_name, extra_prefix);
390let staticlib_prefix =
391&::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0}{1}{2}",
self.target.staticlib_prefix, self.crate_name, extra_prefix))
})format!("{}{}{}", self.target.staticlib_prefix, self.crate_name, extra_prefix);
392let interface_prefix = rmeta_prefix;
393394let rmeta_suffix = ".rmeta";
395let rlib_suffix = ".rlib";
396let dylib_suffix = &self.target.dll_suffix;
397let staticlib_suffix = &self.target.staticlib_suffix;
398let interface_suffix = ".rs";
399400let mut candidates: FxIndexMap<
401_,
402 (FxIndexSet<_>, FxIndexSet<_>, FxIndexSet<_>, FxIndexSet<_>),
403 > = Default::default();
404405// First, find all possible candidate rlibs and dylibs purely based on
406 // the name of the files themselves. We're trying to match against an
407 // exact crate name and a possibly an exact hash.
408 //
409 // During this step, we can filter all found libraries based on the
410 // name and id found in the crate id (we ignore the path portion for
411 // filename matching), as well as the exact hash (if specified). If we
412 // end up having many candidates, we must look at the metadata to
413 // perform exact matches against hashes/crate ids. Note that opening up
414 // the metadata is where we do an exact match against the full contents
415 // of the crate id (path/name/id).
416 //
417 // The goal of this step is to look at as little metadata as possible.
418 // Unfortunately, the prefix-based matching sometimes is over-eager.
419 // E.g. if `rlib_suffix` is `libstd` it'll match the file
420 // `libstd_detect-8d6701fb958915ad.rlib` (incorrect) as well as
421 // `libstd-f3ab5b1dea981f17.rlib` (correct). But this is hard to avoid
422 // given that `extra_filename` comes from the `-C extra-filename`
423 // option and thus can be anything, and the incorrect match will be
424 // handled safely in `extract_one`.
425let mut should_check_staticlibs = true;
426for (prefix, suffix, kind) in [
427 (rlib_prefix.as_str(), rlib_suffix, CrateFlavor::Rlib),
428 (rmeta_prefix.as_str(), rmeta_suffix, CrateFlavor::Rmeta),
429 (dylib_prefix, dylib_suffix, CrateFlavor::Dylib),
430 (interface_prefix, interface_suffix, CrateFlavor::SDylib),
431 ] {
432if prefix == staticlib_prefix && suffix == staticlib_suffix {
433 should_check_staticlibs = false;
434 }
435436for (hash, spf_path) in
437self.filesearch.get_file_candidates(prefix, suffix, self.path_kind)
438 {
439{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_metadata/src/locator.rs:439",
"rustc_metadata::locator", ::tracing::Level::INFO,
::tracing_core::__macro_support::Option::Some("compiler/rustc_metadata/src/locator.rs"),
::tracing_core::__macro_support::Option::Some(439u32),
::tracing_core::__macro_support::Option::Some("rustc_metadata::locator"),
::tracing_core::field::FieldSet::new(&["message"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::INFO <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::INFO <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
__CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("lib candidate: {0}",
spf_path.display()) as &dyn ::tracing::field::Value))])
});
} else { ; }
};info!("lib candidate: {}", spf_path.display());
440441let (rlibs, rmetas, dylibs, interfaces) = candidates.entry(hash).or_default();
442 {
443// As a performance optimisation we canonicalize the path and skip
444 // ones we've already seen. This allows us to ignore crates
445 // we know are exactual equal to ones we've already found.
446 // Going to the same crate through different symlinks does not change the result.
447let path = try_canonicalize(&spf_path).unwrap_or_else(|_| spf_path.clone());
448if seen_paths.contains(&path) {
449continue;
450 };
451 seen_paths.insert(path);
452 }
453// Use the original path (potentially with unresolved symlinks),
454 // filesystem code should not care, but this is nicer for diagnostics.
455match kind {
456 CrateFlavor::Rlib => rlibs.insert(spf_path),
457 CrateFlavor::Rmeta => rmetas.insert(spf_path),
458 CrateFlavor::Dylib => dylibs.insert(spf_path),
459 CrateFlavor::SDylib => interfaces.insert(spf_path),
460 };
461 }
462 }
463464if should_check_staticlibs {
465for (_, path) in self.filesearch.get_file_candidates(
466 staticlib_prefix,
467 staticlib_suffix,
468self.path_kind,
469 ) {
470 crate_rejections.via_kind.push(CrateMismatch { path, got: "static".to_string() });
471 }
472 }
473474// We have now collected all known libraries into a set of candidates
475 // keyed of the filename hash listed. For each filename, we also have a
476 // list of rlibs/dylibs that apply. Here, we map each of these lists
477 // (per hash), to a Library candidate for returning.
478 //
479 // A Library candidate is created if the metadata for the set of
480 // libraries corresponds to the crate id and hash criteria that this
481 // search is being performed for.
482let mut libraries = FxIndexMap::default();
483for (_hash, (rlibs, rmetas, dylibs, interfaces)) in candidates {
484if let Some((svh, lib)) =
485self.extract_lib(crate_rejections, rlibs, rmetas, dylibs, interfaces)?
486{
487 libraries.insert(svh, lib);
488 }
489 }
490491// Having now translated all relevant found hashes into libraries, see
492 // what we've got and figure out if we found multiple candidates for
493 // libraries or not.
494match libraries.len() {
4950 => Ok(None),
4961 => Ok(Some(libraries.into_iter().next().unwrap().1)),
497_ => {
498let mut candidates: Vec<PathBuf> = libraries499 .into_values()
500 .map(|lib| lib.source.paths().next().unwrap().clone())
501 .collect();
502candidates.sort();
503504Err(CrateError::MultipleCandidates(
505self.crate_name,
506// these are the same for all candidates
507get_flavor_from_path(candidates.first().unwrap()),
508candidates,
509 ))
510 }
511 }
512 }
513514fn extract_lib(
515&self,
516 crate_rejections: &mut CrateRejections,
517 rlibs: FxIndexSet<PathBuf>,
518 rmetas: FxIndexSet<PathBuf>,
519 dylibs: FxIndexSet<PathBuf>,
520 interfaces: FxIndexSet<PathBuf>,
521 ) -> Result<Option<(Svh, Library)>, CrateError> {
522let mut slot = None;
523// Order here matters, rmeta should come first.
524 //
525 // Make sure there's at most one rlib and at most one dylib.
526 //
527 // See comment in `extract_one` below.
528let rmeta = self.extract_one(crate_rejections, rmetas, CrateFlavor::Rmeta, &mut slot)?;
529let rlib = self.extract_one(crate_rejections, rlibs, CrateFlavor::Rlib, &mut slot)?;
530let sdylib_interface =
531self.extract_one(crate_rejections, interfaces, CrateFlavor::SDylib, &mut slot)?;
532let dylib = self.extract_one(crate_rejections, dylibs, CrateFlavor::Dylib, &mut slot)?;
533534if sdylib_interface.is_some() && dylib.is_none() {
535return Err(CrateError::FullMetadataNotFound(self.crate_name, CrateFlavor::SDylib));
536 }
537538let source = CrateSource { rmeta, rlib, dylib, sdylib_interface };
539Ok(slot.map(|(svh, metadata, _, _)| (svh, Library { source, metadata })))
540 }
541542fn needs_crate_flavor(&self, flavor: CrateFlavor) -> bool {
543if flavor == CrateFlavor::Dylib && self.is_proc_macro {
544return true;
545 }
546547if self.only_needs_metadata {
548flavor == CrateFlavor::Rmeta549 } else {
550// we need all flavors (perhaps not true, but what we do for now)
551true
552}
553 }
554555// Attempts to extract *one* library from the set `m`. If the set has no
556 // elements, `None` is returned. If the set has more than one element, then
557 // the errors and notes are emitted about the set of libraries.
558 //
559 // With only one library in the set, this function will extract it, and then
560 // read the metadata from it if `*slot` is `None`. If the metadata couldn't
561 // be read, it is assumed that the file isn't a valid rust library (no
562 // errors are emitted).
563 //
564 // The `PathBuf` in `slot` will only be used for diagnostic purposes.
565fn extract_one(
566&self,
567 crate_rejections: &mut CrateRejections,
568 m: FxIndexSet<PathBuf>,
569 flavor: CrateFlavor,
570 slot: &mut Option<(Svh, MetadataBlob, PathBuf, CrateFlavor)>,
571 ) -> Result<Option<PathBuf>, CrateError> {
572// If we are producing an rlib, and we've already loaded metadata, then
573 // we should not attempt to discover further crate sources (unless we're
574 // locating a proc macro; exact logic is in needs_crate_flavor). This means
575 // that under -Zbinary-dep-depinfo we will not emit a dependency edge on
576 // the *unused* rlib, and by returning `None` here immediately we
577 // guarantee that we do indeed not use it.
578 //
579 // See also #68149 which provides more detail on why emitting the
580 // dependency on the rlib is a bad thing.
581if slot.is_some() {
582if m.is_empty() || !self.needs_crate_flavor(flavor) {
583return Ok(None);
584 }
585 }
586587let mut ret: Option<PathBuf> = None;
588let mut err_data: Option<Vec<PathBuf>> = None;
589for lib in m {
590{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_metadata/src/locator.rs:590",
"rustc_metadata::locator", ::tracing::Level::INFO,
::tracing_core::__macro_support::Option::Some("compiler/rustc_metadata/src/locator.rs"),
::tracing_core::__macro_support::Option::Some(590u32),
::tracing_core::__macro_support::Option::Some("rustc_metadata::locator"),
::tracing_core::field::FieldSet::new(&["message"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::INFO <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::INFO <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
__CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("{0} reading metadata from: {1}",
flavor, lib.display()) as &dyn ::tracing::field::Value))])
});
} else { ; }
};info!("{} reading metadata from: {}", flavor, lib.display());
591if flavor == CrateFlavor::Rmeta && lib.metadata().is_ok_and(|m| m.len() == 0) {
592// Empty files will cause get_metadata_section to fail. Rmeta
593 // files can be empty, for example with binaries (which can
594 // often appear with `cargo check` when checking a library as
595 // a unittest). We don't want to emit a user-visible warning
596 // in this case as it is not a real problem.
597{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_metadata/src/locator.rs:597",
"rustc_metadata::locator", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_metadata/src/locator.rs"),
::tracing_core::__macro_support::Option::Some(597u32),
::tracing_core::__macro_support::Option::Some("rustc_metadata::locator"),
::tracing_core::field::FieldSet::new(&["message"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
__CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("skipping empty file")
as &dyn ::tracing::field::Value))])
});
} else { ; }
};debug!("skipping empty file");
598continue;
599 }
600let (hash, metadata) = match get_metadata_section(
601self.target,
602 flavor,
603&lib,
604self.metadata_loader,
605self.cfg_version,
606Some(self.crate_name),
607 ) {
608Ok(blob) => {
609if let Some(h) = self.crate_matches(crate_rejections, &blob, &lib) {
610 (h, blob)
611 } else {
612{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_metadata/src/locator.rs:612",
"rustc_metadata::locator", ::tracing::Level::INFO,
::tracing_core::__macro_support::Option::Some("compiler/rustc_metadata/src/locator.rs"),
::tracing_core::__macro_support::Option::Some(612u32),
::tracing_core::__macro_support::Option::Some("rustc_metadata::locator"),
::tracing_core::field::FieldSet::new(&["message"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::INFO <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::INFO <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
__CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("metadata mismatch")
as &dyn ::tracing::field::Value))])
});
} else { ; }
};info!("metadata mismatch");
613continue;
614 }
615 }
616Err(MetadataError::VersionMismatch { expected_version, found_version }) => {
617// The file was present and created by the same compiler version, but we
618 // couldn't load it for some reason. Give a hard error instead of silently
619 // ignoring it, but only if we would have given an error anyway.
620{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_metadata/src/locator.rs:620",
"rustc_metadata::locator", ::tracing::Level::INFO,
::tracing_core::__macro_support::Option::Some("compiler/rustc_metadata/src/locator.rs"),
::tracing_core::__macro_support::Option::Some(620u32),
::tracing_core::__macro_support::Option::Some("rustc_metadata::locator"),
::tracing_core::field::FieldSet::new(&["message"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::INFO <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::INFO <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
__CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("Rejecting via version: expected {0} got {1}",
expected_version, found_version) as
&dyn ::tracing::field::Value))])
});
} else { ; }
};info!(
621"Rejecting via version: expected {} got {}",
622 expected_version, found_version
623 );
624 crate_rejections
625 .via_version
626 .push(CrateMismatch { path: lib, got: found_version });
627continue;
628 }
629Err(MetadataError::LoadFailure(err)) => {
630{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_metadata/src/locator.rs:630",
"rustc_metadata::locator", ::tracing::Level::INFO,
::tracing_core::__macro_support::Option::Some("compiler/rustc_metadata/src/locator.rs"),
::tracing_core::__macro_support::Option::Some(630u32),
::tracing_core::__macro_support::Option::Some("rustc_metadata::locator"),
::tracing_core::field::FieldSet::new(&["message"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::INFO <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::INFO <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
__CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("no metadata found: {0}",
err) as &dyn ::tracing::field::Value))])
});
} else { ; }
};info!("no metadata found: {}", err);
631// Metadata was loaded from interface file earlier.
632if let Some((.., CrateFlavor::SDylib)) = slot {
633 ret = Some(lib);
634continue;
635 }
636// The file was present and created by the same compiler version, but we
637 // couldn't load it for some reason. Give a hard error instead of silently
638 // ignoring it, but only if we would have given an error anyway.
639crate_rejections.via_invalid.push(CrateMismatch { path: lib, got: err });
640continue;
641 }
642Err(err @ MetadataError::NotPresent(_)) => {
643{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_metadata/src/locator.rs:643",
"rustc_metadata::locator", ::tracing::Level::INFO,
::tracing_core::__macro_support::Option::Some("compiler/rustc_metadata/src/locator.rs"),
::tracing_core::__macro_support::Option::Some(643u32),
::tracing_core::__macro_support::Option::Some("rustc_metadata::locator"),
::tracing_core::field::FieldSet::new(&["message"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::INFO <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::INFO <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
__CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("no metadata found: {0}",
err) as &dyn ::tracing::field::Value))])
});
} else { ; }
};info!("no metadata found: {}", err);
644continue;
645 }
646 };
647// If we see multiple hashes, emit an error about duplicate candidates.
648if slot.as_ref().is_some_and(|s| s.0 != hash) {
649if let Some(candidates) = err_data {
650return Err(CrateError::MultipleCandidates(
651self.crate_name,
652 flavor,
653 candidates,
654 ));
655 }
656 err_data = Some(::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
[slot.take().unwrap().2]))vec![slot.take().unwrap().2]);
657 }
658if let Some(candidates) = &mut err_data {
659 candidates.push(lib);
660continue;
661 }
662663// We error eagerly here. If we're locating a rlib, then in theory the full metadata
664 // could still be in a (later resolved) dylib. In practice, if the rlib and dylib
665 // were produced in a way where one has full metadata and the other hasn't, it would
666 // mean that they were compiled using different compiler flags and probably also have
667 // a different SVH value.
668if metadata.get_header().is_stub {
669// `is_stub` should never be true for .rmeta files.
670{
match (&flavor, &CrateFlavor::Rmeta) {
(left_val, right_val) => {
if *left_val == *right_val {
let kind = ::core::panicking::AssertKind::Ne;
::core::panicking::assert_failed(kind, &*left_val,
&*right_val, ::core::option::Option::None);
}
}
}
};assert_ne!(flavor, CrateFlavor::Rmeta);
671672// Because rmeta files are resolved before rlib/dylib files, if this is a stub and
673 // we haven't found a slot already, it means that the full metadata is missing.
674if slot.is_none() {
675return Err(CrateError::FullMetadataNotFound(self.crate_name, flavor));
676 }
677 } else {
678*slot = Some((hash, metadata, lib.clone(), flavor));
679 }
680 ret = Some(lib);
681 }
682683if let Some(candidates) = err_data {
684Err(CrateError::MultipleCandidates(self.crate_name, flavor, candidates))
685 } else {
686Ok(ret)
687 }
688 }
689690fn crate_matches(
691&self,
692 crate_rejections: &mut CrateRejections,
693 metadata: &MetadataBlob,
694 libpath: &Path,
695 ) -> Option<Svh> {
696let header = metadata.get_header();
697if header.is_proc_macro_crate != self.is_proc_macro {
698{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_metadata/src/locator.rs:698",
"rustc_metadata::locator", ::tracing::Level::INFO,
::tracing_core::__macro_support::Option::Some("compiler/rustc_metadata/src/locator.rs"),
::tracing_core::__macro_support::Option::Some(698u32),
::tracing_core::__macro_support::Option::Some("rustc_metadata::locator"),
::tracing_core::field::FieldSet::new(&["message"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::INFO <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::INFO <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
__CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("Rejecting via proc macro: expected {0} got {1}",
self.is_proc_macro, header.is_proc_macro_crate) as
&dyn ::tracing::field::Value))])
});
} else { ; }
};info!(
699"Rejecting via proc macro: expected {} got {}",
700self.is_proc_macro, header.is_proc_macro_crate,
701 );
702return None;
703 }
704705if self.exact_paths.is_empty() && self.crate_name != header.name {
706{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_metadata/src/locator.rs:706",
"rustc_metadata::locator", ::tracing::Level::INFO,
::tracing_core::__macro_support::Option::Some("compiler/rustc_metadata/src/locator.rs"),
::tracing_core::__macro_support::Option::Some(706u32),
::tracing_core::__macro_support::Option::Some("rustc_metadata::locator"),
::tracing_core::field::FieldSet::new(&["message"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::INFO <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::INFO <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
__CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("Rejecting via crate name")
as &dyn ::tracing::field::Value))])
});
} else { ; }
};info!("Rejecting via crate name");
707return None;
708 }
709710if header.triple != self.tuple {
711{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_metadata/src/locator.rs:711",
"rustc_metadata::locator", ::tracing::Level::INFO,
::tracing_core::__macro_support::Option::Some("compiler/rustc_metadata/src/locator.rs"),
::tracing_core::__macro_support::Option::Some(711u32),
::tracing_core::__macro_support::Option::Some("rustc_metadata::locator"),
::tracing_core::field::FieldSet::new(&["message"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::INFO <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::INFO <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
__CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("Rejecting via crate triple: expected {0} got {1}",
self.tuple, header.triple) as
&dyn ::tracing::field::Value))])
});
} else { ; }
};info!("Rejecting via crate triple: expected {} got {}", self.tuple, header.triple);
712crate_rejections.via_triple.push(CrateMismatch {
713 path: libpath.to_path_buf(),
714 got: header.triple.to_string(),
715 });
716return None;
717 }
718719let hash = header.hash;
720if let Some(expected_hash) = self.hash {
721if hash != expected_hash {
722{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_metadata/src/locator.rs:722",
"rustc_metadata::locator", ::tracing::Level::INFO,
::tracing_core::__macro_support::Option::Some("compiler/rustc_metadata/src/locator.rs"),
::tracing_core::__macro_support::Option::Some(722u32),
::tracing_core::__macro_support::Option::Some("rustc_metadata::locator"),
::tracing_core::field::FieldSet::new(&["message"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::INFO <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::INFO <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
__CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("Rejecting via hash: expected {0} got {1}",
expected_hash, hash) as &dyn ::tracing::field::Value))])
});
} else { ; }
};info!("Rejecting via hash: expected {} got {}", expected_hash, hash);
723crate_rejections724 .via_hash
725 .push(CrateMismatch { path: libpath.to_path_buf(), got: hash.to_string() });
726return None;
727 }
728 }
729730Some(hash)
731 }
732733fn find_commandline_library(
734&self,
735 crate_rejections: &mut CrateRejections,
736 ) -> Result<Option<Library>, CrateError> {
737// First, filter out all libraries that look suspicious. We only accept
738 // files which actually exist that have the correct naming scheme for
739 // rlibs/dylibs.
740let mut rlibs = FxIndexSet::default();
741let mut rmetas = FxIndexSet::default();
742let mut dylibs = FxIndexSet::default();
743let mut sdylib_interfaces = FxIndexSet::default();
744for loc in &self.exact_paths {
745let loc_canon = loc.canonicalized();
746let loc_orig = loc.original();
747if !loc_canon.exists() {
748return Err(CrateError::ExternLocationNotExist(self.crate_name, loc_orig.clone()));
749 }
750if !loc_orig.is_file() {
751return Err(CrateError::ExternLocationNotFile(self.crate_name, loc_orig.clone()));
752 }
753// Note to take care and match against the non-canonicalized name:
754 // some systems save build artifacts into content-addressed stores
755 // that do not preserve extensions, and then link to them using
756 // e.g. symbolic links. If we canonicalize too early, we resolve
757 // the symlink, the file type is lost and we might treat rlibs and
758 // rmetas as dylibs.
759let Some(file) = loc_orig.file_name().and_then(|s| s.to_str()) else {
760return Err(CrateError::ExternLocationNotFile(self.crate_name, loc_orig.clone()));
761 };
762if file.starts_with("lib") {
763if file.ends_with(".rlib") {
764 rlibs.insert(loc_canon.clone());
765continue;
766 }
767if file.ends_with(".rmeta") {
768 rmetas.insert(loc_canon.clone());
769continue;
770 }
771if file.ends_with(".rs") {
772 sdylib_interfaces.insert(loc_canon.clone());
773 }
774 }
775let dll_prefix = self.target.dll_prefix.as_ref();
776let dll_suffix = self.target.dll_suffix.as_ref();
777if file.starts_with(dll_prefix) && file.ends_with(dll_suffix) {
778 dylibs.insert(loc_canon.clone());
779continue;
780 }
781 crate_rejections
782 .via_filename
783 .push(CrateMismatch { path: loc_orig.clone(), got: String::new() });
784 }
785786// Extract the dylib/rlib/rmeta triple.
787self.extract_lib(crate_rejections, rlibs, rmetas, dylibs, sdylib_interfaces)
788 .map(|opt| opt.map(|(_, lib)| lib))
789 }
790791pub(crate) fn into_error(
792self,
793 crate_rejections: CrateRejections,
794 dep_root: Option<CratePaths>,
795 ) -> CrateError {
796 CrateError::LocatorCombined(Box::new(CombinedLocatorError {
797 crate_name: self.crate_name,
798dep_root,
799 triple: self.tuple,
800 dll_prefix: self.target.dll_prefix.to_string(),
801 dll_suffix: self.target.dll_suffix.to_string(),
802crate_rejections,
803 }))
804 }
805}
806807fn get_metadata_section<'p>(
808 target: &Target,
809 flavor: CrateFlavor,
810 filename: &'p Path,
811 loader: &dyn MetadataLoader,
812 cfg_version: &'static str,
813 crate_name: Option<Symbol>,
814) -> Result<MetadataBlob, MetadataError<'p>> {
815if !filename.exists() {
816return Err(MetadataError::NotPresent(filename));
817 }
818let raw_bytes = match flavor {
819 CrateFlavor::Rlib => {
820 loader.get_rlib_metadata(target, filename).map_err(MetadataError::LoadFailure)?
821}
822 CrateFlavor::SDylib => {
823let compiler = std::env::current_exe().map_err(|_err| {
824 MetadataError::LoadFailure(
825"couldn't obtain current compiler binary when loading sdylib interface"
826.to_string(),
827 )
828 })?;
829830let tmp_path = match TempFileBuilder::new().prefix("rustc").tempdir() {
831Ok(tmp_path) => tmp_path,
832Err(error) => {
833return Err(MetadataError::LoadFailure(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("couldn\'t create a temp dir: {0}",
error))
})format!(
834"couldn't create a temp dir: {}",
835 error
836 )));
837 }
838 };
839840let crate_name = crate_name.unwrap();
841{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_metadata/src/locator.rs:841",
"rustc_metadata::locator", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_metadata/src/locator.rs"),
::tracing_core::__macro_support::Option::Some(841u32),
::tracing_core::__macro_support::Option::Some("rustc_metadata::locator"),
::tracing_core::field::FieldSet::new(&["message"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
__CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("compiling {0}",
filename.display()) as &dyn ::tracing::field::Value))])
});
} else { ; }
};debug!("compiling {}", filename.display());
842// FIXME: This will need to be done either within the current compiler session or
843 // as a separate compiler session in the same process.
844let res = std::process::Command::new(compiler)
845 .arg(&filename)
846 .arg("--emit=metadata")
847 .arg(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("--crate-name={0}", crate_name))
})format!("--crate-name={}", crate_name))
848 .arg(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("--out-dir={0}",
tmp_path.path().display()))
})format!("--out-dir={}", tmp_path.path().display()))
849 .arg("-Zbuild-sdylib-interface")
850 .output()
851 .map_err(|err| {
852 MetadataError::LoadFailure(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("couldn\'t compile interface: {0}",
err))
})format!("couldn't compile interface: {}", err))
853 })?;
854855if !res.status.success() {
856return Err(MetadataError::LoadFailure(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("couldn\'t compile interface: {0}",
std::str::from_utf8(&res.stderr).unwrap_or_default()))
})format!(
857"couldn't compile interface: {}",
858 std::str::from_utf8(&res.stderr).unwrap_or_default()
859 )));
860 }
861862// Load interface metadata instead of crate metadata.
863let interface_metadata_name = ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("lib{0}.rmeta", crate_name))
})format!("lib{}.rmeta", crate_name);
864let rmeta_file = tmp_path.path().join(interface_metadata_name);
865{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_metadata/src/locator.rs:865",
"rustc_metadata::locator", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_metadata/src/locator.rs"),
::tracing_core::__macro_support::Option::Some(865u32),
::tracing_core::__macro_support::Option::Some("rustc_metadata::locator"),
::tracing_core::field::FieldSet::new(&["message"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
__CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("loading interface metadata from {0}",
rmeta_file.display()) as &dyn ::tracing::field::Value))])
});
} else { ; }
};debug!("loading interface metadata from {}", rmeta_file.display());
866let rmeta = get_rmeta_metadata_section(&rmeta_file)?;
867let _ = std::fs::remove_file(rmeta_file);
868869rmeta870 }
871 CrateFlavor::Dylib => {
872let buf =
873 loader.get_dylib_metadata(target, filename).map_err(MetadataError::LoadFailure)?;
874let header_len = METADATA_HEADER.len();
875// header + u64 length of data
876let data_start = header_len + 8;
877878{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_metadata/src/locator.rs:878",
"rustc_metadata::locator", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_metadata/src/locator.rs"),
::tracing_core::__macro_support::Option::Some(878u32),
::tracing_core::__macro_support::Option::Some("rustc_metadata::locator"),
::tracing_core::field::FieldSet::new(&["message"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
__CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("checking {0} bytes of metadata-version stamp",
header_len) as &dyn ::tracing::field::Value))])
});
} else { ; }
};debug!("checking {} bytes of metadata-version stamp", header_len);
879let header = &buf[..cmp::min(header_len, buf.len())];
880if header != METADATA_HEADER {
881return Err(MetadataError::LoadFailure(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("invalid metadata version found: {0}",
filename.display()))
})format!(
882"invalid metadata version found: {}",
883 filename.display()
884 )));
885 }
886887// Length of the metadata - this allows linkers to pad the section if they want
888let Ok(len_bytes) =
889 <[u8; 8]>::try_from(&buf[header_len..cmp::min(data_start, buf.len())])
890else {
891return Err(MetadataError::LoadFailure(
892"invalid metadata length found".to_string(),
893 ));
894 };
895let metadata_len = u64::from_le_bytes(len_bytes) as usize;
896897// Header is okay -> inflate the actual metadata
898buf.slice(|buf| &buf[data_start..(data_start + metadata_len)])
899 }
900 CrateFlavor::Rmeta => get_rmeta_metadata_section(filename)?,
901 };
902let Ok(blob) = MetadataBlob::new(raw_bytes) else {
903return Err(MetadataError::LoadFailure(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("corrupt metadata encountered in {0}",
filename.display()))
})format!(
904"corrupt metadata encountered in {}",
905 filename.display()
906 )));
907 };
908match blob.check_compatibility(cfg_version) {
909Ok(()) => {
910{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_metadata/src/locator.rs:910",
"rustc_metadata::locator", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_metadata/src/locator.rs"),
::tracing_core::__macro_support::Option::Some(910u32),
::tracing_core::__macro_support::Option::Some("rustc_metadata::locator"),
::tracing_core::field::FieldSet::new(&["message"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
__CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("metadata blob read okay")
as &dyn ::tracing::field::Value))])
});
} else { ; }
};debug!("metadata blob read okay");
911Ok(blob)
912 }
913Err(None) => Err(MetadataError::LoadFailure(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("invalid metadata version found: {0}",
filename.display()))
})format!(
914"invalid metadata version found: {}",
915 filename.display()
916 ))),
917Err(Some(found_version)) => {
918return Err(MetadataError::VersionMismatch {
919 expected_version: rustc_version(cfg_version),
920found_version,
921 });
922 }
923 }
924}
925926fn get_rmeta_metadata_section<'a, 'p>(filename: &'p Path) -> Result<OwnedSlice, MetadataError<'a>> {
927// mmap the file, because only a small fraction of it is read.
928let file = std::fs::File::open(filename).map_err(|_| {
929 MetadataError::LoadFailure(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("failed to open rmeta metadata: \'{0}\'",
filename.display()))
})format!(
930"failed to open rmeta metadata: '{}'",
931 filename.display()
932 ))
933 })?;
934let mmap = unsafe { Mmap::map(file) };
935let mmap = mmap.map_err(|_| {
936 MetadataError::LoadFailure(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("failed to mmap rmeta metadata: \'{0}\'",
filename.display()))
})format!(
937"failed to mmap rmeta metadata: '{}'",
938 filename.display()
939 ))
940 })?;
941942Ok(slice_owned(mmap, Deref::deref))
943}
944945/// A diagnostic function for dumping crate metadata to an output stream.
946pub fn list_file_metadata(
947 target: &Target,
948 path: &Path,
949 metadata_loader: &dyn MetadataLoader,
950 out: &mut dyn Write,
951 ls_kinds: &[String],
952 cfg_version: &'static str,
953) -> IoResult<()> {
954let flavor = get_flavor_from_path(path);
955match get_metadata_section(target, flavor, path, metadata_loader, cfg_version, None) {
956Ok(metadata) => metadata.list_crate_metadata(out, ls_kinds),
957Err(msg) => Err(IoError::new(IoErrorKind::Other, msg.to_string())),
958 }
959}
960961fn get_flavor_from_path(path: &Path) -> CrateFlavor {
962let filename = path.file_name().unwrap().to_str().unwrap();
963964if filename.ends_with(".rlib") {
965 CrateFlavor::Rlib966 } else if filename.ends_with(".rmeta") {
967 CrateFlavor::Rmeta968 } else {
969 CrateFlavor::Dylib970 }
971}
972973/// A function to fetch about all macros inside a proc-macro crate.
974///
975/// Used by rust-analyzer-proc-macro-srv.
976pub fn get_proc_macros(
977 target: &Target,
978 path: &Path,
979 metadata_loader: &dyn MetadataLoader,
980 cfg_version: &'static str,
981) -> IoResult<Vec<(ProcMacroClient, ProcMacroKind)>> {
982let metadata =
983 get_metadata_section(target, CrateFlavor::Dylib, path, metadata_loader, cfg_version, None)
984 .map_err(|err| io::Error::other(err.to_string()))?;
985let stable_crate_id = metadata.get_root().stable_crate_id();
986987let clients = crate::host_dylib::dlsym_proc_macros(path, stable_crate_id).map_err(|err| {
988let (crate::DylibError::DlOpen(path, err) | crate::DylibError::DlSym(path, err)) = err;
989 io::Error::other(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0}{1}", path, err))
})format!("{path}{err}"))
990 })?;
991992let proc_macro_info = metadata.get_proc_macro_info();
993{
match (&proc_macro_info.len(), &clients.len()) {
(left_val, right_val) => {
if !(*left_val == *right_val) {
let kind = ::core::panicking::AssertKind::Eq;
::core::panicking::assert_failed(kind, &*left_val,
&*right_val, ::core::option::Option::None);
}
}
}
};assert_eq!(proc_macro_info.len(), clients.len());
994995Ok(clients.into_iter().copied().zip(proc_macro_info).collect())
996}
997998// ------------------------------------------ Error reporting -------------------------------------
9991000#[derive(#[automatically_derived]
impl ::core::clone::Clone for CrateMismatch {
#[inline]
fn clone(&self) -> CrateMismatch {
CrateMismatch {
path: ::core::clone::Clone::clone(&self.path),
got: ::core::clone::Clone::clone(&self.got),
}
}
}Clone, #[automatically_derived]
impl ::core::fmt::Debug for CrateMismatch {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
::core::fmt::Formatter::debug_struct_field2_finish(f, "CrateMismatch",
"path", &self.path, "got", &&self.got)
}
}Debug)]
1001struct CrateMismatch {
1002 path: PathBuf,
1003 got: String,
1004}
10051006#[derive(#[automatically_derived]
impl ::core::clone::Clone for CrateRejections {
#[inline]
fn clone(&self) -> CrateRejections {
CrateRejections {
via_hash: ::core::clone::Clone::clone(&self.via_hash),
via_triple: ::core::clone::Clone::clone(&self.via_triple),
via_kind: ::core::clone::Clone::clone(&self.via_kind),
via_version: ::core::clone::Clone::clone(&self.via_version),
via_filename: ::core::clone::Clone::clone(&self.via_filename),
via_invalid: ::core::clone::Clone::clone(&self.via_invalid),
}
}
}Clone, #[automatically_derived]
impl ::core::fmt::Debug for CrateRejections {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
let names: &'static _ =
&["via_hash", "via_triple", "via_kind", "via_version",
"via_filename", "via_invalid"];
let values: &[&dyn ::core::fmt::Debug] =
&[&self.via_hash, &self.via_triple, &self.via_kind,
&self.via_version, &self.via_filename, &&self.via_invalid];
::core::fmt::Formatter::debug_struct_fields_finish(f,
"CrateRejections", names, values)
}
}Debug, #[automatically_derived]
impl ::core::default::Default for CrateRejections {
#[inline]
fn default() -> CrateRejections {
CrateRejections {
via_hash: ::core::default::Default::default(),
via_triple: ::core::default::Default::default(),
via_kind: ::core::default::Default::default(),
via_version: ::core::default::Default::default(),
via_filename: ::core::default::Default::default(),
via_invalid: ::core::default::Default::default(),
}
}
}Default)]
1007pub(crate) struct CrateRejections {
1008 via_hash: Vec<CrateMismatch>,
1009 via_triple: Vec<CrateMismatch>,
1010 via_kind: Vec<CrateMismatch>,
1011 via_version: Vec<CrateMismatch>,
1012 via_filename: Vec<CrateMismatch>,
1013 via_invalid: Vec<CrateMismatch>,
1014}
10151016/// Candidate rejection reasons collected during crate search.
1017/// If no candidate is accepted, then these reasons are presented to the user,
1018/// otherwise they are ignored.
1019#[derive(#[automatically_derived]
impl ::core::fmt::Debug for CombinedLocatorError {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
let names: &'static _ =
&["crate_name", "dep_root", "triple", "dll_prefix", "dll_suffix",
"crate_rejections"];
let values: &[&dyn ::core::fmt::Debug] =
&[&self.crate_name, &self.dep_root, &self.triple,
&self.dll_prefix, &self.dll_suffix,
&&self.crate_rejections];
::core::fmt::Formatter::debug_struct_fields_finish(f,
"CombinedLocatorError", names, values)
}
}Debug)]
1020pub(crate) struct CombinedLocatorError {
1021 crate_name: Symbol,
1022 dep_root: Option<CratePaths>,
1023 triple: TargetTuple,
1024 dll_prefix: String,
1025 dll_suffix: String,
1026 crate_rejections: CrateRejections,
1027}
10281029#[derive(#[automatically_derived]
impl ::core::fmt::Debug for CrateError {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
match self {
CrateError::NonAsciiName(__self_0) =>
::core::fmt::Formatter::debug_tuple_field1_finish(f,
"NonAsciiName", &__self_0),
CrateError::ExternLocationNotExist(__self_0, __self_1) =>
::core::fmt::Formatter::debug_tuple_field2_finish(f,
"ExternLocationNotExist", __self_0, &__self_1),
CrateError::ExternLocationNotFile(__self_0, __self_1) =>
::core::fmt::Formatter::debug_tuple_field2_finish(f,
"ExternLocationNotFile", __self_0, &__self_1),
CrateError::MultipleCandidates(__self_0, __self_1, __self_2) =>
::core::fmt::Formatter::debug_tuple_field3_finish(f,
"MultipleCandidates", __self_0, __self_1, &__self_2),
CrateError::FullMetadataNotFound(__self_0, __self_1) =>
::core::fmt::Formatter::debug_tuple_field2_finish(f,
"FullMetadataNotFound", __self_0, &__self_1),
CrateError::SymbolConflictsCurrent(__self_0) =>
::core::fmt::Formatter::debug_tuple_field1_finish(f,
"SymbolConflictsCurrent", &__self_0),
CrateError::StableCrateIdCollision(__self_0, __self_1) =>
::core::fmt::Formatter::debug_tuple_field2_finish(f,
"StableCrateIdCollision", __self_0, &__self_1),
CrateError::DlOpen(__self_0, __self_1) =>
::core::fmt::Formatter::debug_tuple_field2_finish(f, "DlOpen",
__self_0, &__self_1),
CrateError::DlSym(__self_0, __self_1) =>
::core::fmt::Formatter::debug_tuple_field2_finish(f, "DlSym",
__self_0, &__self_1),
CrateError::LocatorCombined(__self_0) =>
::core::fmt::Formatter::debug_tuple_field1_finish(f,
"LocatorCombined", &__self_0),
CrateError::NotFound(__self_0) =>
::core::fmt::Formatter::debug_tuple_field1_finish(f,
"NotFound", &__self_0),
}
}
}Debug)]
1030pub(crate) enum CrateError {
1031 NonAsciiName(Symbol),
1032 ExternLocationNotExist(Symbol, PathBuf),
1033 ExternLocationNotFile(Symbol, PathBuf),
1034 MultipleCandidates(Symbol, CrateFlavor, Vec<PathBuf>),
1035 FullMetadataNotFound(Symbol, CrateFlavor),
1036 SymbolConflictsCurrent(Symbol),
1037 StableCrateIdCollision(Symbol, Symbol),
1038 DlOpen(String, String),
1039 DlSym(String, String),
1040 LocatorCombined(Box<CombinedLocatorError>),
1041 NotFound(Symbol),
1042}
10431044#[derive(#[automatically_derived]
impl<'a> ::core::fmt::Debug for MetadataError<'a> {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
match self {
MetadataError::NotPresent(__self_0) =>
::core::fmt::Formatter::debug_tuple_field1_finish(f,
"NotPresent", &__self_0),
MetadataError::LoadFailure(__self_0) =>
::core::fmt::Formatter::debug_tuple_field1_finish(f,
"LoadFailure", &__self_0),
MetadataError::VersionMismatch {
expected_version: __self_0, found_version: __self_1 } =>
::core::fmt::Formatter::debug_struct_field2_finish(f,
"VersionMismatch", "expected_version", __self_0,
"found_version", &__self_1),
}
}
}Debug)]
1045pub(crate) enum MetadataError<'a> {
1046/// The file was missing.
1047NotPresent(&'a Path),
1048/// The file was present and invalid.
1049LoadFailure(String),
1050/// The file was present, but compiled with a different rustc version.
1051VersionMismatch { expected_version: String, found_version: String },
1052}
10531054impl fmt::Displayfor MetadataError<'_> {
1055fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1056match self {
1057 MetadataError::NotPresent(filename) => {
1058f.write_str(&::alloc::__export::must_use({
::alloc::fmt::format(format_args!("no such file: \'{0}\'",
filename.display()))
})format!("no such file: '{}'", filename.display()))
1059 }
1060 MetadataError::LoadFailure(msg) => f.write_str(msg),
1061 MetadataError::VersionMismatch { expected_version, found_version } => {
1062f.write_str(&::alloc::__export::must_use({
::alloc::fmt::format(format_args!("rustc version mismatch. expected {0}, found {1}",
expected_version, found_version))
})format!(
1063"rustc version mismatch. expected {}, found {}",
1064 expected_version, found_version,
1065 ))
1066 }
1067 }
1068 }
1069}
10701071impl CrateError {
1072pub(crate) fn report(self, sess: &Session, span: Span, missing_core: bool) {
1073let dcx = sess.dcx();
1074match self {
1075 CrateError::NonAsciiName(crate_name) => {
1076dcx.emit_err(diagnostics::NonAsciiName { span, crate_name });
1077 }
1078 CrateError::ExternLocationNotExist(crate_name, loc) => {
1079dcx.emit_err(diagnostics::ExternLocationNotExist {
1080span,
1081crate_name,
1082 location: &loc,
1083 });
1084 }
1085 CrateError::ExternLocationNotFile(crate_name, loc) => {
1086dcx.emit_err(diagnostics::ExternLocationNotFile {
1087span,
1088crate_name,
1089 location: &loc,
1090 });
1091 }
1092 CrateError::MultipleCandidates(crate_name, flavor, candidates) => {
1093dcx.emit_err(diagnostics::MultipleCandidates {
1094span,
1095crate_name,
1096flavor,
1097candidates,
1098 });
1099 }
1100 CrateError::FullMetadataNotFound(crate_name, flavor) => {
1101dcx.emit_err(diagnostics::FullMetadataNotFound { span, crate_name, flavor });
1102 }
1103 CrateError::SymbolConflictsCurrent(root_name) => {
1104dcx.emit_err(diagnostics::SymbolConflictsCurrent { span, crate_name: root_name });
1105 }
1106 CrateError::StableCrateIdCollision(crate_name0, crate_name1) => {
1107dcx.emit_err(diagnostics::StableCrateIdCollision {
1108span,
1109crate_name0,
1110crate_name1,
1111 });
1112 }
1113 CrateError::DlOpen(path, err) | CrateError::DlSym(path, err) => {
1114dcx.emit_err(diagnostics::DlError { span, path, err });
1115 }
1116 CrateError::LocatorCombined(locator) => {
1117let crate_name = locator.crate_name;
1118let add_info = match &locator.dep_root {
1119None => String::new(),
1120Some(r) => ::alloc::__export::must_use({
::alloc::fmt::format(format_args!(" which `{0}` depends on", r.name))
})format!(" which `{}` depends on", r.name),
1121 };
1122if !locator.crate_rejections.via_filename.is_empty() {
1123let mismatches = locator.crate_rejections.via_filename.iter();
1124for CrateMismatch { path, .. } in mismatches {
1125 dcx.emit_err(diagnostics::CrateLocationUnknownType {
1126 span,
1127 path,
1128 crate_name,
1129 });
1130 dcx.emit_err(diagnostics::LibFilenameForm {
1131 span,
1132 dll_prefix: &locator.dll_prefix,
1133 dll_suffix: &locator.dll_suffix,
1134 });
1135 }
1136 }
1137let mut found_crates = String::new();
1138if !locator.crate_rejections.via_hash.is_empty() {
1139let mismatches = locator.crate_rejections.via_hash.iter();
1140for CrateMismatch { path, .. } in mismatches {
1141 found_crates.push_str(&::alloc::__export::must_use({
::alloc::fmt::format(format_args!("\ncrate `{0}`: {1}", crate_name,
path.display()))
})format!(
1142"\ncrate `{}`: {}",
1143 crate_name,
1144 path.display()
1145 ));
1146 }
1147if let Some(r) = locator.dep_root {
1148for path in r.source.paths() {
1149 found_crates.push_str(&::alloc::__export::must_use({
::alloc::fmt::format(format_args!("\ncrate `{0}`: {1}", r.name,
path.display()))
})format!(
1150"\ncrate `{}`: {}",
1151 r.name,
1152 path.display()
1153 ));
1154 }
1155 }
1156dcx.emit_err(diagnostics::NewerCrateVersion {
1157span,
1158crate_name,
1159add_info,
1160found_crates,
1161 });
1162 } else if !locator.crate_rejections.via_triple.is_empty() {
1163let mismatches = locator.crate_rejections.via_triple.iter();
1164for CrateMismatch { path, got } in mismatches {
1165 found_crates.push_str(&::alloc::__export::must_use({
::alloc::fmt::format(format_args!("\ncrate `{0}`, target triple {1}: {2}",
crate_name, got, path.display()))
})format!(
1166"\ncrate `{}`, target triple {}: {}",
1167 crate_name,
1168 got,
1169 path.display(),
1170 ));
1171 }
1172dcx.emit_err(diagnostics::NoCrateWithTriple {
1173span,
1174crate_name,
1175 locator_triple: locator.triple.tuple(),
1176add_info,
1177found_crates,
1178 });
1179 } else if !locator.crate_rejections.via_kind.is_empty() {
1180let mismatches = locator.crate_rejections.via_kind.iter();
1181for CrateMismatch { path, .. } in mismatches {
1182 found_crates.push_str(&::alloc::__export::must_use({
::alloc::fmt::format(format_args!("\ncrate `{0}`: {1}", crate_name,
path.display()))
})format!(
1183"\ncrate `{}`: {}",
1184 crate_name,
1185 path.display()
1186 ));
1187 }
1188dcx.emit_err(diagnostics::FoundStaticlib {
1189span,
1190crate_name,
1191add_info,
1192found_crates,
1193 });
1194 } else if !locator.crate_rejections.via_version.is_empty() {
1195let mismatches = locator.crate_rejections.via_version.iter();
1196for CrateMismatch { path, got } in mismatches {
1197 found_crates.push_str(&::alloc::__export::must_use({
::alloc::fmt::format(format_args!("\ncrate `{0}` compiled by {1}: {2}",
crate_name, got, path.display()))
})format!(
1198"\ncrate `{}` compiled by {}: {}",
1199 crate_name,
1200 got,
1201 path.display(),
1202 ));
1203 }
1204dcx.emit_err(diagnostics::IncompatibleRustc {
1205span,
1206crate_name,
1207add_info,
1208found_crates,
1209 rustc_version: rustc_version(sess.cfg_version),
1210 });
1211 } else if !locator.crate_rejections.via_invalid.is_empty() {
1212let mut crate_rejections = Vec::new();
1213for CrateMismatch { path: _, got } in locator.crate_rejections.via_invalid {
1214 crate_rejections.push(got);
1215 }
1216dcx.emit_err(diagnostics::InvalidMetadataFiles {
1217span,
1218crate_name,
1219add_info,
1220crate_rejections,
1221 });
1222 } else {
1223let error = diagnostics::CannotFindCrate {
1224span,
1225crate_name,
1226add_info,
1227missing_core,
1228 current_crate: sess1229 .opts
1230 .crate_name
1231 .clone()
1232 .unwrap_or_else(|| "<unknown>".to_string()),
1233 is_nightly_build: sess.is_nightly_build(),
1234 profiler_runtime: Symbol::intern(&sess.opts.unstable_opts.profiler_runtime),
1235 locator_triple: locator.triple,
1236 is_ui_testing: sess.opts.unstable_opts.ui_testing,
1237 is_tier_3: sess.target.metadata.tier == Some(3),
1238 };
1239// The diagnostic for missing core is very good, but it is followed by a lot of
1240 // other diagnostics that do not add information.
1241if missing_core {
1242dcx.emit_fatal(error);
1243 } else {
1244dcx.emit_err(error);
1245 }
1246 }
1247 }
1248 CrateError::NotFound(crate_name) => {
1249let error = diagnostics::CannotFindCrate {
1250span,
1251crate_name,
1252 add_info: String::new(),
1253missing_core,
1254 current_crate: sess1255 .opts
1256 .crate_name
1257 .clone()
1258 .unwrap_or_else(|| "<unknown>".to_string()),
1259 is_nightly_build: sess.is_nightly_build(),
1260 profiler_runtime: Symbol::intern(&sess.opts.unstable_opts.profiler_runtime),
1261 locator_triple: sess.opts.target_triple.clone(),
1262 is_ui_testing: sess.opts.unstable_opts.ui_testing,
1263 is_tier_3: sess.target.metadata.tier == Some(3),
1264 };
1265// The diagnostic for missing core is very good, but it is followed by a lot of
1266 // other diagnostics that do not add information.
1267if missing_core {
1268dcx.emit_fatal(error);
1269 } else {
1270dcx.emit_err(error);
1271 }
1272 }
1273 }
1274 }
1275}