xref: /rust-libc-0.2.174/build.rs (revision 8d68ec6f)
1 use std::env;
2 use std::process::{Command, Output};
3 use std::str;
4 
5 // List of cfgs this build script is allowed to set. The list is needed to support check-cfg, as we
6 // need to know all the possible cfgs that this script will set. If you need to set another cfg
7 // make sure to add it to this list as well.
8 const ALLOWED_CFGS: &'static [&'static str] = &[
9     "emscripten_new_stat_abi",
10     "espidf_time32",
11     "freebsd10",
12     "freebsd11",
13     "freebsd12",
14     "freebsd13",
15     "freebsd14",
16     "freebsd15",
17     "libc_const_extern_fn",
18     "libc_const_extern_fn_unstable",
19     "libc_deny_warnings",
20     "libc_long_array",
21     "libc_thread_local",
22     "libc_underscore_const_names",
23     "libc_ctest",
24 ];
25 
26 // Extra values to allow for check-cfg.
27 const CHECK_CFG_EXTRA: &'static [(&'static str, &'static [&'static str])] = &[
28     (
29         "target_os",
30         &[
31             "switch", "aix", "ohos", "hurd", "rtems", "visionos", "nuttx",
32         ],
33     ),
34     ("target_env", &["illumos", "wasi", "aix", "ohos"]),
35     (
36         "target_arch",
37         &["loongarch64", "mips32r6", "mips64r6", "csky"],
38     ),
39 ];
40 
41 fn main() {
42     // Avoid unnecessary re-building.
43     println!("cargo:rerun-if-changed=build.rs");
44 
45     let (rustc_minor_ver, is_nightly) = rustc_minor_nightly();
46     let rustc_dep_of_std = env::var("CARGO_FEATURE_RUSTC_DEP_OF_STD").is_ok();
47     let const_extern_fn_cargo_feature = env::var("CARGO_FEATURE_CONST_EXTERN_FN").is_ok();
48     let libc_ci = env::var("LIBC_CI").is_ok();
49     let libc_check_cfg = env::var("LIBC_CHECK_CFG").is_ok() || rustc_minor_ver >= 80;
50 
51     // The ABI of libc used by std is backward compatible with FreeBSD 12.
52     // The ABI of libc from crates.io is backward compatible with FreeBSD 11.
53     //
54     // On CI, we detect the actual FreeBSD version and match its ABI exactly,
55     // running tests to ensure that the ABI is correct.
56     let which_freebsd = if libc_ci {
57         which_freebsd().unwrap_or(11)
58     } else if rustc_dep_of_std {
59         12
60     } else {
61         11
62     };
63     match which_freebsd {
64         x if x < 10 => panic!("FreeBSD older than 10 is not supported"),
65         10 => set_cfg("freebsd10"),
66         11 => set_cfg("freebsd11"),
67         12 => set_cfg("freebsd12"),
68         13 => set_cfg("freebsd13"),
69         14 => set_cfg("freebsd14"),
70         _ => set_cfg("freebsd15"),
71     }
72 
73     match emcc_version_code() {
74         Some(v) if (v >= 30142) => set_cfg("emscripten_new_stat_abi"),
75         // Non-Emscripten or version < 3.1.42.
76         Some(_) | None => (),
77     }
78 
79     // On CI: deny all warnings
80     if libc_ci {
81         set_cfg("libc_deny_warnings");
82     }
83 
84     // Rust >= 1.47 supports long array:
85     if rustc_minor_ver >= 47 || rustc_dep_of_std {
86         set_cfg("libc_long_array");
87     }
88 
89     // Rust >= 1.37.0 allows underscores as anonymous constant names.
90     if rustc_minor_ver >= 37 || rustc_dep_of_std {
91         set_cfg("libc_underscore_const_names");
92     }
93 
94     // #[thread_local] is currently unstable
95     if rustc_dep_of_std {
96         set_cfg("libc_thread_local");
97     }
98 
99     // Rust >= 1.62.0 allows to use `const_extern_fn` for "Rust" and "C".
100     if rustc_minor_ver >= 62 {
101         set_cfg("libc_const_extern_fn");
102     } else {
103         // Rust < 1.62.0 requires a crate feature and feature gate.
104         if const_extern_fn_cargo_feature {
105             if !is_nightly || rustc_minor_ver < 40 {
106                 panic!("const-extern-fn requires a nightly compiler >= 1.40");
107             }
108             set_cfg("libc_const_extern_fn_unstable");
109             set_cfg("libc_const_extern_fn");
110         }
111     }
112 
113     // check-cfg is a nightly cargo/rustc feature to warn when unknown cfgs are used across the
114     // codebase. libc can configure it if the appropriate environment variable is passed. Since
115     // rust-lang/rust enforces it, this is useful when using a custom libc fork there.
116     //
117     // https://doc.rust-lang.org/nightly/cargo/reference/unstable.html#check-cfg
118     if libc_check_cfg {
119         for cfg in ALLOWED_CFGS {
120             if rustc_minor_ver >= 75 {
121                 println!("cargo:rustc-check-cfg=cfg({})", cfg);
122             } else {
123                 println!("cargo:rustc-check-cfg=values({})", cfg);
124             }
125         }
126         for &(name, values) in CHECK_CFG_EXTRA {
127             let values = values.join("\",\"");
128             if rustc_minor_ver >= 75 {
129                 println!("cargo:rustc-check-cfg=cfg({},values(\"{}\"))", name, values);
130             } else {
131                 println!("cargo:rustc-check-cfg=values({},\"{}\")", name, values);
132             }
133         }
134     }
135 }
136 
137 /// Run `rustc --version` and capture the output, adjusting arguments as needed if `clippy-driver`
138 /// is used instead.
139 fn rustc_version_cmd(is_clippy_driver: bool) -> Output {
140     let rustc = env::var_os("RUSTC").expect("Failed to get rustc version: missing RUSTC env");
141 
142     let mut cmd = match env::var_os("RUSTC_WRAPPER") {
143         Some(ref wrapper) if wrapper.is_empty() => Command::new(rustc),
144         Some(wrapper) => {
145             let mut cmd = Command::new(wrapper);
146             cmd.arg(rustc);
147             if is_clippy_driver {
148                 cmd.arg("--rustc");
149             }
150 
151             cmd
152         }
153         None => Command::new(rustc),
154     };
155 
156     cmd.arg("--version");
157 
158     let output = cmd.output().ok().expect("Failed to get rustc version");
159 
160     if !output.status.success() {
161         panic!(
162             "failed to run rustc: {}",
163             String::from_utf8_lossy(output.stderr.as_slice())
164         );
165     }
166 
167     output
168 }
169 
170 /// Return the minor version of `rustc`, as well as a bool indicating whether or not the version
171 /// is a nightly.
172 fn rustc_minor_nightly() -> (u32, bool) {
173     macro_rules! otry {
174         ($e:expr) => {
175             match $e {
176                 Some(e) => e,
177                 None => panic!("Failed to get rustc version"),
178             }
179         };
180     }
181 
182     let mut output = rustc_version_cmd(false);
183 
184     if otry!(str::from_utf8(&output.stdout).ok()).starts_with("clippy") {
185         output = rustc_version_cmd(true);
186     }
187 
188     let version = otry!(str::from_utf8(&output.stdout).ok());
189 
190     let mut pieces = version.split('.');
191 
192     if pieces.next() != Some("rustc 1") {
193         panic!("Failed to get rustc version");
194     }
195 
196     let minor = pieces.next();
197 
198     // If `rustc` was built from a tarball, its version string
199     // will have neither a git hash nor a commit date
200     // (e.g. "rustc 1.39.0"). Treat this case as non-nightly,
201     // since a nightly build should either come from CI
202     // or a git checkout
203     let nightly_raw = otry!(pieces.next()).split('-').nth(1);
204     let nightly = nightly_raw
205         .map(|raw| raw.starts_with("dev") || raw.starts_with("nightly"))
206         .unwrap_or(false);
207     let minor = otry!(otry!(minor).parse().ok());
208 
209     (minor, nightly)
210 }
211 
212 fn which_freebsd() -> Option<i32> {
213     let output = std::process::Command::new("freebsd-version").output().ok();
214     if output.is_none() {
215         return None;
216     }
217     let output = output.unwrap();
218     if !output.status.success() {
219         return None;
220     }
221 
222     let stdout = String::from_utf8(output.stdout).ok();
223     if stdout.is_none() {
224         return None;
225     }
226     let stdout = stdout.unwrap();
227 
228     match &stdout {
229         s if s.starts_with("10") => Some(10),
230         s if s.starts_with("11") => Some(11),
231         s if s.starts_with("12") => Some(12),
232         s if s.starts_with("13") => Some(13),
233         s if s.starts_with("14") => Some(14),
234         s if s.starts_with("15") => Some(15),
235         _ => None,
236     }
237 }
238 
239 fn emcc_version_code() -> Option<u64> {
240     let output = std::process::Command::new("emcc")
241         .arg("-dumpversion")
242         .output()
243         .ok();
244     if output.is_none() {
245         return None;
246     }
247     let output = output.unwrap();
248     if !output.status.success() {
249         return None;
250     }
251 
252     let stdout = String::from_utf8(output.stdout).ok();
253     if stdout.is_none() {
254         return None;
255     }
256     let version = stdout.unwrap();
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(|c| c == '.' || c == '-');
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     if !ALLOWED_CFGS.contains(&cfg) {
271         panic!("trying to set cfg {}, but it is not in ALLOWED_CFGS", cfg);
272     }
273     println!("cargo:rustc-cfg={}", cfg);
274 }
275