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`.
38pub 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)> {
44let exclude_sysroot = kind.matches(PathKind::Crate) && !self.use_implicit_sysroot_deps;
4546// The indices are clipped to have only a single iterator returned from this function, to
47 // avoid allocating it.
48let start = self.files.partition_point(|v| *v.filename < *prefix).min(self.files.len());
49let end = self.files[start..].partition_point(|v| v.filename.starts_with(prefix));
50let prefixed_items = &self.files[start..][..end];
5152prefixed_items53 .into_iter()
54 .filter(move |c| {
55c.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 }
6162pub fn new(
63 cli_search_paths: &[SearchPath],
64 tlib_path: &SearchPath,
65 target: &Target,
66 use_implicit_sysroot_deps: bool,
67 ) -> Self {
68let prefixes = ["lib", &target.staticlib_prefix, &target.dll_prefix];
6970// 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.
72let mut files: Vec<FileSearchCandidate> = Vec::with_capacity(cli_search_paths.len());
73for (search_path, is_sysroot) in
74cli_search_paths.iter().map(|path| (path, false)).chain(iter::once((tlib_path, true)))
75 {
76let Ok(dir) = fs::read_dir(&search_path.dir) else {
77continue;
78 };
79 files.extend(dir.filter_map(|entry| {
80let entry = entry.ok()?;
8182let filename = entry.file_name();
83let filename = filename.to_str()?;
8485if !prefixes.iter().any(|prefix| filename.starts_with(prefix)) {
86return None;
87 }
88Some(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 }
96files.sort_unstable_by(|lhs, rhs| lhs.filename.cmp(&rhs.filename));
9798FileSearch {
99 cli_search_paths: cli_search_paths.to_owned(),
100 tlib_path: tlib_path.clone(),
101use_implicit_sysroot_deps,
102files,
103 }
104 }
105}
106107/// 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?
119from_sysroot: bool,
120}
121122impl FileSearchCandidate {
123/// Constructs the full path to the file.
124fn path(&self) -> PathBuf {
125self.dir.join(&*self.filename)
126 }
127}
128129pub fn make_target_lib_path(sysroot: &Path, target_triple: &str) -> PathBuf {
130let rustlib_path = rustc_target::relative_target_rustlib_path(sysroot, target_triple);
131sysroot.join(rustlib_path).join("lib")
132}
133134/// 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 {
138let rustlib_path = rustc_target::relative_target_rustlib_path(sysroot, target_triple);
139sysroot.join(rustlib_path).join("bin")
140}
141142#[cfg(unix)]
143fn current_dll_path() -> Result<PathBuf, String> {
144use std::sync::OnceLock;
145146// 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.
149static CURRENT_DLL_PATH: OnceLock<Result<PathBuf, String>> = OnceLock::new();
150CURRENT_DLL_PATH151 .get_or_init(|| {
152use std::ffi::{CStr, OsStr};
153use std::os::unix::prelude::*;
154155#[cfg(not(target_os = "aix"))]
156unsafe {
157let addr = current_dll_pathas fn() -> Result<PathBuf, String> as *mut _;
158let mut info = std::mem::zeroed();
159if libc::dladdr(addr, &mut info) == 0 {
160return Err("dladdr failed".into());
161 }
162#[cfg(target_os = "cygwin")]
163let fname_ptr = info.dli_fname.as_ptr();
164#[cfg(not(target_os = "cygwin"))]
165let fname_ptr = {
166if !!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");
167info.dli_fname
168 };
169let bytes = CStr::from_ptr(fname_ptr).to_bytes();
170let os = OsStr::from_bytes(bytes);
171try_canonicalize(Path::new(os)).map_err(|e| e.to_string())
172 }
173174#[cfg(target_os = "aix")]
175unsafe {
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.
182let addr = current_dll_path as u64;
183let mut buffer = vec![std::mem::zeroed::<libc::ld_info>(); 64];
184loop {
185if 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{
191break;
192 } else {
193if std::io::Error::last_os_error().raw_os_error().unwrap() != libc::ENOMEM {
194return Err("loadquery failed".into());
195 }
196 buffer.resize(buffer.len() * 2, std::mem::zeroed::<libc::ld_info>());
197 }
198 }
199let mut current = buffer.as_mut_ptr() as *mut libc::ld_info;
200loop {
201let data_base = (*current).ldinfo_dataorg as u64;
202let data_end = data_base + (*current).ldinfo_datasize;
203if (data_base..data_end).contains(&addr) {
204let bytes = CStr::from_ptr(&(*current).ldinfo_filename[0]).to_bytes();
205let os = OsStr::from_bytes(bytes);
206return try_canonicalize(Path::new(os)).map_err(|e| e.to_string());
207 }
208if (*current).ldinfo_next == 0 {
209break;
210 }
211 current = (current as *mut i8).offset((*current).ldinfo_next as isize)
212as *mut libc::ld_info;
213 }
214return Err(format!("current dll's address {} is not in the load map", addr));
215 }
216 })
217 .clone()
218}
219220#[cfg(windows)]
221fn current_dll_path() -> Result<PathBuf, String> {
222use std::ffi::OsString;
223use std::io;
224use std::os::windows::prelude::*;
225226use windows::Win32::Foundation::HMODULE;
227use windows::Win32::System::LibraryLoader::{
228 GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS, GetModuleFileNameW, GetModuleHandleExW,
229 };
230use windows::core::PCWSTR;
231232let mut module = HMODULE::default();
233unsafe {
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>
238as *mut u16,
239 ),
240&mut module,
241 )
242 }
243 .map_err(|e| e.to_string())?;
244245let mut filename = vec![0; 1024];
246let n = unsafe { GetModuleFileNameW(Some(module), &mut filename) } as usize;
247if n == 0 {
248return Err(format!("GetModuleFileNameW failed: {}", io::Error::last_os_error()));
249 }
250if n >= filename.capacity() {
251return Err(format!("our buffer was too small? {}", io::Error::last_os_error()));
252 }
253254 filename.truncate(n);
255256let path = try_canonicalize(OsString::from_wide(&filename)).map_err(|e| e.to_string())?;
257258// 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.
261Ok(rustc_fs_util::fix_windows_verbatim_for_gcc(&path))
262}
263264#[cfg(target_os = "wasi")]
265fn current_dll_path() -> Result<PathBuf, String> {
266Err("current_dll_path is not supported on WASI".to_string())
267}
268269/// 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 {
272fn default_from_rustc_driver_dll() -> Result<PathBuf, String> {
273let dll = current_dll_path()?;
274275// `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
281let 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 })?;
284285// if `dir` points to target's dir, move up to the sysroot
286let 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 {
295dir.to_owned()
296 };
297298// 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.
301if sysroot_dir.ends_with("lib") {
302sysroot_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}
307308Ok(sysroot_dir)
309 }
310311// 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).
315fn from_env_args_next() -> Option<PathBuf> {
316let mut p = PathBuf::from(env::args_os().next()?);
317318// 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.
322if fs::read_link(&p).is_err() {
323// Path is not a symbolic link or does not exist.
324return None;
325 }
326327// Pop off `bin/rustc`, obtaining the suspected sysroot.
328p.pop();
329p.pop();
330// Look for the target rustlib directory in the suspected sysroot.
331let mut rustlib_path = rustc_target::relative_target_rustlib_path(&p, "dummy");
332rustlib_path.pop(); // pop off the dummy target.
333rustlib_path.exists().then_some(p)
334 }
335336from_env_args_next()
337 .unwrap_or_else(|| default_from_rustc_driver_dll().expect("Failed finding sysroot"))
338}