1//! A module for searching for libraries
23use std::path::{Path, PathBuf};
4use std::sync::Arc;
5use std::{env, fs, iter};
67use rustc_fs_util::try_canonicalize;
8use rustc_target::spec::Target;
910use crate::search_paths::{PathKind, SearchPath};
1112pub struct FileSearch {
13 cli_search_paths: Vec<SearchPath>,
14 tlib_path: SearchPath,
15 use_implicit_sysroot_deps: bool,
16 files: Vec<FileSearchCandidate>,
17}
1819impl FileSearch {
20pub fn cli_search_paths<'b>(&'b self, kind: PathKind) -> impl Iterator<Item = &'b SearchPath> {
21self.cli_search_paths.iter().filter(move |sp| sp.kind.matches(kind))
22 }
2324pub 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.
27let exclude_sysroot = kind.matches(PathKind::Crate) && !self.use_implicit_sysroot_deps;
28let maybe_tlib = (!exclude_sysroot).then_some(&self.tlib_path);
2930self.cli_search_paths
31 .iter()
32 .filter(move |sp| sp.kind.matches(kind))
33 .chain(maybe_tlib.into_iter())
34 }
3536/// 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.
42pub 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)> {
48let exclude_sysroot = kind.matches(PathKind::Crate) && !self.use_implicit_sysroot_deps;
4950// The indices are clipped to have only a single iterator returned from this function, to
51 // avoid allocating it.
52let start = self.files.partition_point(|v| *v.filename < *prefix).min(self.files.len());
53let end = self.files[start..].partition_point(|v| v.filename.starts_with(prefix));
54let prefixed_items = &self.files[start..][..end];
5556prefixed_items57 .into_iter()
58 .filter(move |c| {
59c.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 }
6566pub 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`.
75let prefixes = ["lib", &target.staticlib_prefix, &target.dll_prefix];
7677// 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.
79let mut files: Vec<FileSearchCandidate> = Vec::with_capacity(cli_search_paths.len());
80for (search_path, is_sysroot) in
81cli_search_paths.iter().map(|path| (path, false)).chain(iter::once((tlib_path, true)))
82 {
83let Ok(dir) = fs::read_dir(&search_path.dir) else {
84continue;
85 };
86 files.extend(dir.filter_map(|entry| {
87let entry = entry.ok()?;
8889let filename = entry.file_name();
90let filename = filename.to_str()?;
9192if !prefixes.iter().any(|prefix| filename.starts_with(prefix)) {
93return None;
94 }
95Some(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 }
103files.sort_unstable_by(|lhs, rhs| lhs.filename.cmp(&rhs.filename));
104105FileSearch {
106 cli_search_paths: cli_search_paths.to_owned(),
107 tlib_path: tlib_path.clone(),
108use_implicit_sysroot_deps,
109files,
110 }
111 }
112}
113114/// 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?
126from_sysroot: bool,
127}
128129impl FileSearchCandidate {
130/// Constructs the full path to the file.
131fn path(&self) -> PathBuf {
132self.dir.join(&*self.filename)
133 }
134}
135136pub fn make_target_lib_path(sysroot: &Path, target_triple: &str) -> PathBuf {
137let rustlib_path = rustc_target::relative_target_rustlib_path(sysroot, target_triple);
138sysroot.join(rustlib_path).join("lib")
139}
140141/// 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 {
145let rustlib_path = rustc_target::relative_target_rustlib_path(sysroot, target_triple);
146sysroot.join(rustlib_path).join("bin")
147}
148149/// 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> {
154use std::ffi::{CStr, OsStr};
155use std::os::unix::prelude::*;
156157#[cfg(not(target_os = "aix"))]
158unsafe {
159let mut info = std::mem::zeroed();
160if libc::dladdr(function, &mut info) == 0 {
161return Err("dladdr failed".into());
162 }
163#[cfg(target_os = "cygwin")]
164let fname_ptr = info.dli_fname.as_ptr();
165#[cfg(not(target_os = "cygwin"))]
166let fname_ptr = {
167if !!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");
168info.dli_fname
169 };
170let bytes = CStr::from_ptr(fname_ptr).to_bytes();
171let os = OsStr::from_bytes(bytes);
172try_canonicalize(Path::new(os)).map_err(|e| e.to_string())
173 }
174175#[cfg(target_os = "aix")]
176unsafe {
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.
183let addr = function as u64;
184let mut buffer = vec![std::mem::zeroed::<libc::ld_info>(); 64];
185loop {
186if 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{
192break;
193 } else {
194if std::io::Error::last_os_error().raw_os_error().unwrap() != libc::ENOMEM {
195return Err("loadquery failed".into());
196 }
197 buffer.resize(buffer.len() * 2, std::mem::zeroed::<libc::ld_info>());
198 }
199 }
200let mut current = buffer.as_mut_ptr() as *mut libc::ld_info;
201loop {
202let data_base = (*current).ldinfo_dataorg as u64;
203let data_end = data_base + (*current).ldinfo_datasize;
204if (data_base..data_end).contains(&addr) {
205let bytes = CStr::from_ptr(&(*current).ldinfo_filename[0]).to_bytes();
206let os = OsStr::from_bytes(bytes);
207return try_canonicalize(Path::new(os)).map_err(|e| e.to_string());
208 }
209if (*current).ldinfo_next == 0 {
210break;
211 }
212 current =
213 (current as *mut i8).offset((*current).ldinfo_next as isize) as *mut libc::ld_info;
214 }
215return Err(format!("current dll's address {} is not in the load map", addr));
216 }
217}
218219#[cfg(windows)]
220pub unsafe fn dll_path(function: *mut std::ffi::c_void) -> Result<PathBuf, String> {
221use std::ffi::OsString;
222use std::io;
223use std::os::windows::prelude::*;
224225use windows::Win32::Foundation::HMODULE;
226use windows::Win32::System::LibraryLoader::{
227 GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS, GetModuleFileNameW, GetModuleHandleExW,
228 };
229use windows::core::PCWSTR;
230231let mut module = HMODULE::default();
232unsafe {
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())?;
240241let mut filename = vec![0; 1024];
242let n = unsafe { GetModuleFileNameW(Some(module), &mut filename) } as usize;
243if n == 0 {
244return Err(format!("GetModuleFileNameW failed: {}", io::Error::last_os_error()));
245 }
246if n >= filename.capacity() {
247return Err(format!("our buffer was too small? {}", io::Error::last_os_error()));
248 }
249250 filename.truncate(n);
251252let path = try_canonicalize(OsString::from_wide(&filename)).map_err(|e| e.to_string())?;
253254// 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.
257Ok(rustc_fs_util::fix_windows_verbatim_for_gcc(&path))
258}
259260#[cfg(target_os = "wasi")]
261pub unsafe fn dll_path(_function: *mut std::ffi::c_void) -> Result<PathBuf, String> {
262Err("dll_path is not supported on WASI".to_string())
263}
264265fn current_dll_path() -> Result<PathBuf, String> {
266use std::sync::OnceLock;
267268// 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.
271static CURRENT_DLL_PATH: OnceLock<Result<PathBuf, String>> = OnceLock::new();
272CURRENT_DLL_PATH273 .get_or_init(|| unsafe { dll_path(current_dll_pathas fn() -> _ as *mut _) })
274 .clone()
275}
276277/// 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 {
280fn default_from_rustc_driver_dll() -> Result<PathBuf, String> {
281let dll = current_dll_path()?;
282283// `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
289let 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 })?;
292293// if `dir` points to target's dir, move up to the sysroot
294let 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 {
303dir.to_owned()
304 };
305306// 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.
309if sysroot_dir.ends_with("lib") {
310sysroot_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}
315316Ok(sysroot_dir)
317 }
318319// 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).
323fn from_env_args_next() -> Option<PathBuf> {
324let mut p = PathBuf::from(env::args_os().next()?);
325326// 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.
330if fs::read_link(&p).is_err() {
331// Path is not a symbolic link or does not exist.
332return None;
333 }
334335// Pop off `bin/rustc`, obtaining the suspected sysroot.
336p.pop();
337p.pop();
338// Look for the target rustlib directory in the suspected sysroot.
339let mut rustlib_path = rustc_target::relative_target_rustlib_path(&p, "dummy");
340rustlib_path.pop(); // pop off the dummy target.
341rustlib_path.exists().then_some(p)
342 }
343344from_env_args_next()
345 .unwrap_or_else(|| default_from_rustc_driver_dll().expect("Failed finding sysroot"))
346}