Debian Codegraph @

third_party/rust/nss-gk-api/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 #![cfg_attr(feature = "deny-warnings", deny(warnings))]
8 #![warn(clippy::pedantic)]
9
10 use bindgen::Builder;
11 use serde_derive::Deserialize;
12 use std::collections::HashMap;
13 use std::collections::HashSet;
14 use std::env;
15 use std::fs;
16 use std::path::{Path, PathBuf};
17 use std::process::Command;
18
19 const BINDINGS_DIR: &str = "bindings";
20 const BINDINGS_CONFIG: &str = "bindings.toml";
21
22 // This is the format of a single section of the configuration file.
23 #[derive(Deserialize)]
24 struct Bindings {
25 /// types that are explicitly included
26 #[serde(default)]
27 types: Vec<String>,
28 /// functions that are explicitly included
29 #[serde(default)]
30 functions: Vec<String>,
31 /// variables (and `#define`s) that are explicitly included
32 #[serde(default)]
33 variables: Vec<String>,
34 /// types that should be explicitly marked as opaque
35 #[serde(default)]
36 opaque: Vec<String>,
37 /// enumerations that are turned into a module (without this, the enum is
38 /// mapped using the default, which means that the individual values are
39 /// formed with an underscore as <enum_type>_<enum_value_name>).
40 #[serde(default)]
41 enums: Vec<String>,
42
43 /// Any item that is specifically excluded; if none of the types, functions,
44 /// or variables fields are specified, everything defined will be mapped,
45 /// so this can be used to limit that.
46 #[serde(default)]
47 exclude: Vec<String>,
48
49 /// Whether the file is to be interpreted as C++
50 #[serde(default)]
51 cplusplus: bool,
52 }
53
54 fn is_debug() -> bool {
55 env::var("DEBUG")
56 .map(|d| d.parse::<bool>().unwrap_or(false))
57 .unwrap_or(false)
58 }
59
60 // bindgen needs access to libclang.
61 // On windows, this doesn't just work, you have to set LIBCLANG_PATH.
62 // Rather than download the 400Mb+ files, like gecko does, let's just reuse their work.
63 fn setup_clang() {
64 if env::consts::OS != "windows" {
65 return;
66 }
67 println!("rerun-if-env-changed=LIBCLANG_PATH");
68 println!("rerun-if-env-changed=MOZBUILD_STATE_PATH");
69 if env::var("LIBCLANG_PATH").is_ok() {
70 return;
71 }
72 let mozbuild_root = if let Ok(dir) = env::var("MOZBUILD_STATE_PATH") {
73 PathBuf::from(dir.trim())
74 } else {
75 eprintln!("warning: Building without a gecko setup is not likely to work.");
76 eprintln!(" A working libclang is needed to build nss-sys.");
77 eprintln!(" Either LIBCLANG_PATH or MOZBUILD_STATE_PATH needs to be set.");
78 eprintln!();
79 eprintln!(" We recommend checking out https://github.com/mozilla/gecko-dev");
80 eprintln!(" Then run `./mach bootstrap` which will retrieve clang.");
81 eprintln!(" Make sure to export MOZBUILD_STATE_PATH when building.");
82 return;
83 };
84 let libclang_dir = mozbuild_root.join("clang").join("lib");
85 if libclang_dir.is_dir() {
86 env::set_var("LIBCLANG_PATH", libclang_dir.to_str().unwrap());
87 println!("rustc-env:LIBCLANG_PATH={}", libclang_dir.to_str().unwrap());
88 } else {
89 println!("warning: LIBCLANG_PATH isn't set; maybe run ./mach bootstrap with gecko");
90 }
91 }
92
93 fn nss_dir() -> PathBuf {
94 let dir = if let Ok(dir) = env::var("NSS_DIR") {
95 let path = PathBuf::from(dir.trim());
96 assert!(
97 !path.is_relative(),
98 "The NSS_DIR environment variable is expected to be an absolute path."
99 );
100 path
101 } else {
102 let out_dir = env::var("OUT_DIR").unwrap();
103 let dir = Path::new(&out_dir).join("nss");
104 if !dir.exists() {
105 Command::new("hg")
106 .args(&[
107 "clone",
108 "https://hg.mozilla.org/projects/nss",
109 dir.to_str().unwrap(),
110 ])
111 .status()
112 .expect("can't clone nss");
113 }
114 let nspr_dir = Path::new(&out_dir).join("nspr");
115 if !nspr_dir.exists() {
116 Command::new("hg")
117 .args(&[
118 "clone",
119 "https://hg.mozilla.org/projects/nspr",
120 nspr_dir.to_str().unwrap(),
121 ])
122 .status()
123 .expect("can't clone nspr");
124 }
125 dir
126 };
127 assert!(dir.is_dir(), "NSS_DIR {:?} doesn't exist", dir);
128 // Note that this returns a relative path because UNC
129 // paths on windows cause certain tools to explode.
130 dir
131 }
132
133 fn get_bash() -> PathBuf {
134 // When running under MOZILLABUILD, we need to make sure not to invoke
135 // another instance of bash that might be sitting around (like WSL).
136 match env::var("MOZILLABUILD") {
137 Ok(d) => PathBuf::from(d).join("msys").join("bin").join("bash.exe"),
138 Err(_) => PathBuf::from("bash"),
139 }
140 }
141
142 fn build_nss(dir: PathBuf) {
143 let mut build_nss = vec![
144 String::from("./build.sh"),
145 String::from("-Ddisable_tests=1"),
146 ];
147 if is_debug() {
148 build_nss.push(String::from("--static"));
149 } else {
150 build_nss.push(String::from("-o"));
151 }
152 if let Ok(d) = env::var("NSS_JOBS") {
153 build_nss.push(String::from("-j"));
154 build_nss.push(d);
155 }
156 let status = Command::new(get_bash())
157 .args(build_nss)
158 .current_dir(dir)
159 .status()
160 .expect("couldn't start NSS build");
161 assert!(status.success(), "NSS build failed");
162 }
163
164 fn dynamic_link() {
165 let libs = if env::consts::OS == "windows" {
166 &["nssutil3.dll", "nss3.dll", "ssl3.dll"]
167 } else {
168 &["nssutil3", "nss3", "ssl3"]
169 };
170 dynamic_link_both(libs);
171 }
172
173 fn dynamic_link_both(extra_libs: &[&str]) {
174 let nspr_libs = if env::consts::OS == "windows" {
175 &["libplds4", "libplc4", "libnspr4"]
176 } else {
177 &["plds4", "plc4", "nspr4"]
178 };
179 for lib in nspr_libs.iter().chain(extra_libs) {
180 println!("cargo:rustc-link-lib=dylib={}", lib);
181 }
182 }
183
184 fn static_link() {
185 let mut static_libs = vec![
186 "certdb",
187 "certhi",
188 "cryptohi",
189 "freebl",
190 "nss_static",
191 "nssb",
192 "nssdev",
193 "nsspki",
194 "nssutil",
195 "pk11wrap",
196 "pkcs12",
197 "pkcs7",
198 "smime",
199 "softokn_static",
200 "ssl",
201 ];
202 if env::consts::OS != "macos" {
203 static_libs.push("sqlite");
204 }
205 for lib in static_libs {
206 println!("cargo:rustc-link-lib=static={}", lib);
207 }
208
209 // Dynamic libs that aren't transitively included by NSS libs.
210 let mut other_libs = Vec::new();
211 if env::consts::OS != "windows" {
212 other_libs.extend_from_slice(&["pthread", "dl", "c", "z"]);
213 }
214 if env::consts::OS == "macos" {
215 other_libs.push("sqlite3");
216 }
217 dynamic_link_both(&other_libs);
218 }
219
220 fn get_includes(nsstarget: &Path, nssdist: &Path) -> Vec<PathBuf> {
221 let nsprinclude = nsstarget.join("include").join("nspr");
222 let nssinclude = nssdist.join("public").join("nss");
223 let includes = vec![nsprinclude, nssinclude];
224 for i in &includes {
225 println!("cargo:include={}", i.to_str().unwrap());
226 }
227 includes
228 }
229
230 fn build_bindings(base: &str, bindings: &Bindings, flags: &[String], gecko: bool) {
231 let suffix = if bindings.cplusplus { ".hpp" } else { ".h" };
232 let header_path = PathBuf::from(BINDINGS_DIR).join(String::from(base) + suffix);
233 let header = header_path.to_str().unwrap();
234 let out = PathBuf::from(env::var("OUT_DIR").unwrap()).join(String::from(base) + ".rs");
235
236 println!("cargo:rerun-if-changed={}", header);
237
238 let mut builder = Builder::default().header(header);
239 builder = builder.generate_comments(false);
240 builder = builder.size_t_is_usize(true);
241
242 builder = builder.clang_arg("-v");
243
244 if !gecko {
245 builder = builder.clang_arg("-DNO_NSPR_10_SUPPORT");
246 if env::consts::OS == "windows" {
247 builder = builder.clang_arg("-DWIN");
248 } else if env::consts::OS == "macos" {
249 builder = builder.clang_arg("-DDARWIN");
250 } else if env::consts::OS == "linux" {
251 builder = builder.clang_arg("-DLINUX");
252 } else if env::consts::OS == "android" {
253 builder = builder.clang_arg("-DLINUX");
254 builder = builder.clang_arg("-DANDROID");
255 }
256 if bindings.cplusplus {
257 builder = builder.clang_args(&["-x", "c++", "-std=c++11"]);
258 }
259 }
260
261 builder = builder.clang_args(flags);
262
263 // Apply the configuration.
264 for v in &bindings.types {
265 builder = builder.allowlist_type(v);
266 }
267 for v in &bindings.functions {
268 builder = builder.allowlist_function(v);
269 }
270 for v in &bindings.variables {
271 builder = builder.allowlist_var(v);
272 }
273 for v in &bindings.exclude {
274 builder = builder.blocklist_item(v);
275 }
276 for v in &bindings.opaque {
277 builder = builder.opaque_type(v);
278 }
279 for v in &bindings.enums {
280 builder = builder.constified_enum_module(v);
281 }
282
283 let bindings = builder.generate().expect("unable to generate bindings");
284 bindings
285 .write_to_file(out)
286 .expect("couldn't write bindings");
287 }
288
289 fn setup_standalone() -> Vec<String> {
290 setup_clang();
291
292 let nss = nss_dir();
293 println!("cargo:rerun-if-env-changed={}", nss.display());
294
295 build_nss(nss.clone());
296
297 // $NSS_DIR/../dist/
298 let nssdist = nss.parent().unwrap().join("dist");
299 println!("cargo:rerun-if-env-changed={}", nssdist.display());
300
301 let nsstarget = env::var("NSS_TARGET")
302 .unwrap_or_else(|_| fs::read_to_string(nssdist.join("latest")).unwrap());
303 let nsstarget = nssdist.join(nsstarget.trim());
304
305 let includes = get_includes(&nsstarget, &nssdist);
306
307 let nsslibdir = nsstarget.join("lib");
308 println!(
309 "cargo:rustc-link-search=native={}",
310 nsslibdir.to_str().unwrap()
311 );
312 if is_debug() {
313 static_link();
314 } else {
315 dynamic_link();
316 }
317
318 let mut flags: Vec<String> = Vec::new();
319 for i in includes {
320 flags.push(String::from("-I") + i.to_str().unwrap());
321 }
322
323 flags
324 }
325
326 #[cfg(feature = "gecko")]
327 fn setup_for_gecko() -> Vec<String> {
328 use mozbuild::TOPOBJDIR;
329
330 let fold_libs = mozbuild::config::MOZ_FOLD_LIBS;
331 let libs = if fold_libs {
332 vec!["nss3"]
333 } else {
334 vec!["nssutil3", "nss3", "ssl3", "plds4", "plc4", "nspr4"]
335 };
336
337 for lib in &libs {
338 println!("cargo:rustc-link-lib=dylib={}", lib);
339 }
340
341 if fold_libs {
342 println!(
343 "cargo:rustc-link-search=native={}",
344 TOPOBJDIR.join("security").to_str().unwrap()
345 );
346 } else {
347 println!(
348 "cargo:rustc-link-search=native={}",
349 TOPOBJDIR.join("dist").join("bin").to_str().unwrap()
350 );
351 let nsslib_path = TOPOBJDIR.join("security").join("nss").join("lib");
352 println!(
353 "cargo:rustc-link-search=native={}",
354 nsslib_path.join("nss").join("nss_nss3").to_str().unwrap()
355 );
356 println!(
357 "cargo:rustc-link-search=native={}",
358 nsslib_path.join("ssl").join("ssl_ssl3").to_str().unwrap()
359 );
360 println!(
361 "cargo:rustc-link-search=native={}",
362 TOPOBJDIR
363 .join("config")
364 .join("external")
365 .join("nspr")
366 .join("pr")
367 .to_str()
368 .unwrap()
369 );
370 }
371
372 let flags_path = TOPOBJDIR.join("netwerk/socket/neqo/extra-bindgen-flags");
373
374 println!("cargo:rerun-if-changed={}", flags_path.to_str().unwrap());
375 let mut flags = fs::read_to_string(flags_path)
376 .expect("Failed to read extra-bindgen-flags file")
377 .split_whitespace()
378 .map(std::borrow::ToOwned::to_owned)
379 .collect::<Vec<String>>();
380
381 flags.push(String::from("-include"));
382 flags.push(
383 TOPOBJDIR
384 .join("dist")
385 .join("include")
386 .join("mozilla-config.h")
387 .to_str()
388 .unwrap()
389 .to_string(),
390 );
391 flags
392 }
393
394 #[cfg(not(feature = "gecko"))]
395 fn setup_for_gecko() -> Vec<String> {
396 unreachable!()
397 }
398
399 fn process_config(config: &mut HashMap<String, Bindings>) {
400 let mut excludes = HashMap::new();
401 for header in config.keys().cloned() {
402 // Collect the list of types, functions, and variables configured
403 // for generation in any other configured header, and add it to the list
404 // of items excluded from generation in this header. This ensures that
405 // each item only appears in one bindings module, which prevents some
406 // type conflicts. (However, it does mean that appropriate `use`
407 // declarations must be added for the generated modules.)
408 excludes.insert(
409 header.clone(),
410 config.iter().flat_map(|(h, b)| {
411 if *h != header {
412 vec![
413 &b.types,
414 &b.functions,
415 &b.variables,
416 ]
417 } else {
418 vec![]
419 }.into_iter().flat_map(|v| v.iter()).cloned()
420 }).collect::<HashSet<String>>()
421 );
422 }
423
424 for (header, excludes) in excludes.into_iter() {
425 config.get_mut(&header).expect("key disappeared from config?").exclude.extend(excludes.into_iter());
426 }
427 }
428
429 fn main() {
430 let flags = if cfg!(feature = "gecko") {
431 setup_for_gecko()
432 } else {
433 setup_standalone()
434 };
435
436 let config_file = PathBuf::from(BINDINGS_DIR).join(BINDINGS_CONFIG);
437 println!("cargo:rerun-if-changed={}", config_file.to_str().unwrap());
438 let config = fs::read_to_string(config_file).expect("unable to read binding configuration");
439 let mut config: HashMap<String, Bindings> = ::toml::from_str(&config).unwrap();
440 process_config(&mut config);
441
442 for (k, v) in &config {
443 build_bindings(k, v, &flags[..], cfg!(feature = "gecko"));
444 }
445 }