1 //! A module for searching for libraries
3 use smallvec::{smallvec, SmallVec};
6 use std::iter::FromIterator;
7 use std::path::{Path, PathBuf};
9 use crate::search_paths::{PathKind, SearchPath};
10 use rustc_fs_util::fix_windows_verbatim_for_gcc;
12 #[derive(Copy, Clone)]
19 pub struct FileSearch<'a> {
22 search_paths: &'a [SearchPath],
23 tlib_path: &'a SearchPath,
27 impl<'a> FileSearch<'a> {
28 pub fn search_paths(&self) -> impl Iterator<Item = &'a SearchPath> {
32 .filter(move |sp| sp.kind.matches(kind))
33 .chain(std::iter::once(self.tlib_path))
36 pub fn get_lib_path(&self) -> PathBuf {
37 make_target_lib_path(self.sysroot, self.triple)
40 pub fn get_self_contained_lib_path(&self) -> PathBuf {
41 self.get_lib_path().join("self-contained")
47 search_paths: &'a [SearchPath],
48 tlib_path: &'a SearchPath,
51 debug!("using sysroot = {}, triple = {}", sysroot.display(), triple);
52 FileSearch { sysroot, triple, search_paths, tlib_path, kind }
55 /// Returns just the directories within the search paths.
56 pub fn search_path_dirs(&self) -> Vec<PathBuf> {
57 self.search_paths().map(|sp| sp.dir.to_path_buf()).collect()
61 pub fn make_target_lib_path(sysroot: &Path, target_triple: &str) -> PathBuf {
62 let rustlib_path = rustc_target::target_rustlib_path(sysroot, target_triple);
63 PathBuf::from_iter([sysroot, Path::new(&rustlib_path), Path::new("lib")])
67 fn current_dll_path() -> Result<PathBuf, String> {
68 use std::ffi::{CStr, OsStr};
69 use std::os::unix::prelude::*;
72 let addr = current_dll_path as usize as *mut _;
73 let mut info = std::mem::zeroed();
74 if libc::dladdr(addr, &mut info) == 0 {
75 return Err("dladdr failed".into());
77 if info.dli_fname.is_null() {
78 return Err("dladdr returned null pointer".into());
80 let bytes = CStr::from_ptr(info.dli_fname).to_bytes();
81 let os = OsStr::from_bytes(bytes);
87 fn current_dll_path() -> Result<PathBuf, String> {
88 use std::ffi::OsString;
90 use std::os::windows::prelude::*;
93 use winapi::um::libloaderapi::{
94 GetModuleFileNameW, GetModuleHandleExW, GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS,
98 let mut module = ptr::null_mut();
99 let r = GetModuleHandleExW(
100 GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS,
101 current_dll_path as usize as *mut _,
105 return Err(format!("GetModuleHandleExW failed: {}", io::Error::last_os_error()));
107 let mut space = Vec::with_capacity(1024);
108 let r = GetModuleFileNameW(module, space.as_mut_ptr(), space.capacity() as u32);
110 return Err(format!("GetModuleFileNameW failed: {}", io::Error::last_os_error()));
113 if r >= space.capacity() {
114 return Err(format!("our buffer was too small? {}", io::Error::last_os_error()));
117 let os = OsString::from_wide(&space);
118 Ok(PathBuf::from(os))
122 pub fn sysroot_candidates() -> SmallVec<[PathBuf; 2]> {
123 let target = crate::config::host_triple();
124 let mut sysroot_candidates: SmallVec<[PathBuf; 2]> =
125 smallvec![get_or_default_sysroot().expect("Failed finding sysroot")];
126 let path = current_dll_path().and_then(|s| Ok(s.canonicalize().map_err(|e| e.to_string())?));
127 if let Ok(dll) = path {
128 // use `parent` twice to chop off the file name and then also the
129 // directory containing the dll which should be either `lib` or `bin`.
130 if let Some(path) = dll.parent().and_then(|p| p.parent()) {
131 // The original `path` pointed at the `rustc_driver` crate's dll.
132 // Now that dll should only be in one of two locations. The first is
133 // in the compiler's libdir, for example `$sysroot/lib/*.dll`. The
134 // other is the target's libdir, for example
135 // `$sysroot/lib/rustlib/$target/lib/*.dll`.
137 // We don't know which, so let's assume that if our `path` above
138 // ends in `$target` we *could* be in the target libdir, and always
139 // assume that we may be in the main libdir.
140 sysroot_candidates.push(path.to_owned());
142 if path.ends_with(target) {
143 sysroot_candidates.extend(
144 path.parent() // chop off `$target`
145 .and_then(|p| p.parent()) // chop off `rustlib`
146 .and_then(|p| p.parent()) // chop off `lib`
147 .map(|s| s.to_owned()),
153 return sysroot_candidates;
156 /// This function checks if sysroot is found using env::args().next(), and if it
157 /// is not found, finds sysroot from current rustc_driver dll.
158 pub fn get_or_default_sysroot() -> Result<PathBuf, String> {
159 // Follow symlinks. If the resolved path is relative, make it absolute.
160 fn canonicalize(path: PathBuf) -> PathBuf {
161 let path = fs::canonicalize(&path).unwrap_or(path);
162 // See comments on this target function, but the gist is that
163 // gcc chokes on verbatim paths which fs::canonicalize generates
164 // so we try to avoid those kinds of paths.
165 fix_windows_verbatim_for_gcc(&path)
168 fn default_from_rustc_driver_dll() -> Result<PathBuf, String> {
169 let dll = current_dll_path().and_then(|s| Ok(canonicalize(s)))?;
171 // `dll` will be in one of the following two:
172 // - compiler's libdir: $sysroot/lib/*.dll
173 // - target's libdir: $sysroot/lib/rustlib/$target/lib/*.dll
175 // use `parent` twice to chop off the file name and then also the
176 // directory containing the dll
177 let dir = dll.parent().and_then(|p| p.parent()).ok_or(format!(
178 "Could not move 2 levels upper using `parent()` on {}",
182 // if `dir` points target's dir, move up to the sysroot
183 if dir.ends_with(crate::config::host_triple()) {
184 dir.parent() // chop off `$target`
185 .and_then(|p| p.parent()) // chop off `rustlib`
186 .and_then(|p| p.parent()) // chop off `lib`
187 .map(|s| s.to_owned())
189 "Could not move 3 levels upper using `parent()` on {}",
197 // Use env::args().next() to get the path of the executable without
198 // following symlinks/canonicalizing any component. This makes the rustc
199 // binary able to locate Rust libraries in systems using content-addressable
201 fn from_env_args_next() -> Option<PathBuf> {
202 match env::args_os().next() {
204 let mut p = PathBuf::from(first_arg);
206 // Check if sysroot is found using env::args().next() only if the rustc in argv[0]
207 // is a symlink (see #79253). We might want to change/remove it to conform with
208 // https://www.gnu.org/prep/standards/standards.html#Finding-Program-Files in the
210 if fs::read_link(&p).is_err() {
211 // Path is not a symbolic link or does not exist.
215 // Pop off `bin/rustc`, obtaining the suspected sysroot.
218 // Look for the target rustlib directory in the suspected sysroot.
219 let mut rustlib_path = rustc_target::target_rustlib_path(&p, "dummy");
220 rustlib_path.pop(); // pop off the dummy target.
221 if rustlib_path.exists() { Some(p) } else { None }
227 Ok(from_env_args_next().unwrap_or(default_from_rustc_driver_dll()?))