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#[cfg(unix)]
150fn current_dll_path() -> Result<PathBuf, String> {
151use std::sync::OnceLock;
152153// 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.
156static CURRENT_DLL_PATH: OnceLock<Result<PathBuf, String>> = OnceLock::new();
157CURRENT_DLL_PATH158 .get_or_init(|| {
159use std::ffi::{CStr, OsStr};
160use std::os::unix::prelude::*;
161162#[cfg(not(target_os = "aix"))]
163unsafe {
164let addr = current_dll_pathas fn() -> Result<PathBuf, String> as *mut _;
165let mut info = std::mem::zeroed();
166if libc::dladdr(addr, &mut info) == 0 {
167return Err("dladdr failed".into());
168 }
169#[cfg(target_os = "cygwin")]
170let fname_ptr = info.dli_fname.as_ptr();
171#[cfg(not(target_os = "cygwin"))]
172let fname_ptr = {
173if !!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");
174info.dli_fname
175 };
176let bytes = CStr::from_ptr(fname_ptr).to_bytes();
177let os = OsStr::from_bytes(bytes);
178try_canonicalize(Path::new(os)).map_err(|e| e.to_string())
179 }
180181#[cfg(target_os = "aix")]
182unsafe {
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.
189let addr = current_dll_path as u64;
190let mut buffer = vec![std::mem::zeroed::<libc::ld_info>(); 64];
191loop {
192if 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{
198break;
199 } else {
200if std::io::Error::last_os_error().raw_os_error().unwrap() != libc::ENOMEM {
201return Err("loadquery failed".into());
202 }
203 buffer.resize(buffer.len() * 2, std::mem::zeroed::<libc::ld_info>());
204 }
205 }
206let mut current = buffer.as_mut_ptr() as *mut libc::ld_info;
207loop {
208let data_base = (*current).ldinfo_dataorg as u64;
209let data_end = data_base + (*current).ldinfo_datasize;
210if (data_base..data_end).contains(&addr) {
211let bytes = CStr::from_ptr(&(*current).ldinfo_filename[0]).to_bytes();
212let os = OsStr::from_bytes(bytes);
213return try_canonicalize(Path::new(os)).map_err(|e| e.to_string());
214 }
215if (*current).ldinfo_next == 0 {
216break;
217 }
218 current = (current as *mut i8).offset((*current).ldinfo_next as isize)
219as *mut libc::ld_info;
220 }
221return Err(format!("current dll's address {} is not in the load map", addr));
222 }
223 })
224 .clone()
225}
226227#[cfg(windows)]
228fn current_dll_path() -> Result<PathBuf, String> {
229use std::ffi::OsString;
230use std::io;
231use std::os::windows::prelude::*;
232233use windows::Win32::Foundation::HMODULE;
234use windows::Win32::System::LibraryLoader::{
235 GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS, GetModuleFileNameW, GetModuleHandleExW,
236 };
237use windows::core::PCWSTR;
238239let mut module = HMODULE::default();
240unsafe {
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>
245as *mut u16,
246 ),
247&mut module,
248 )
249 }
250 .map_err(|e| e.to_string())?;
251252let mut filename = vec![0; 1024];
253let n = unsafe { GetModuleFileNameW(Some(module), &mut filename) } as usize;
254if n == 0 {
255return Err(format!("GetModuleFileNameW failed: {}", io::Error::last_os_error()));
256 }
257if n >= filename.capacity() {
258return Err(format!("our buffer was too small? {}", io::Error::last_os_error()));
259 }
260261 filename.truncate(n);
262263let path = try_canonicalize(OsString::from_wide(&filename)).map_err(|e| e.to_string())?;
264265// 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.
268Ok(rustc_fs_util::fix_windows_verbatim_for_gcc(&path))
269}
270271#[cfg(target_os = "wasi")]
272fn current_dll_path() -> Result<PathBuf, String> {
273Err("current_dll_path is not supported on WASI".to_string())
274}
275276/// 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 {
279fn default_from_rustc_driver_dll() -> Result<PathBuf, String> {
280let dll = current_dll_path()?;
281282// `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
288let 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 })?;
291292// if `dir` points to target's dir, move up to the sysroot
293let 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 {
302dir.to_owned()
303 };
304305// 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.
308if sysroot_dir.ends_with("lib") {
309sysroot_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}
314315Ok(sysroot_dir)
316 }
317318// 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).
322fn from_env_args_next() -> Option<PathBuf> {
323let mut p = PathBuf::from(env::args_os().next()?);
324325// 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.
329if fs::read_link(&p).is_err() {
330// Path is not a symbolic link or does not exist.
331return None;
332 }
333334// Pop off `bin/rustc`, obtaining the suspected sysroot.
335p.pop();
336p.pop();
337// Look for the target rustlib directory in the suspected sysroot.
338let mut rustlib_path = rustc_target::relative_target_rustlib_path(&p, "dummy");
339rustlib_path.pop(); // pop off the dummy target.
340rustlib_path.exists().then_some(p)
341 }
342343from_env_args_next()
344 .unwrap_or_else(|| default_from_rustc_driver_dll().expect("Failed finding sysroot"))
345}