1 //! Various utility functions used throughout rustbuild.
3 //! Simple things like testing the various filesystem operations here and there,
4 //! not a lot of interesting happenings here unfortunately.
10 use std::path::{Path, PathBuf};
11 use std::process::Command;
12 use std::time::Instant;
16 use crate::config::Config;
17 use crate::builder::Builder;
18 use crate::cache::Interned;
20 /// Returns the `name` as the filename of a static library for `target`.
21 pub fn staticlib(name: &str, target: &str) -> String {
22 if target.contains("windows") {
23 format!("{}.lib", name)
25 format!("lib{}.a", name)
29 /// Given an executable called `name`, return the filename for the
30 /// executable for a particular target.
31 pub fn exe(name: &str, target: &str) -> String {
32 if target.contains("windows") {
33 format!("{}.exe", name)
39 /// Returns `true` if the file name given looks like a dynamic library.
40 pub fn is_dylib(name: &str) -> bool {
41 name.ends_with(".dylib") || name.ends_with(".so") || name.ends_with(".dll")
44 /// Returns the corresponding relative library directory that the compiler's
45 /// dylibs will be found in.
46 pub fn libdir(target: &str) -> &'static str {
47 if target.contains("windows") {"bin"} else {"lib"}
50 /// Adds a list of lookup paths to `cmd`'s dynamic library lookup path.
51 pub fn add_lib_path(path: Vec<PathBuf>, cmd: &mut Command) {
52 let mut list = dylib_path();
56 cmd.env(dylib_path_var(), t!(env::join_paths(list)));
59 /// Returns the environment variable which the dynamic library lookup path
60 /// resides in for this platform.
61 pub fn dylib_path_var() -> &'static str {
62 if cfg!(target_os = "windows") {
64 } else if cfg!(target_os = "macos") {
66 } else if cfg!(target_os = "haiku") {
73 /// Parses the `dylib_path_var()` environment variable, returning a list of
74 /// paths that are members of this lookup path.
75 pub fn dylib_path() -> Vec<PathBuf> {
76 let var = match env::var_os(dylib_path_var()) {
78 None => return vec![],
80 env::split_paths(&var).collect()
83 /// `push` all components to `buf`. On windows, append `.exe` to the last component.
84 pub fn push_exe_path(mut buf: PathBuf, components: &[&str]) -> PathBuf {
85 let (&file, components) = components.split_last().expect("at least one component required");
86 let mut file = file.to_owned();
89 file.push_str(".exe");
92 buf.extend(components);
98 pub struct TimeIt(bool, Instant);
100 /// Returns an RAII structure that prints out how long it took to drop.
101 pub fn timeit(builder: &Builder<'_>) -> TimeIt {
102 TimeIt(builder.config.dry_run, Instant::now())
105 impl Drop for TimeIt {
107 let time = self.1.elapsed();
109 println!("\tfinished in {}.{:03}",
111 time.subsec_nanos() / 1_000_000);
116 /// Symlinks two directories, using junctions on Windows and normal symlinks on
118 pub fn symlink_dir(config: &Config, src: &Path, dest: &Path) -> io::Result<()> {
119 if config.dry_run { return Ok(()); }
120 let _ = fs::remove_dir(dest);
121 return symlink_dir_inner(src, dest);
124 fn symlink_dir_inner(src: &Path, dest: &Path) -> io::Result<()> {
125 use std::os::unix::fs;
126 fs::symlink(src, dest)
129 // Creating a directory junction on windows involves dealing with reparse
130 // points and the DeviceIoControl function, and this code is a skeleton of
131 // what can be found here:
133 // http://www.flexhex.com/docs/articles/hard-links.phtml
137 #[allow(nonstandard_style)]
138 fn symlink_dir_inner(target: &Path, junction: &Path) -> io::Result<()> {
141 use std::os::windows::ffi::OsStrExt;
143 const MAXIMUM_REPARSE_DATA_BUFFER_SIZE: usize = 16 * 1024;
144 const GENERIC_WRITE: DWORD = 0x40000000;
145 const OPEN_EXISTING: DWORD = 3;
146 const FILE_FLAG_OPEN_REPARSE_POINT: DWORD = 0x00200000;
147 const FILE_FLAG_BACKUP_SEMANTICS: DWORD = 0x02000000;
148 const FSCTL_SET_REPARSE_POINT: DWORD = 0x900a4;
149 const IO_REPARSE_TAG_MOUNT_POINT: DWORD = 0xa0000003;
150 const FILE_SHARE_DELETE: DWORD = 0x4;
151 const FILE_SHARE_READ: DWORD = 0x1;
152 const FILE_SHARE_WRITE: DWORD = 0x2;
156 type HANDLE = *mut u8;
157 type LPCWSTR = *const u16;
158 type LPDWORD = *mut DWORD;
159 type LPOVERLAPPED = *mut u8;
160 type LPSECURITY_ATTRIBUTES = *mut u8;
161 type LPVOID = *mut u8;
166 struct REPARSE_MOUNTPOINT_DATA_BUFFER {
168 ReparseDataLength: DWORD,
170 ReparseTargetLength: WORD,
171 ReparseTargetMaximumLength: WORD,
173 ReparseTarget: WCHAR,
177 fn CreateFileW(lpFileName: LPCWSTR,
178 dwDesiredAccess: DWORD,
180 lpSecurityAttributes: LPSECURITY_ATTRIBUTES,
181 dwCreationDisposition: DWORD,
182 dwFlagsAndAttributes: DWORD,
183 hTemplateFile: HANDLE)
185 fn DeviceIoControl(hDevice: HANDLE,
186 dwIoControlCode: DWORD,
188 nInBufferSize: DWORD,
190 nOutBufferSize: DWORD,
191 lpBytesReturned: LPDWORD,
192 lpOverlapped: LPOVERLAPPED) -> BOOL;
193 fn CloseHandle(hObject: HANDLE) -> BOOL;
196 fn to_u16s<S: AsRef<OsStr>>(s: S) -> io::Result<Vec<u16>> {
197 Ok(s.as_ref().encode_wide().chain(Some(0)).collect())
200 // We're using low-level APIs to create the junction, and these are more
201 // picky about paths. For example, forward slashes cannot be used as a
202 // path separator, so we should try to canonicalize the path first.
203 let target = fs::canonicalize(target)?;
205 fs::create_dir(junction)?;
207 let path = to_u16s(junction)?;
210 let h = CreateFileW(path.as_ptr(),
212 FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE,
215 FILE_FLAG_OPEN_REPARSE_POINT | FILE_FLAG_BACKUP_SEMANTICS,
218 let mut data = [0u8; MAXIMUM_REPARSE_DATA_BUFFER_SIZE];
219 let db = data.as_mut_ptr()
220 as *mut REPARSE_MOUNTPOINT_DATA_BUFFER;
221 let buf = &mut (*db).ReparseTarget as *mut u16;
223 // FIXME: this conversion is very hacky
225 let v = v.iter().map(|x| *x as u16);
226 for c in v.chain(target.as_os_str().encode_wide().skip(4)) {
232 (*db).ReparseTag = IO_REPARSE_TAG_MOUNT_POINT;
233 (*db).ReparseTargetMaximumLength = (i * 2) as WORD;
234 (*db).ReparseTargetLength = ((i - 1) * 2) as WORD;
235 (*db).ReparseDataLength =
236 (*db).ReparseTargetLength as DWORD + 12;
239 let res = DeviceIoControl(h as *mut _,
240 FSCTL_SET_REPARSE_POINT,
241 data.as_ptr() as *mut _,
242 (*db).ReparseDataLength + 8,
247 let out = if res == 0 {
248 Err(io::Error::last_os_error())
258 /// The CI environment rustbuild is running in. This mainly affects how the logs
260 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
262 /// Not a CI environment.
264 /// The Azure Pipelines environment, for Linux (including Docker), Windows, and macOS builds.
266 /// The GitHub Actions environment, for Linux (including Docker), Windows and macOS builds.
271 /// Obtains the current CI environment.
272 pub fn current() -> CiEnv {
273 if env::var("TF_BUILD").ok().map_or(false, |e| &*e == "True") {
274 CiEnv::AzurePipelines
275 } else if env::var("GITHUB_ACTIONS").ok().map_or(false, |e| &*e == "true") {
282 /// If in a CI environment, forces the command to run with colors.
283 pub fn force_coloring_in_ci(self, cmd: &mut Command) {
284 if self != CiEnv::None {
285 // Due to use of stamp/docker, the output stream of rustbuild is not
286 // a TTY in CI, so coloring is by-default turned off.
287 // The explicit `TERM=xterm` environment is needed for
288 // `--color always` to actually work. This env var was lost when
289 // compiling through the Makefile. Very strange.
290 cmd.env("TERM", "xterm").args(&["--color", "always"]);
295 pub fn forcing_clang_based_tests() -> bool {
296 if let Some(var) = env::var_os("RUSTBUILD_FORCE_CLANG_BASED_TESTS") {
297 match &var.to_string_lossy().to_lowercase()[..] {
298 "1" | "yes" | "on" => true,
299 "0" | "no" | "off" => false,
301 // Let's make sure typos don't go unnoticed
302 panic!("Unrecognized option '{}' set in \
303 RUSTBUILD_FORCE_CLANG_BASED_TESTS", other)
311 pub fn use_host_linker(target: &Interned<String>) -> bool {
312 // FIXME: this information should be gotten by checking the linker flavor
313 // of the rustc target
315 target.contains("emscripten") ||
316 target.contains("wasm32") ||
317 target.contains("nvptx") ||
318 target.contains("fortanix") ||
319 target.contains("fuchsia")