Debian Codegraph @

debian/missing-sources/libc/build.rs

raw
1 use std::env::VarError;
2 use std::process::{
3 Command,
4 Output,
5 };
6 use std::{
7 env,
8 str,
9 };
10
11 // List of cfgs this build script is allowed to set. The list is needed to support check-cfg, as we
12 // need to know all the possible cfgs that this script will set. If you need to set another cfg
13 // make sure to add it to this list as well.
14 const ALLOWED_CFGS: &[&str] = &[
15 "emscripten_old_stat_abi",
16 "espidf_time32",
17 "freebsd10",
18 "freebsd11",
19 "freebsd12",
20 "freebsd13",
21 "freebsd14",
22 "freebsd15",
23 // Corresponds to `_FILE_OFFSET_BITS=64` in glibc
24 "gnu_file_offset_bits64",
25 // Corresponds to `_TIME_BITS=64` in glibc
26 "gnu_time_bits64",
27 "libc_deny_warnings",
28 // Corresponds to `__USE_TIME_BITS64` in UAPI
29 "linux_time_bits64",
30 "musl_v1_2_3",
31 // Corresponds to `_REDIR_TIME64` in musl
32 "musl32_time64",
33 "vxworks_lt_25_09",
34 ];
35
36 // Extra values to allow for check-cfg.
37 const CHECK_CFG_EXTRA: &[(&str, &[&str])] = &[
38 (
39 "target_os",
40 &[
41 "switch", "aix", "ohos", "hurd", "rtems", "visionos", "nuttx", "cygwin", "qurt",
42 ],
43 ),
44 (
45 "target_env",
46 &["illumos", "wasi", "aix", "ohos", "nto71_iosock", "nto80"],
47 ),
48 (
49 "target_arch",
50 &["loongarch64", "mips32r6", "mips64r6", "csky"],
51 ),
52 ];
53
54 /// Musl architectures that set `#define _REDIR_TIME64 1`.
55 const MUSL_REDIR_TIME64_ARCHES: &[&str] = &["arm", "mips", "powerpc", "x86"];
56
57 fn main() {
58 // Avoid unnecessary re-building.
59 println!("cargo:rerun-if-changed=build.rs");
60
61 let (rustc_minor_ver, _is_nightly) = rustc_minor_nightly();
62 let libc_ci = env_flag("LIBC_CI");
63 let target_env = env::var("CARGO_CFG_TARGET_ENV").unwrap_or_default();
64 let target_os = env::var("CARGO_CFG_TARGET_OS").unwrap_or_default();
65 let target_ptr_width = env::var("CARGO_CFG_TARGET_POINTER_WIDTH").unwrap_or_default();
66 let target_arch = env::var("CARGO_CFG_TARGET_ARCH").unwrap_or_default();
67
68 // The ABI of libc used by std is backward compatible with FreeBSD 12.
69 // The ABI of libc from crates.io is backward compatible with FreeBSD 12.
70 //
71 // On CI, we detect the actual FreeBSD version and match its ABI exactly,
72 // running tests to ensure that the ABI is correct.
73 println!("cargo:rerun-if-env-changed=RUST_LIBC_UNSTABLE_FREEBSD_VERSION");
74 // Allow overriding the default version for testing
75 let which_freebsd = if let Ok(version) = env::var("RUST_LIBC_UNSTABLE_FREEBSD_VERSION") {
76 let vers = version.parse().unwrap();
77 println!("cargo:warning=setting FreeBSD version to {vers}");
78 vers
79 } else if libc_ci {
80 which_freebsd().unwrap_or(12)
81 } else {
82 12
83 };
84
85 match which_freebsd {
86 x if x < 10 => panic!("FreeBSD older than 10 is not supported"),
87 10 => set_cfg("freebsd10"),
88 11 => set_cfg("freebsd11"),
89 12 => set_cfg("freebsd12"),
90 13 => set_cfg("freebsd13"),
91 14 => set_cfg("freebsd14"),
92 _ => set_cfg("freebsd15"),
93 }
94
95 match emcc_version_code() {
96 Some(v) if (v < 30142) => set_cfg("emscripten_old_stat_abi"),
97 // Non-Emscripten or version >= 3.1.42.
98 _ => (),
99 }
100
101 match vxworks_version_code() {
102 Some(v) if (v < (25, 9)) => set_cfg("vxworks_lt_25_09"),
103 // VxWorks version >= 25.09
104 _ => (),
105 }
106
107 let mut musl_v1_2_3 = env_flag("RUST_LIBC_UNSTABLE_MUSL_V1_2_3");
108 println!("cargo:rerun-if-env-changed=RUST_LIBC_UNSTABLE_MUSL_V1_2_3");
109
110 // OpenHarmony uses a fork of the musl libc
111 let musl = target_env == "musl" || target_env == "ohos";
112
113 // loongarch64 and ohos only exist with recent musl
114 if target_arch == "loongarch64" || target_env == "ohos" {
115 musl_v1_2_3 = true;
116 }
117
118 if musl && musl_v1_2_3 {
119 set_cfg("musl_v1_2_3");
120 if MUSL_REDIR_TIME64_ARCHES.contains(&target_arch.as_str()) {
121 set_cfg("musl32_time64");
122 set_cfg("linux_time_bits64");
123 }
124 }
125
126 let linux_time_bits64 = env::var("RUST_LIBC_UNSTABLE_LINUX_TIME_BITS64").is_ok();
127 println!("cargo:rerun-if-env-changed=RUST_LIBC_UNSTABLE_LINUX_TIME_BITS64");
128 if linux_time_bits64 {
129 set_cfg("linux_time_bits64");
130 }
131 println!("cargo:rerun-if-env-changed=RUST_LIBC_UNSTABLE_GNU_FILE_OFFSET_BITS");
132 println!("cargo:rerun-if-env-changed=RUST_LIBC_UNSTABLE_GNU_TIME_BITS");
133 if target_env == "gnu"
134 && target_os == "linux"
135 && target_ptr_width == "32"
136 && target_arch != "riscv32"
137 && target_arch != "x86_64"
138 {
139 let defaultbits = "32".to_string();
140 let (timebits, filebits) = match (
141 env::var("RUST_LIBC_UNSTABLE_GNU_TIME_BITS"),
142 env::var("RUST_LIBC_UNSTABLE_GNU_FILE_OFFSET_BITS"),
143 ) {
144 (Ok(_), Ok(_)) => panic!("Do not set both RUST_LIBC_UNSTABLE_GNU_TIME_BITS and RUST_LIBC_UNSTABLE_GNU_FILE_OFFSET_BITS"),
145 (Err(_), Err(_)) => (defaultbits.clone(), defaultbits.clone()),
146 (Ok(tb), Err(_)) if tb == "64" => (tb.clone(), tb.clone()),
147 (Ok(tb), Err(_)) if tb == "32" => (tb, defaultbits.clone()),
148 (Ok(_), Err(_)) => panic!("Invalid value for RUST_LIBC_UNSTABLE_GNU_TIME_BITS, must be 32 or 64"),
149 (Err(_), Ok(fb)) if fb == "32" || fb == "64" => (defaultbits.clone(), fb),
150 (Err(_), Ok(_)) => panic!("Invalid value for RUST_LIBC_UNSTABLE_GNU_FILE_OFFSET_BITS, must be 32 or 64"),
151 };
152 let valid_bits = ["32", "64"];
153 assert!(
154 valid_bits.contains(&filebits.as_str()) && valid_bits.contains(&timebits.as_str()),
155 "Invalid value for RUST_LIBC_UNSTABLE_GNU_TIME_BITS or RUST_LIBC_UNSTABLE_GNU_FILE_OFFSET_BITS, must be 32, 64 or unset"
156 );
157 assert!(
158 !(filebits == "32" && timebits == "64"),
159 "RUST_LIBC_UNSTABLE_GNU_FILE_OFFSET_BITS must be 64 or unset if RUST_LIBC_UNSTABLE_GNU_TIME_BITS is 64"
160 );
161 if timebits == "64" {
162 set_cfg("linux_time_bits64");
163 set_cfg("gnu_time_bits64");
164 }
165 if filebits == "64" {
166 set_cfg("gnu_file_offset_bits64");
167 }
168 }
169
170 // On CI: deny all warnings
171 if libc_ci {
172 set_cfg("libc_deny_warnings");
173 }
174
175 // Since Rust 1.80, configuration that isn't recognized by default needs to be provided to
176 // avoid warnings.
177 if rustc_minor_ver >= 80 {
178 for cfg in ALLOWED_CFGS {
179 println!("cargo:rustc-check-cfg=cfg({cfg})");
180 }
181 for &(name, values) in CHECK_CFG_EXTRA {
182 let values = values.join("\",\"");
183 println!("cargo:rustc-check-cfg=cfg({name},values(\"{values}\"))");
184 }
185 }
186 }
187
188 /// Run `rustc --version` and capture the output, adjusting arguments as needed if `clippy-driver`
189 /// is used instead.
190 fn rustc_version_cmd(is_clippy_driver: bool) -> Output {
191 let rustc = env::var_os("RUSTC").expect("Failed to get rustc version: missing RUSTC env");
192
193 let mut cmd = match env::var_os("RUSTC_WRAPPER") {
194 Some(ref wrapper) if wrapper.is_empty() => Command::new(rustc),
195 Some(wrapper) => {
196 let mut cmd = Command::new(wrapper);
197 cmd.arg(rustc);
198 if is_clippy_driver {
199 cmd.arg("--rustc");
200 }
201
202 cmd
203 }
204 None => Command::new(rustc),
205 };
206
207 cmd.arg("--version");
208
209 let output = cmd.output().expect("Failed to get rustc version");
210
211 assert!(
212 output.status.success(),
213 "failed to run rustc: {}",
214 String::from_utf8_lossy(output.stderr.as_slice())
215 );
216
217 output
218 }
219
220 /// Return the minor version of `rustc`, as well as a bool indicating whether or not the version
221 /// is a nightly.
222 fn rustc_minor_nightly() -> (u32, bool) {
223 macro_rules! otry {
224 ($e:expr) => {
225 match $e {
226 Some(e) => e,
227 None => panic!("Failed to get rustc version"),
228 }
229 };
230 }
231
232 let mut output = rustc_version_cmd(false);
233
234 if otry!(str::from_utf8(&output.stdout).ok()).starts_with("clippy") {
235 output = rustc_version_cmd(true);
236 }
237
238 let version = otry!(str::from_utf8(&output.stdout).ok());
239
240 let mut pieces = version.split('.');
241
242 assert_eq!(
243 pieces.next(),
244 Some("rustc 1"),
245 "Failed to get rustc version"
246 );
247
248 let minor = pieces.next();
249
250 // If `rustc` was built from a tarball, its version string
251 // will have neither a git hash nor a commit date
252 // (e.g. "rustc 1.39.0"). Treat this case as non-nightly,
253 // since a nightly build should either come from CI
254 // or a git checkout
255 let nightly_raw = otry!(pieces.next()).split('-').nth(1);
256 let nightly = nightly_raw.map_or(false, |raw| {
257 raw.starts_with("dev") || raw.starts_with("nightly")
258 });
259 let minor = otry!(otry!(minor).parse().ok());
260
261 (minor, nightly)
262 }
263
264 fn which_freebsd() -> Option<i32> {
265 let output = Command::new("freebsd-version").output().ok()?;
266 if !output.status.success() {
267 return None;
268 }
269
270 let stdout = String::from_utf8(output.stdout).ok()?;
271
272 match &stdout {
273 s if s.starts_with("10") => Some(10),
274 s if s.starts_with("11") => Some(11),
275 s if s.starts_with("12") => Some(12),
276 s if s.starts_with("13") => Some(13),
277 s if s.starts_with("14") => Some(14),
278 s if s.starts_with("15") => Some(15),
279 _ => None,
280 }
281 }
282
283 fn emcc_version_code() -> Option<u64> {
284 let emcc = if cfg!(target_os = "windows") {
285 "emcc.bat"
286 } else {
287 "emcc"
288 };
289
290 let output = Command::new(emcc).arg("-dumpversion").output().ok()?;
291 if !output.status.success() {
292 return None;
293 }
294
295 let version = String::from_utf8(output.stdout).ok()?;
296
297 // Some Emscripten versions come with `-git` attached, so split the
298 // version string also on the `-` char.
299 let mut pieces = version.trim().split(['.', '-']);
300
301 let major = pieces.next().and_then(|x| x.parse().ok()).unwrap_or(0);
302 let minor = pieces.next().and_then(|x| x.parse().ok()).unwrap_or(0);
303 let patch = pieces.next().and_then(|x| x.parse().ok()).unwrap_or(0);
304
305 Some(major * 10000 + minor * 100 + patch)
306 }
307
308 /// Retrieve the VxWorks release version from the environment variable set by the VxWorks build
309 /// environment, in `(minor, patch)` form. Currently the only major version supported by Rust
310 /// is 7.
311 fn vxworks_version_code() -> Option<(u32, u32)> {
312 let version = env::var("WIND_RELEASE_ID").ok()?;
313
314 let mut pieces = version.trim().split(['.']);
315
316 let major: u32 = pieces.next().and_then(|x| x.parse().ok()).unwrap_or(0);
317 let minor: u32 = pieces.next().and_then(|x| x.parse().ok()).unwrap_or(0);
318
319 Some((major, minor))
320 }
321
322 fn set_cfg(cfg: &str) {
323 assert!(
324 ALLOWED_CFGS.contains(&cfg),
325 "trying to set cfg {cfg}, but it is not in ALLOWED_CFGS",
326 );
327 println!("cargo:rustc-cfg={cfg}");
328 }
329
330 /// Return true if the env is set to a value other than `0`.
331 fn env_flag(key: &str) -> bool {
332 match env::var(key) {
333 Ok(x) if x == "0" => false,
334 Err(VarError::NotPresent) => false,
335 Err(VarError::NotUnicode(_)) => panic!("non-unicode var for `{key}`"),
336 Ok(_) => true,
337 }
338 }