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