Skip to main content

rustc_session/
filesearch.rs

1//! A module for searching for libraries
2
3use std::path::{Path, PathBuf};
4use std::sync::Arc;
5use std::{env, fs, iter};
6
7use rustc_fs_util::try_canonicalize;
8use rustc_target::spec::Target;
9
10use crate::search_paths::{PathKind, SearchPath};
11
12pub struct FileSearch {
13    cli_search_paths: Vec<SearchPath>,
14    tlib_path: SearchPath,
15    use_implicit_sysroot_deps: bool,
16    files: Vec<FileSearchCandidate>,
17}
18
19impl FileSearch {
20    pub fn cli_search_paths<'b>(&'b self, kind: PathKind) -> impl Iterator<Item = &'b SearchPath> {
21        self.cli_search_paths.iter().filter(move |sp| sp.kind.matches(kind))
22    }
23
24    pub fn search_paths<'b>(&'b self, kind: PathKind) -> impl Iterator<Item = &'b SearchPath> {
25        // If the crate is `PathKind::Crate` (a top level dependency)
26        // and `-Z implicit-sysroot-deps=false`, then don't include the sysroot in the search paths.
27        let exclude_sysroot = kind.matches(PathKind::Crate) && !self.use_implicit_sysroot_deps;
28        let maybe_tlib = (!exclude_sysroot).then_some(&self.tlib_path);
29
30        self.cli_search_paths
31            .iter()
32            .filter(move |sp| sp.kind.matches(kind))
33            .chain(maybe_tlib.into_iter())
34    }
35
36    /// Return files from the search dirs of this filesearch that match the given `prefix` and
37    /// `suffix` and have the given `kind`.
38    ///
39    /// Note that this function only searches files that match lib/staticlib/dlllib prefixes, not
40    /// all files from the search paths!
41    /// Access `search_paths` directly if you want to scan all files within them.
42    pub fn get_library_candidates<'b>(
43        &'b self,
44        prefix: &'b str,
45        suffix: &'b str,
46        kind: PathKind,
47    ) -> impl Iterator<Item = (&'b str, PathBuf)> {
48        let exclude_sysroot = kind.matches(PathKind::Crate) && !self.use_implicit_sysroot_deps;
49
50        // The indices are clipped to have only a single iterator returned from this function, to
51        // avoid allocating it.
52        let start = self.files.partition_point(|v| *v.filename < *prefix).min(self.files.len());
53        let end = self.files[start..].partition_point(|v| v.filename.starts_with(prefix));
54        let prefixed_items = &self.files[start..][..end];
55
56        prefixed_items
57            .into_iter()
58            .filter(move |c| {
59                c.kind.matches(kind)
60                    && !(exclude_sysroot && c.from_sysroot)
61                    && c.filename.ends_with(suffix)
62            })
63            .map(|c| (&c.filename[prefix.len()..c.filename.len() - suffix.len()], c.path()))
64    }
65
66    pub fn new(
67        cli_search_paths: &[SearchPath],
68        tlib_path: &SearchPath,
69        target: &Target,
70        use_implicit_sysroot_deps: bool,
71    ) -> Self {
72        // We keep a list of all found paths that look like libraries in `FileSearch`, to optimize
73        // lookup in `get_library_candidates`.
74        // These prefixes should be kept in sync with `CrateLocator::find_library_crate`.
75        let prefixes = ["lib", &target.staticlib_prefix, &target.dll_prefix];
76
77        // Load all files from all search paths, filter them by supported prefixes, and sort them,
78        // so that we can efficiently look them up in `get_file_candidates` via binary search.
79        let mut files: Vec<FileSearchCandidate> = Vec::with_capacity(cli_search_paths.len());
80        for (search_path, is_sysroot) in
81            cli_search_paths.iter().map(|path| (path, false)).chain(iter::once((tlib_path, true)))
82        {
83            let Ok(dir) = fs::read_dir(&search_path.dir) else {
84                continue;
85            };
86            files.extend(dir.filter_map(|entry| {
87                let entry = entry.ok()?;
88
89                let filename = entry.file_name();
90                let filename = filename.to_str()?;
91
92                if !prefixes.iter().any(|prefix| filename.starts_with(prefix)) {
93                    return None;
94                }
95                Some(FileSearchCandidate {
96                    dir: Arc::clone(&search_path.dir),
97                    filename: filename.into(),
98                    kind: search_path.kind,
99                    from_sysroot: is_sysroot,
100                })
101            }));
102        }
103        files.sort_unstable_by(|lhs, rhs| lhs.filename.cmp(&rhs.filename));
104
105        FileSearch {
106            cli_search_paths: cli_search_paths.to_owned(),
107            tlib_path: tlib_path.clone(),
108            use_implicit_sysroot_deps,
109            files,
110        }
111    }
112}
113
114/// This type stores `Box<str>` instead of `PathBuf` for the filename, because getting the
115/// `file_name` of a `PathBuf` allocates, which is unnecessary. We have to go through the files
116/// a lot of times, so storing file name and the directory separately saves time and memory.
117///
118/// The filename must be valid UTF-8. If it's not, the entry should be skipped, because all Rust
119/// output files are valid UTF-8, and so a non-UTF-8 filename couldn't be one we're looking for.
120#[derive(#[automatically_derived]
impl ::core::fmt::Debug for FileSearchCandidate {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        ::core::fmt::Formatter::debug_struct_field4_finish(f,
            "FileSearchCandidate", "dir", &self.dir, "filename",
            &self.filename, "kind", &self.kind, "from_sysroot",
            &&self.from_sysroot)
    }
}Debug)]
121struct FileSearchCandidate {
122    dir: Arc<Path>,
123    filename: Box<str>,
124    kind: PathKind,
125    /// Was this file added through the target sysroot?
126    from_sysroot: bool,
127}
128
129impl FileSearchCandidate {
130    /// Constructs the full path to the file.
131    fn path(&self) -> PathBuf {
132        self.dir.join(&*self.filename)
133    }
134}
135
136pub fn make_target_lib_path(sysroot: &Path, target_triple: &str) -> PathBuf {
137    let rustlib_path = rustc_target::relative_target_rustlib_path(sysroot, target_triple);
138    sysroot.join(rustlib_path).join("lib")
139}
140
141/// Returns a path to the target's `bin` folder within its `rustlib` path in the sysroot. This is
142/// where binaries are usually installed, e.g. the self-contained linkers, lld-wrappers, LLVM tools,
143/// etc.
144pub fn make_target_bin_path(sysroot: &Path, target_triple: &str) -> PathBuf {
145    let rustlib_path = rustc_target::relative_target_rustlib_path(sysroot, target_triple);
146    sysroot.join(rustlib_path).join("bin")
147}
148
149#[cfg(unix)]
150fn current_dll_path() -> Result<PathBuf, String> {
151    use std::sync::OnceLock;
152
153    // This is somewhat expensive relative to other work when compiling `fn main() {}` as `dladdr`
154    // needs to iterate over the symbol table of librustc_driver.so until it finds a match.
155    // As such cache this to avoid recomputing if we try to get the sysroot in multiple places.
156    static CURRENT_DLL_PATH: OnceLock<Result<PathBuf, String>> = OnceLock::new();
157    CURRENT_DLL_PATH
158        .get_or_init(|| {
159            use std::ffi::{CStr, OsStr};
160            use std::os::unix::prelude::*;
161
162            #[cfg(not(target_os = "aix"))]
163            unsafe {
164                let addr = current_dll_path as fn() -> Result<PathBuf, String> as *mut _;
165                let mut info = std::mem::zeroed();
166                if libc::dladdr(addr, &mut info) == 0 {
167                    return Err("dladdr failed".into());
168                }
169                #[cfg(target_os = "cygwin")]
170                let fname_ptr = info.dli_fname.as_ptr();
171                #[cfg(not(target_os = "cygwin"))]
172                let fname_ptr = {
173                    if !!info.dli_fname.is_null() {
    {
        ::core::panicking::panic_fmt(format_args!("dli_fname cannot be null"));
    }
};assert!(!info.dli_fname.is_null(), "dli_fname cannot be null");
174                    info.dli_fname
175                };
176                let bytes = CStr::from_ptr(fname_ptr).to_bytes();
177                let os = OsStr::from_bytes(bytes);
178                try_canonicalize(Path::new(os)).map_err(|e| e.to_string())
179            }
180
181            #[cfg(target_os = "aix")]
182            unsafe {
183                // On AIX, the symbol `current_dll_path` references a function descriptor.
184                // A function descriptor is consisted of (See https://reviews.llvm.org/D62532)
185                // * The address of the entry point of the function.
186                // * The TOC base address for the function.
187                // * The environment pointer.
188                // The function descriptor is in the data section.
189                let addr = current_dll_path as u64;
190                let mut buffer = vec![std::mem::zeroed::<libc::ld_info>(); 64];
191                loop {
192                    if libc::loadquery(
193                        libc::L_GETINFO,
194                        buffer.as_mut_ptr() as *mut libc::c_void,
195                        (size_of::<libc::ld_info>() * buffer.len()) as u32,
196                    ) >= 0
197                    {
198                        break;
199                    } else {
200                        if std::io::Error::last_os_error().raw_os_error().unwrap() != libc::ENOMEM {
201                            return Err("loadquery failed".into());
202                        }
203                        buffer.resize(buffer.len() * 2, std::mem::zeroed::<libc::ld_info>());
204                    }
205                }
206                let mut current = buffer.as_mut_ptr() as *mut libc::ld_info;
207                loop {
208                    let data_base = (*current).ldinfo_dataorg as u64;
209                    let data_end = data_base + (*current).ldinfo_datasize;
210                    if (data_base..data_end).contains(&addr) {
211                        let bytes = CStr::from_ptr(&(*current).ldinfo_filename[0]).to_bytes();
212                        let os = OsStr::from_bytes(bytes);
213                        return try_canonicalize(Path::new(os)).map_err(|e| e.to_string());
214                    }
215                    if (*current).ldinfo_next == 0 {
216                        break;
217                    }
218                    current = (current as *mut i8).offset((*current).ldinfo_next as isize)
219                        as *mut libc::ld_info;
220                }
221                return Err(format!("current dll's address {} is not in the load map", addr));
222            }
223        })
224        .clone()
225}
226
227#[cfg(windows)]
228fn current_dll_path() -> Result<PathBuf, String> {
229    use std::ffi::OsString;
230    use std::io;
231    use std::os::windows::prelude::*;
232
233    use windows::Win32::Foundation::HMODULE;
234    use windows::Win32::System::LibraryLoader::{
235        GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS, GetModuleFileNameW, GetModuleHandleExW,
236    };
237    use windows::core::PCWSTR;
238
239    let mut module = HMODULE::default();
240    unsafe {
241        GetModuleHandleExW(
242            GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS,
243            PCWSTR(
244                current_dll_path as fn() -> Result<std::path::PathBuf, std::string::String>
245                    as *mut u16,
246            ),
247            &mut module,
248        )
249    }
250    .map_err(|e| e.to_string())?;
251
252    let mut filename = vec![0; 1024];
253    let n = unsafe { GetModuleFileNameW(Some(module), &mut filename) } as usize;
254    if n == 0 {
255        return Err(format!("GetModuleFileNameW failed: {}", io::Error::last_os_error()));
256    }
257    if n >= filename.capacity() {
258        return Err(format!("our buffer was too small? {}", io::Error::last_os_error()));
259    }
260
261    filename.truncate(n);
262
263    let path = try_canonicalize(OsString::from_wide(&filename)).map_err(|e| e.to_string())?;
264
265    // See comments on this target function, but the gist is that
266    // gcc chokes on verbatim paths which fs::canonicalize generates
267    // so we try to avoid those kinds of paths.
268    Ok(rustc_fs_util::fix_windows_verbatim_for_gcc(&path))
269}
270
271#[cfg(target_os = "wasi")]
272fn current_dll_path() -> Result<PathBuf, String> {
273    Err("current_dll_path is not supported on WASI".to_string())
274}
275
276/// This function checks if sysroot is found using env::args().next(), and if it
277/// is not found, finds sysroot from current rustc_driver dll.
278pub(crate) fn default_sysroot() -> PathBuf {
279    fn default_from_rustc_driver_dll() -> Result<PathBuf, String> {
280        let dll = current_dll_path()?;
281
282        // `dll` will be in one of the following two:
283        // - compiler's libdir: $sysroot/lib/*.dll
284        // - target's libdir: $sysroot/lib/rustlib/$target/lib/*.dll
285        //
286        // use `parent` twice to chop off the file name and then also the
287        // directory containing the dll
288        let dir = dll.parent().and_then(|p| p.parent()).ok_or_else(|| {
289            ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("Could not move 2 levels upper using `parent()` on {0}",
                dll.display()))
    })format!("Could not move 2 levels upper using `parent()` on {}", dll.display())
290        })?;
291
292        // if `dir` points to target's dir, move up to the sysroot
293        let mut sysroot_dir = if dir.ends_with(crate::config::host_tuple()) {
294            dir.parent() // chop off `$target`
295                .and_then(|p| p.parent()) // chop off `rustlib`
296                .and_then(|p| p.parent()) // chop off `lib`
297                .map(|s| s.to_owned())
298                .ok_or_else(|| {
299                    ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("Could not move 3 levels upper using `parent()` on {0}",
                dir.display()))
    })format!("Could not move 3 levels upper using `parent()` on {}", dir.display())
