Debian Codegraph @

debian/missing-sources/rustix/build.rs

raw
1 use std::env::var;
2 use std::io::Write as _;
3 use std::path::PathBuf;
4
5 /// The directory for inline asm.
6 const ASM_PATH: &str = "src/backend/linux_raw/arch";
7
8 fn main() {
9 // Don't rerun this on changes other than build.rs, as we only depend on
10 // the rustc version.
11 println!("cargo:rerun-if-changed=build.rs");
12
13 // Gather target information.
14 let arch = var("CARGO_CFG_TARGET_ARCH").unwrap();
15 let env = var("CARGO_CFG_TARGET_ENV").unwrap();
16 let abi = var("CARGO_CFG_TARGET_ABI");
17 let inline_asm_name = format!("{}/{}.rs", ASM_PATH, arch);
18 let inline_asm_name_present = std::fs::metadata(inline_asm_name).is_ok();
19 let os = var("CARGO_CFG_TARGET_OS").unwrap();
20 let pointer_width = var("CARGO_CFG_TARGET_POINTER_WIDTH").unwrap();
21 let endian = var("CARGO_CFG_TARGET_ENDIAN").unwrap();
22
23 // Check for special target variants.
24 let is_x32 = arch == "x86_64" && pointer_width == "32";
25 let is_arm64_ilp32 = arch == "aarch64" && pointer_width == "32";
26 let is_powerpc64be = arch == "powerpc64" && endian == "big";
27 let is_mipseb = (arch == "mips" || arch == "mips32r6") && endian == "big";
28 let is_mips64eb = arch.contains("mips64") && endian == "big";
29 let is_unsupported_abi = is_x32 || is_arm64_ilp32 || is_powerpc64be || is_mipseb || is_mips64eb;
30
31 // Check for `--features=use-libc`. This allows crate users to enable the
32 // libc backend.
33 let feature_use_libc = var("CARGO_FEATURE_USE_LIBC").is_ok();
34
35 // Check for `RUSTFLAGS=--cfg=rustix_use_libc`. This allows end users to
36 // enable the libc backend even if rustix is depended on transitively.
37 let cfg_use_libc = var("CARGO_CFG_RUSTIX_USE_LIBC").is_ok();
38
39 // Check for `RUSTFLAGS=--cfg=rustix_no_linux_raw`. This allows Linux users to
40 // enable the libc backend without the linux raw dependency.
41 let cfg_no_linux_raw = var("CARGO_CFG_RUSTIX_NO_LINUX_RAW").is_ok();
42
43 // Check for `--features=rustc-dep-of-std`.
44 let rustc_dep_of_std = var("CARGO_FEATURE_RUSTC_DEP_OF_STD").is_ok();
45
46 // Check for eg. `RUSTFLAGS=--cfg=rustix_use_experimental_features`. This
47 // is a rustc flag rather than a cargo feature flag because it's
48 // experimental and not something we want accidentally enabled via
49 // `--all-features`.
50 let rustix_use_experimental_features =
51 var("CARGO_CFG_RUSTIX_USE_EXPERIMENTAL_FEATURES").is_ok();
52
53 // Check for eg. `RUSTFLAGS=--cfg=rustix_use_experimental_asm`. This is a
54 // rustc flag rather than a cargo feature flag because it's experimental
55 // and not something we want accidentally enabled via `--all-features`.
56 let rustix_use_experimental_asm = var("CARGO_CFG_RUSTIX_USE_EXPERIMENTAL_ASM").is_ok();
57
58 // Miri doesn't support inline asm, and has builtin support for recognizing
59 // libc FFI calls, so if we're running under miri, use the libc backend.
60 let miri = var("CARGO_CFG_MIRI").is_ok();
61
62 // If experimental features are enabled, auto-detect and use available
63 // features.
64 if rustc_dep_of_std {
65 use_feature("rustc_attrs");
66 use_feature("core_intrinsics");
67 } else if rustix_use_experimental_features {
68 use_feature_or_nothing("rustc_attrs");
69 use_feature_or_nothing("core_intrinsics");
70 }
71
72 // Features needed only in no-std configurations.
73 #[cfg(not(feature = "std"))]
74 {
75 use_feature_or_nothing("core_c_str");
76 use_feature_or_nothing("core_ffi_c");
77 use_feature_or_nothing("alloc_c_string");
78 use_feature_or_nothing("alloc_ffi");
79 use_feature_or_nothing("error_in_core");
80 }
81
82 // Feature needed for testing.
83 if use_static_assertions() {
84 use_feature("static_assertions");
85 }
86
87 // `LowerExp`/`UpperExp` for `NonZeroI32` etc.
88 if has_lower_upper_exp_for_non_zero() {
89 use_feature("lower_upper_exp_for_non_zero");
90 }
91
92 if can_compile("#[diagnostic::on_unimplemented()] trait Foo {}") {
93 use_feature("rustc_diagnostics")
94 }
95
96 // WASI support can utilize wasi_ext if present.
97 if os == "wasi" {
98 use_feature_or_nothing("wasi_ext");
99 use_feature_or_nothing("wasip2");
100 }
101
102 // If the libc backend is requested, or if we're not on a platform for
103 // which we have linux_raw support, use the libc backend.
104 //
105 // For now Android uses the libc backend; in theory it could use the
106 // linux_raw backend, but to do that we'll need to figure out how to
107 // install the toolchain for it.
108 let libc = feature_use_libc
109 || cfg_use_libc
110 || os != "linux"
111 || !inline_asm_name_present
112 || is_unsupported_abi
113 || miri
114 || ((arch == "powerpc"
115 || arch == "powerpc64"
116 || arch == "s390x"
117 || arch.starts_with("mips"))
118 && !rustix_use_experimental_asm);
119 if libc {
120 if (os == "linux" || os == "android") && !cfg_no_linux_raw {
121 use_feature("linux_raw_dep");
122 }
123
124 // Use the libc backend.
125 use_feature("libc");
126 } else {
127 // Use the linux_raw backend.
128 use_feature("linux_raw_dep");
129 use_feature("linux_raw");
130 if rustix_use_experimental_asm {
131 use_feature("asm_experimental_arch");
132 }
133 }
134
135 // Detect whether the compiler requires us to use thumb mode on ARM.
136 if arch == "arm" && use_thumb_mode() {
137 use_feature("thumb_mode");
138 }
139
140 // Rust's libc crate groups some OS's together which have similar APIs;
141 // create similarly-named features to make `cfg` tests more concise.
142 let freebsdlike = os == "freebsd" || os == "dragonfly";
143 if freebsdlike {
144 use_feature("freebsdlike");
145 }
146 let netbsdlike = os == "openbsd" || os == "netbsd";
147 if netbsdlike {
148 use_feature("netbsdlike");
149 }
150 let apple = os == "macos" || os == "ios" || os == "tvos" || os == "visionos" || os == "watchos";
151 if apple {
152 use_feature("apple");
153 }
154 if os == "linux" || os == "l4re" || os == "android" || os == "emscripten" {
155 use_feature("linux_like");
156 }
157 if os == "solaris" || os == "illumos" {
158 use_feature("solarish");
159 }
160 if apple || freebsdlike || netbsdlike {
161 use_feature("bsd");
162 }
163
164 // Add some additional common target combinations.
165
166 // Android and "regular" Linux both use the Linux kernel.
167 if os == "android" || os == "linux" {
168 use_feature("linux_kernel");
169 }
170
171 // These platforms have a 32-bit `time_t`.
172 if libc
173 && (arch == "arm"
174 || arch == "powerpc"
175 || arch == "mips"
176 || arch == "sparc"
177 || arch == "x86"
178 || (arch == "aarch64" && os == "linux" && abi == Ok("ilp32".to_string())))
179 && (apple
180 || os == "android"
181 || (os == "freebsd" && arch == "x86")
182 || os == "haiku"
183 || env == "gnu"
184 || (env == "musl" && arch == "x86")
185 || (arch == "aarch64" && os == "linux" && abi == Ok("ilp32".to_string())))
186 {
187 use_feature("fix_y2038");
188 }
189
190 println!("cargo:rerun-if-env-changed=CARGO_CFG_RUSTIX_USE_EXPERIMENTAL_ASM");
191 println!("cargo:rerun-if-env-changed=CARGO_CFG_RUSTIX_USE_LIBC");
192
193 // Rerun this script if any of our features or configuration flags change,
194 // or if the toolchain we used for feature detection changes.
195 println!("cargo:rerun-if-env-changed=CARGO_FEATURE_USE_LIBC");
196 println!("cargo:rerun-if-env-changed=CARGO_FEATURE_RUSTC_DEP_OF_STD");
197 println!("cargo:rerun-if-env-changed=CARGO_CFG_MIRI");
198 }
199
200 fn use_static_assertions() -> bool {
201 // `offset_from` was made const in Rust 1.65.
202 can_compile("const unsafe fn foo(p: *const u8) -> isize { p.offset_from(p) }")
203 }
204
205 fn use_thumb_mode() -> bool {
206 // In thumb mode, r7 is reserved.
207 !can_compile("pub unsafe fn f() { core::arch::asm!(\"udf #16\", in(\"r7\") 0); }")
208 }
209
210 fn has_lower_upper_exp_for_non_zero() -> bool {
211 // LowerExp/UpperExp for NonZero* were added in Rust 1.84.
212 // <https://doc.rust-lang.org/stable/std/fmt/trait.LowerExp.html#impl-LowerExp-for-NonZero%3CT%3E>
213 can_compile("fn a(x: &core::num::NonZeroI32, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { core::fmt::LowerExp::fmt(x, f) }")
214 }
215
216 fn use_feature_or_nothing(feature: &str) {
217 if has_feature(feature) {
218 use_feature(feature);
219 }
220 }
221
222 fn use_feature(feature: &str) {
223 println!("cargo:rustc-cfg={}", feature);
224 }
225
226 /// Test whether the rustc at `var("RUSTC")` supports the given feature.
227 fn has_feature(feature: &str) -> bool {
228 can_compile(format!(
229 "#![allow(stable_features)]\n#![feature({})]",
230 feature
231 ))
232 }
233
234 /// Test whether the rustc at `var("RUSTC")` can compile the given code.
235 fn can_compile<T: AsRef<str>>(test: T) -> bool {
236 use std::process::Stdio;
237
238 let rustc = var("RUSTC").unwrap();
239 let target = var("TARGET").unwrap();
240
241 // Use `RUSTC_WRAPPER` if it's set, unless it's set to an empty string, as
242 // documented [here].
243 // [here]: https://doc.rust-lang.org/cargo/reference/environment-variables.html#environment-variables-cargo-reads
244 let wrapper = var("RUSTC_WRAPPER")
245 .ok()
246 .and_then(|w| if w.is_empty() { None } else { Some(w) });
247
248 let mut cmd = if let Some(wrapper) = wrapper {
249 let mut cmd = std::process::Command::new(wrapper);
250 // The wrapper's first argument is supposed to be the path to rustc.
251 cmd.arg(rustc);
252 cmd
253 } else {
254 std::process::Command::new(rustc)
255 };
256
257 let out_dir = var("OUT_DIR").unwrap();
258 let out_file = PathBuf::from(out_dir).join("rustix_test_can_compile");
259 cmd.arg("--crate-type=rlib") // Don't require `main`.
260 .arg("--emit=metadata") // Do as little as possible but still parse.
261 .arg("--target")
262 .arg(target)
263 .arg("-o")
264 .arg(out_file)
265 .stdout(Stdio::null()); // We don't care about the output (only whether it builds or not)
266
267 // If Cargo wants to set RUSTFLAGS, use that.
268 if let Ok(rustflags) = var("CARGO_ENCODED_RUSTFLAGS") {
269 if !rustflags.is_empty() {
270 for arg in rustflags.split('\x1f') {
271 cmd.arg(arg);
272 }
273 }
274 }
275
276 let mut child = cmd
277 .arg("-") // Read from stdin.
278 .stdin(Stdio::piped()) // Stdin is a pipe.
279 .stderr(Stdio::null()) // Errors from feature detection aren't interesting and can be confusing.
280 .spawn()
281 .unwrap();
282
283 writeln!(child.stdin.take().unwrap(), "{}", test.as_ref()).unwrap();
284
285 child.wait().unwrap().success()
286 }