forked from cloudflare/boring
-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathbuild.rs
462 lines (417 loc) · 15.4 KB
/
build.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
use std::path::{Path, PathBuf};
use std::process::Command;
// NOTE: this build script is adopted from quiche (https://github.com/cloudflare/quiche)
// Additional parameters for Android build of BoringSSL.
//
// Android NDK < 18 with GCC.
const CMAKE_PARAMS_ANDROID_NDK_OLD_GCC: &[(&str, &[(&str, &str)])] = &[
(
"aarch64",
&[("ANDROID_TOOLCHAIN_NAME", "aarch64-linux-android-4.9")],
),
(
"arm",
&[("ANDROID_TOOLCHAIN_NAME", "arm-linux-androideabi-4.9")],
),
(
"x86",
&[("ANDROID_TOOLCHAIN_NAME", "x86-linux-android-4.9")],
),
(
"x86_64",
&[("ANDROID_TOOLCHAIN_NAME", "x86_64-linux-android-4.9")],
),
];
// Android NDK >= 19.
const CMAKE_PARAMS_ANDROID_NDK: &[(&str, &[(&str, &str)])] = &[
("aarch64", &[("ANDROID_ABI", "arm64-v8a")]),
("arm", &[("ANDROID_ABI", "armeabi-v7a")]),
("x86", &[("ANDROID_ABI", "x86")]),
("x86_64", &[("ANDROID_ABI", "x86_64")]),
];
fn cmake_params_android() -> &'static [(&'static str, &'static str)] {
let arch = std::env::var("CARGO_CFG_TARGET_ARCH").unwrap();
let cmake_params_android = if cfg!(feature = "ndk-old-gcc") {
CMAKE_PARAMS_ANDROID_NDK_OLD_GCC
} else {
CMAKE_PARAMS_ANDROID_NDK
};
for (android_arch, params) in cmake_params_android {
if *android_arch == arch {
return *params;
}
}
&[]
}
const CMAKE_PARAMS_IOS: &[(&str, &[(&str, &str)])] = &[
(
"aarch64-apple-ios",
&[
("CMAKE_OSX_ARCHITECTURES", "arm64"),
("CMAKE_OSX_SYSROOT", "iphoneos"),
],
),
(
"aarch64-apple-ios-sim",
&[
("CMAKE_OSX_ARCHITECTURES", "arm64"),
("CMAKE_OSX_SYSROOT", "iphonesimulator"),
],
),
(
"x86_64-apple-ios",
&[
("CMAKE_OSX_ARCHITECTURES", "x86_64"),
("CMAKE_OSX_SYSROOT", "iphonesimulator"),
],
),
];
fn cmake_params_ios() -> &'static [(&'static str, &'static str)] {
let target = std::env::var("TARGET").unwrap();
for (ios_target, params) in CMAKE_PARAMS_IOS {
if *ios_target == target {
return *params;
}
}
&[]
}
fn get_ios_sdk_name() -> &'static str {
for (name, value) in cmake_params_ios() {
if *name == "CMAKE_OSX_SYSROOT" {
return *value;
}
}
let target = std::env::var("TARGET").unwrap();
panic!("cannot find iOS SDK for {} in CMAKE_PARAMS_IOS", target);
}
/// Returns the platform-specific output path for lib.
///
/// MSVC generator on Windows place static libs in a target sub-folder,
/// so adjust library location based on platform and build target.
/// See issue: https://github.com/alexcrichton/cmake-rs/issues/18
fn get_boringssl_platform_output_path() -> String {
if cfg!(target_env = "msvc") {
// Code under this branch should match the logic in cmake-rs
let debug_env_var = std::env::var("DEBUG").expect("DEBUG variable not defined in env");
let deb_info = match &debug_env_var[..] {
"false" => false,
"true" => true,
unknown => panic!("Unknown DEBUG={} env var.", unknown),
};
let opt_env_var =
std::env::var("OPT_LEVEL").expect("OPT_LEVEL variable not defined in env");
let subdir = match &opt_env_var[..] {
"0" => "Debug",
"1" | "2" | "3" => {
if deb_info {
"RelWithDebInfo"
} else {
"Release"
}
}
"s" | "z" => "MinSizeRel",
unknown => panic!("Unknown OPT_LEVEL={} env var.", unknown),
};
subdir.to_string()
} else {
"".to_string()
}
}
#[cfg(feature = "fips")]
const BORING_SSL_PATH: &str = "deps/boringssl-fips";
#[cfg(not(feature = "fips"))]
const BORING_SSL_PATH: &str = "deps/boringssl";
/// Returns a new cmake::Config for building BoringSSL.
///
/// It will add platform-specific parameters if needed.
fn get_boringssl_cmake_config() -> cmake::Config {
let arch = std::env::var("CARGO_CFG_TARGET_ARCH").unwrap();
let os = std::env::var("CARGO_CFG_TARGET_OS").unwrap();
let pwd = std::env::current_dir().unwrap();
let mut boringssl_cmake = cmake::Config::new(BORING_SSL_PATH);
// Add platform-specific parameters.
match os.as_ref() {
"android" => {
// We need ANDROID_NDK_HOME to be set properly.
println!("cargo:rerun-if-env-changed=ANDROID_NDK_HOME");
let android_ndk_home = std::env::var("ANDROID_NDK_HOME")
.expect("Please set ANDROID_NDK_HOME for Android build");
let android_ndk_home = std::path::Path::new(&android_ndk_home);
for (name, value) in cmake_params_android() {
eprintln!("android arch={} add {}={}", arch, name, value);
boringssl_cmake.define(name, value);
}
let toolchain_file = android_ndk_home.join("build/cmake/android.toolchain.cmake");
let toolchain_file = toolchain_file.to_str().unwrap();
eprintln!("android toolchain={}", toolchain_file);
boringssl_cmake.define("CMAKE_TOOLCHAIN_FILE", toolchain_file);
// 21 is the minimum level tested. You can give higher value.
boringssl_cmake.define("ANDROID_NATIVE_API_LEVEL", "21");
boringssl_cmake.define("ANDROID_STL", "c++_shared");
boringssl_cmake
}
"ios" => {
for (name, value) in cmake_params_ios() {
eprintln!("ios arch={} add {}={}", arch, name, value);
boringssl_cmake.define(name, value);
}
// Bitcode is always on.
let bitcode_cflag = "-fembed-bitcode";
// Hack for Xcode 10.1.
let target_cflag = if arch == "x86_64" {
"-target x86_64-apple-ios-simulator"
} else {
""
};
let cflag = format!("{} {}", bitcode_cflag, target_cflag);
boringssl_cmake.define("CMAKE_ASM_FLAGS", &cflag);
boringssl_cmake.cflag(&cflag);
boringssl_cmake
}
_ => {
// Configure BoringSSL for building on 32-bit non-windows platforms.
if arch == "x86" && os != "windows" {
boringssl_cmake.define(
"CMAKE_TOOLCHAIN_FILE",
pwd.join(BORING_SSL_PATH)
.join("src/util/32-bit-toolchain.cmake")
.as_os_str(),
);
}
boringssl_cmake
}
}
}
/// Verify that the toolchains match https://csrc.nist.gov/CSRC/media/projects/cryptographic-module-validation-program/documents/security-policies/140sp3678.pdf
/// See "Installation Instructions" under section 12.1.
// TODO: maybe this should also verify the Go and Ninja versions? But those haven't been an issue in practice ...
fn verify_fips_clang_version() -> (&'static str, &'static str) {
fn version(tool: &str) -> String {
let output = match Command::new(tool).arg("--version").output() {
Ok(o) => o,
Err(e) => {
eprintln!("warning: missing {}, trying other compilers: {}", tool, e);
// NOTE: hard-codes that the loop below checks the version
return String::new();
}
};
assert!(output.status.success());
let output = std::str::from_utf8(&output.stdout).expect("invalid utf8 output");
output.lines().next().expect("empty output").to_string()
}
const REQUIRED_CLANG_VERSION: &str = "7.0.1";
for (cc, cxx) in [
("clang-7", "clang++-7"),
("clang", "clang++"),
("cc", "c++"),
] {
let cc_version = version(cc);
if cc_version.contains(REQUIRED_CLANG_VERSION) {
assert!(
version(cxx).contains(REQUIRED_CLANG_VERSION),
"mismatched versions of cc and c++"
);
return (cc, cxx);
} else if cc == "cc" {
panic!(
"unsupported clang version \"{}\": FIPS requires clang {}",
cc_version, REQUIRED_CLANG_VERSION
);
} else if !cc_version.is_empty() {
eprintln!(
"warning: FIPS requires clang version {}, skipping incompatible version \"{}\"",
REQUIRED_CLANG_VERSION, cc_version
);
}
}
unreachable!()
}
fn get_extra_clang_args_for_bindgen() -> Vec<String> {
let os = std::env::var("CARGO_CFG_TARGET_OS").unwrap();
let mut params = Vec::new();
// Add platform-specific parameters.
#[allow(clippy::single_match)]
match os.as_ref() {
"ios" => {
use std::io::Write;
// When cross-compiling for iOS, tell bindgen to use iOS sysroot,
// and *don't* use system headers of the host macOS.
let sdk = get_ios_sdk_name();
let output = std::process::Command::new("xcrun")
.args(["--show-sdk-path", "--sdk", sdk])
.output()
.unwrap();
if !output.status.success() {
if let Some(exit_code) = output.status.code() {
eprintln!("xcrun failed: exit code {}", exit_code);
} else {
eprintln!("xcrun failed: killed");
}
std::io::stderr().write_all(&output.stderr).unwrap();
// Uh... let's try anyway, I guess?
return params;
}
let mut sysroot = String::from_utf8(output.stdout).unwrap();
// There is typically a newline at the end which confuses clang.
sysroot.truncate(sysroot.trim_end().len());
params.push("-isysroot".to_string());
params.push(sysroot);
}
"android" => {
let android_ndk_home = std::env::var("ANDROID_NDK_HOME")
.expect("Please set ANDROID_NDK_HOME for Android build");
let mut android_sysroot = std::path::PathBuf::from(android_ndk_home);
android_sysroot.push("sysroot");
params.push("--sysroot".to_string());
// If ANDROID_NDK_HOME weren't a valid UTF-8 string,
// we'd already know from std::env::var.
params.push(android_sysroot.into_os_string().into_string().unwrap());
}
_ => {}
}
params
}
fn main() {
use std::env;
println!("cargo:rerun-if-env-changed=BORING_BSSL_PATH");
let bssl_dir = std::env::var("BORING_BSSL_PATH").unwrap_or_else(|_| {
if !Path::new(BORING_SSL_PATH).join("CMakeLists.txt").exists() {
println!("cargo:warning=fetching boringssl git submodule");
// fetch the boringssl submodule
let status = Command::new("git")
.args(&[
"submodule",
"update",
"--init",
"--recursive",
BORING_SSL_PATH,
])
.status();
if !status.map_or(false, |status| status.success()) {
panic!("failed to fetch submodule - consider running `git submodule update --init --recursive deps/boringssl` yourself");
}
}
let mut cfg = get_boringssl_cmake_config();
if cfg!(feature = "fuzzing") {
cfg.cxxflag("-DBORINGSSL_UNSAFE_DETERMINISTIC_MODE")
.cxxflag("-DBORINGSSL_UNSAFE_FUZZER_MODE");
}
if cfg!(feature = "fips") {
let (clang, clangxx) = verify_fips_clang_version();
cfg.define("CMAKE_C_COMPILER", clang);
cfg.define("CMAKE_CXX_COMPILER", clangxx);
cfg.define("CMAKE_ASM_COMPILER", clang);
cfg.define("FIPS", "1");
}
cfg.build_target("ssl").build();
cfg.build_target("crypto").build().display().to_string()
});
let build_path = get_boringssl_platform_output_path();
if cfg!(feature = "fips") {
println!(
"cargo:rustc-link-search=native={}/build/crypto/{}",
bssl_dir, build_path
);
println!(
"cargo:rustc-link-search=native={}/build/ssl/{}",
bssl_dir, build_path
);
} else {
println!(
"cargo:rustc-link-search=native={}/build/{}",
bssl_dir, build_path
);
}
println!("cargo:rustc-link-lib=static=crypto");
println!("cargo:rustc-link-lib=static=ssl");
// MacOS: Allow cdylib to link with undefined symbols
let target_os = std::env::var("CARGO_CFG_TARGET_OS").unwrap();
if target_os == "macos" {
println!("cargo:rustc-cdylib-link-arg=-Wl,-undefined,dynamic_lookup");
}
println!("cargo:rerun-if-env-changed=BORING_BSSL_INCLUDE_PATH");
let include_path = std::env::var("BORING_BSSL_INCLUDE_PATH").unwrap_or_else(|_| {
if cfg!(feature = "fips") {
format!("{}/include", BORING_SSL_PATH)
} else {
format!("{}/src/include", BORING_SSL_PATH)
}
});
let mut builder = bindgen::Builder::default()
.derive_copy(true)
.derive_debug(true)
.derive_default(true)
.derive_eq(true)
.default_enum_style(bindgen::EnumVariation::NewType { is_bitfield: false })
.default_macro_constant_type(bindgen::MacroTypeVariation::Signed)
.generate_comments(true)
.fit_macro_constants(false)
.size_t_is_usize(true)
.layout_tests(true)
.prepend_enum_name(true)
.rustfmt_bindings(true)
.clang_args(get_extra_clang_args_for_bindgen())
.clang_args(&["-I", &include_path]);
let target = std::env::var("TARGET").unwrap();
match target.as_ref() {
// bindgen produces alignment tests that cause undefined behavior [1]
// when applied to explicitly unaligned types like OSUnalignedU64.
//
// There is no way to disable these tests for only some types
// and it's not nice to suppress warnings for the entire crate,
// so let's disable all alignment tests and hope for the best.
//
// [1]: https://github.com/rust-lang/rust-bindgen/issues/1651
"aarch64-apple-ios" | "aarch64-apple-ios-sim" => {
builder = builder.layout_tests(false);
}
_ => {}
}
let headers = [
"aes.h",
"asn1_mac.h",
"asn1t.h",
#[cfg(not(feature = "fips"))]
"blake2.h",
"blowfish.h",
"cast.h",
"chacha.h",
"cmac.h",
"cpu.h",
"curve25519.h",
"des.h",
"dtls1.h",
"hkdf.h",
"hrss.h",
"md4.h",
"md5.h",
"obj_mac.h",
"objects.h",
"opensslv.h",
"ossl_typ.h",
"pkcs12.h",
"poly1305.h",
"rand.h",
"rc4.h",
"ripemd.h",
"siphash.h",
"srtp.h",
#[cfg(not(feature = "fips"))]
"trust_token.h",
"x509v3.h",
];
for header in &headers {
builder = builder.header(
Path::new(&include_path)
.join("openssl")
.join(header)
.to_str()
.unwrap(),
);
}
let bindings = builder.generate().expect("Unable to generate bindings");
let out_path = PathBuf::from(env::var("OUT_DIR").unwrap());
bindings
.write_to_file(out_path.join("bindings.rs"))
.expect("Couldn't write bindings!");
}