Skip to main content

rustc_metadata/
locator.rs

1//! Finds crate binaries and loads their metadata
2//!
3//! Might I be the first to welcome you to a world of platform differences,
4//! version requirements, dependency graphs, conflicting desires, and fun! This
5//! is the major guts (along with metadata::creader) of the compiler for loading
6//! crates and resolving dependencies. Let's take a tour!
7//!
8//! # The problem
9//!
10//! Each invocation of the compiler is immediately concerned with one primary
11//! problem, to connect a set of crates to resolved crates on the filesystem.
12//! Concretely speaking, the compiler follows roughly these steps to get here:
13//!
14//! 1. Discover a set of `extern crate` statements.
15//! 2. Transform these directives into crate names. If the directive does not
16//!    have an explicit name, then the identifier is the name.
17//! 3. For each of these crate names, find a corresponding crate on the
18//!    filesystem.
19//!
20//! Sounds easy, right? Let's walk into some of the nuances.
21//!
22//! ## Transitive Dependencies
23//!
24//! Let's say we've got three crates: A, B, and C. A depends on B, and B depends
25//! on C. When we're compiling A, we primarily need to find and locate B, but we
26//! also end up needing to find and locate C as well.
27//!
28//! The reason for this is that any of B's types could be composed of C's types,
29//! any function in B could return a type from C, etc. To be able to guarantee
30//! that we can always type-check/translate any function, we have to have
31//! complete knowledge of the whole ecosystem, not just our immediate
32//! dependencies.
33//!
34//! So now as part of the "find a corresponding crate on the filesystem" step
35//! above, this involves also finding all crates for *all upstream
36//! dependencies*. This includes all dependencies transitively.
37//!
38//! ## Rlibs and Dylibs
39//!
40//! The compiler has two forms of intermediate dependencies. These are dubbed
41//! rlibs and dylibs for the static and dynamic variants, respectively. An rlib
42//! is a rustc-defined file format (currently just an ar archive) while a dylib
43//! is a platform-defined dynamic library. Each library has a metadata somewhere
44//! inside of it.
45//!
46//! A third kind of dependency is an rmeta file. These are metadata files and do
47//! not contain any code, etc. To a first approximation, these are treated in the
48//! same way as rlibs. Where there is both an rlib and an rmeta file, the rlib
49//! gets priority (even if the rmeta file is newer). An rmeta file is only
50//! useful for checking a downstream crate, attempting to link one will cause an
51//! error.
52//!
53//! When translating a crate name to a crate on the filesystem, we all of a
54//! sudden need to take into account both rlibs and dylibs! Linkage later on may
55//! use either one of these files, as each has their pros/cons. The job of crate
56//! loading is to discover what's possible by finding all candidates.
57//!
58//! Most parts of this loading systems keep the dylib/rlib as just separate
59//! variables.
60//!
61//! ## Where to look?
62//!
63//! We can't exactly scan your whole hard drive when looking for dependencies,
64//! so we need to places to look. Currently the compiler will implicitly add the
65//! target lib search path ($prefix/lib/rustlib/$target/lib) to any compilation,
66//! and otherwise all -L flags are added to the search paths.
67//!
68//! ## What criterion to select on?
69//!
70//! This 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!
214
215use std::borrow::Cow;
216use std::io::{self, Result as IoResult, Write};
217use std::ops::Deref;
218use std::path::{Path, PathBuf};
219use std::{cmp, fmt};
220
221use 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::Client as 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::Builder as TempFileBuilder;
236use tracing::{debug, info};
237
238use crate::creader::{Library, MetadataLoader};
239use crate::diagnostics;
240use crate::rmeta::{METADATA_HEADER, MetadataBlob, ProcMacroKind, rustc_version};
241
242#[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.
245    only_needs_metadata: bool,
246    metadata_loader: &'a dyn MetadataLoader,
247    cfg_version: &'static str,
248
249    // Immutable per-search configuration.
250    crate_name: Symbol,
251    exact_paths: Vec<CanonicalizedPath>,
252    pub 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}
260
261#[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 {
263    pub(crate) name: Symbol,
264    source: CrateSource,
265}
266
267impl CratePaths {
268    pub(crate) fn new(name: Symbol, source: CrateSource) -> CratePaths {
269        CratePaths { name, source }
270    }
271}
272
273#[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}
280
281impl fmt::Display for CrateFlavor {
282    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
283        f.write_str(match *self {
284            CrateFlavor::Rlib => "rlib",
285            CrateFlavor::Rmeta => "rmeta",
286            CrateFlavor::Dylib => "dylib",
287            CrateFlavor::SDylib => "sdylib",
288        })
289    }
290}
291
292impl IntoDiagArg for CrateFlavor {
293    fn into_diag_arg(self, _: &mut Option<std::path::PathBuf>) -> rustc_errors::DiagArgValue {
294        match 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}
302
303impl<'a> CrateLocator<'a> {
304    pub(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> {
313        let 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).
317        let only_needs_metadata = is_rlib || !needs_object_code;
318
319        CrateLocator {
320            only_needs_metadata,
321            metadata_loader,
322            cfg_version: sess.cfg_version,
323            crate_name,
324            exact_paths: if hash.is_none() {
325                sess.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.
336                Vec::new()
337            },
338            hash,
339            extra_filename,
340            target: &sess.target,
341            tuple: sess.opts.target_triple.clone(),
342            filesearch: sess.target_filesearch(),
343            path_kind,
344            is_proc_macro: false,
345        }
346    }
347
348    pub(crate) fn for_proc_macro(&mut self, sess: &'a Session, path_kind: PathKind) {
349        self.is_proc_macro = true;
350        self.target = &sess.host;
351        self.tuple = TargetTuple::from_tuple(config::host_tuple());
352        self.filesearch = sess.host_filesearch();
353        self.path_kind = path_kind;
354    }
355
356    pub(crate) fn for_target_proc_macro(&mut self, sess: &'a Session, path_kind: PathKind) {
357        self.is_proc_macro = true;
358        self.target = &sess.target;
359        self.tuple = sess.opts.target_triple.clone();
360        self.filesearch = sess.target_filesearch();
361        self.path_kind = path_kind;
362    }
363
364    pub(crate) fn maybe_load_library_crate(
365        &self,
366        crate_rejections: &mut CrateRejections,
367    ) -> Result<Option<Library>, CrateError> {
368        if !self.exact_paths.is_empty() {
369            return self.find_commandline_library(crate_rejections);
370        }
371        let mut seen_paths = FxHashSet::default();
372        if let Some(extra_filename) = self.extra_filename
373            && let library @ Some(_) =
374                self.find_library_crate(crate_rejections, extra_filename, &mut seen_paths)?
375        {
376            return Ok(library);
377        }
378        self.find_library_crate(crate_rejections, "", &mut seen_paths)
379    }
380
381    fn 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> {
387        let 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);
388        let rlib_prefix = rmeta_prefix;
389        let 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);
391        let 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);
393        let interface_prefix = rmeta_prefix;
394
395        let rmeta_suffix = ".rmeta";
396        let rlib_suffix = ".rlib";
397        let dylib_suffix = &self.target.dll_suffix;
398        let staticlib_suffix = &self.target.staticlib_suffix;
399        let interface_suffix = ".rs";
400
401        let mut candidates: FxIndexMap<
402            _,
403            (FxIndexSet<_>, FxIndexSet<_>, FxIndexSet<_>, FxIndexSet<_>),
404        > = Default::default();
405
406        // 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`.
426        for 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());
428            let spf = &search_path.files;
429
430            let mut should_check_staticlibs = true;
431            for (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            ] {
437                if prefix == staticlib_prefix && suffix == staticlib_suffix {
438                    should_check_staticlibs = false;
439                }
440                if let Some(matches) = spf.query(prefix, suffix) {
441                    for (hash, spf) in matches {
442                        let 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());
444
445                        let (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.
452                            let path =
453                                try_canonicalize(&spf_path).unwrap_or_else(|_| spf_path.clone());
454                            if seen_paths.contains(&path) {
455                                continue;
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.
461                        match 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            }
470            if let Some(static_matches) = should_check_staticlibs
471                .then(|| spf.query(staticlib_prefix, staticlib_suffix))
472                .flatten()
473            {
474                for (_, 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        }
482
483        // 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.
491        let mut libraries = FxIndexMap::default();
492        for (_hash, (rlibs, rmetas, dylibs, interfaces)) in candidates {
493            if let Some((svh, lib)) =
494                self.extract_lib(crate_rejections, rlibs, rmetas, dylibs, interfaces)?
495            {
496                libraries.insert(svh, lib);
497            }
498        }
499
500        // 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.
503        match libraries.len() {
504            0 => Ok(None),
505            1 => Ok(Some(libraries.into_iter().next().unwrap().1)),
506            _ => {
507                let mut candidates: Vec<PathBuf> = libraries
508                    .into_values()
509                    .map(|lib| lib.source.paths().next().unwrap().clone())
510                    .collect();
511                candidates.sort();
512
513                Err(CrateError::MultipleCandidates(
514                    self.crate_name,
515                    // these are the same for all candidates
516                    get_flavor_from_path(candidates.first().unwrap()),
517                    candidates,
518                ))
519            }
520        }
521    }
522
523    fn 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> {
531        let 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.
537        let rmeta = self.extract_one(crate_rejections, rmetas, CrateFlavor::Rmeta, &mut slot)?;
538        let rlib = self.extract_one(crate_rejections, rlibs, CrateFlavor::Rlib, &mut slot)?;
539        let sdylib_interface =
540            self.extract_one(crate_rejections, interfaces, CrateFlavor::SDylib, &mut slot)?;
541        let dylib = self.extract_one(crate_rejections, dylibs, CrateFlavor::Dylib, &mut slot)?;
542
543        if sdylib_interface.is_some() && dylib.is_none() {
544            return Err(CrateError::FullMetadataNotFound(self.crate_name, CrateFlavor::SDylib));
545        }
546
547        let source = CrateSource { rmeta, rlib, dylib, sdylib_interface };
548        Ok(slot.map(|(svh, metadata, _, _)| (svh, Library { source, metadata })))
549    }
550
551    fn needs_crate_flavor(&self, flavor: CrateFlavor) -> bool {
552        if flavor == CrateFlavor::Dylib && self.is_proc_macro {
553            return true;
554        }
555
556        if self.only_needs_metadata {
557            flavor == CrateFlavor::Rmeta
558        } else {
559            // we need all flavors (perhaps not true, but what we do for now)
560            true
561        }
562    }
563
564    // 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.
574    fn 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.
590        if slot.is_some() {
591            if m.is_empty() || !self.needs_crate_flavor(flavor) {
592                return Ok(None);
593            }
594        }
595
596        let mut ret: Option<PathBuf> = None;
597        let mut err_data: Option<Vec<PathBuf>> = None;
598        for 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());
600            if 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");
607                continue;
608            }
609            let (hash, metadata) = match get_metadata_section(
610                self.target,
611                flavor,
612                &lib,
613                self.metadata_loader,
614                self.cfg_version,
615                Some(self.crate_name),
616            ) {
617                Ok(blob) => {
618                    if 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");
622                        continue;
623                    }
624                }
625                Err(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 });
636                    continue;
637                }
638                Err(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.
641                    if let Some((.., CrateFlavor::SDylib)) = slot {
642                        ret = Some(lib);
643                        continue;
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.
648                    crate_rejections.via_invalid.push(CrateMismatch { path: lib, got: err });
649                    continue;
650                }
651                Err(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);
653                    continue;
654                }
655            };
656            // If we see multiple hashes, emit an error about duplicate candidates.
657            if slot.as_ref().is_some_and(|s| s.0 != hash) {
658                if let Some(candidates) = err_data {
659                    return Err(CrateError::MultipleCandidates(
660                        self.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            }
667            if let Some(candidates) = &mut err_data {
668                candidates.push(lib);
669                continue;
670            }
671
672            // 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.
677            if metadata.get_header().is_stub {
678                // `is_stub` should never be true for .rmeta files.
679                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);
680
681                // 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.
683                if slot.is_none() {
684                    return Err(CrateError::FullMetadataNotFound(self.crate_name, flavor));
685                }
686            } else {
687                *slot = Some((hash, metadata, lib.clone(), flavor));
688            }
689            ret = Some(lib);
690        }
691
692        if let Some(candidates) = err_data {
693            Err(CrateError::MultipleCandidates(self.crate_name, flavor, candidates))
694        } else {
695            Ok(ret)
696        }
697    }
698
699    fn crate_matches(
700        &self,
701        crate_rejections: &mut CrateRejections,
702        metadata: &MetadataBlob,
703        libpath: &Path,
704    ) -> Option<Svh> {
705        let header = metadata.get_header();
706        if 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 {}",
709                self.is_proc_macro, header.is_proc_macro_crate,
710            );
711            return None;
712        }
713
714        if 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");
716            return None;
717        }
718
719        if 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);
721            crate_rejections.via_triple.push(CrateMismatch {
722                path: libpath.to_path_buf(),
723                got: header.triple.to_string(),
724            });
725            return None;
726        }
727
728        let hash = header.hash;
729        if let Some(expected_hash) = self.hash {
730            if 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);
732                crate_rejections
733                    .via_hash
734                    .push(CrateMismatch { path: libpath.to_path_buf(), got: hash.to_string() });
735                return None;
736            }
737        }
738
739        Some(hash)
740    }
741
742    fn 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.
749        let mut rlibs = FxIndexSet::default();
750        let mut rmetas = FxIndexSet::default();
751        let mut dylibs = FxIndexSet::default();
752        let mut sdylib_interfaces = FxIndexSet::default();
753        for loc in &self.exact_paths {
754            let loc_canon = loc.canonicalized();
755            let loc_orig = loc.original();
756            if !loc_canon.exists() {
757                return Err(CrateError::ExternLocationNotExist(self.crate_name, loc_orig.clone()));
758            }
759            if !loc_orig.is_file() {
760                return 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.
768            let Some(file) = loc_orig.file_name().and_then(|s| s.to_str()) else {
769                return Err(CrateError::ExternLocationNotFile(self.crate_name, loc_orig.clone()));
770            };
771            if file.starts_with("lib") {
772                if file.ends_with(".rlib") {
773                    rlibs.insert(loc_canon.clone());
774                    continue;
775                }
776                if file.ends_with(".rmeta") {
777                    rmetas.insert(loc_canon.clone());
778                    continue;
779                }
780                if file.ends_with(".rs") {
781                    sdylib_interfaces.insert(loc_canon.clone());
782                }
783            }
784            let dll_prefix = self.target.dll_prefix.as_ref();
785            let dll_suffix = self.target.dll_suffix.as_ref();
786            if file.starts_with(dll_prefix) && file.ends_with(dll_suffix) {
787                dylibs.insert(loc_canon.clone());
788                continue;
789            }
790            crate_rejections
791                .via_filename
792                .push(CrateMismatch { path: loc_orig.clone(), got: String::new() });
793        }
794
795        // Extract the dylib/rlib/rmeta triple.
796        self.extract_lib(crate_rejections, rlibs, rmetas, dylibs, sdylib_interfaces)
797            .map(|opt| opt.map(|(_, lib)| lib))
798    }
799
800    pub(crate) fn into_error(
801        self,
802        crate_rejections: CrateRejections,
803        dep_root: Option<CratePaths>,
804    ) -> CrateError {
805        CrateError::LocatorCombined(Box::new(CombinedLocatorError {
806            crate_name: self.crate_name,
807            dep_root,
808            triple: self.tuple,
809            dll_prefix: self.target.dll_prefix.to_string(),
810            dll_suffix: self.target.dll_suffix.to_string(),
811            crate_rejections,
812        }))
813    }
814}
815
816fn 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>> {
824    if !filename.exists() {
825        return Err(MetadataError::NotPresent(filename));
826    }
827    let raw_bytes = match flavor {
828        CrateFlavor::Rlib => {
829            loader.get_rlib_metadata(target, filename).map_err(MetadataError::LoadFailure)?
830        }
831        CrateFlavor::SDylib => {
832            let 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            })?;
838
839            let tmp_path = match TempFileBuilder::new().prefix("rustc").tempdir() {
840                Ok(tmp_path) => tmp_path,
841                Err(error) => {
842                    return 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            };
848
849            let 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.
853            let 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                })?;
863
864            if !res.status.success() {
865                return 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            }
870
871            // Load interface metadata instead of crate metadata.
872            let interface_metadata_name = ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("lib{0}.rmeta", crate_name))
    })format!("lib{}.rmeta", crate_name);
