Debian Codegraph @

third_party/rust/neqo-crypto/build.rs

raw
1 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
2 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
3 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
4 // option. This file may not be copied, modified, or distributed
5 // except according to those terms.
6
7 #![expect(
8 clippy::unwrap_used,
9 clippy::iter_over_hash_type,
10 reason = "OK in a build script."
11 )]
12
13 use std::{
14 collections::HashMap,
15 env, fs,
16 path::{Path, PathBuf},
17 process::Command,
18 };
19
20 use bindgen::Builder;
21 use semver::{Version, VersionReq};
22 use serde_derive::Deserialize;
23
24 #[path = "src/min_version.rs"]
25 mod min_version;
26 use min_version::MINIMUM_NSS_VERSION;
27
28 const BINDINGS_DIR: &str = "bindings";
29 const BINDINGS_CONFIG: &str = "bindings.toml";
30
31 // This is the format of a single section of the configuration file.
32 #[derive(Deserialize)]
33 struct Bindings {
34 /// types that are explicitly included
35 #[serde(default)]
36 types: Vec<String>,
37 /// functions that are explicitly included
38 #[serde(default)]
39 functions: Vec<String>,
40 /// variables (and `#define`s) that are explicitly included
41 #[serde(default)]
42 variables: Vec<String>,
43 /// types that should be explicitly marked as opaque
44 #[serde(default)]
45 opaque: Vec<String>,
46 /// enumerations that are turned into a module (without this, the enum is
47 /// mapped using the default, which means that the individual values are
48 /// formed with an underscore as <`enum_type`>_<`enum_value_name`>).
49 #[serde(default)]
50 enums: Vec<String>,
51
52 /// Any item that is specifically excluded; if none of the types, functions,
53 /// or variables fields are specified, everything defined will be mapped,
54 /// so this can be used to limit that.
55 #[serde(default)]
56 exclude: Vec<String>,
57
58 /// Whether the file is to be interpreted as C++
59 #[serde(default)]
60 cplusplus: bool,
61 }
62
63 // bindgen needs access to libclang.
64 // On windows, this doesn't just work, you have to set LIBCLANG_PATH.
65 // Rather than download the 400Mb+ files, like gecko does, let's just reuse their work.
66 fn setup_clang() {
67 // If this isn't Windows, or we're in CI, then we don't need to do anything.
68 if env::consts::OS != "windows" || env::var("GITHUB_WORKFLOW").unwrap_or_default() == "CI" {
69 return;
70 }
71 println!("rerun-if-env-changed=LIBCLANG_PATH");
72 println!("rerun-if-env-changed=MOZBUILD_STATE_PATH");
73 if env::var("LIBCLANG_PATH").is_ok() {
74 return;
75 }
76 let mozbuild_root = if let Ok(dir) = env::var("MOZBUILD_STATE_PATH") {
77 PathBuf::from(dir.trim())
78 } else {
79 eprintln!("warning: Building without a gecko setup is not likely to work.");
80 eprintln!(" A working libclang is needed to build neqo.");
81 eprintln!(" Either LIBCLANG_PATH or MOZBUILD_STATE_PATH needs to be set.");
82 eprintln!();
83 eprintln!(" We recommend checking out https://github.com/mozilla/gecko-dev");
84 eprintln!(" Then run `./mach bootstrap` which will retrieve clang.");
85 eprintln!(" Make sure to export MOZBUILD_STATE_PATH when building.");
86 return;
87 };
88 let libclang_dir = mozbuild_root.join("clang").join("lib");
89 if libclang_dir.is_dir() {
90 env::set_var("LIBCLANG_PATH", libclang_dir.to_str().unwrap());
91 println!("rustc-env:LIBCLANG_PATH={}", libclang_dir.to_str().unwrap());
92 } else {
93 println!("warning: LIBCLANG_PATH isn't set; maybe run ./mach bootstrap with gecko");
94 }
95 }
96
97 fn get_bash() -> PathBuf {
98 // If BASH is set, use that.
99 if let Ok(bash) = env::var("BASH") {
100 return PathBuf::from(bash);
101 }
102
103 // When running under MOZILLABUILD, we need to make sure not to invoke
104 // another instance of bash that might be sitting around (like WSL).
105 env::var("MOZILLABUILD").map_or_else(
106 |_| PathBuf::from("bash"),
107 |d| PathBuf::from(d).join("msys").join("bin").join("bash.exe"),
108 )
109 }
110
111 fn build_nss(dir: PathBuf, nsstarget: &str) {
112 let mut build_nss = vec![
113 String::from("./build.sh"),
114 String::from("-Ddisable_tests=1"),
115 // Generate static libraries in addition to shared libraries.
116 String::from("--static"),
117 ];
118 if nsstarget == "Release" {
119 build_nss.push(String::from("-o"));
120 }
121 if let Ok(d) = env::var("NSS_JOBS") {
122 build_nss.push(String::from("-j"));
123 build_nss.push(d);
124 }
125 let target = env::var("TARGET").unwrap();
126 if target.strip_prefix("aarch64-").is_some() {
127 build_nss.push(String::from("--target=arm64"));
128 }
129 let status = Command::new(get_bash())
130 .args(build_nss)
131 .current_dir(dir)
132 .status()
133 .expect("couldn't start NSS build");
134 assert!(status.success(), "NSS build failed");
135 }
136
137 fn dynamic_link() {
138 let dynamic_libs = if env::consts::OS == "windows" {
139 [
140 "nssutil3.dll",
141 "nss3.dll",
142 "ssl3.dll",
143 "libplds4.dll",
144 "libplc4.dll",
145 "libnspr4.dll",
146 ]
147 } else {
148 ["nssutil3", "nss3", "ssl3", "plds4", "plc4", "nspr4"]
149 };
150 for lib in dynamic_libs {
151 println!("cargo:rustc-link-lib=dylib={lib}");
152 }
153 }
154
155 fn static_link() {
156 let mut static_libs = vec![
157 "certdb",
158 "certhi",
159 "cryptohi",
160 "freebl_static",
161 if env::consts::OS == "windows" {
162 "libnspr4"
163 } else {
164 "nspr4"
165 },
166 "nss_static",
167 "nssb",
168 "nssdev",
169 "nsspki",
170 "nssutil",
171 "pk11wrap_static",
172 if env::consts::OS == "windows" {
173 "libplc4"
174 } else {
175 "plc4"
176 },
177 if env::consts::OS == "windows" {
178 "libplds4"
179 } else {
180 "plds4"
181 },
182 "softokn_static",
183 "ssl",
184 ];
185 // macOS always dynamically links against the system sqlite library.
186 // See https://github.com/nss-dev/nss/blob/a8c22d8fc0458db3e261acc5e19b436ab573a961/coreconf/Darwin.mk#L130-L135
187 if env::consts::OS == "macos" {
188 println!("cargo:rustc-link-lib=dylib=sqlite3");
189 } else {
190 static_libs.push("sqlite");
191 }
192 // Hardware specific libs.
193 // See https://github.com/mozilla/application-services/blob/0a2dac76f979b8bcfb6bacb5424b50f58520b8fe/components/support/rc_crypto/nss/nss_build_common/src/lib.rs#L127-L157
194 let target_arch = env::var("CARGO_CFG_TARGET_ARCH").unwrap();
195 let target_os = env::var("CARGO_CFG_TARGET_OS").unwrap();
196 // https://searchfox.org/nss/rev/0d5696b3edce5124353f03159d2aa15549db8306/lib/freebl/freebl.gyp#508-542
197 if target_arch == "arm" || target_arch == "aarch64" {
198 static_libs.push("armv8_c_lib");
199 }
200 if target_arch == "x86_64" || target_arch == "x86" {
201 static_libs.push("gcm-aes-x86_c_lib");
202 static_libs.push("sha-x86_c_lib");
203 }
204 if target_arch == "arm" {
205 static_libs.push("gcm-aes-arm32-neon_c_lib");
206 }
207 if target_arch == "aarch64" {
208 static_libs.push("gcm-aes-aarch64_c_lib");
209 }
210 if target_arch == "x86_64" {
211 static_libs.push("hw-acc-crypto-avx");
212 static_libs.push("hw-acc-crypto-avx2");
213 }
214 // https://searchfox.org/nss/rev/08c4d05078d00089f8d7540651b0717a9d66f87e/lib/freebl/freebl.gyp#315-324
215 if (target_os == "android" || target_os == "linux") && target_arch == "x86_64" {
216 static_libs.push("intel-gcm-wrap_c_lib");
217 // https://searchfox.org/nss/rev/08c4d05078d00089f8d7540651b0717a9d66f87e/lib/freebl/freebl.gyp#43-47
218 if (target_os == "android" || target_os == "linux") && target_arch == "x86_64" {
219 static_libs.push("intel-gcm-s_lib");
220 }
221 }
222 for lib in static_libs {
223 println!("cargo:rustc-link-lib=static={lib}");
224 }
225 }
226
227 fn get_includes(nsstarget: &Path, nssdist: &Path) -> Vec<PathBuf> {
228 let nsprinclude = nsstarget.join("include").join("nspr");
229 let nssinclude = nssdist.join("public").join("nss");
230 let includes = vec![nsprinclude, nssinclude];
231 for i in &includes {
232 println!("cargo:include={}", i.to_str().unwrap());
233 }
234 includes
235 }
236
237 fn build_bindings(base: &str, bindings: &Bindings, flags: &[String], gecko: bool) {
238 let suffix = if bindings.cplusplus { ".hpp" } else { ".h" };
239 let header_path = PathBuf::from(BINDINGS_DIR).join(String::from(base) + suffix);
240 let header = header_path.to_str().unwrap();
241 let out = PathBuf::from(env::var("OUT_DIR").unwrap()).join(String::from(base) + ".rs");
242
243 println!("cargo:rerun-if-changed={header}");
244
245 let mut builder = Builder::default().header(header);
246 builder = builder.generate_comments(false);
247 builder = builder.size_t_is_usize(true);
248
249 builder = builder.clang_arg("-v");
250
251 if !gecko {
252 builder = builder.clang_arg("-DNO_NSPR_10_SUPPORT");
253 if env::consts::OS == "windows" {
254 builder = builder.clang_arg("-DWIN");
255 } else if env::consts::OS == "macos" {
256 builder = builder.clang_arg("-DDARWIN");
257 } else if env::consts::OS == "linux" {
258 builder = builder.clang_arg("-DLINUX");
259 } else if env::consts::OS == "android" {
260 builder = builder.clang_arg("-DLINUX");
261 builder = builder.clang_arg("-DANDROID");
262 }
263 if bindings.cplusplus {
264 builder = builder.clang_args(&["-x", "c++", "-std=c++14"]);
265 }
266 }
267
268 builder = builder.clang_args(flags);
269
270 // Apply the configuration.
271 for v in &bindings.types {
272 builder = builder.allowlist_type(v);
273 }
274 for v in &bindings.functions {
275 builder = builder.allowlist_function(v);
276 }
277 for v in &bindings.variables {
278 builder = builder.allowlist_var(v);
279 }
280 for v in &bindings.exclude {
281 builder = builder.blocklist_item(v);
282 }
283 for v in &bindings.opaque {
284 builder = builder.opaque_type(v);
285 }
286 for v in &bindings.enums {
287 builder = builder.constified_enum_module(v);
288 }
289
290 let bindings = builder.generate().expect("unable to generate bindings");
291 bindings
292 .write_to_file(out)
293 .expect("couldn't write bindings");
294 }
295
296 fn pkg_config() -> Vec<String> {
297 let modversion = Command::new("pkg-config")
298 .args(["--modversion", "nss"])
299 .output()
300 .expect("pkg-config reports NSS as absent")
301 .stdout;
302 let modversion = String::from_utf8(modversion).expect("non-UTF8 from pkg-config");
303 let modversion = modversion.trim();
304 // The NSS version number does not follow semver numbering, because it omits the patch version
305 // when that's 0. Deal with that.
306 let modversion_for_cmp = if modversion.chars().filter(|c| *c == '.').count() == 1 {
307 modversion.to_owned() + ".0"
308 } else {
309 modversion.to_owned()
310 };
311 let modversion_for_cmp =
312 Version::parse(&modversion_for_cmp).expect("NSS version not in semver format");
313 let version_req = VersionReq::parse(&format!(">={}", MINIMUM_NSS_VERSION.trim())).unwrap();
314 assert!(
315 version_req.matches(&modversion_for_cmp),
316 "neqo has NSS version requirement {version_req}, found {modversion}"
317 );
318
319 let cfg = Command::new("pkg-config")
320 .args(["--cflags", "--libs", "nss"])
321 .output()
322 .expect("NSS flags not returned by pkg-config")
323 .stdout;
324 let cfg_str = String::from_utf8(cfg).expect("non-UTF8 from pkg-config");
325
326 let mut flags: Vec<String> = Vec::new();
327 for f in cfg_str.split(' ') {
328 if let Some(include) = f.strip_prefix("-I") {
329 flags.push(String::from(f));
330 println!("cargo:include={include}");
331 } else if let Some(path) = f.strip_prefix("-L") {
332 println!("cargo:rustc-link-search=native={path}");
333 } else if let Some(lib) = f.strip_prefix("-l") {
334 println!("cargo:rustc-link-lib=dylib={lib}");
335 } else {
336 println!("Warning: Unknown flag from pkg-config: {f}");
337 }
338 }
339
340 flags
341 }
342
343 fn setup_standalone(nss: &str) -> Vec<String> {
344 setup_clang();
345
346 println!("cargo:rerun-if-env-changed=NSS_DIR");
347 let nss = PathBuf::from(nss);
348 assert!(
349 !nss.is_relative(),
350 "The NSS_DIR environment variable is expected to be an absolute path."
351 );
352
353 // $NSS_DIR/../dist/
354 let nssdist = nss.parent().unwrap().join("dist");
355 println!("cargo:rerun-if-env-changed=NSS_TARGET");
356 let nsstarget = env::var("NSS_TARGET")
357 .unwrap_or_else(|_| fs::read_to_string(nssdist.join("latest")).unwrap());
358
359 // If NSS_PREBUILT is set, we assume that the NSS libraries are already built.
360 if env::var("NSS_PREBUILT").is_err() {
361 build_nss(nss, &nsstarget);
362 }
363
364 let nsstarget = nssdist.join(nsstarget.trim());
365 let includes = get_includes(&nsstarget, &nssdist);
366
367 let nsslibdir = nsstarget.join("lib");
368 println!(
369 "cargo:rustc-link-search=native={}",
370 nsslibdir.to_str().unwrap()
371 );
372 if env::var("CARGO_CFG_FUZZING").is_ok()
373 || env::var("PROFILE").unwrap_or_default() == "debug"
374 // FIXME: NSPR doesn't build proper dynamic libraries on Windows.
375 || env::consts::OS == "windows"
376 {
377 static_link();
378 } else {
379 dynamic_link();
380 }
381
382 let mut flags: Vec<String> = Vec::new();
383 for i in includes {
384 flags.push(String::from("-I") + i.to_str().unwrap());
385 }
386
387 flags
388 }
389
390 #[cfg(feature = "gecko")]
391 fn setup_for_gecko() -> Vec<String> {
392 use mozbuild::{
393 config::{BINDGEN_SYSTEM_FLAGS, NSPR_CFLAGS, NSS_CFLAGS},
394 TOPOBJDIR,
395 };
396
397 let fold_libs = mozbuild::config::MOZ_FOLD_LIBS;
398 let libs = if fold_libs {
399 vec!["nss3"]
400 } else {
401 vec!["nssutil3", "nss3", "ssl3", "plds4", "plc4", "nspr4"]
402 };
403
404 for lib in &libs {
405 println!("cargo:rustc-link-lib=dylib={}", lib);
406 }
407
408 if fold_libs {
409 println!(
410 "cargo:rustc-link-search=native={}",
411 TOPOBJDIR.join("security").to_str().unwrap()
412 );
413 } else {
414 println!(
415 "cargo:rustc-link-search=native={}",
416 TOPOBJDIR.join("dist").join("bin").to_str().unwrap()
417 );
418 let nsslib_path = TOPOBJDIR.join("security").join("nss").join("lib");
419 println!(
420 "cargo:rustc-link-search=native={}",
421 nsslib_path.join("nss").join("nss_nss3").to_str().unwrap()
422 );
423 println!(
424 "cargo:rustc-link-search=native={}",
425 nsslib_path.join("ssl").join("ssl_ssl3").to_str().unwrap()
426 );
427 println!(
428 "cargo:rustc-link-search=native={}",
429 TOPOBJDIR
430 .join("config")
431 .join("external")
432 .join("nspr")
433 .join("pr")
434 .to_str()
435 .unwrap()
436 );
437 }
438
439 let mut flags = BINDGEN_SYSTEM_FLAGS
440 .iter()
441 .chain(&NSPR_CFLAGS)
442 .chain(&NSS_CFLAGS)
443 .map(|s| s.to_string())
444 .collect::<Vec<_>>();
445
446 flags.push(String::from("-include"));
447 flags.push(
448 TOPOBJDIR
449 .join("dist")
450 .join("include")
451 .join("mozilla-config.h")
452 .to_str()
453 .unwrap()
454 .to_string(),
455 );
456 flags
457 }
458
459 #[cfg(not(feature = "gecko"))]
460 fn setup_for_gecko() -> Vec<String> {
461 unreachable!()
462 }
463
464 fn main() {
465 println!("cargo:rustc-check-cfg=cfg(nss_nodb)");
466 let flags = if cfg!(feature = "gecko") {
467 setup_for_gecko()
468 } else if let Ok(nss_dir) = env::var("NSS_DIR") {
469 setup_standalone(nss_dir.trim())
470 } else {
471 pkg_config()
472 };
473
474 let config_file = PathBuf::from(BINDINGS_DIR).join(BINDINGS_CONFIG);
475 println!("cargo:rerun-if-changed={}", config_file.to_str().unwrap());
476 let config = fs::read_to_string(config_file).expect("unable to read binding configuration");
477 let config: HashMap<String, Bindings> = ::toml::from_str(&config).unwrap();
478
479 for (k, v) in &config {
480 build_bindings(k, v, &flags[..], cfg!(feature = "gecko"));
481 }
482 }