rustc_session/
filesearch.rs

1//! A module for searching for libraries
2
3use std::path::{Path, PathBuf};
4use std::{env, fs};
5
6use rustc_fs_util::{fix_windows_verbatim_for_gcc, try_canonicalize};
7use rustc_target::spec::Target;
8use smallvec::{SmallVec, smallvec};
9
10use crate::search_paths::{PathKind, SearchPath};
11
12#[derive(Clone)]
13pub struct FileSearch {
14    cli_search_paths: Vec<SearchPath>,
15    tlib_path: SearchPath,
16}
17
18impl FileSearch {
19    pub fn cli_search_paths<'b>(&'b self, kind: PathKind) -> impl Iterator<Item = &'b SearchPath> {
20        self.cli_search_paths.iter().filter(move |sp| sp.kind.matches(kind))
21    }
22
23    pub fn search_paths<'b>(&'b self, kind: PathKind) -> impl Iterator<Item = &'b SearchPath> {
24        self.cli_search_paths
25            .iter()
26            .filter(move |sp| sp.kind.matches(kind))
27            .chain(std::iter::once(&self.tlib_path))
28    }
29
30    pub fn new(cli_search_paths: &[SearchPath], tlib_path: &SearchPath, target: &Target) -> Self {
31        let this = FileSearch {
32            cli_search_paths: cli_search_paths.to_owned(),
33            tlib_path: tlib_path.clone(),
34        };
35        this.refine(&["lib", &target.staticlib_prefix, &target.dll_prefix])
36    }
37    // Produce a new file search from this search that has a smaller set of candidates.
38    fn refine(mut self, allowed_prefixes: &[&str]) -> FileSearch {
39        self.cli_search_paths
40            .iter_mut()
41            .for_each(|search_paths| search_paths.files.retain(allowed_prefixes));
42        self.tlib_path.files.retain(allowed_prefixes);
43
44        self
45    }
46}
47
48pub fn make_target_lib_path(sysroot: &Path, target_triple: &str) -> PathBuf {
49    let rustlib_path = rustc_target::relative_target_rustlib_path(sysroot, target_triple);
50    sysroot.join(rustlib_path).join("lib")
51}
52
53/// Returns a path to the target's `bin` folder within its `rustlib` path in the sysroot. This is
54/// where binaries are usually installed, e.g. the self-contained linkers, lld-wrappers, LLVM tools,
55/// etc.
56pub fn make_target_bin_path(sysroot: &Path, target_triple: &str) -> PathBuf {
57    let rustlib_path = rustc_target::relative_target_rustlib_path(sysroot, target_triple);
58    sysroot.join(rustlib_path).join("bin")
59}
60
61#[cfg(unix)]
62fn current_dll_path() -> Result<PathBuf, String> {
63    use std::ffi::{CStr, OsStr};
64    use std::os::unix::prelude::*;
65
66    #[cfg(not(target_os = "aix"))]
67    unsafe {
68        let addr = current_dll_path as usize as *mut _;
69        let mut info = std::mem::zeroed();
70        if libc::dladdr(addr, &mut info) == 0 {
71            return Err("dladdr failed".into());
72        }
73        if info.dli_fname.is_null() {
74            return Err("dladdr returned null pointer".into());
75        }
76        let bytes = CStr::from_ptr(info.dli_fname).to_bytes();
77        let os = OsStr::from_bytes(bytes);
78        Ok(PathBuf::from(os))
79    }
80
81    #[cfg(target_os = "aix")]
82    unsafe {
83        // On AIX, the symbol `current_dll_path` references a function descriptor.
84        // A function descriptor is consisted of (See https://reviews.llvm.org/D62532)
85        // * The address of the entry point of the function.
86        // * The TOC base address for the function.
87        // * The environment pointer.
88        // The function descriptor is in the data section.
89        let addr = current_dll_path as u64;
90        let mut buffer = vec![std::mem::zeroed::<libc::ld_info>(); 64];
91        loop {
92            if libc::loadquery(
93                libc::L_GETINFO,
94                buffer.as_mut_ptr() as *mut u8,
95                (std::mem::size_of::<libc::ld_info>() * buffer.len()) as u32,
96            ) >= 0
97            {
98                break;
99            } else {
100                if std::io::Error::last_os_error().raw_os_error().unwrap() != libc::ENOMEM {
101                    return Err("loadquery failed".into());
102                }
103                buffer.resize(buffer.len() * 2, std::mem::zeroed::<libc::ld_info>());
104            }
105        }
106        let mut current = buffer.as_mut_ptr() as *mut libc::ld_info;
107        loop {
108            let data_base = (*current).ldinfo_dataorg as u64;
109            let data_end = data_base + (*current).ldinfo_datasize;
110            if (data_base..data_end).contains(&addr) {
111                let bytes = CStr::from_ptr(&(*current).ldinfo_filename[0]).to_bytes();
112                let os = OsStr::from_bytes(bytes);
113                return Ok(PathBuf::from(os));
114            }
115            if (*current).ldinfo_next == 0 {
116                break;
117            }
118            current =
119                (current as *mut i8).offset((*current).ldinfo_next as isize) as *mut libc::ld_info;
120        }
121        return Err(format!("current dll's address {} is not in the load map", addr));
122    }
123}
124
125#[cfg(windows)]
126fn current_dll_path() -> Result<PathBuf, String> {
127    use std::ffi::OsString;
128    use std::io;
129    use std::os::windows::prelude::*;
130
131    use windows::Win32::Foundation::HMODULE;
132    use windows::Win32::System::LibraryLoader::{
133        GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS, GetModuleFileNameW, GetModuleHandleExW,
134    };
135    use windows::core::PCWSTR;
136
137    let mut module = HMODULE::default();
138    unsafe {
139        GetModuleHandleExW(
140            GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS,
141            PCWSTR(current_dll_path as *mut u16),
142            &mut module,
143        )
144    }
145    .map_err(|e| e.to_string())?;
146
147    let mut filename = vec![0; 1024];
148    let n = unsafe { GetModuleFileNameW(Some(module), &mut filename) } as usize;
149    if n == 0 {
150        return Err(format!("GetModuleFileNameW failed: {}", io::Error::last_os_error()));
151    }
152    if n >= filename.capacity() {
153        return Err(format!("our buffer was too small? {}", io::Error::last_os_error()));
154    }
155
156    filename.truncate(n);
157
158    Ok(OsString::from_wide(&filename).into())
159}
160
161pub fn sysroot_candidates() -> SmallVec<[PathBuf; 2]> {
162    let target = crate::config::host_tuple();
163    let mut sysroot_candidates: SmallVec<[PathBuf; 2]> =
164        smallvec![get_or_default_sysroot().expect("Failed finding sysroot")];
165    let path = current_dll_path().and_then(|s| try_canonicalize(s).map_err(|e| e.to_string()));
166    if let Ok(dll) = path {
167        // use `parent` twice to chop off the file name and then also the
168        // directory containing the dll which should be either `lib` or `bin`.
169        if let Some(path) = dll.parent().and_then(|p| p.parent()) {
170            // The original `path` pointed at the `rustc_driver` crate's dll.
171            // Now that dll should only be in one of two locations. The first is
172            // in the compiler's libdir, for example `$sysroot/lib/*.dll`. The
173            // other is the target's libdir, for example
174            // `$sysroot/lib/rustlib/$target/lib/*.dll`.
175            //
176            // We don't know which, so let's assume that if our `path` above
177            // ends in `$target` we *could* be in the target libdir, and always
178            // assume that we may be in the main libdir.
179            sysroot_candidates.push(path.to_owned());
180
181            if path.ends_with(target) {
182                sysroot_candidates.extend(
183                    path.parent() // chop off `$target`
184                        .and_then(|p| p.parent()) // chop off `rustlib`
185                        .and_then(|p| p.parent()) // chop off `lib`
186                        .map(|s| s.to_owned()),
187                );
188            }
189        }
190    }
191
192    sysroot_candidates
193}
194
195/// Returns the provided sysroot or calls [`get_or_default_sysroot`] if it's none.
196/// Panics if [`get_or_default_sysroot`]  returns an error.
197pub fn materialize_sysroot(maybe_sysroot: Option<PathBuf>) -> PathBuf {
198    maybe_sysroot.unwrap_or_else(|| get_or_default_sysroot().expect("Failed finding sysroot"))
199}
200
201/// This function checks if sysroot is found using env::args().next(), and if it
202/// is not found, finds sysroot from current rustc_driver dll.
203pub fn get_or_default_sysroot() -> Result<PathBuf, String> {
204    // Follow symlinks. If the resolved path is relative, make it absolute.
205    fn canonicalize(path: PathBuf) -> PathBuf {
206        let path = try_canonicalize(&path).unwrap_or(path);
207        // See comments on this target function, but the gist is that
208        // gcc chokes on verbatim paths which fs::canonicalize generates
209        // so we try to avoid those kinds of paths.
210        fix_windows_verbatim_for_gcc(&path)
211    }
212
213    fn default_from_rustc_driver_dll() -> Result<PathBuf, String> {
214        let dll = current_dll_path().map(|s| canonicalize(s))?;
215
216        // `dll` will be in one of the following two:
217        // - compiler's libdir: $sysroot/lib/*.dll
218        // - target's libdir: $sysroot/lib/rustlib/$target/lib/*.dll
219        //
220        // use `parent` twice to chop off the file name and then also the
221        // directory containing the dll
222        let dir = dll.parent().and_then(|p| p.parent()).ok_or(format!(
223            "Could not move 2 levels upper using `parent()` on {}",
224            dll.display()
225        ))?;
226
227        // if `dir` points target's dir, move up to the sysroot
228        let mut sysroot_dir = if dir.ends_with(crate::config::host_tuple()) {
229            dir.parent() // chop off `$target`
230                .and_then(|p| p.parent()) // chop off `rustlib`
231                .and_then(|p| p.parent()) // chop off `lib`
232                .map(|s| s.to_owned())
233                .ok_or_else(|| {
234                    format!("Could not move 3 levels upper using `parent()` on {}", dir.display())
235                })?
236        } else {
237            dir.to_owned()
238        };
239
240        // On multiarch linux systems, there will be multiarch directory named
241        // with the architecture(e.g `x86_64-linux-gnu`) under the `lib` directory.
242        // Which cause us to mistakenly end up in the lib directory instead of the sysroot directory.
243        if sysroot_dir.ends_with("lib") {
244            sysroot_dir =
245                sysroot_dir.parent().map(|real_sysroot| real_sysroot.to_owned()).ok_or_else(
246                    || format!("Could not move to parent path of {}", sysroot_dir.display()),
247                )?
248        }
249
250        Ok(sysroot_dir)
251    }
252
253    // Use env::args().next() to get the path of the executable without
254    // following symlinks/canonicalizing any component. This makes the rustc
255    // binary able to locate Rust libraries in systems using content-addressable
256    // storage (CAS).
257    fn from_env_args_next() -> Option<PathBuf> {
258        match env::args_os().next() {
259            Some(first_arg) => {
260                let mut p = PathBuf::from(first_arg);
261
262                // Check if sysroot is found using env::args().next() only if the rustc in argv[0]
263                // is a symlink (see #79253). We might want to change/remove it to conform with
264                // https://www.gnu.org/prep/standards/standards.html#Finding-Program-Files in the
265                // future.
266                if fs::read_link(&p).is_err() {
267                    // Path is not a symbolic link or does not exist.
268                    return None;
269                }
270
271                // Pop off `bin/rustc`, obtaining the suspected sysroot.
272                p.pop();
273                p.pop();
274                // Look for the target rustlib directory in the suspected sysroot.
275                let mut rustlib_path = rustc_target::relative_target_rustlib_path(&p, "dummy");
276                rustlib_path.pop(); // pop off the dummy target.
277                rustlib_path.exists().then_some(p)
278            }
279            None => None,
280        }
281    }
282
283    Ok(from_env_args_next().unwrap_or(default_from_rustc_driver_dll()?))
284}