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, 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 .into_iter()
329 .filter_map(|entry| entry.files())
330 .flatten()
331 .cloned()
332 .collect()
333 } else {
334// SVH being specified means this is a transitive dependency,
335 // so `--extern` options do not apply.
336Vec::new()
337 },
338hash,
339extra_filename,
340 target: &sess.target,
341 tuple: sess.opts.target_triple.clone(),
342 filesearch: sess.target_filesearch(),
343path_kind,
344 is_proc_macro: false,
345 }
346 }
347348pub(crate) fn for_proc_macro(&mut self, sess: &'a Session, path_kind: PathKind) {
349self.is_proc_macro = true;
350self.target = &sess.host;
351self.tuple = TargetTuple::from_tuple(config::host_tuple());
352self.filesearch = sess.host_filesearch();
353self.path_kind = path_kind;
354 }
355356pub(crate) fn for_target_proc_macro(&mut self, sess: &'a Session, path_kind: PathKind) {
357self.is_proc_macro = true;
358self.target = &sess.target;
359self.tuple = sess.opts.target_triple.clone();
360self.filesearch = sess.target_filesearch();
361self.path_kind = path_kind;
362 }
363364pub(crate) fn maybe_load_library_crate(
365&self,
366 crate_rejections: &mut CrateRejections,
367 ) -> Result<Option<Library>, CrateError> {
368if !self.exact_paths.is_empty() {
369return self.find_commandline_library(crate_rejections);
370 }
371let mut seen_paths = FxHashSet::default();
372if let Some(extra_filename) = self.extra_filename
373 && let library @ Some(_) =
374self.find_library_crate(crate_rejections, extra_filename, &mut seen_paths)?
375{
376return Ok(library);
377 }
378self.find_library_crate(crate_rejections, "", &mut seen_paths)
379 }
380381fn find_library_crate(
382&self,
383 crate_rejections: &mut CrateRejections,
384 extra_prefix: &str,
385 seen_paths: &mut FxHashSet<PathBuf>,
386 ) -> Result<Option<Library>, CrateError> {
387let 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);
388let rlib_prefix = rmeta_prefix;
389let dylib_prefix =
390&::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);
391let staticlib_prefix =
392&::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);
393let interface_prefix = rmeta_prefix;
394395let rmeta_suffix = ".rmeta";
396let rlib_suffix = ".rlib";
397let dylib_suffix = &self.target.dll_suffix;
398let staticlib_suffix = &self.target.staticlib_suffix;
399let interface_suffix = ".rs";
400401let mut candidates: FxIndexMap<
402_,
403 (FxIndexSet<_>, FxIndexSet<_>, FxIndexSet<_>, FxIndexSet<_>),
404 > = Default::default();
405406// First, find all possible candidate rlibs and dylibs purely based on
407 // the name of the files themselves. We're trying to match against an
408 // exact crate name and a possibly an exact hash.
409 //
410 // During this step, we can filter all found libraries based on the
411 // name and id found in the crate id (we ignore the path portion for
412 // filename matching), as well as the exact hash (if specified). If we
413 // end up having many candidates, we must look at the metadata to
414 // perform exact matches against hashes/crate ids. Note that opening up
415 // the metadata is where we do an exact match against the full contents
416 // of the crate id (path/name/id).
417 //
418 // The goal of this step is to look at as little metadata as possible.
419 // Unfortunately, the prefix-based matching sometimes is over-eager.
420 // E.g. if `rlib_suffix` is `libstd` it'll match the file
421 // `libstd_detect-8d6701fb958915ad.rlib` (incorrect) as well as
422 // `libstd-f3ab5b1dea981f17.rlib` (correct). But this is hard to avoid
423 // given that `extra_filename` comes from the `-C extra-filename`
424 // option and thus can be anything, and the incorrect match will be
425 // handled safely in `extract_one`.
426for search_path in self.filesearch.search_paths(self.path_kind) {
427{
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:427",
"rustc_metadata::locator", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_metadata/src/locator.rs"),
::tracing_core::__macro_support::Option::Some(427u32),
::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};
let mut iter = __CALLSITE.metadata().fields().iter();
__CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&format_args!("searching {0}",
search_path.dir.display()) as &dyn Value))])
});
} else { ; }
};debug!("searching {}", search_path.dir.display());
428let spf = &search_path.files;
429430let mut should_check_staticlibs = true;
431for (prefix, suffix, kind) in [
432 (rlib_prefix.as_str(), rlib_suffix, CrateFlavor::Rlib),
433 (rmeta_prefix.as_str(), rmeta_suffix, CrateFlavor::Rmeta),
434 (dylib_prefix, dylib_suffix, CrateFlavor::Dylib),
435 (interface_prefix, interface_suffix, CrateFlavor::SDylib),
436 ] {
437if prefix == staticlib_prefix && suffix == staticlib_suffix {
438 should_check_staticlibs = false;
439 }
440if let Some(matches) = spf.query(prefix, suffix) {
441for (hash, spf) in matches {
442let spf_path = spf.path(&search_path.dir);
443{
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:443",
"rustc_metadata::locator", ::tracing::Level::INFO,
::tracing_core::__macro_support::Option::Some("compiler/rustc_metadata/src/locator.rs"),
::tracing_core::__macro_support::Option::Some(443u32),
::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};
let mut iter = __CALLSITE.metadata().fields().iter();
__CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&format_args!("lib candidate: {0}",
spf_path.display()) as &dyn Value))])
});
} else { ; }
};info!("lib candidate: {}", spf_path.display());
444445let (rlibs, rmetas, dylibs, interfaces) =
446 candidates.entry(hash).or_default();
447 {
448// As a performance optimisation we canonicalize the path and skip
449 // ones we've already seen. This allows us to ignore crates
450 // we know are exactual equal to ones we've already found.
451 // Going to the same crate through different symlinks does not change the result.
452let path =
453 try_canonicalize(&spf_path).unwrap_or_else(|_| spf_path.clone());
454if seen_paths.contains(&path) {
455continue;
456 };
457 seen_paths.insert(path);
458 }
459// Use the original path (potentially with unresolved symlinks),
460 // filesystem code should not care, but this is nicer for diagnostics.
461match kind {
462 CrateFlavor::Rlib => rlibs.insert(spf_path),
463 CrateFlavor::Rmeta => rmetas.insert(spf_path),
464 CrateFlavor::Dylib => dylibs.insert(spf_path),
465 CrateFlavor::SDylib => interfaces.insert(spf_path),
466 };
467 }
468 }
469 }
470if let Some(static_matches) = should_check_staticlibs
471 .then(|| spf.query(staticlib_prefix, staticlib_suffix))
472 .flatten()
473 {
474for (_, spf) in static_matches {
475 crate_rejections.via_kind.push(CrateMismatch {
476 path: spf.path(&search_path.dir),
477 got: "static".to_string(),
478 });
479 }
480 }
481 }
482483// We have now collected all known libraries into a set of candidates
484 // keyed of the filename hash listed. For each filename, we also have a
485 // list of rlibs/dylibs that apply. Here, we map each of these lists
486 // (per hash), to a Library candidate for returning.
487 //
488 // A Library candidate is created if the metadata for the set of
489 // libraries corresponds to the crate id and hash criteria that this
490 // search is being performed for.
491let mut libraries = FxIndexMap::default();
492for (_hash, (rlibs, rmetas, dylibs, interfaces)) in candidates {
493if let Some((svh, lib)) =
494self.extract_lib(crate_rejections, rlibs, rmetas, dylibs, interfaces)?
495{
496 libraries.insert(svh, lib);
497 }
498 }
499500// Having now translated all relevant found hashes into libraries, see
501 // what we've got and figure out if we found multiple candidates for
502 // libraries or not.
503match libraries.len() {
5040 => Ok(None),
5051 => Ok(Some(libraries.into_iter().next().unwrap().1)),
506_ => {
507let mut candidates: Vec<PathBuf> = libraries508 .into_values()
509 .map(|lib| lib.source.paths().next().unwrap().clone())
510 .collect();
511candidates.sort();
512513Err(CrateError::MultipleCandidates(
514self.crate_name,
515// these are the same for all candidates
516get_flavor_from_path(candidates.first().unwrap()),
517candidates,
518 ))
519 }
520 }
521 }
522523fn extract_lib(
524&self,
525 crate_rejections: &mut CrateRejections,
526 rlibs: FxIndexSet<PathBuf>,
527 rmetas: FxIndexSet<PathBuf>,
528 dylibs: FxIndexSet<PathBuf>,
529 interfaces: FxIndexSet<PathBuf>,
530 ) -> Result<Option<(Svh, Library)>, CrateError> {
531let mut slot = None;
532// Order here matters, rmeta should come first.
533 //
534 // Make sure there's at most one rlib and at most one dylib.
535 //
536 // See comment in `extract_one` below.
537let rmeta = self.extract_one(crate_rejections, rmetas, CrateFlavor::Rmeta, &mut slot)?;
538let rlib = self.extract_one(crate_rejections, rlibs, CrateFlavor::Rlib, &mut slot)?;
539let sdylib_interface =
540self.extract_one(crate_rejections, interfaces, CrateFlavor::SDylib, &mut slot)?;
541let dylib = self.extract_one(crate_rejections, dylibs, CrateFlavor::Dylib, &mut slot)?;
542543if sdylib_interface.is_some() && dylib.is_none() {
544return Err(CrateError::FullMetadataNotFound(self.crate_name, CrateFlavor::SDylib));
545 }
546547let source = CrateSource { rmeta, rlib, dylib, sdylib_interface };
548Ok(slot.map(|(svh, metadata, _, _)| (svh, Library { source, metadata })))
549 }
550551fn needs_crate_flavor(&self, flavor: CrateFlavor) -> bool {
552if flavor == CrateFlavor::Dylib && self.is_proc_macro {
553return true;
554 }
555556if self.only_needs_metadata {
557flavor == CrateFlavor::Rmeta558 } else {
559// we need all flavors (perhaps not true, but what we do for now)
560true
561}
562 }
563564// Attempts to extract *one* library from the set `m`. If the set has no
565 // elements, `None` is returned. If the set has more than one element, then
566 // the errors and notes are emitted about the set of libraries.
567 //
568 // With only one library in the set, this function will extract it, and then
569 // read the metadata from it if `*slot` is `None`. If the metadata couldn't
570 // be read, it is assumed that the file isn't a valid rust library (no
571 // errors are emitted).
572 //
573 // The `PathBuf` in `slot` will only be used for diagnostic purposes.
574fn extract_one(
575&self,
576 crate_rejections: &mut CrateRejections,
577 m: FxIndexSet<PathBuf>,
578 flavor: CrateFlavor,
579 slot: &mut Option<(Svh, MetadataBlob, PathBuf, CrateFlavor)>,
580 ) -> Result<Option<PathBuf>, CrateError> {
581// If we are producing an rlib, and we've already loaded metadata, then
582 // we should not attempt to discover further crate sources (unless we're
583 // locating a proc macro; exact logic is in needs_crate_flavor). This means
584 // that under -Zbinary-dep-depinfo we will not emit a dependency edge on
585 // the *unused* rlib, and by returning `None` here immediately we
586 // guarantee that we do indeed not use it.
587 //
588 // See also #68149 which provides more detail on why emitting the
589 // dependency on the rlib is a bad thing.
590if slot.is_some() {
591if m.is_empty() || !self.needs_crate_flavor(flavor) {
592return Ok(None);
593 }
594 }
595596let mut ret: Option<PathBuf> = None;
597let mut err_data: Option<Vec<PathBuf>> = None;
598for lib in m {
599{
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:599",
"rustc_metadata::locator", ::tracing::Level::INFO,
::tracing_core::__macro_support::Option::Some("compiler/rustc_metadata/src/locator.rs"),
::tracing_core::__macro_support::Option::Some(599u32),
::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};
let mut iter = __CALLSITE.metadata().fields().iter();
__CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&format_args!("{0} reading metadata from: {1}",
flavor, lib.display()) as &dyn Value))])
});
} else { ; }
};info!("{} reading metadata from: {}", flavor, lib.display());
600if flavor == CrateFlavor::Rmeta && lib.metadata().is_ok_and(|m| m.len() == 0) {
601// Empty files will cause get_metadata_section to fail. Rmeta
602 // files can be empty, for example with binaries (which can
603 // often appear with `cargo check` when checking a library as
604 // a unittest). We don't want to emit a user-visible warning
605 // in this case as it is not a real problem.
606{
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:606",
"rustc_metadata::locator", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_metadata/src/locator.rs"),
::tracing_core::__macro_support::Option::Some(606u32),
::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};
let mut iter = __CALLSITE.metadata().fields().iter();
__CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&format_args!("skipping empty file")
as &dyn Value))])
});
} else { ; }
};debug!("skipping empty file");
607continue;
608 }
609let (hash, metadata) = match get_metadata_section(
610self.target,
611 flavor,
612&lib,
613self.metadata_loader,
614self.cfg_version,
615Some(self.crate_name),
616 ) {
617Ok(blob) => {
618if let Some(h) = self.crate_matches(crate_rejections, &blob, &lib) {
619 (h, blob)
620 } else {
621{
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:621",
"rustc_metadata::locator", ::tracing::Level::INFO,
::tracing_core::__macro_support::Option::Some("compiler/rustc_metadata/src/locator.rs"),
::tracing_core::__macro_support::Option::Some(621u32),
::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};
let mut iter = __CALLSITE.metadata().fields().iter();
__CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&format_args!("metadata mismatch")
as &dyn Value))])
});
} else { ; }
};info!("metadata mismatch");
622continue;
623 }
624 }
625Err(MetadataError::VersionMismatch { expected_version, found_version }) => {
626// The file was present and created by the same compiler version, but we
627 // couldn't load it for some reason. Give a hard error instead of silently
628 // ignoring it, but only if we would have given an error anyway.
629{
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:629",
"rustc_metadata::locator", ::tracing::Level::INFO,
::tracing_core::__macro_support::Option::Some("compiler/rustc_metadata/src/locator.rs"),
::tracing_core::__macro_support::Option::Some(629u32),
::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};
let mut iter = __CALLSITE.metadata().fields().iter();
__CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&format_args!("Rejecting via version: expected {0} got {1}",
expected_version, found_version) as &dyn Value))])
});
} else { ; }
};info!(
630"Rejecting via version: expected {} got {}",
631 expected_version, found_version
632 );
633 crate_rejections
634 .via_version
635 .push(CrateMismatch { path: lib, got: found_version });
636continue;
637 }
638Err(MetadataError::LoadFailure(err)) => {
639{
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:639",
"rustc_metadata::locator", ::tracing::Level::INFO,
::tracing_core::__macro_support::Option::Some("compiler/rustc_metadata/src/locator.rs"),
::tracing_core::__macro_support::Option::Some(639u32),
::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};
let mut iter = __CALLSITE.metadata().fields().iter();
__CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&format_args!("no metadata found: {0}",
err) as &dyn Value))])
});
} else { ; }
};info!("no metadata found: {}", err);
640// Metadata was loaded from interface file earlier.
641if let Some((.., CrateFlavor::SDylib)) = slot {
642 ret = Some(lib);
643continue;
644 }
645// The file was present and created by the same compiler version, but we
646 // couldn't load it for some reason. Give a hard error instead of silently
647 // ignoring it, but only if we would have given an error anyway.
648crate_rejections.via_invalid.push(CrateMismatch { path: lib, got: err });
649continue;
650 }
651Err(err @ MetadataError::NotPresent(_)) => {
652{
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:652",
"rustc_metadata::locator", ::tracing::Level::INFO,
::tracing_core::__macro_support::Option::Some("compiler/rustc_metadata/src/locator.rs"),
::tracing_core::__macro_support::Option::Some(652u32),
::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};
let mut iter = __CALLSITE.metadata().fields().iter();
__CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&format_args!("no metadata found: {0}",
err) as &dyn Value))])
});
} else { ; }
};info!("no metadata found: {}", err);
653continue;
654 }
655 };
656// If we see multiple hashes, emit an error about duplicate candidates.
657if slot.as_ref().is_some_and(|s| s.0 != hash) {
658if let Some(candidates) = err_data {
659return Err(CrateError::MultipleCandidates(
660self.crate_name,
661 flavor,
662 candidates,
663 ));
664 }
665 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]);
666 }
667if let Some(candidates) = &mut err_data {
668 candidates.push(lib);
669continue;
670 }
671672// We error eagerly here. If we're locating a rlib, then in theory the full metadata
673 // could still be in a (later resolved) dylib. In practice, if the rlib and dylib
674 // were produced in a way where one has full metadata and the other hasn't, it would
675 // mean that they were compiled using different compiler flags and probably also have
676 // a different SVH value.
677if metadata.get_header().is_stub {
678// `is_stub` should never be true for .rmeta files.
679match (&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);
680681// Because rmeta files are resolved before rlib/dylib files, if this is a stub and
682 // we haven't found a slot already, it means that the full metadata is missing.
683if slot.is_none() {
684return Err(CrateError::FullMetadataNotFound(self.crate_name, flavor));
685 }
686 } else {
687*slot = Some((hash, metadata, lib.clone(), flavor));
688 }
689 ret = Some(lib);
690 }
691692if let Some(candidates) = err_data {
693Err(CrateError::MultipleCandidates(self.crate_name, flavor, candidates))
694 } else {
695Ok(ret)
696 }
697 }
698699fn crate_matches(
700&self,
701 crate_rejections: &mut CrateRejections,
702 metadata: &MetadataBlob,
703 libpath: &Path,
704 ) -> Option<Svh> {
705let header = metadata.get_header();
706if header.is_proc_macro_crate != self.is_proc_macro {
707{
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:707",
"rustc_metadata::locator", ::tracing::Level::INFO,
::tracing_core::__macro_support::Option::Some("compiler/rustc_metadata/src/locator.rs"),
::tracing_core::__macro_support::Option::Some(707u32),
::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};
let mut iter = __CALLSITE.metadata().fields().iter();
__CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::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 Value))])
});
} else { ; }
};info!(
708"Rejecting via proc macro: expected {} got {}",
709self.is_proc_macro, header.is_proc_macro_crate,
710 );
711return None;
712 }
713714if self.exact_paths.is_empty() && self.crate_name != header.name {
715{
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:715",
"rustc_metadata::locator", ::tracing::Level::INFO,
::tracing_core::__macro_support::Option::Some("compiler/rustc_metadata/src/locator.rs"),
::tracing_core::__macro_support::Option::Some(715u32),
::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};
let mut iter = __CALLSITE.metadata().fields().iter();
__CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&format_args!("Rejecting via crate name")
as &dyn Value))])
});
} else { ; }
};info!("Rejecting via crate name");
716return None;
717 }
718719if header.triple != self.tuple {
720{
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:720",
"rustc_metadata::locator", ::tracing::Level::INFO,
::tracing_core::__macro_support::Option::Some("compiler/rustc_metadata/src/locator.rs"),
::tracing_core::__macro_support::Option::Some(720u32),
::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};
let mut iter = __CALLSITE.metadata().fields().iter();
__CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&format_args!("Rejecting via crate triple: expected {0} got {1}",
self.tuple, header.triple) as &dyn Value))])
});
} else { ; }
};info!("Rejecting via crate triple: expected {} got {}", self.tuple, header.triple);
721crate_rejections.via_triple.push(CrateMismatch {
722 path: libpath.to_path_buf(),
723 got: header.triple.to_string(),
724 });
725return None;
726 }
727728let hash = header.hash;
729if let Some(expected_hash) = self.hash {
730if hash != expected_hash {
731{
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:731",
"rustc_metadata::locator", ::tracing::Level::INFO,
::tracing_core::__macro_support::Option::Some("compiler/rustc_metadata/src/locator.rs"),
::tracing_core::__macro_support::Option::Some(731u32),
::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};
let mut iter = __CALLSITE.metadata().fields().iter();
__CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&format_args!("Rejecting via hash: expected {0} got {1}",
expected_hash, hash) as &dyn Value))])
});
} else { ; }
};info!("Rejecting via hash: expected {} got {}", expected_hash, hash);
732crate_rejections733 .via_hash
734 .push(CrateMismatch { path: libpath.to_path_buf(), got: hash.to_string() });
735return None;
736 }
737 }
738739Some(hash)
740 }
741742fn find_commandline_library(
743&self,
744 crate_rejections: &mut CrateRejections,
745 ) -> Result<Option<Library>, CrateError> {
746// First, filter out all libraries that look suspicious. We only accept
747 // files which actually exist that have the correct naming scheme for
748 // rlibs/dylibs.
749let mut rlibs = FxIndexSet::default();
750let mut rmetas = FxIndexSet::default();
751let mut dylibs = FxIndexSet::default();
752let mut sdylib_interfaces = FxIndexSet::default();
753for loc in &self.exact_paths {
754let loc_canon = loc.canonicalized();
755let loc_orig = loc.original();
756if !loc_canon.exists() {
757return Err(CrateError::ExternLocationNotExist(self.crate_name, loc_orig.clone()));
758 }
759if !loc_orig.is_file() {
760return Err(CrateError::ExternLocationNotFile(self.crate_name, loc_orig.clone()));
761 }
762// Note to take care and match against the non-canonicalized name:
763 // some systems save build artifacts into content-addressed stores
764 // that do not preserve extensions, and then link to them using
765 // e.g. symbolic links. If we canonicalize too early, we resolve
766 // the symlink, the file type is lost and we might treat rlibs and
767 // rmetas as dylibs.
768let Some(file) = loc_orig.file_name().and_then(|s| s.to_str()) else {
769return Err(CrateError::ExternLocationNotFile(self.crate_name, loc_orig.clone()));
770 };
771if file.starts_with("lib") {
772if file.ends_with(".rlib") {
773 rlibs.insert(loc_canon.clone());
774continue;
775 }
776if file.ends_with(".rmeta") {
777 rmetas.insert(loc_canon.clone());
778continue;
779 }
780if file.ends_with(".rs") {
781 sdylib_interfaces.insert(loc_canon.clone());
782 }
783 }
784let dll_prefix = self.target.dll_prefix.as_ref();
785let dll_suffix = self.target.dll_suffix.as_ref();
786if file.starts_with(dll_prefix) && file.ends_with(dll_suffix) {
787 dylibs.insert(loc_canon.clone());
788continue;
789 }
790 crate_rejections
791 .via_filename
792 .push(CrateMismatch { path: loc_orig.clone(), got: String::new() });
793 }
794795// Extract the dylib/rlib/rmeta triple.
796self.extract_lib(crate_rejections, rlibs, rmetas, dylibs, sdylib_interfaces)
797 .map(|opt| opt.map(|(_, lib)| lib))
798 }
799800pub(crate) fn into_error(
801self,
802 crate_rejections: CrateRejections,
803 dep_root: Option<CratePaths>,
804 ) -> CrateError {
805 CrateError::LocatorCombined(Box::new(CombinedLocatorError {
806 crate_name: self.crate_name,
807dep_root,
808 triple: self.tuple,
809 dll_prefix: self.target.dll_prefix.to_string(),
810 dll_suffix: self.target.dll_suffix.to_string(),
811crate_rejections,
812 }))
813 }
814}
815816fn get_metadata_section<'p>(
817 target: &Target,
818 flavor: CrateFlavor,
819 filename: &'p Path,
820 loader: &dyn MetadataLoader,
821 cfg_version: &'static str,
822 crate_name: Option<Symbol>,
823) -> Result<MetadataBlob, MetadataError<'p>> {
824if !filename.exists() {
825return Err(MetadataError::NotPresent(filename));
826 }
827let raw_bytes = match flavor {
828 CrateFlavor::Rlib => {
829 loader.get_rlib_metadata(target, filename).map_err(MetadataError::LoadFailure)?
830}
831 CrateFlavor::SDylib => {
832let compiler = std::env::current_exe().map_err(|_err| {
833 MetadataError::LoadFailure(
834"couldn't obtain current compiler binary when loading sdylib interface"
835.to_string(),
836 )
837 })?;
838839let tmp_path = match TempFileBuilder::new().prefix("rustc").tempdir() {
840Ok(tmp_path) => tmp_path,
841Err(error) => {
842return Err(MetadataError::LoadFailure(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("couldn\'t create a temp dir: {0}",
error))
})format!(
843"couldn't create a temp dir: {}",
844 error
845 )));
846 }
847 };
848849let crate_name = crate_name.unwrap();
850{
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:850",
"rustc_metadata::locator", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_metadata/src/locator.rs"),
::tracing_core::__macro_support::Option::Some(850u32),
::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};
let mut iter = __CALLSITE.metadata().fields().iter();
__CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&format_args!("compiling {0}",
filename.display()) as &dyn Value))])
});
} else { ; }
};debug!("compiling {}", filename.display());
851// FIXME: This will need to be done either within the current compiler session or
852 // as a separate compiler session in the same process.
853let res = std::process::Command::new(compiler)
854 .arg(&filename)
855 .arg("--emit=metadata")
856 .arg(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("--crate-name={0}", crate_name))
})format!("--crate-name={}", crate_name))
857 .arg(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("--out-dir={0}",
tmp_path.path().display()))
})format!("--out-dir={}", tmp_path.path().display()))
858 .arg("-Zbuild-sdylib-interface")
859 .output()
860 .map_err(|err| {
861 MetadataError::LoadFailure(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("couldn\'t compile interface: {0}",
err))
})format!("couldn't compile interface: {}", err))
862 })?;
863864if !res.status.success() {
865return 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!(
866"couldn't compile interface: {}",
867 std::str::from_utf8(&res.stderr).unwrap_or_default()
868 )));
869 }
870871// Load interface metadata instead of crate metadata.
872let interface_metadata_name = ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("lib{0}.rmeta", crate_name))
})format!("lib{}.rmeta", crate_name);
873let rmeta_file = tmp_path.path().join(interface_metadata_name);
874{
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:874",
"rustc_metadata::locator", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_metadata/src/locator.rs"),
::tracing_core::__macro_support::Option::Some(874u32),
::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};
let mut iter = __CALLSITE.metadata().fields().iter();
__CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&format_args!("loading interface metadata from {0}",
rmeta_file.display()) as &dyn Value))])
});
} else { ; }
};debug!("loading interface metadata from {}", rmeta_file.display());
875let rmeta = get_rmeta_metadata_section(&rmeta_file)?;
876let _ = std::fs::remove_file(rmeta_file);
877878rmeta879 }
880 CrateFlavor::Dylib => {
881let buf =
882 loader.get_dylib_metadata(target, filename).map_err(MetadataError::LoadFailure)?;
883let header_len = METADATA_HEADER.len();
884// header + u64 length of data
885let data_start = header_len + 8;
886887{
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:887",
"rustc_metadata::locator", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_metadata/src/locator.rs"),
::tracing_core::__macro_support::Option::Some(887u32),
::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};
let mut iter = __CALLSITE.metadata().fields().iter();
__CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&format_args!("checking {0} bytes of metadata-version stamp",
header_len) as &dyn Value))])
});
} else { ; }
};debug!("checking {} bytes of metadata-version stamp", header_len);
888let header = &buf[..cmp::min(header_len, buf.len())];
889if header != METADATA_HEADER {
890return Err(MetadataError::LoadFailure(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("invalid metadata version found: {0}",
filename.display()))
})format!(
891"invalid metadata version found: {}",
892 filename.display()
893 )));
894 }
895896// Length of the metadata - this allows linkers to pad the section if they want
897let Ok(len_bytes) =
898 <[u8; 8]>::try_from(&buf[header_len..cmp::min(data_start, buf.len())])
899else {
900return Err(MetadataError::LoadFailure(
901"invalid metadata length found".to_string(),
902 ));
903 };
904let metadata_len = u64::from_le_bytes(len_bytes) as usize;
905906// Header is okay -> inflate the actual metadata
907buf.slice(|buf| &buf[data_start..(data_start + metadata_len)])
908 }
909 CrateFlavor::Rmeta => get_rmeta_metadata_section(filename)?,
910 };
911let Ok(blob) = MetadataBlob::new(raw_bytes) else {
912return Err(MetadataError::LoadFailure(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("corrupt metadata encountered in {0}",
filename.display()))
})format!(
913"corrupt metadata encountered in {}",
914 filename.display()
915 )));
916 };
917match blob.check_compatibility(cfg_version) {
918Ok(()) => {
919{
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:919",
"rustc_metadata::locator", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_metadata/src/locator.rs"),
::tracing_core::__macro_support::Option::Some(919u32),
::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};
let mut iter = __CALLSITE.metadata().fields().iter();
__CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&format_args!("metadata blob read okay")
as &dyn Value))])
});
} else { ; }
};debug!("metadata blob read okay");
920Ok(blob)
921 }
922Err(None) => Err(MetadataError::LoadFailure(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("invalid metadata version found: {0}",
filename.display()))
})format!(
923"invalid metadata version found: {}",
924 filename.display()
925 ))),
926Err(Some(found_version)) => {
927return Err(MetadataError::VersionMismatch {
928 expected_version: rustc_version(cfg_version),
929found_version,
930 });
931 }
932 }
933}
934935fn get_rmeta_metadata_section<'a, 'p>(filename: &'p Path) -> Result<OwnedSlice, MetadataError<'a>> {
936// mmap the file, because only a small fraction of it is read.
937let file = std::fs::File::open(filename).map_err(|_| {
938 MetadataError::LoadFailure(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("failed to open rmeta metadata: \'{0}\'",
filename.display()))
})format!(
939"failed to open rmeta metadata: '{}'",
940 filename.display()
941 ))
942 })?;
943let mmap = unsafe { Mmap::map(file) };
944let mmap = mmap.map_err(|_| {
945 MetadataError::LoadFailure(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("failed to mmap rmeta metadata: \'{0}\'",
filename.display()))
})format!(
946"failed to mmap rmeta metadata: '{}'",
947 filename.display()
948 ))
949 })?;
950951Ok(slice_owned(mmap, Deref::deref))
952}
953954/// A diagnostic function for dumping crate metadata to an output stream.
955pub fn list_file_metadata(
956 target: &Target,
957 path: &Path,
958 metadata_loader: &dyn MetadataLoader,
959 out: &mut dyn Write,
960 ls_kinds: &[String],
961 cfg_version: &'static str,
962) -> IoResult<()> {
963let flavor = get_flavor_from_path(path);
964match get_metadata_section(target, flavor, path, metadata_loader, cfg_version, None) {
965Ok(metadata) => metadata.list_crate_metadata(out, ls_kinds),
966Err(msg) => out.write_fmt(format_args!("{0}\n", msg))write!(out, "{msg}\n"),
967 }
968}
969970fn get_flavor_from_path(path: &Path) -> CrateFlavor {
971let filename = path.file_name().unwrap().to_str().unwrap();
972973if filename.ends_with(".rlib") {
974 CrateFlavor::Rlib975 } else if filename.ends_with(".rmeta") {
976 CrateFlavor::Rmeta977 } else {
978 CrateFlavor::Dylib979 }
980}
981982/// A function to fetch about all macros inside a proc-macro crate.
983///
984/// Used by rust-analyzer-proc-macro-srv.
985pub fn get_proc_macros(
986 target: &Target,
987 path: &Path,
988 metadata_loader: &dyn MetadataLoader,
989 cfg_version: &'static str,
990) -> IoResult<Vec<(ProcMacroClient, ProcMacroKind)>> {
991let metadata =
992 get_metadata_section(target, CrateFlavor::Dylib, path, metadata_loader, cfg_version, None)
993 .map_err(|err| io::Error::other(err.to_string()))?;
994let stable_crate_id = metadata.get_root().stable_crate_id();
995996let clients = crate::host_dylib::dlsym_proc_macros(path, stable_crate_id).map_err(|err| {
997let (crate::DylibError::DlOpen(path, err) | crate::DylibError::DlSym(path, err)) = err;
998 io::Error::other(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0}{1}", path, err))
})format!("{path}{err}"))
999 })?;
10001001let proc_macro_info = metadata.get_proc_macro_info();
1002match (&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());
10031004Ok(clients.into_iter().copied().zip(proc_macro_info).collect())
1005}
10061007// ------------------------------------------ Error reporting -------------------------------------
10081009#[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)]
1010struct CrateMismatch {
1011 path: PathBuf,
1012 got: String,
1013}
10141015#[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)]
1016pub(crate) struct CrateRejections {
1017 via_hash: Vec<CrateMismatch>,
1018 via_triple: Vec<CrateMismatch>,
1019 via_kind: Vec<CrateMismatch>,
1020 via_version: Vec<CrateMismatch>,
1021 via_filename: Vec<CrateMismatch>,
1022 via_invalid: Vec<CrateMismatch>,
1023}
10241025/// Candidate rejection reasons collected during crate search.
1026/// If no candidate is accepted, then these reasons are presented to the user,
1027/// otherwise they are ignored.
1028#[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)]
1029pub(crate) struct CombinedLocatorError {
1030 crate_name: Symbol,
1031 dep_root: Option<CratePaths>,
1032 triple: TargetTuple,
1033 dll_prefix: String,
1034 dll_suffix: String,
1035 crate_rejections: CrateRejections,
1036}
10371038#[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)]
1039pub(crate) enum CrateError {
1040 NonAsciiName(Symbol),
1041 ExternLocationNotExist(Symbol, PathBuf),
1042 ExternLocationNotFile(Symbol, PathBuf),
1043 MultipleCandidates(Symbol, CrateFlavor, Vec<PathBuf>),
1044 FullMetadataNotFound(Symbol, CrateFlavor),
1045 SymbolConflictsCurrent(Symbol),
1046 StableCrateIdCollision(Symbol, Symbol),
1047 DlOpen(String, String),
1048 DlSym(String, String),
1049 LocatorCombined(Box<CombinedLocatorError>),
1050 NotFound(Symbol),
1051}
10521053#[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)]
1054pub(crate) enum MetadataError<'a> {
1055/// The file was missing.
1056NotPresent(&'a Path),
1057/// The file was present and invalid.
1058LoadFailure(String),
1059/// The file was present, but compiled with a different rustc version.
1060VersionMismatch { expected_version: String, found_version: String },
1061}
10621063impl fmt::Displayfor MetadataError<'_> {
1064fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1065match self {
1066 MetadataError::NotPresent(filename) => {
1067f.write_str(&::alloc::__export::must_use({
::alloc::fmt::format(format_args!("no such file: \'{0}\'",
filename.display()))
})format!("no such file: '{}'", filename.display()))
1068 }
1069 MetadataError::LoadFailure(msg) => f.write_str(msg),
1070 MetadataError::VersionMismatch { expected_version, found_version } => {
1071f.write_str(&::alloc::__export::must_use({
::alloc::fmt::format(format_args!("rustc version mismatch. expected {0}, found {1}",
expected_version, found_version))
})format!(
1072"rustc version mismatch. expected {}, found {}",
1073 expected_version, found_version,
1074 ))
1075 }
1076 }
1077 }
1078}
10791080impl CrateError {
1081pub(crate) fn report(self, sess: &Session, span: Span, missing_core: bool) {
1082let dcx = sess.dcx();
1083match self {
1084 CrateError::NonAsciiName(crate_name) => {
1085dcx.emit_err(diagnostics::NonAsciiName { span, crate_name });
1086 }
1087 CrateError::ExternLocationNotExist(crate_name, loc) => {
1088dcx.emit_err(diagnostics::ExternLocationNotExist {
1089span,
1090crate_name,
1091 location: &loc,
1092 });
1093 }
1094 CrateError::ExternLocationNotFile(crate_name, loc) => {
1095dcx.emit_err(diagnostics::ExternLocationNotFile {
1096span,
1097crate_name,
1098 location: &loc,
1099 });
1100 }
1101 CrateError::MultipleCandidates(crate_name, flavor, candidates) => {
1102dcx.emit_err(diagnostics::MultipleCandidates {
1103span,
1104crate_name,
1105flavor,
1106candidates,
1107 });
1108 }
1109 CrateError::FullMetadataNotFound(crate_name, flavor) => {
1110dcx.emit_err(diagnostics::FullMetadataNotFound { span, crate_name, flavor });
1111 }
1112 CrateError::SymbolConflictsCurrent(root_name) => {
1113dcx.emit_err(diagnostics::SymbolConflictsCurrent { span, crate_name: root_name });
1114 }
1115 CrateError::StableCrateIdCollision(crate_name0, crate_name1) => {
1116dcx.emit_err(diagnostics::StableCrateIdCollision {
1117span,
1118crate_name0,
1119crate_name1,
1120 });
1121 }
1122 CrateError::DlOpen(path, err) | CrateError::DlSym(path, err) => {
1123dcx.emit_err(diagnostics::DlError { span, path, err });
1124 }
1125 CrateError::LocatorCombined(locator) => {
1126let crate_name = locator.crate_name;
1127let add_info = match &locator.dep_root {
1128None => String::new(),
1129Some(r) => ::alloc::__export::must_use({
::alloc::fmt::format(format_args!(" which `{0}` depends on", r.name))
})format!(" which `{}` depends on", r.name),
1130 };
1131if !locator.crate_rejections.via_filename.is_empty() {
1132let mismatches = locator.crate_rejections.via_filename.iter();
1133for CrateMismatch { path, .. } in mismatches {
1134 dcx.emit_err(diagnostics::CrateLocationUnknownType {
1135 span,
1136 path,
1137 crate_name,
1138 });
1139 dcx.emit_err(diagnostics::LibFilenameForm {
1140 span,
1141 dll_prefix: &locator.dll_prefix,
1142 dll_suffix: &locator.dll_suffix,
1143 });
1144 }
1145 }
1146let mut found_crates = String::new();
1147if !locator.crate_rejections.via_hash.is_empty() {
1148let mismatches = locator.crate_rejections.via_hash.iter();
1149for CrateMismatch { path, .. } in mismatches {
1150 found_crates.push_str(&::alloc::__export::must_use({
::alloc::fmt::format(format_args!("\ncrate `{0}`: {1}", crate_name,
path.display()))
})format!(
1151"\ncrate `{}`: {}",
1152 crate_name,
1153 path.display()
1154 ));
1155 }
1156if let Some(r) = locator.dep_root {
1157for path in r.source.paths() {
1158 found_crates.push_str(&::alloc::__export::must_use({
::alloc::fmt::format(format_args!("\ncrate `{0}`: {1}", r.name,
path.display()))
})format!(
1159"\ncrate `{}`: {}",
1160 r.name,
1161 path.display()
1162 ));
1163 }
1164 }
1165dcx.emit_err(diagnostics::NewerCrateVersion {
1166span,
1167crate_name,
1168add_info,
1169found_crates,
1170 });
1171 } else if !locator.crate_rejections.via_triple.is_empty() {
1172let mismatches = locator.crate_rejections.via_triple.iter();
1173for CrateMismatch { path, got } in mismatches {
1174 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!(
1175"\ncrate `{}`, target triple {}: {}",
1176 crate_name,
1177 got,
1178 path.display(),
1179 ));
1180 }
1181dcx.emit_err(diagnostics::NoCrateWithTriple {
1182span,
1183crate_name,
1184 locator_triple: locator.triple.tuple(),
1185add_info,
1186found_crates,
1187 });
1188 } else if !locator.crate_rejections.via_kind.is_empty() {
1189let mismatches = locator.crate_rejections.via_kind.iter();
1190for CrateMismatch { path, .. } in mismatches {
1191 found_crates.push_str(&::alloc::__export::must_use({
::alloc::fmt::format(format_args!("\ncrate `{0}`: {1}", crate_name,
path.display()))
})format!(
1192"\ncrate `{}`: {}",
1193 crate_name,
1194 path.display()
1195 ));
1196 }
1197dcx.emit_err(diagnostics::FoundStaticlib {
1198span,
1199crate_name,
1200add_info,
1201found_crates,
1202 });
1203 } else if !locator.crate_rejections.via_version.is_empty() {
1204let mismatches = locator.crate_rejections.via_version.iter();
1205for CrateMismatch { path, got } in mismatches {
1206 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!(
1207"\ncrate `{}` compiled by {}: {}",
1208 crate_name,
1209 got,
1210 path.display(),
1211 ));
1212 }
1213dcx.emit_err(diagnostics::IncompatibleRustc {
1214span,
1215crate_name,
1216add_info,
1217found_crates,
1218 rustc_version: rustc_version(sess.cfg_version),
1219 });
1220 } else if !locator.crate_rejections.via_invalid.is_empty() {
1221let mut crate_rejections = Vec::new();
1222for CrateMismatch { path: _, got } in locator.crate_rejections.via_invalid {
1223 crate_rejections.push(got);
1224 }
1225dcx.emit_err(diagnostics::InvalidMetadataFiles {
1226span,
1227crate_name,
1228add_info,
1229crate_rejections,
1230 });
1231 } else {
1232let error = diagnostics::CannotFindCrate {
1233span,
1234crate_name,
1235add_info,
1236missing_core,
1237 current_crate: sess1238 .opts
1239 .crate_name
1240 .clone()
1241 .unwrap_or_else(|| "<unknown>".to_string()),
1242 is_nightly_build: sess.is_nightly_build(),
1243 profiler_runtime: Symbol::intern(&sess.opts.unstable_opts.profiler_runtime),
1244 locator_triple: locator.triple,
1245 is_ui_testing: sess.opts.unstable_opts.ui_testing,
1246 is_tier_3: sess.target.metadata.tier == Some(3),
1247 };
1248// The diagnostic for missing core is very good, but it is followed by a lot of
1249 // other diagnostics that do not add information.
1250if missing_core {
1251dcx.emit_fatal(error);
1252 } else {
1253dcx.emit_err(error);
1254 }
1255 }
1256 }
1257 CrateError::NotFound(crate_name) => {
1258let error = diagnostics::CannotFindCrate {
1259span,
1260crate_name,
1261 add_info: String::new(),
1262missing_core,
1263 current_crate: sess1264 .opts
1265 .crate_name
1266 .clone()
1267 .unwrap_or_else(|| "<unknown>".to_string()),
1268 is_nightly_build: sess.is_nightly_build(),
1269 profiler_runtime: Symbol::intern(&sess.opts.unstable_opts.profiler_runtime),
1270 locator_triple: sess.opts.target_triple.clone(),
1271 is_ui_testing: sess.opts.unstable_opts.ui_testing,
1272 is_tier_3: sess.target.metadata.tier == Some(3),
1273 };
1274// The diagnostic for missing core is very good, but it is followed by a lot of
1275 // other diagnostics that do not add information.
1276if missing_core {
1277dcx.emit_fatal(error);
1278 } else {
1279dcx.emit_err(error);
1280 }
1281 }
1282 }
1283 }
1284}