Debian Codegraph @

third_party/rust/ohttp/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 #![deny(clippy::pedantic)]
8
9 #[cfg(feature = "nss")]
10 mod nss {
11 use bindgen::Builder;
12 use serde_derive::Deserialize;
13 use std::{
14 collections::HashMap,
15 env, fs,
16 path::{Path, PathBuf},
17 process::Command,
18 };
19
20 const BINDINGS_DIR: &str = "bindings";
21 const BINDINGS_CONFIG: &str = "bindings.toml";
22
23 // This is the format of a single section of the configuration file.
24 #[derive(Deserialize)]
25 struct Bindings {
26 /// types that are explicitly included
27 #[serde(default)]
28 types: Vec<String>,
29 /// functions that are explicitly included
30 #[serde(default)]
31 functions: Vec<String>,
32 /// variables (and `#define`s) that are explicitly included
33 #[serde(default)]
34 variables: Vec<String>,
35 /// types that should be explicitly marked as opaque
36 #[serde(default)]
37 opaque: Vec<String>,
38 /// enumerations that are turned into a module (without this, the enum is
39 /// mapped using the default, which means that the individual values are
40 /// formed with an underscore as <enum_type>_<enum_value_name>).
41 #[serde(default)]
42 enums: Vec<String>,
43
44 /// Any item that is specifically excluded; if none of the types, functions,
45 /// or variables fields are specified, everything defined will be mapped,
46 /// so this can be used to limit that.
47 #[serde(default)]
48 exclude: Vec<String>,
49
50 /// Whether the file is to be interpreted as C++
51 #[serde(default)]
52 cplusplus: bool,
53 }
54
55 fn is_debug() -> bool {
56 env::var("DEBUG")
57 .map(|d| d.parse::<bool>().unwrap_or(false))
58 .unwrap_or(false)
59 }
60
61 // bindgen needs access to libclang.
62 // On windows, this doesn't just work, you have to set LIBCLANG_PATH.
63 // Rather than download the 400Mb+ files, like gecko does, let's just reuse their work.
64 fn setup_clang() {
65 if env::consts::OS != "windows" {
66 return;
67 }
68 println!("rerun-if-env-changed=LIBCLANG_PATH");
69 println!("rerun-if-env-changed=MOZBUILD_STATE_PATH");
70 if env::var("LIBCLANG_PATH").is_ok() {
71 return;
72 }
73 let mozbuild_root = if let Ok(dir) = env::var("MOZBUILD_STATE_PATH") {
74 PathBuf::from(dir.trim())
75 } else {
76 eprintln!("warning: Building without a gecko setup is not likely to work.");
77 eprintln!(" A working libclang is needed to build neqo.");
78 eprintln!(" Either LIBCLANG_PATH or MOZBUILD_STATE_PATH needs to be set.");
79 eprintln!();
80 eprintln!(" We recommend checking out https://github.com/mozilla/gecko-dev");
81 eprintln!(" Then run `./mach bootstrap` which will retrieve clang.");
82 eprintln!(" Make sure to export MOZBUILD_STATE_PATH when building.");
83 return;
84 };
85 let libclang_dir = mozbuild_root.join("clang").join("lib");
86 if libclang_dir.is_dir() {
87 env::set_var("LIBCLANG_PATH", libclang_dir.to_str().unwrap());
88 println!("rustc-env:LIBCLANG_PATH={}", libclang_dir.to_str().unwrap());
89 } else {
90 println!("warning: LIBCLANG_PATH isn't set; maybe run ./mach bootstrap with gecko");
91 }
92 }
93
94 fn nss_dir() -> Option<PathBuf> {
95 // Note that this returns a relative path because UNC
96 // paths on windows cause certain tools to explode.
97 env::var("NSS_DIR").ok().map(|dir| {
98 let dir = PathBuf::from(dir.trim());
99 assert!(dir.is_dir());
100 dir
101 })
102 }
103
104 fn get_bash() -> PathBuf {
105 // When running under MOZILLABUILD, we need to make sure not to invoke
106 // another instance of bash that might be sitting around (like WSL).
107 match env::var("MOZILLABUILD") {
108 Ok(d) => PathBuf::from(d).join("msys").join("bin").join("bash.exe"),
109 Err(_) => PathBuf::from("bash"),
110 }
111 }
112
113 fn run_build_script(dir: &Path) {
114 let mut build_nss = vec![
115 String::from("./build.sh"),
116 String::from("-Ddisable_tests=1"),
117 String::from("-Denable_draft_hpke=1"),
118 ];
119 if is_debug() {
120 build_nss.push(String::from("--static"));
121 } else {
122 build_nss.push(String::from("-o"));
123 }
124 if let Ok(d) = env::var("NSS_JOBS") {
125 build_nss.push(String::from("-j"));
126 build_nss.push(d);
127 }
128 let status = Command::new(get_bash())
129 .args(build_nss)
130 .current_dir(dir)
131 .status()
132 .expect("couldn't start NSS build");
133 assert!(status.success(), "NSS build failed");
134 }
135
136 fn nspr_libs() -> Vec<&'static str> {
137 if env::consts::OS == "windows" {
138 vec!["libplds4", "libplc4", "libnspr4"]
139 } else {
140 vec!["plds4", "plc4", "nspr4"]
141 }
142 }
143
144 fn dynamic_link() {
145 let mut libs = if env::consts::OS == "windows" {
146 vec!["nssutil3.dll", "nss3.dll"]
147 } else {
148 vec!["nssutil3", "nss3"]
149 };
150
151 libs.append(&mut nspr_libs());
152
153 for lib in &libs {
154 println!("cargo:rustc-link-lib=dylib={}", lib);
155 }
156 }
157
158 fn static_softoken_libs(nsslibdir: &Path) -> Vec<&'static str> {
159 let mut static_libs = vec!["pk11wrap_static", "softokn_static", "freebl_static"];
160
161 // NSS optionally builds platform-specific acceleration libraries as
162 // separate static libraries.
163 let accel_libs = &[
164 "gcm-aes-x86_c_lib",
165 "sha-x86_c_lib",
166 "hw-acc-crypto-avx",
167 "hw-acc-crypto-avx2",
168 "armv8_c_lib",
169 "gcm-aes-arm32-neon_c_lib",
170 "gcm-aes-aarch64_c_lib",
171 // NOTE: The intel-gcm-* libraries are already automatically
172 // included in freebl_static as source files.
173 ];
174
175 // Build rules are complex, so simply check the lib directory to see if
176 // any of the accelerator libraries were built to decide what to
177 // include. Check different variations of the filename to handle
178 // platform differences.
179 for libname in accel_libs {
180 let filename = if env::consts::OS == "windows" {
181 format!("{libname}.lib")
182 } else {
183 format!("lib{libname}.a")
184 };
185 if nsslibdir.join(filename).is_file() {
186 static_libs.push(libname);
187 }
188 }
189
190 static_libs
191 }
192
193 fn static_link(nsslibdir: &Path, use_static_softoken: bool, use_static_nspr: bool) {
194 let mut static_libs = vec![
195 "certdb",
196 "certhi",
197 "cryptohi",
198 "nss_static",
199 "nssb",
200 "nssdev",
201 "nsspki",
202 "nssutil",
203 ];
204 let mut dynamic_libs = vec![];
205
206 if use_static_softoken {
207 // Statically link pk11/softokn/freebl
208 static_libs.append(&mut static_softoken_libs(nsslibdir));
209 } else {
210 // Use dlopen to get softokn3.so
211 static_libs.push("pk11wrap");
212 }
213
214 if use_static_nspr {
215 static_libs.append(&mut nspr_libs());
216 } else {
217 dynamic_libs.append(&mut nspr_libs());
218 }
219
220 if cfg!(not(feature = "external-sqlite")) && env::consts::OS != "macos" {
221 static_libs.push("sqlite");
222 }
223
224 // Dynamic libs that aren't transitively included by NSS libs.
225 if env::consts::OS != "windows" {
226 dynamic_libs.extend_from_slice(&["pthread", "dl", "c", "z"]);
227 }
228 if cfg!(not(feature = "external-sqlite")) && env::consts::OS == "macos" {
229 dynamic_libs.push("sqlite3");
230 }
231
232 for lib in &static_libs {
233 println!("cargo:rustc-link-lib=static={}", lib);
234 }
235 for lib in &dynamic_libs {
236 println!("cargo:rustc-link-lib=dylib={}", lib);
237 }
238 }
239
240 fn get_includes(nsstarget: &Path, nssdist: &Path) -> Vec<PathBuf> {
241 let nsprinclude = nsstarget.join("include").join("nspr");
242 let nssinclude = nssdist.join("public").join("nss");
243 let includes = vec![nsprinclude, nssinclude];
244 for i in &includes {
245 println!("cargo:include={}", i.to_str().unwrap());
246 }
247 includes
248 }
249
250 fn build_bindings(base: &str, bindings: &Bindings, flags: &[String]) {
251 let suffix = if bindings.cplusplus { ".hpp" } else { ".h" };
252 let header_path = PathBuf::from(BINDINGS_DIR).join(String::from(base) + suffix);
253 let header = header_path.to_str().unwrap();
254 let out = PathBuf::from(env::var("OUT_DIR").unwrap()).join(String::from(base) + ".rs");
255
256 println!("cargo:rerun-if-changed={}", header);
257
258 let mut builder = Builder::default().header(header);
259 builder = builder.generate_comments(false);
260 builder = builder.size_t_is_usize(true);
261
262 builder = builder.clang_arg("-v");
263
264 builder = builder.clang_arg("-DNO_NSPR_10_SUPPORT");
265 if env::consts::OS == "windows" {
266 builder = builder.clang_arg("-DWIN");
267 } else if env::consts::OS == "macos" {
268 builder = builder.clang_arg("-DDARWIN");
269 } else if env::consts::OS == "linux" {
270 builder = builder.clang_arg("-DLINUX");
271 } else if env::consts::OS == "android" {
272 builder = builder.clang_arg("-DLINUX");
273 builder = builder.clang_arg("-DANDROID");
274 }
275 if bindings.cplusplus {
276 builder = builder.clang_args(&["-x", "c++", "-std=c++11"]);
277 }
278
279 builder = builder.clang_args(flags);
280
281 // Apply the configuration.
282 for v in &bindings.types {
283 builder = builder.allowlist_type(v);
284 }
285 for v in &bindings.functions {
286 builder = builder.allowlist_function(v);
287 }
288 for v in &bindings.variables {
289 builder = builder.allowlist_var(v);
290 }
291 for v in &bindings.exclude {
292 builder = builder.blocklist_item(v);
293 }
294 for v in &bindings.opaque {
295 builder = builder.opaque_type(v);
296 }
297 for v in &bindings.enums {
298 builder = builder.constified_enum_module(v);
299 }
300
301 let bindings = builder.generate().expect("unable to generate bindings");
302 bindings
303 .write_to_file(out)
304 .expect("couldn't write bindings");
305 }
306
307 fn build_nss(nss: &Path) -> Vec<String> {
308 setup_clang();
309
310 run_build_script(nss);
311
312 // $NSS_DIR/../dist/
313 let nssdist = nss.parent().unwrap().join("dist");
314 println!("cargo:rerun-if-env-changed=NSS_TARGET");
315 let nsstarget = env::var("NSS_TARGET")
316 .unwrap_or_else(|_| fs::read_to_string(nssdist.join("latest")).unwrap());
317 let nsstarget = nssdist.join(nsstarget.trim());
318
319 let includes = get_includes(&nsstarget, &nssdist);
320
321 let nsslibdir = nsstarget.join("lib");
322 println!(
323 "cargo:rustc-link-search=native={}",
324 nsslibdir.to_str().unwrap()
325 );
326 if is_debug() {
327 let use_static_softoken = true;
328 let use_static_nspr = true;
329 static_link(&nsslibdir, use_static_softoken, use_static_nspr);
330 } else {
331 dynamic_link();
332 }
333
334 let mut flags: Vec<String> = Vec::new();
335 for i in includes {
336 flags.push(String::from("-I") + i.to_str().unwrap());
337 }
338
339 flags
340 }
341
342 fn pkg_config() -> Vec<String> {
343 let modversion = Command::new("pkg-config")
344 .args(&["--modversion", "nss"])
345 .output()
346 .expect("pkg-config reports NSS as absent")
347 .stdout;
348 let modversion_str = String::from_utf8(modversion).expect("non-UTF8 from pkg-config");
349 let mut v = modversion_str.split('.');
350 assert_eq!(
351 v.next(),
352 Some("3"),
353 "NSS version 3.62 or higher is needed (or set $NSS_DIR)"
354 );
355 if let Some(minor) = v.next() {
356 let minor = minor
357 .trim_end()
358 .parse::<u32>()
359 .expect("NSS minor version is not a number");
360 assert!(
361 minor >= 62,
362 "NSS version 3.62 or higher is needed (or set $NSS_DIR)",
363 );
364 }
365
366 let cfg = Command::new("pkg-config")
367 .args(&["--cflags", "--libs", "nss"])
368 .output()
369 .expect("NSS flags not returned by pkg-config")
370 .stdout;
371 let cfg_str = String::from_utf8(cfg).expect("non-UTF8 from pkg-config");
372
373 let mut flags: Vec<String> = Vec::new();
374 for f in cfg_str.split(' ') {
375 if let Some(include) = f.strip_prefix("-I") {
376 flags.push(String::from(f));
377 println!("cargo:include={}", include);
378 } else if let Some(path) = f.strip_prefix("-L") {
379 println!("cargo:rustc-link-search=native={}", path);
380 } else if let Some(lib) = f.strip_prefix("-l") {
381 println!("cargo:rustc-link-lib=dylib={}", lib);
382 } else {
383 println!("Warning: Unknown flag from pkg-config: {}", f);
384 }
385 }
386
387 flags
388 }
389
390 #[cfg(feature = "gecko")]
391 fn setup_for_gecko() -> Vec<String> {
392 use mozbuild::TOPOBJDIR;
393
394 let mut flags: Vec<String> = Vec::new();
395
396 let fold_libs = mozbuild::config::MOZ_FOLD_LIBS;
397 let libs = if fold_libs {
398 vec!["nss3"]
399 } else {
400 vec!["nssutil3", "nss3", "ssl3", "plds4", "plc4", "nspr4"]
401 };
402
403 for lib in &libs {
404 println!("cargo:rustc-link-lib=dylib={}", lib);
405 }
406
407 if fold_libs {
408 println!(
409 "cargo:rustc-link-search=native={}",
410 TOPOBJDIR.join("security").to_str().unwrap()
411 );
412 } else {
413 println!(
414 "cargo:rustc-link-search=native={}",
415 TOPOBJDIR.join("dist").join("bin").to_str().unwrap()
416 );
417 let nsslib_path = TOPOBJDIR.join("security").join("nss").join("lib");
418 println!(
419 "cargo:rustc-link-search=native={}",
420 nsslib_path.join("nss").join("nss_nss3").to_str().unwrap()
421 );
422 println!(
423 "cargo:rustc-link-search=native={}",
424 nsslib_path.join("ssl").join("ssl_ssl3").to_str().unwrap()
425 );
426 println!(
427 "cargo:rustc-link-search=native={}",
428 TOPOBJDIR
429 .join("config")
430 .join("external")
431 .join("nspr")
432 .join("pr")
433 .to_str()
434 .unwrap()
435 );
436 }
437
438 let flags_path = TOPOBJDIR.join("netwerk/socket/neqo/extra-bindgen-flags");
439
440 println!("cargo:rerun-if-changed={}", flags_path.to_str().unwrap());
441 flags = fs::read_to_string(flags_path)
442 .expect("Failed to read extra-bindgen-flags file")
443 .split_whitespace()
444 .map(std::borrow::ToOwned::to_owned)
445 .collect();
446
447 flags.push(String::from("-include"));
448 flags.push(
449 TOPOBJDIR
450 .join("dist")
451 .join("include")
452 .join("mozilla-config.h")
453 .to_str()
454 .unwrap()
455 .to_string(),
456 );
457 flags
458 }
459
460 #[cfg(not(feature = "gecko"))]
461 fn setup_for_gecko() -> Vec<String> {
462 unreachable!()
463 }
464
465 #[cfg(feature = "app-svc")]
466 fn setup_for_app_svc() -> Vec<String> {
467 // Locate the NSS libraries that application_services is using.
468 // NOTE: This directory has a slightly different layout than then normal
469 // 'dist' directory that NSS builds output.
470 let nss_dir = nss_dir().expect("NSS_DIR env must be set for app_svc builds");
471 if !nss_dir.exists() {
472 eprintln!(
473 "NSS_DIR path (obtained via `env`) does not exist: {}",
474 nss_dir.display()
475 );
476 panic!("It looks like NSS is not built. Please run `libs/verify-[platform]-environment.sh` in application-services first!");
477 }
478
479 let lib_dir = nss_dir.join("lib");
480 println!(
481 "cargo:rustc-link-search=native={}",
482 lib_dir.to_string_lossy()
483 );
484
485 // For app_svc builds, we use static linking of NSS.
486 let use_static_softoken = true;
487 let use_static_nspr = true;
488 static_link(&lib_dir, use_static_softoken, use_static_nspr);
489
490 let include_dir = nss_dir.join("include");
491 println!("cargo:include={}", include_dir.to_string_lossy());
492
493 vec![String::from("-I") + &include_dir.join("nss").to_string_lossy()]
494 }
495
496 #[cfg(not(feature = "app-svc"))]
497 fn setup_for_app_svc() -> Vec<String> {
498 unreachable!()
499 }
500
501 pub fn build() {
502 println!("cargo:rerun-if-env-changed=NSS_DIR");
503 let flags = if cfg!(feature = "gecko") {
504 setup_for_gecko()
505 } else if cfg!(feature = "app-svc") {
506 setup_for_app_svc()
507 } else {
508 nss_dir().map_or_else(pkg_config, |nss| build_nss(&nss))
509 };
510
511 let config_file = PathBuf::from(BINDINGS_DIR).join(BINDINGS_CONFIG);
512 println!("cargo:rerun-if-changed={}", config_file.to_str().unwrap());
513 let config = fs::read_to_string(config_file).expect("unable to read binding configuration");
514 let config: HashMap<String, Bindings> = ::toml::from_str(&config).unwrap();
515
516 for (k, v) in &config {
517 build_bindings(k, v, &flags[..]);
518 }
519 }
520 }
521
522 fn main() {
523 #[cfg(feature = "nss")]
524 nss::build();
525 }