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