873            let 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());
875            let rmeta = get_rmeta_metadata_section(&rmeta_file)?;
876            let _ = std::fs::remove_file(rmeta_file);
877
878            rmeta
879        }
880        CrateFlavor::Dylib => {
881            let buf =
882                loader.get_dylib_metadata(target, filename).map_err(MetadataError::LoadFailure)?;
883            let header_len = METADATA_HEADER.len();
884            // header + u64 length of data
885            let data_start = header_len + 8;
886
887            {
    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);
888            let header = &buf[..cmp::min(header_len, buf.len())];
889            if header != METADATA_HEADER {
890                return 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            }
895
896            // Length of the metadata - this allows linkers to pad the section if they want
897            let Ok(len_bytes) =
898                <[u8; 8]>::try_from(&buf[header_len..cmp::min(data_start, buf.len())])
899            else {
900                return Err(MetadataError::LoadFailure(
901                    "invalid metadata length found".to_string(),
902                ));
903            };
904            let metadata_len = u64::from_le_bytes(len_bytes) as usize;
905
906            // Header is okay -> inflate the actual metadata
907            buf.slice(|buf| &buf[data_start..(data_start + metadata_len)])
908        }
909        CrateFlavor::Rmeta => get_rmeta_metadata_section(filename)?,
910    };
911    let Ok(blob) = MetadataBlob::new(raw_bytes) else {
912        return 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    };
917    match blob.check_compatibility(cfg_version) {
918        Ok(()) => {
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");
920            Ok(blob)
921        }
922        Err(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        ))),
926        Err(Some(found_version)) => {
927            return Err(MetadataError::VersionMismatch {
928                expected_version: rustc_version(cfg_version),
929                found_version,
930            });
931        }
932    }
933}
934
935fn 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.
937    let 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    })?;
943    let mmap = unsafe { Mmap::map(file) };
944    let 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    })?;
950
951    Ok(slice_owned(mmap, Deref::deref))
952}
953
954/// 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<()> {
963    let flavor = get_flavor_from_path(path);
964    match get_metadata_section(target, flavor, path, metadata_loader, cfg_version, None) {
965        Ok(metadata) => metadata.list_crate_metadata(out, ls_kinds),
966        Err(msg) => out.write_fmt(format_args!("{0}\n", msg))write!(out, "{msg}\n"),
967    }
968}
969
970fn get_flavor_from_path(path: &Path) -> CrateFlavor {
971    let filename = path.file_name().unwrap().to_str().unwrap();
972
973    if filename.ends_with(".rlib") {
974        CrateFlavor::Rlib
975    } else if filename.ends_with(".rmeta") {
976        CrateFlavor::Rmeta
977    } else {
978        CrateFlavor::Dylib
979    }
980}
981
982/// 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)>> {
991    let metadata =
992        get_metadata_section(target, CrateFlavor::Dylib, path, metadata_loader, cfg_version, None)
993            .map_err(|err| io::Error::other(err.to_string()))?;
994    let stable_crate_id = metadata.get_root().stable_crate_id();
995
996    let clients = crate::host_dylib::dlsym_proc_macros(path, stable_crate_id).map_err(|err| {
997        let (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    })?;
1000
1001    let proc_macro_info = metadata.get_proc_macro_info();
1002    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());
1003
1004    Ok(clients.into_iter().copied().zip(proc_macro_info).collect())
1005}
1006
1007// ------------------------------------------ Error reporting -------------------------------------
1008
1009#[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}
1014
1015#[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}
1024
1025/// 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}
1037
1038#[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}
1052
1053#[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.
1056    NotPresent(&'a Path),
1057    /// The file was present and invalid.
1058    LoadFailure(String),
1059    /// The file was present, but compiled with a different rustc version.
1060    VersionMismatch { expected_version: String, found_version: String },
1061}
1062
1063impl fmt::Display for MetadataError<'_> {
1064    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1065        match self {
1066            MetadataError::NotPresent(filename) => {
1067                f.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 } => {
1071                f.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}
1079
1080impl CrateError {
1081    pub(crate) fn report(self, sess: &Session, span: Span, missing_core: bool) {
1082        let dcx = sess.dcx();
1083        match self {
1084            CrateError::NonAsciiName(crate_name) => {
1085                dcx.emit_err(diagnostics::NonAsciiName { span, crate_name });
1086            }
1087            CrateError::ExternLocationNotExist(crate_name, loc) => {
1088                dcx.emit_err(diagnostics::ExternLocationNotExist {
1089                    span,
1090                    crate_name,
1091                    location: &loc,
1092                });
1093            }
1094            CrateError::ExternLocationNotFile(crate_name, loc) => {
1095                dcx.emit_err(diagnostics::ExternLocationNotFile {
1096                    span,
1097                    crate_name,
1098                    location: &loc,
1099                });
1100            }
1101            CrateError::MultipleCandidates(crate_name, flavor, candidates) => {
1102                dcx.emit_err(diagnostics::MultipleCandidates {
1103                    span,
1104                    crate_name,
1105                    flavor,
1106                    candidates,
1107                });
1108            }
1109            CrateError::FullMetadataNotFound(crate_name, flavor) => {
1110                dcx.emit_err(diagnostics::FullMetadataNotFound { span, crate_name, flavor });
1111            }
1112            CrateError::SymbolConflictsCurrent(root_name) => {
1113                dcx.emit_err(diagnostics::SymbolConflictsCurrent { span, crate_name: root_name });
1114            }
1115            CrateError::StableCrateIdCollision(crate_name0, crate_name1) => {
1116                dcx.emit_err(diagnostics::StableCrateIdCollision {
1117                    span,
1118                    crate_name0,
1119                    crate_name1,
1120                });
1121            }
1122            CrateError::DlOpen(path, err) | CrateError::DlSym(path, err) => {
1123                dcx.emit_err(diagnostics::DlError { span, path, err });
1124            }
1125            CrateError::LocatorCombined(locator) => {
1126                let crate_name = locator.crate_name;
1127                let add_info = match &locator.dep_root {
1128                    None => String::new(),
1129                    Some(r) => ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!(" which `{0}` depends on", r.name))
    })format!(" which `{}` depends on", r.name),
1130                };
1131                if !locator.crate_rejections.via_filename.is_empty() {
1132                    let mismatches = locator.crate_rejections.via_filename.iter();
1133                    for 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                }
1146                let mut found_crates = String::new();
1147                if !locator.crate_rejections.via_hash.is_empty() {
1148                    let mismatches = locator.crate_rejections.via_hash.iter();
1149                    for 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                    }
1156                    if let Some(r) = locator.dep_root {
1157                        for 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                    }
1165                    dcx.emit_err(diagnostics::NewerCrateVersion {
1166                        span,
1167                        crate_name,
1168                        add_info,
1169                        found_crates,
1170                    });
1171                } else if !locator.crate_rejections.via_triple.is_empty() {
1172                    let mismatches = locator.crate_rejections.via_triple.iter();
1173                    for 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                    }
1181                    dcx.emit_err(diagnostics::NoCrateWithTriple {
1182                        span,
1183                        crate_name,
1184                        locator_triple: locator.triple.tuple(),
1185                        add_info,
1186                        found_crates,
1187                    });
1188                } else if !locator.crate_rejections.via_kind.is_empty() {
1189                    let mismatches = locator.crate_rejections.via_kind.iter();
1190                    for 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                    }
1197                    dcx.emit_err(diagnostics::FoundStaticlib {
1198                        span,
1199                        crate_name,
1200                        add_info,
1201                        found_crates,
1202                    });
1203                } else if !locator.crate_rejections.via_version.is_empty() {
1204                    let mismatches = locator.crate_rejections.via_version.iter();
1205                    for 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                    }
1213                    dcx.emit_err(diagnostics::IncompatibleRustc {
1214                        span,
1215                        crate_name,
1216                        add_info,
1217                        found_crates,
1218                        rustc_version: rustc_version(sess.cfg_version),
1219                    });
1220                } else if !locator.crate_rejections.via_invalid.is_empty() {
1221                    let mut crate_rejections = Vec::new();
1222                    for CrateMismatch { path: _, got } in locator.crate_rejections.via_invalid {
1223                        crate_rejections.push(got);
1224                    }
1225                    dcx.emit_err(diagnostics::InvalidMetadataFiles {
1226                        span,
1227                        crate_name,
1228                        add_info,
1229                        crate_rejections,
1230                    });
1231                } else {
1232                    let error = diagnostics::CannotFindCrate {
1233                        span,
1234                        crate_name,
1235                        add_info,
1236                        missing_core,
1237                        current_crate: sess
1238                            .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.
1250                    if missing_core {
1251                        dcx.emit_fatal(error);
1252                    } else {
1253                        dcx.emit_err(error);
1254                    }
1255                }
1256            }
1257            CrateError::NotFound(crate_name) => {
1258                let error = diagnostics::CannotFindCrate {
1259                    span,
1260                    crate_name,
1261                    add_info: String::new(),
1262                    missing_core,
1263                    current_crate: sess
1264                        .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.
1276                if missing_core {
1277                    dcx.emit_fatal(error);
1278                } else {
1279                    dcx.emit_err(error);
1280                }
1281            }
1282        }
1283    }
1284}