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/// Attempts to find the path to the dynamic library containing a function.
150///
151/// SAFETY: `function` must be a valid pointer to some function.
152#[cfg(unix)]
153pub unsafe fn dll_path(function: *mut std::ffi::c_void) -> Result<PathBuf, String> {
154    use std::ffi::{CStr, OsStr};
155    use std::os::unix::prelude::*;
156
157    #[cfg(not(target_os = "aix"))]
158    unsafe {
159        let mut info = std::mem::zeroed();
160        if libc::dladdr(function, &mut info) == 0 {
161            return Err("dladdr failed".into());
162        }
163        #[cfg(target_os = "cygwin")]
164        let fname_ptr = info.dli_fname.as_ptr();
165        #[cfg(not(target_os = "cygwin"))]
166        let fname_ptr = {
167            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");
168            info.dli_fname
169        };
170        let bytes = CStr::from_ptr(fname_ptr).to_bytes();
171        let os = OsStr::from_bytes(bytes);
172        try_canonicalize(Path::new(os)).map_err(|e| e.to_string())
173    }
174
175    #[cfg(target_os = "aix")]
176    unsafe {
177        // On AIX, the symbol references a function descriptor.
178        // A function descriptor is consisted of (See https://reviews.llvm.org/D62532)
179        // * The address of the entry point of the function.
180        // * The TOC base address for the function.
181        // * The environment pointer.
182        // The function descriptor is in the data section.
183        let addr = function as u64;
184        let mut buffer = vec![std::mem::zeroed::<libc::ld_info>(); 64];
185        loop {
186            if libc::loadquery(
187                libc::L_GETINFO,
188                buffer.as_mut_ptr() as *mut libc::c_void,
189                (size_of::<libc::ld_info>() * buffer.len()) as u32,
190            ) >= 0
191            {
192                break;
193            } else {
194                if std::io::Error::last_os_error().raw_os_error().unwrap() != libc::ENOMEM {
195                    return Err("loadquery failed".into());
196                }
197                buffer.resize(buffer.len() * 2, std::mem::zeroed::<libc::ld_info>());
198            }
199        }
200        let mut current = buffer.as_mut_ptr() as *mut libc::ld_info;
201        loop {
202            let data_base = (*current).ldinfo_dataorg as u64;
203            let data_end = data_base + (*current).ldinfo_datasize;
204            if (data_base..data_end).contains(&addr) {
205                let bytes = CStr::from_ptr(&(*current).ldinfo_filename[0]).to_bytes();
206                let os = OsStr::from_bytes(bytes);
207                return try_canonicalize(Path::new(os)).map_err(|e| e.to_string());
208            }
209            if (*current).ldinfo_next == 0 {
210                break;
211            }
212            current =
213                (current as *mut i8).offset((*current).ldinfo_next as isize) as *mut libc::ld_info;
214        }
215        return Err(format!("current dll's address {} is not in the load map", addr));
216    }
217}
218
219#[cfg(windows)]
220pub unsafe fn dll_path(function: *mut std::ffi::c_void) -> Result<PathBuf, String> {
221    use std::ffi::OsString;
222    use std::io;
223    use std::os::windows::prelude::*;
224
225    use windows::Win32::Foundation::HMODULE;
226    use windows::Win32::System::LibraryLoader::{
227        GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS, GetModuleFileNameW, GetModuleHandleExW,
228    };
229    use windows::core::PCWSTR;
230
231    let mut module = HMODULE::default();
232    unsafe {
233        GetModuleHandleExW(
234            GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS,
235            PCWSTR(function as *mut u16),
236            &mut module,
237        )
238    }
239    .map_err(|e| e.to_string())?;
240
241    let mut filename = vec![0; 1024];
242    let n = unsafe { GetModuleFileNameW(Some(module), &mut filename) } as usize;
243    if n == 0 {
244        return Err(format!("GetModuleFileNameW failed: {}", io::Error::last_os_error()));
245    }
246    if n >= filename.capacity() {
247        return Err(format!("our buffer was too small? {}", io::Error::last_os_error()));
248    }
249
250    filename.truncate(n);
251
252    let path = try_canonicalize(OsString::from_wide(&filename)).map_err(|e| e.to_string())?;
253
254    // See comments on this target function, but the gist is that
255    // gcc chokes on verbatim paths which fs::canonicalize generates
256    // so we try to avoid those kinds of paths.
257    Ok(rustc_fs_util::fix_windows_verbatim_for_gcc(&path))
258}
259
260#[cfg(target_os = "wasi")]
261pub unsafe fn dll_path(_function: *mut std::ffi::c_void) -> Result<PathBuf, String> {
262    Err("dll_path is not supported on WASI".to_string())
263}
264
265fn current_dll_path() -> Result<PathBuf, String> {
266    use std::sync::OnceLock;
267
268    // This is somewhat expensive relative to other work when compiling `fn main() {}` as `dladdr`
269    // needs to iterate over the symbol table of librustc_driver.so until it finds a match.
270    // As such cache this to avoid recomputing if we try to get the sysroot in multiple places.
271    static CURRENT_DLL_PATH: OnceLock<Result<PathBuf, String>> = OnceLock::new();
272    CURRENT_DLL_PATH
273        .get_or_init(|| unsafe { dll_path(current_dll_path as fn() -> _ as *mut _) })
274        .clone()
275}
276
277/// This function checks if sysroot is found using env::args().next(), and if it
278/// is not found, finds sysroot from current rustc_driver dll.
279pub(crate) fn default_sysroot() -> PathBuf {
280    fn default_from_rustc_driver_dll() -> Result<PathBuf, String> {
281        let dll = current_dll_path()?;
282
283        // `dll` will be in one of the following two:
284        // - compiler's libdir: $sysroot/lib/*.dll
285        // - target's libdir: $sysroot/lib/rustlib/$target/lib/*.dll
286        //
287        // use `parent` twice to chop off the file name and then also the
288        // directory containing the dll
289        let dir = dll.parent().and_then(|p| p.parent()).ok_or_else(|| {
290            ::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())
291        })?;
292
293        // if `dir` points to target's dir, move up to the sysroot
294        let mut sysroot_dir = if dir.ends_with(crate::config::host_tuple()) {
295            dir.parent() // chop off `$target`
296                .and_then(|p| p.parent()) // chop off `rustlib`
297                .and_then(|p| p.parent()) // chop off `lib`
298                .map(|s| s.to_owned())
299                .ok_or_else(|| {
300                    ::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())
301                })?
302        } else {
303            dir.to_owned()
304        };
305
306        // On multiarch linux systems, there will be multiarch directory named
307        // with the architecture(e.g `x86_64-linux-gnu`) under the `lib` directory.
308        // Which cause us to mistakenly end up in the lib directory instead of the sysroot directory.
309        if sysroot_dir.ends_with("lib") {
310            sysroot_dir =
311                sysroot_dir.parent().map(|real_sysroot| real_sysroot.to_owned()).ok_or_else(
312                    || ::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()),
313                )?
314        }
315
316        Ok(sysroot_dir)
317    }
318
319    // Use env::args().next() to get the path of the executable without
320    // following symlinks/canonicalizing any component. This makes the rustc
321    // binary able to locate Rust libraries in systems using content-addressable
322    // storage (CAS).
323    fn from_env_args_next() -> Option<PathBuf> {
324        let mut p = PathBuf::from(env::args_os().next()?);
325
326        // Check if sysroot is found using env::args().next() only if the rustc in argv[0]
327        // is a symlink (see #79253). We might want to change/remove it to conform with
328        // https://www.gnu.org/prep/standards/standards.html#Finding-Program-Files in the
329        // future.
330        if fs::read_link(&p).is_err() {
331            // Path is not a symbolic link or does not exist.
332            return None;
333        }
334
335        // Pop off `bin/rustc`, obtaining the suspected sysroot.
336        p.pop();
337        p.pop();
338        // Look for the target rustlib directory in the suspected sysroot.
339        let mut rustlib_path = rustc_target::relative_target_rustlib_path(&p, "dummy");
340        rustlib_path.pop(); // pop off the dummy target.
341        rustlib_path.exists().then_some(p)
342    }
343
344    from_env_args_next()
345        .unwrap_or_else(|| default_from_rustc_driver_dll().expect("Failed finding sysroot"))
346}