bootstrap/utils/shared_helpers.rs
1//! This module serves two purposes:
2//! 1. It is part of the `utils` module and used in other parts of bootstrap.
3//! 2. It is embedded inside bootstrap shims to avoid a dependency on the bootstrap library.
4//! Therefore, this module should never use any other bootstrap module. This reduces binary
5//! size and improves compilation time by minimizing linking time.
6
7#![allow(dead_code)]
8
9use std::env;
10use std::ffi::OsString;
11use std::fs::OpenOptions;
12use std::io::Write;
13use std::process::Command;
14use std::str::FromStr;
15
16// If we were to declare a tests submodule here, the shim binaries that include this
17// module via `#[path]` would fail to find it, which breaks `./x check bootstrap`.
18// So instead the unit tests for this module are in `super::tests::shared_helpers_tests`.
19
20/// Returns the environment variable which the dynamic library lookup path
21/// resides in for this platform.
22pub fn dylib_path_var() -> &'static str {
23 if cfg!(any(target_os = "windows", target_os = "cygwin")) {
24 "PATH"
25 } else if cfg!(target_vendor = "apple") {
26 "DYLD_LIBRARY_PATH"
27 } else if cfg!(target_os = "haiku") {
28 "LIBRARY_PATH"
29 } else if cfg!(target_os = "aix") {
30 "LIBPATH"
31 } else {
32 "LD_LIBRARY_PATH"
33 }
34}
35
36/// Parses the `dylib_path_var()` environment variable, returning a list of
37/// paths that are members of this lookup path.
38pub fn dylib_path() -> Vec<std::path::PathBuf> {
39 let var = match std::env::var_os(dylib_path_var()) {
40 Some(v) => v,
41 None => return vec![],
42 };
43 std::env::split_paths(&var).collect()
44}
45
46/// Given an executable called `name`, return the filename for the
47/// executable for a particular target.
48pub fn exe(name: &str, target: &str) -> String {
49 // On Cygwin, the decision to append .exe or not is not as straightforward.
50 // Executable files do actually have .exe extensions so on hosts other than
51 // Cygwin it is necessary. But on a Cygwin host there is magic happening
52 // that redirects requests for file X to file X.exe if it exists, and
53 // furthermore /proc/self/exe (and thus std::env::current_exe) always
54 // returns the name *without* the .exe extension. For comparisons against
55 // that to match, we therefore do not append .exe for Cygwin targets on
56 // a Cygwin host.
57 if target.contains("windows") || (cfg!(not(target_os = "cygwin")) && target.contains("cygwin"))
58 {
59 format!("{name}.exe")
60 } else if target.contains("uefi") {
61 format!("{name}.efi")
62 } else if target.contains("wasm") {
63 format!("{name}.wasm")
64 } else {
65 name.to_string()
66 }
67}
68
69/// Parses the value of the "RUSTC_VERBOSE" environment variable and returns it as a `usize`.
70/// If it was not defined, returns 0 by default.
71///
72/// Panics if "RUSTC_VERBOSE" is defined with the value that is not an unsigned integer.
73pub fn parse_rustc_verbose() -> usize {
74 match env::var("RUSTC_VERBOSE") {
75 Ok(s) => usize::from_str(&s).expect("RUSTC_VERBOSE should be an integer"),
76 Err(_) => 0,
77 }
78}
79
80/// Parses the value of the "RUSTC_STAGE" environment variable and returns it as a `String`.
81///
82/// If "RUSTC_STAGE" was not set, the program will be terminated with 101.
83pub fn parse_rustc_stage() -> String {
84 env::var("RUSTC_STAGE").unwrap_or_else(|_| {
85 // Don't panic here; it's reasonable to try and run these shims directly. Give a helpful error instead.
86 eprintln!("rustc shim: FATAL: RUSTC_STAGE was not set");
87 eprintln!("rustc shim: NOTE: use `x.py build -vvv` to see all environment variables set by bootstrap");
88 std::process::exit(101);
89 })
90}
91
92/// Writes the command invocation to a file if `DUMP_BOOTSTRAP_SHIMS` is set during bootstrap.
93///
94/// Before writing it, replaces user-specific values to create generic dumps for cross-environment
95/// comparisons.
96pub fn maybe_dump(dump_name: String, cmd: &Command) {
97 if let Ok(dump_dir) = env::var("DUMP_BOOTSTRAP_SHIMS") {
98 let dump_file = format!("{dump_dir}/{dump_name}");
99
100 let mut file = OpenOptions::new().create(true).append(true).open(dump_file).unwrap();
101
102 let cmd_dump = format!("{cmd:?}\n");
103 let cmd_dump = cmd_dump.replace(&env::var("BUILD_OUT").unwrap(), "${BUILD_OUT}");
104 let cmd_dump = cmd_dump.replace(&env::var("CARGO_HOME").unwrap(), "${CARGO_HOME}");
105
106 file.write_all(cmd_dump.as_bytes()).expect("Unable to write file");
107 }
108}
109
110/// Finds `key` and returns its value from the given list of arguments `args`.
111pub fn parse_value_from_args<'a>(args: &'a [OsString], key: &str) -> Option<&'a str> {
112 let mut args = args.iter();
113 while let Some(arg) = args.next() {
114 let arg = arg.to_str().unwrap();
115
116 if let Some(value) = arg.strip_prefix(&format!("{key}=")) {
117 return Some(value);
118 } else if arg == key {
119 return args.next().map(|v| v.to_str().unwrap());
120 }
121 }
122
123 None
124}