xref: /rust-libc-0.2.174/build.rs (revision f90afeff)
1 use std::env;
2 use std::process::Command;
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_time64",
11     "freebsd10",
12     "freebsd11",
13     "freebsd12",
14     "freebsd13",
15     "freebsd14",
16     "freebsd15",
17     "libc_align",
18     "libc_cfg_target_vendor",
19     "libc_const_extern_fn",
20     "libc_const_extern_fn_unstable",
21     "libc_const_size_of",
22     "libc_core_cvoid",
23     "libc_deny_warnings",
24     "libc_int128",
25     "libc_long_array",
26     "libc_non_exhaustive",
27     "libc_packedN",
28     "libc_priv_mod_use",
29     "libc_ptr_addr_of",
30     "libc_thread_local",
31     "libc_underscore_const_names",
32     "libc_union",
33 ];
34 
35 // Extra values to allow for check-cfg.
36 const CHECK_CFG_EXTRA: &'static [(&'static str, &'static [&'static str])] = &[
37     ("target_os", &["switch", "aix", "ohos", "hurd", "visionos"]),
38     ("target_env", &["illumos", "wasi", "aix", "ohos"]),
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 align_cargo_feature = env::var("CARGO_FEATURE_ALIGN").is_ok();
52     let const_extern_fn_cargo_feature = env::var("CARGO_FEATURE_CONST_EXTERN_FN").is_ok();
53     let libc_ci = env::var("LIBC_CI").is_ok();
54     let libc_check_cfg = env::var("LIBC_CHECK_CFG").is_ok() || rustc_minor_ver >= 80;
55 
56     if env::var("CARGO_FEATURE_USE_STD").is_ok() {
57         println!(
58             "cargo:warning=\"libc's use_std cargo feature is deprecated since libc 0.2.55; \
59              please consider using the `std` cargo feature instead\""
60         );
61     }
62 
63     // The ABI of libc used by std is backward compatible with FreeBSD 12.
64     // The ABI of libc from crates.io is backward compatible with FreeBSD 11.
65     //
66     // On CI, we detect the actual FreeBSD version and match its ABI exactly,
67     // running tests to ensure that the ABI is correct.
68     let which_freebsd = if libc_ci {
69         which_freebsd().unwrap_or(11)
70     } else if rustc_dep_of_std {
71         12
72     } else {
73         11
74     };
75     match which_freebsd {
76         x if x < 10 => panic!("FreeBSD older than 10 is not supported"),
77         10 => set_cfg("freebsd10"),
78         11 => set_cfg("freebsd11"),
79         12 => set_cfg("freebsd12"),
80         13 => set_cfg("freebsd13"),
81         14 => set_cfg("freebsd14"),
82         _ => set_cfg("freebsd15"),
83     }
84 
85     match emcc_version_code() {
86         Some(v) if (v >= 30142) => set_cfg("emscripten_new_stat_abi"),
87         // Non-Emscripten or version < 3.1.42.
88         Some(_) | None => (),
89     }
90 
91     // On CI: deny all warnings
92     if libc_ci {
93         set_cfg("libc_deny_warnings");
94     }
95 
96     // Rust >= 1.15 supports private module use:
97     if rustc_minor_ver >= 15 || rustc_dep_of_std {
98         set_cfg("libc_priv_mod_use");
99     }
100 
101     // Rust >= 1.19 supports unions:
102     if rustc_minor_ver >= 19 || rustc_dep_of_std {
103         set_cfg("libc_union");
104     }
105 
106     // Rust >= 1.24 supports const mem::size_of:
107     if rustc_minor_ver >= 24 || rustc_dep_of_std {
108         set_cfg("libc_const_size_of");
109     }
110 
111     // Rust >= 1.25 supports repr(align):
112     if rustc_minor_ver >= 25 || rustc_dep_of_std || align_cargo_feature {
113         set_cfg("libc_align");
114     }
115 
116     // Rust >= 1.26 supports i128 and u128:
117     if rustc_minor_ver >= 26 || rustc_dep_of_std {
118         set_cfg("libc_int128");
119     }
120 
121     // Rust >= 1.30 supports `core::ffi::c_void`, so libc can just re-export it.
122     // Otherwise, it defines an incompatible type to retaining
123     // backwards-compatibility.
124     if rustc_minor_ver >= 30 || rustc_dep_of_std {
125         set_cfg("libc_core_cvoid");
126     }
127 
128     // Rust >= 1.33 supports repr(packed(N)) and cfg(target_vendor).
129     if rustc_minor_ver >= 33 || rustc_dep_of_std {
130         set_cfg("libc_packedN");
131         set_cfg("libc_cfg_target_vendor");
132     }
133 
134     // Rust >= 1.40 supports #[non_exhaustive].
135     if rustc_minor_ver >= 40 || rustc_dep_of_std {
136         set_cfg("libc_non_exhaustive");
137     }
138 
139     // Rust >= 1.47 supports long array:
140     if rustc_minor_ver >= 47 || rustc_dep_of_std {
141         set_cfg("libc_long_array");
142     }
143 
144     if rustc_minor_ver >= 51 || rustc_dep_of_std {
145         set_cfg("libc_ptr_addr_of");
146     }
147 
148     // Rust >= 1.37.0 allows underscores as anonymous constant names.
149     if rustc_minor_ver >= 37 || rustc_dep_of_std {
150         set_cfg("libc_underscore_const_names");
151     }
152 
153     // #[thread_local] is currently unstable
154     if rustc_dep_of_std {
155         set_cfg("libc_thread_local");
156     }
157 
158     // Rust >= 1.62.0 allows to use `const_extern_fn` for "Rust" and "C".
159     if rustc_minor_ver >= 62 {
160         set_cfg("libc_const_extern_fn");
161     } else {
162         // Rust < 1.62.0 requires a crate feature and feature gate.
163         if const_extern_fn_cargo_feature {
164             if !is_nightly || rustc_minor_ver < 40 {
165                 panic!("const-extern-fn requires a nightly compiler >= 1.40");
166             }
167             set_cfg("libc_const_extern_fn_unstable");
168             set_cfg("libc_const_extern_fn");
169         }
170     }
171 
172     // check-cfg is a nightly cargo/rustc feature to warn when unknown cfgs are used across the
173     // codebase. libc can configure it if the appropriate environment variable is passed. Since
174     // rust-lang/rust enforces it, this is useful when using a custom libc fork there.
175     //
176     // https://doc.rust-lang.org/nightly/cargo/reference/unstable.html#check-cfg
177     if libc_check_cfg {
178         for cfg in ALLOWED_CFGS {
179             if rustc_minor_ver >= 75 {
180                 println!("cargo:rustc-check-cfg=cfg({})", cfg);
181             } else {
182                 println!("cargo:rustc-check-cfg=values({})", cfg);
183             }
184         }
185         for &(name, values) in CHECK_CFG_EXTRA {
186             let values = values.join("\",\"");
187             if rustc_minor_ver >= 75 {
188                 println!("cargo:rustc-check-cfg=cfg({},values(\"{}\"))", name, values);
189             } else {
190                 println!("cargo:rustc-check-cfg=values({},\"{}\")", name, values);
191             }
192         }
193     }
194 }
195 
196 fn rustc_minor_nightly() -> (u32, bool) {
197     macro_rules! otry {
198         ($e:expr) => {
199             match $e {
200                 Some(e) => e,
201                 None => panic!("Failed to get rustc version"),
202             }
203         };
204     }
205 
206     let rustc = env::var_os("RUSTC").expect("Failed to get rustc version: missing RUSTC env");
207     let mut cmd = match env::var_os("RUSTC_WRAPPER").as_ref() {
208         Some(wrapper) if !wrapper.is_empty() => {
209             let mut cmd = Command::new(wrapper);
210             cmd.arg(rustc);
211             cmd
212         }
213         _ => Command::new(rustc),
214     };
215 
216     let output = cmd
217         .arg("--version")
218         .output()
219         .ok()
220         .expect("Failed to get rustc version");
221     if !output.status.success() {
222         panic!(
223             "failed to run rustc: {}",
224             String::from_utf8_lossy(output.stderr.as_slice())
225         );
226     }
227 
228     let version = otry!(str::from_utf8(&output.stdout).ok());
229     let mut pieces = version.split('.');
230 
231     if pieces.next() != Some("rustc 1") {
232         panic!("Failed to get rustc version");
233     }
234 
235     let minor = pieces.next();
236 
237     // If `rustc` was built from a tarball, its version string
238     // will have neither a git hash nor a commit date
239     // (e.g. "rustc 1.39.0"). Treat this case as non-nightly,
240     // since a nightly build should either come from CI
241     // or a git checkout
242     let nightly_raw = otry!(pieces.next()).split('-').nth(1);
243     let nightly = nightly_raw
244         .map(|raw| raw.starts_with("dev") || raw.starts_with("nightly"))
245         .unwrap_or(false);
246     let minor = otry!(otry!(minor).parse().ok());
247 
248     (minor, nightly)
249 }
250 
251 fn which_freebsd() -> Option<i32> {
252     let output = std::process::Command::new("freebsd-version").output().ok();
253     if output.is_none() {
254         return None;
255     }
256     let output = output.unwrap();
257     if !output.status.success() {
258         return None;
259     }
260 
261     let stdout = String::from_utf8(output.stdout).ok();
262     if stdout.is_none() {
263         return None;
264     }
265     let stdout = stdout.unwrap();
266 
267     match &stdout {
268         s if s.starts_with("10") => Some(10),
269         s if s.starts_with("11") => Some(11),
270         s if s.starts_with("12") => Some(12),
271         s if s.starts_with("13") => Some(13),
272         s if s.starts_with("14") => Some(14),
273         s if s.starts_with("15") => Some(15),
274         _ => None,
275     }
276 }
277 
278 fn emcc_version_code() -> Option<u64> {
279     let output = std::process::Command::new("emcc")
280         .arg("-dumpversion")
281         .output()
282         .ok();
283     if output.is_none() {
284         return None;
285     }
286     let output = output.unwrap();
287     if !output.status.success() {
288         return None;
289     }
290 
291     let stdout = String::from_utf8(output.stdout).ok();
292     if stdout.is_none() {
293         return None;
294     }
295     let version = stdout.unwrap();
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(|c| c == '.' || c == '-');
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 fn set_cfg(cfg: &str) {
309     if !ALLOWED_CFGS.contains(&cfg) {
310         panic!("trying to set cfg {}, but it is not in ALLOWED_CFGS", cfg);
311     }
312     println!("cargo:rustc-cfg={}", cfg);
313 }
314