300                })?
301        } else {
302            dir.to_owned()
303        };
304
305        // On multiarch linux systems, there will be multiarch directory named
306        // with the architecture(e.g `x86_64-linux-gnu`) under the `lib` directory.
307        // Which cause us to mistakenly end up in the lib directory instead of the sysroot directory.
308        if sysroot_dir.ends_with("lib") {
309            sysroot_dir =
310                sysroot_dir.parent().map(|real_sysroot| real_sysroot.to_owned()).ok_or_else(
311                    || ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("Could not move to parent path of {0}",
                sysroot_dir.display()))
    })format!("Could not move to parent path of {}", sysroot_dir.display()),
312                )?
313        }
314
315        Ok(sysroot_dir)
316    }
317
318    // Use env::args().next() to get the path of the executable without
319    // following symlinks/canonicalizing any component. This makes the rustc
320    // binary able to locate Rust libraries in systems using content-addressable
321    // storage (CAS).
322    fn from_env_args_next() -> Option<PathBuf> {
323        let mut p = PathBuf::from(env::args_os().next()?);
324
325        // Check if sysroot is found using env::args().next() only if the rustc in argv[0]
326        // is a symlink (see #79253). We might want to change/remove it to conform with
327        // https://www.gnu.org/prep/standards/standards.html#Finding-Program-Files in the
328        // future.
329        if fs::read_link(&p).is_err() {
330            // Path is not a symbolic link or does not exist.
331            return None;
332        }
333
334        // Pop off `bin/rustc`, obtaining the suspected sysroot.
335        p.pop();
336        p.pop();
337        // Look for the target rustlib directory in the suspected sysroot.
338        let mut rustlib_path = rustc_target::relative_target_rustlib_path(&p, "dummy");
339        rustlib_path.pop(); // pop off the dummy target.
340        rustlib_path.exists().then_some(p)
341    }
342
343    from_env_args_next()
344        .unwrap_or_else(|| default_from_rustc_driver_dll().expect("Failed finding sysroot"))
345}