Debian Codegraph @

debian/rust-vendor/aws-lc-sys/builder/main.rs

raw
1 // Copyright (c) 2022, Google Inc.
2 // SPDX-License-Identifier: ISC
3 // Modifications copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
4 // SPDX-License-Identifier: Apache-2.0 OR ISC
5
6 // Needed until MSRV >= 1.70
7 #![allow(clippy::unnecessary_map_or)]
8 #![allow(clippy::ref_option)]
9 // Clippy can only be run on nightly toolchain
10 #![cfg_attr(clippy, feature(custom_inner_attributes))]
11 #![cfg_attr(clippy, clippy::msrv = "1.77")]
12
13 use std::ffi::{OsStr, OsString};
14 use std::fmt::Debug;
15 use std::path::{Path, PathBuf};
16 use std::process::Command;
17 use std::sync::OnceLock;
18 use std::{env, fmt};
19
20 use cc_builder::CcBuilder;
21 use cmake_builder::CmakeBuilder;
22
23 // These should generally match those found in aws-lc/include/openssl/opensslconf.h
24 const OSSL_CONF_DEFINES: &[&str] = &[
25 "OPENSSL_NO_ASYNC",
26 "OPENSSL_NO_BF",
27 "OPENSSL_NO_BLAKE2",
28 "OPENSSL_NO_BUF_FREELISTS",
29 "OPENSSL_NO_CAMELLIA",
30 "OPENSSL_NO_CAPIENG",
31 "OPENSSL_NO_CAST",
32 "OPENSSL_NO_CMS",
33 "OPENSSL_NO_COMP",
34 "OPENSSL_NO_CRYPTO_MDEBUG",
35 "OPENSSL_NO_CT",
36 "OPENSSL_NO_DANE",
37 "OPENSSL_NO_DEPRECATED",
38 "OPENSSL_NO_DGRAM",
39 "OPENSSL_NO_DYNAMIC_ENGINE",
40 "OPENSSL_NO_EC_NISTP_64_GCC_128",
41 "OPENSSL_NO_EC2M",
42 "OPENSSL_NO_EGD",
43 "OPENSSL_NO_ENGINE",
44 "OPENSSL_NO_GMP",
45 "OPENSSL_NO_GOST",
46 "OPENSSL_NO_HEARTBEATS",
47 "OPENSSL_NO_HW",
48 "OPENSSL_NO_IDEA",
49 "OPENSSL_NO_JPAKE",
50 "OPENSSL_NO_KRB5",
51 "OPENSSL_NO_MD2",
52 "OPENSSL_NO_MDC2",
53 "OPENSSL_NO_OCB",
54 "OPENSSL_NO_RC2",
55 "OPENSSL_NO_RC5",
56 "OPENSSL_NO_RFC3779",
57 "OPENSSL_NO_RIPEMD",
58 "OPENSSL_NO_RMD160",
59 "OPENSSL_NO_SCTP",
60 "OPENSSL_NO_SEED",
61 "OPENSSL_NO_SM2",
62 "OPENSSL_NO_SM3",
63 "OPENSSL_NO_SM4",
64 "OPENSSL_NO_SRP",
65 "OPENSSL_NO_SSL_TRACE",
66 "OPENSSL_NO_SSL2",
67 "OPENSSL_NO_SSL3",
68 "OPENSSL_NO_SSL3_METHOD",
69 "OPENSSL_NO_STATIC_ENGINE",
70 "OPENSSL_NO_STORE",
71 "OPENSSL_NO_TS",
72 "OPENSSL_NO_WHIRLPOOL",
73 ];
74
75 mod cc_builder;
76 mod cmake_builder;
77 mod nasm_builder;
78 #[cfg(any(feature = "bindgen", feature = "fips"))]
79 mod sys_bindgen;
80
81 pub(crate) struct EnvGuard {
82 key: String,
83 original_value: Option<String>,
84 }
85
86 impl EnvGuard {
87 fn new<T: AsRef<OsStr>>(key: &str, new_value: T) -> Self {
88 let original_value = env::var(key).ok();
89 env::set_var(key, new_value);
90 Self {
91 key: key.to_string(),
92 original_value,
93 }
94 }
95 }
96
97 impl Drop for EnvGuard {
98 fn drop(&mut self) {
99 if let Some(ref value) = self.original_value {
100 env::set_var(&self.key, value);
101 } else {
102 env::remove_var(&self.key);
103 }
104 }
105 }
106
107 fn is_fips_build() -> bool {
108 is_fips_crate() || cfg!(feature = "fips")
109 }
110
111 fn is_fips_crate() -> bool {
112 crate_name().contains("fips")
113 }
114
115 fn is_all_bindings() -> bool {
116 is_fips_crate() || env::var("CARGO_FEATURE_ALL_BINDINGS").is_ok()
117 }
118
119 fn is_prebuilt_nasm() -> bool {
120 !is_fips_build() && env::var("CARGO_FEATURE_PREBUILT_NASM").is_ok()
121 }
122
123 fn is_disable_prebuilt_nasm() -> bool {
124 is_fips_build() || env::var("CARGO_FEATURE_DISABLE_PREBUILT_NASM").is_ok()
125 }
126
127 pub(crate) fn get_aws_lc_include_path(manifest_dir: &Path) -> PathBuf {
128 manifest_dir.join("aws-lc").join("include")
129 }
130
131 pub(crate) fn get_rust_include_path(manifest_dir: &Path) -> PathBuf {
132 manifest_dir.join("include")
133 }
134
135 pub(crate) fn get_generated_include_path(manifest_dir: &Path) -> PathBuf {
136 manifest_dir.join("generated-include")
137 }
138
139 #[allow(unknown_lints)]
140 #[allow(static_mut_refs)]
141 pub(crate) fn get_env_includes_path() -> Option<Vec<PathBuf>> {
142 unsafe { SYS_INCLUDES.clone() }
143 }
144
145 #[allow(dead_code)]
146 #[derive(Clone, Copy, PartialEq, Eq)]
147 enum OutputLib {
148 Crypto,
149 Ssl,
150 }
151
152 #[allow(dead_code)]
153 #[derive(Clone, Copy, PartialEq, Eq)]
154 enum OutputLibType {
155 Static,
156 Dynamic,
157 }
158
159 fn cargo_env<N: AsRef<str>>(name: N) -> String {
160 let name = name.as_ref();
161 env::var(name).unwrap_or_else(|_| panic!("missing env var {name:?}"))
162 }
163
164 fn env_name_for_target<K: AsRef<OsStr>>(env_var: K) -> String {
165 let target = target().to_lowercase();
166 let target = target.replace('-', "_");
167 format!("{}_{target}", env_var.as_ref().to_str().unwrap())
168 }
169
170 // "CFLAGS" =>
171 // "SYS_CFLAGS_aarch64_unknown_linux_gnu" OR "SYS_CFLAGS"
172 // OR "CFLAGS_aarch64_unknown_linux_gnu" OR "CFLAGS"
173 fn optional_env_optional_crate_target<N: AsRef<str>>(name: N) -> Option<String> {
174 let name = name.as_ref();
175 optional_env_crate_target(name).or(optional_env_target(name))
176 }
177
178 // "EFFECTIVE_TARGET" => "SYS_EFFECTIVE_TARGET_aarch64_unknown_linux_gnu" + "SYS_EFFECTIVE_TARGET"
179 fn optional_env_crate_target<N: AsRef<str>>(name: N) -> Option<String> {
180 let name = name.as_ref();
181 let crate_name = crate_name().to_uppercase().replace('-', "_");
182 let name_for_crate = format!("{crate_name}_{name}");
183 let name_for_crate_target = env_name_for_target(&name_for_crate);
184 optional_env(name_for_crate_target).or(optional_env(name_for_crate))
185 }
186
187 fn optional_env_target<N: AsRef<str>>(name: N) -> Option<String> {
188 let name_for_target = env_name_for_target(name.as_ref());
189 optional_env(name_for_target).or(optional_env(name))
190 }
191
192 fn optional_env<N: AsRef<str>>(name: N) -> Option<String> {
193 let name = name.as_ref();
194 println!("cargo:rerun-if-env-changed={name}");
195 if let Ok(value) = env::var(name) {
196 emit_warning(format!("Environment Variable found '{name}': '{value}'"));
197 return Some(value);
198 }
199 None
200 }
201
202 fn set_env_for_target<K, V>(env_var: K, value: V)
203 where
204 K: AsRef<OsStr>,
205 V: AsRef<OsStr>,
206 {
207 let env_var = env_name_for_target(env_var);
208 #[allow(unused_unsafe)]
209 unsafe {
210 env::set_var(&env_var, &value);
211 }
212 emit_warning(format!(
213 "Setting {env_var}: {}",
214 value.as_ref().to_str().unwrap()
215 ));
216 }
217
218 fn set_env<K, V>(env_var: K, value: V)
219 where
220 K: AsRef<OsStr>,
221 V: AsRef<OsStr>,
222 {
223 #[allow(unused_unsafe)]
224 unsafe {
225 env::set_var(&env_var, &value);
226 }
227 emit_warning(format!(
228 "Setting {}: {}",
229 env_var.as_ref().to_str().unwrap(),
230 value.as_ref().to_str().unwrap()
231 ));
232 }
233
234 fn env_var_to_bool(name: &str) -> Option<bool> {
235 if let Some(value) = optional_env(name) {
236 return parse_to_bool(&value);
237 }
238 None
239 }
240
241 fn env_crate_var_to_bool(name: &str) -> Option<bool> {
242 if let Some(value) = optional_env_crate_target(name) {
243 return parse_to_bool(&value);
244 }
245 None
246 }
247
248 fn parse_to_bool(env_var_value: &str) -> Option<bool> {
249 let env_var_value = env_var_value.to_lowercase();
250 if env_var_value.starts_with('0')
251 || env_var_value.starts_with('n')
252 || env_var_value.starts_with("off")
253 || env_var_value.starts_with('f')
254 {
255 emit_warning(format!("Value: {env_var_value} is false."));
256 return Some(false);
257 }
258 if env_var_value.starts_with(|c: char| c.is_ascii_digit())
259 || env_var_value.starts_with('y')
260 || env_var_value.starts_with("on")
261 || env_var_value.starts_with('t')
262 {
263 emit_warning(format!("Value: {env_var_value} is true."));
264 return Some(true);
265 }
266 None
267 }
268
269 impl Default for OutputLibType {
270 fn default() -> Self {
271 if let Some(stc_lib) = env_crate_var_to_bool("STATIC") {
272 if stc_lib {
273 OutputLibType::Static
274 } else {
275 OutputLibType::Dynamic
276 }
277 } else if !is_fips_build()
278 || (is_fips_build()
279 && (target_os() == "linux" || target_os().ends_with("bsd"))
280 && (target_arch() == "x86_64" || target_arch() == "aarch64"))
281 {
282 OutputLibType::Static
283 } else {
284 OutputLibType::Dynamic
285 }
286 }
287 }
288
289 impl OutputLibType {
290 fn rust_lib_type(&self) -> &str {
291 match self {
292 OutputLibType::Static => "static",
293 OutputLibType::Dynamic => "dylib",
294 }
295 }
296 }
297
298 impl OutputLib {
299 fn libname(self, prefix: &Option<String>) -> String {
300 let name = match self {
301 OutputLib::Crypto => "crypto",
302 OutputLib::Ssl => "ssl",
303 };
304 if let Some(prefix) = prefix {
305 format!("{prefix}_{name}")
306 } else {
307 name.to_string()
308 }
309 }
310 }
311
312 const VERSION: &str = env!("CARGO_PKG_VERSION");
313
314 fn prefix_string() -> String {
315 format!(
316 "aws_lc{}_{}",
317 if is_fips_crate() { "_fips" } else { "" },
318 VERSION.to_string().replace('.', "_")
319 )
320 }
321
322 fn target_has_prefixed_symbols() -> bool {
323 target_vendor() == "apple" || (target_arch() == "x86" && target_os() == "windows")
324 }
325
326 fn is_cranelift_backend() -> bool {
327 // CARGO_ENCODED_RUSTFLAGS contains flags separated by 0x1f (ASCII Unit Separator)
328 if let Some(rustflags) = optional_env("CARGO_ENCODED_RUSTFLAGS") {
329 for flag in rustflags.split('\x1f') {
330 if flag.contains("codegen-backend") && flag.contains("cranelift") {
331 return true;
332 }
333 }
334 }
335 false
336 }
337
338 fn target_chokes_on_u1() -> bool {
339 target_arch() == "mips" || target_arch() == "mips64" || is_cranelift_backend()
340 }
341
342 #[cfg(any(feature = "bindgen", feature = "fips"))]
343 fn target_platform_prefix(name: &str) -> String {
344 if is_all_bindings() {
345 format!("{}_{}", effective_target().replace('-', "_"), name)
346 } else if target_has_prefixed_symbols() {
347 format!("universal_prefixed_{}", name.replace('-', "_"))
348 } else {
349 format!("universal_{}", name.replace('-', "_"))
350 }
351 }
352
353 pub(crate) struct TestCommandResult {
354 #[allow(dead_code)]
355 stderr: Box<str>,
356 #[allow(dead_code)]
357 stdout: Box<str>,
358 executed: bool,
359 status: bool,
360 }
361
362 const MAX_CMD_OUTPUT_SIZE: usize = 1 << 15;
363 fn execute_command(executable: &OsStr, args: &[&OsStr]) -> TestCommandResult {
364 if let Ok(mut result) = Command::new(executable).args(args).output() {
365 result.stderr.truncate(MAX_CMD_OUTPUT_SIZE);
366 let stderr = String::from_utf8(result.stderr)
367 .unwrap_or_default()
368 .into_boxed_str();
369 result.stdout.truncate(MAX_CMD_OUTPUT_SIZE);
370 let stdout = String::from_utf8(result.stdout)
371 .unwrap_or_default()
372 .into_boxed_str();
373 return TestCommandResult {
374 stderr,
375 stdout,
376 executed: true,
377 status: result.status.success(),
378 };
379 }
380 TestCommandResult {
381 stderr: String::new().into_boxed_str(),
382 stdout: String::new().into_boxed_str(),
383 executed: false,
384 status: false,
385 }
386 }
387
388 #[cfg(any(feature = "bindgen", feature = "fips"))]
389 fn generate_bindings(manifest_dir: &Path, prefix: &Option<String>, bindings_path: &PathBuf) {
390 let options = BindingOptions {
391 build_prefix: prefix.clone(),
392 include_ssl: cfg!(feature = "ssl"),
393 disable_prelude: true,
394 };
395
396 let bindings = sys_bindgen::generate_bindings(manifest_dir, &options);
397
398 bindings
399 .write(Box::new(std::fs::File::create(bindings_path).unwrap()))
400 .expect("written bindings");
401 }
402
403 #[cfg(any(feature = "bindgen", feature = "fips"))]
404 fn generate_src_bindings(manifest_dir: &Path, prefix: &Option<String>, src_bindings_path: &Path) {
405 sys_bindgen::generate_bindings(
406 manifest_dir,
407 &BindingOptions {
408 build_prefix: prefix.clone(),
409 include_ssl: false,
410 ..Default::default()
411 },
412 )
413 .write_to_file(src_bindings_path)
414 .expect("write bindings");
415 }
416
417 fn emit_rustc_cfg(cfg: &str) {
418 let cfg = cfg.replace('-', "_");
419 emit_warning(format!("Emitting configuration: cargo:rustc-cfg={cfg}"));
420 println!("cargo:rustc-cfg={cfg}");
421 }
422
423 fn emit_warning<T: AsRef<str>>(message: T) {
424 println!("cargo:warning={}", message.as_ref());
425 }
426
427 #[allow(dead_code)]
428 fn target_family() -> String {
429 cargo_env("CARGO_CFG_TARGET_FAMILY")
430 }
431
432 fn target_os() -> String {
433 cargo_env("CARGO_CFG_TARGET_OS")
434 }
435
436 fn target_arch() -> String {
437 cargo_env("CARGO_CFG_TARGET_ARCH")
438 }
439
440 #[allow(unused)]
441 fn target_env() -> String {
442 cargo_env("CARGO_CFG_TARGET_ENV")
443 }
444
445 #[allow(unused)]
446 fn target_vendor() -> String {
447 cargo_env("CARGO_CFG_TARGET_VENDOR")
448 }
449
450 fn target() -> String {
451 cargo_env("TARGET")
452 }
453
454 fn crate_name() -> String {
455 cargo_env("CARGO_PKG_NAME")
456 }
457
458 fn effective_target() -> String {
459 #[allow(unknown_lints)]
460 #[allow(static_mut_refs)]
461 unsafe {
462 if !SYS_EFFECTIVE_TARGET.is_empty() {
463 return SYS_EFFECTIVE_TARGET.clone();
464 }
465 }
466 let target = target();
467 match target.as_str() {
468 "x86_64-alpine-linux-musl" => "x86_64-unknown-linux-musl".to_string(),
469 "aarch64-alpine-linux-musl" => "aarch64-unknown-linux-musl".to_string(),
470 _ => target,
471 }
472 }
473
474 #[allow(unused)]
475 fn target_underscored() -> String {
476 effective_target().replace('-', "_")
477 }
478
479 fn out_dir() -> PathBuf {
480 let out = PathBuf::from(cargo_env("OUT_DIR"));
481 #[cfg(windows)]
482 let out = to_short_path(&out);
483 out
484 }
485
486 /// On Windows, convert a path to its 8.3 short form to avoid MAX_PATH (260 char) limits
487 /// when cl.exe is invoked with deeply nested source trees (e.g. Bazel runfiles).
488 #[cfg(windows)]
489 fn to_short_path(path: &Path) -> PathBuf {
490 use std::os::windows::ffi::{OsStrExt, OsStringExt};
491 extern "system" {
492 fn GetShortPathNameW(
493 lpszLongPath: *const u16,
494 lpszShortPath: *mut u16,
495 cchBuffer: u32,
496 ) -> u32;
497 }
498 let wide: Vec<u16> = path
499 .as_os_str()
500 .encode_wide()
501 .chain(std::iter::once(0))
502 .collect();
503 let len = unsafe { GetShortPathNameW(wide.as_ptr(), std::ptr::null_mut(), 0) };
504 if len == 0 {
505 return path.to_path_buf();
506 }
507 let mut buf = vec![0u16; len as usize];
508 let result = unsafe { GetShortPathNameW(wide.as_ptr(), buf.as_mut_ptr(), len) };
509 if result == 0 {
510 return path.to_path_buf();
511 }
512 buf.truncate(result as usize);
513 let short_path = PathBuf::from(std::ffi::OsString::from_wide(&buf));
514
515 const MAX_PATH: usize = 260;
516 let original_len = wide.len() - 1;
517 if original_len >= MAX_PATH && (result as usize) >= MAX_PATH {
518 emit_warning(format!(
519 "Path length ({}) exceeds MAX_PATH ({}) and 8.3 short name conversion was ineffective. \
520 8.3 short names may be disabled on this volume. \
521 See: https://learn.microsoft.com/en-us/windows-server/administration/windows-commands/fsutil-8dot3name",
522 original_len, MAX_PATH,
523 ));
524 }
525
526 short_path
527 }
528
529 fn current_dir() -> PathBuf {
530 std::env::current_dir().unwrap()
531 }
532
533 fn get_builder(prefix: &Option<String>, manifest_dir: &Path, out_dir: &Path) -> Box<dyn Builder> {
534 let cmake_builder_builder = || {
535 Box::new(CmakeBuilder::new(
536 manifest_dir.to_path_buf(),
537 out_dir.to_path_buf(),
538 prefix.clone(),
539 OutputLibType::default(),
540 ))
541 };
542
543 if is_fips_build() {
544 return cmake_builder_builder();
545 }
546
547 let cc_builder_builder = || {
548 Box::new(CcBuilder::new(
549 manifest_dir.to_path_buf(),
550 out_dir.to_path_buf(),
551 prefix.clone(),
552 OutputLibType::default(),
553 ))
554 };
555
556 if let Some(val) = is_cmake_builder() {
557 let builder: Box<dyn Builder> = if val {
558 cmake_builder_builder()
559 } else {
560 cc_builder_builder()
561 };
562 builder.check_dependencies().unwrap();
563 return builder;
564 } else if is_no_asm() || sanitizer().is_some() {
565 let builder = cmake_builder_builder();
566 builder.check_dependencies().unwrap();
567 return builder;
568 } else if !is_bindgen_required() {
569 let cc_builder = cc_builder_builder();
570 if cc_builder.check_dependencies().is_ok() {
571 return cc_builder;
572 }
573 }
574 let cmake_builder = cmake_builder_builder();
575 cmake_builder.check_dependencies().unwrap();
576 cmake_builder
577 }
578
579 trait Builder {
580 fn check_dependencies(&self) -> Result<(), String>;
581 fn build(&self) -> Result<(), String>;
582 fn name(&self) -> &str;
583 }
584
585 #[derive(Clone, Copy, Debug, PartialEq, Eq)]
586 pub(crate) enum CStdRequested {
587 C99,
588 C11,
589 None,
590 }
591
592 impl CStdRequested {
593 fn from_env() -> Self {
594 if let Some(val) = optional_env_crate_target("C_STD") {
595 let cstd = match val.as_str() {
596 "99" => CStdRequested::C99,
597 "11" => CStdRequested::C11,
598 _ => CStdRequested::None,
599 };
600 emit_warning(format!("SYS_C_STD environment variable set: {cstd:?}"));
601 return cstd;
602 }
603 CStdRequested::None
604 }
605 }
606
607 static mut PREGENERATED: bool = false;
608 static mut SYS_NO_PREFIX: bool = false;
609 static mut SYS_PREGENERATING_BINDINGS: bool = false;
610 static mut SYS_EXTERNAL_BINDGEN: Option<bool> = None;
611 static mut SYS_NO_ASM: bool = false;
612 static mut SYS_PREBUILT_NASM: Option<bool> = None;
613 static mut SYS_CMAKE_BUILDER: Option<bool> = None;
614 static mut SYS_NO_PREGENERATED_SRC: bool = false;
615 static mut SYS_EFFECTIVE_TARGET: String = String::new();
616 static mut SYS_NO_JITTER_ENTROPY: Option<bool> = None;
617 static mut SYS_NO_U1_BINDINGS: Option<bool> = None;
618 static mut SYS_INCLUDES: Option<Vec<PathBuf>> = None;
619 static mut SYS_SANITIZER: Option<String> = None;
620
621 static mut SYS_C_STD: CStdRequested = CStdRequested::None;
622
623 fn initialize() {
624 unsafe {
625 SYS_NO_PREFIX = env_crate_var_to_bool("NO_PREFIX").unwrap_or(false);
626 SYS_PREGENERATING_BINDINGS =
627 env_crate_var_to_bool("PREGENERATING_BINDINGS").unwrap_or(false);
628 SYS_EXTERNAL_BINDGEN = env_crate_var_to_bool("EXTERNAL_BINDGEN");
629 SYS_NO_ASM = env_crate_var_to_bool("NO_ASM").unwrap_or(false);
630 SYS_PREBUILT_NASM = env_crate_var_to_bool("PREBUILT_NASM");
631 SYS_C_STD = CStdRequested::from_env();
632 SYS_CMAKE_BUILDER = env_crate_var_to_bool("CMAKE_BUILDER");
633 SYS_NO_PREGENERATED_SRC = env_crate_var_to_bool("NO_PREGENERATED_SRC").unwrap_or(false);
634 SYS_EFFECTIVE_TARGET = optional_env_crate_target("EFFECTIVE_TARGET").unwrap_or_default();
635 SYS_NO_JITTER_ENTROPY = env_crate_var_to_bool("NO_JITTER_ENTROPY");
636 SYS_NO_U1_BINDINGS = env_crate_var_to_bool("NO_U1_BINDINGS");
637 SYS_INCLUDES =
638 optional_env_crate_target("INCLUDES").map(|v| std::env::split_paths(&v).collect());
639 SYS_SANITIZER = optional_env_crate_target("SANITIZER").map(|v| v.to_lowercase());
640 }
641
642 assert!(
643 !is_fips_crate() || is_fips_build(),
644 "aws-lc-fips-sys requires 'fips' feature to be enabled.",
645 );
646
647 if !is_external_bindgen_requested().unwrap_or(false)
648 && (is_pregenerating_bindings() || !has_bindgen_feature())
649 && !cfg!(feature = "ssl")
650 {
651 if is_all_bindings() {
652 assert!(
653 use_no_u1_bindings() != Some(true),
654 "Bindgen currently cannot generate prefixed bindings w/o the \\x01 prefix.",
655 );
656 let target = effective_target();
657 let supported_platform = match (is_fips_crate(), target.as_str()) {
658 (
659 _,
660 "aarch64-apple-darwin"
661 | "aarch64-unknown-linux-gnu"
662 | "aarch64-unknown-linux-musl"
663 | "x86_64-apple-darwin"
664 | "x86_64-unknown-linux-gnu"
665 | "x86_64-unknown-linux-musl",
666 )
667 | (
668 false,
669 "aarch64-linux-android"
670 | "aarch64-pc-windows-msvc"
671 | "i686-pc-windows-msvc"
672 | "i686-unknown-linux-gnu"
673 | "riscv64gc-unknown-linux-gnu"
674 | "x86_64-pc-windows-gnu"
675 | "x86_64-pc-windows-msvc",
676 ) => Some(target),
677 _ => None,
678 };
679 if let Some(platform) = supported_platform {
680 emit_rustc_cfg(platform.as_str());
681 unsafe {
682 PREGENERATED = true;
683 }
684 }
685 } else if !is_fips_crate() {
686 if use_no_u1_bindings() == Some(true)
687 || (target_chokes_on_u1() && use_no_u1_bindings().is_none())
688 {
689 if is_cranelift_backend() {
690 emit_warning(
691 "Cranelift codegen backend detected. Using universal_no_u1 bindings.",
692 );
693 }
694 if target_has_prefixed_symbols() {
695 emit_rustc_cfg("universal-no-u1-prefixed");
696 } else {
697 emit_rustc_cfg("universal-no-u1");
698 }
699 } else if target_has_prefixed_symbols() {
700 emit_rustc_cfg("universal-prefixed");
701 } else {
702 emit_rustc_cfg("universal");
703 }
704 unsafe {
705 PREGENERATED = true;
706 }
707 }
708 }
709 }
710
711 fn is_bindgen_required() -> bool {
712 is_no_prefix()
713 || is_pregenerating_bindings()
714 || is_external_bindgen_requested().unwrap_or(false)
715 || has_bindgen_feature()
716 || !has_pregenerated()
717 }
718
719 #[cfg(any(feature = "bindgen", feature = "fips"))]
720 fn internal_bindgen_supported() -> bool {
721 let cv = bindgen::clang_version();
722 emit_warning(format!("Clang version: {}", cv.full));
723 true
724 }
725
726 fn is_no_prefix() -> bool {
727 unsafe { SYS_NO_PREFIX }
728 }
729
730 fn is_pregenerating_bindings() -> bool {
731 unsafe { SYS_PREGENERATING_BINDINGS }
732 }
733
734 fn is_external_bindgen_requested() -> Option<bool> {
735 unsafe { SYS_EXTERNAL_BINDGEN }
736 }
737
738 fn is_no_asm() -> bool {
739 unsafe { SYS_NO_ASM }
740 }
741
742 #[allow(static_mut_refs)]
743 fn sanitizer() -> Option<String> {
744 unsafe { SYS_SANITIZER.clone() }
745 }
746
747 fn is_cmake_builder() -> Option<bool> {
748 if is_no_pregenerated_src() {
749 Some(true)
750 } else {
751 unsafe { SYS_CMAKE_BUILDER }
752 }
753 }
754
755 fn is_no_pregenerated_src() -> bool {
756 unsafe { SYS_NO_PREGENERATED_SRC }
757 }
758
759 fn disable_jitter_entropy() -> Option<bool> {
760 unsafe { SYS_NO_JITTER_ENTROPY }
761 }
762
763 /// Returns true if jitter entropy should be built. This is false when the user
764 /// explicitly set `AWS_LC_SYS_NO_JITTER_ENTROPY=1`, or when auto-detection
765 /// determined that required headers are unavailable.
766 fn should_build_jitter_entropy() -> bool {
767 static AVAILABLE: OnceLock<bool> = OnceLock::new();
768
769 // If the user explicitly set the env var, respect it unconditionally.
770 if let Some(val) = disable_jitter_entropy() {
771 return !val;
772 }
773
774 *AVAILABLE.get_or_init(|| {
775 // The current FIPS branch does not include jitter entropy.
776 if is_fips_build() {
777 return true;
778 }
779 // Only Apple targets need the CoreServices header.
780 if target_vendor() != "apple" {
781 return true;
782 }
783 probe_apple_core_services()
784 })
785 }
786
787 /// Probes whether `CoreServices/CoreServices.h` is available for the current
788 /// target toolchain. On Apple targets, jitterentropy requires this header which
789 /// is only present when the macOS SDK is installed. When cross-compiling to
790 /// Apple targets from non-macOS hosts (e.g., Linux → macOS via cargo-zigbuild),
791 /// this header is typically missing.
792 fn probe_apple_core_services() -> bool {
793 let probe_dir = out_dir().join("out-apple_core_services_check");
794 let src_dir = probe_dir.join("src");
795 let _ = std::fs::create_dir_all(&src_dir);
796 let source_file = src_dir.join("apple_core_services_check.c");
797 if std::fs::write(&source_file, "#include <CoreServices/CoreServices.h>\n").is_err() {
798 emit_warning("Failed to write CoreServices probe file; assuming available.");
799 return true;
800 }
801
802 let mut cc_build = cc::Build::default();
803 cc_build.file(&source_file).out_dir(&probe_dir);
804 let available = cc_build.try_compile_intermediates().is_ok();
805 let _ = std::fs::remove_dir_all(&probe_dir);
806
807 if !available {
808 emit_warning(
809 "CoreServices/CoreServices.h not available; \
810 automatically disabling CPU jitter entropy.",
811 );
812 }
813 available
814 }
815
816 fn use_no_u1_bindings() -> Option<bool> {
817 unsafe { SYS_NO_U1_BINDINGS }
818 }
819
820 fn get_crate_cc() -> Option<String> {
821 optional_env_optional_crate_target("TARGET_CC").or(optional_env_optional_crate_target("CC"))
822 }
823
824 fn get_crate_cxx() -> Option<String> {
825 optional_env_optional_crate_target("TARGET_CXX").or(optional_env_optional_crate_target("CXX"))
826 }
827
828 fn get_crate_cflags() -> Option<String> {
829 optional_env_optional_crate_target("TARGET_CFLAGS")
830 .or(optional_env_optional_crate_target("CFLAGS"))
831 }
832
833 fn use_prebuilt_nasm() -> bool {
834 target_os() == "windows"
835 && target_arch() == "x86_64"
836 && !is_no_asm()
837 && !test_nasm_command() // NASM not found in environment
838 && Some(false) != allow_prebuilt_nasm() // not prevented by environment
839 && !is_disable_prebuilt_nasm() // not prevented by feature
840 // permitted by environment or by feature
841 && (Some(true) == allow_prebuilt_nasm() || is_prebuilt_nasm())
842 }
843
844 fn allow_prebuilt_nasm() -> Option<bool> {
845 unsafe { SYS_PREBUILT_NASM }
846 }
847
848 fn requested_c_std() -> CStdRequested {
849 unsafe { SYS_C_STD }
850 }
851
852 fn has_bindgen_feature() -> bool {
853 cfg!(feature = "bindgen")
854 }
855
856 fn has_pregenerated() -> bool {
857 unsafe { PREGENERATED }
858 }
859
860 fn test_nasm_command() -> bool {
861 let status = execute_command("nasm".as_ref(), &["-version".as_ref()]).status;
862 if !status {
863 emit_warning("NASM command not found or failed to execute.");
864 }
865 status
866 }
867
868 fn find_clang_cl() -> Option<OsString> {
869 static CACHE: OnceLock<Option<OsString>> = OnceLock::new();
870 CACHE
871 .get_or_init(|| {
872 // Check if clang-cl is directly available (e.g., in PATH)
873 if execute_command("clang-cl".as_ref(), &["--version".as_ref()]).status {
874 return Some("clang-cl".into());
875 }
876
877 // Try to find clang-cl in a Visual Studio installation
878 find_clang_cl_in_vs()
879 })
880 .clone()
881 }
882
883 fn find_clang_cl_in_vs() -> Option<OsString> {
884 // Use the cc crate's VS discovery (which calls vswhere internally) to
885 // locate the VS installation, then look for clang-cl relative to it.
886 let tool = cc::windows_registry::find_tool(&target(), "cl.exe")?;
887 let cl_path = tool.path().to_path_buf();
888
889 // cl.exe lives deep inside the VS installation:
890 // <VS>/VC/Tools/MSVC/<ver>/bin/<host>/<target>/cl.exe
891 // clang-cl lives at:
892 // <VS>/VC/Tools/Llvm/<arch>/bin/clang-cl.exe
893 // Walk up from cl.exe until we find the VS root.
894 for ancestor in cl_path.ancestors() {
895 let vc_llvm = ancestor.join("VC").join("Tools").join("Llvm");
896 if vc_llvm.exists() {
897 for arch_dir in &["ARM64", "x64"] {
898 let clang_cl = vc_llvm.join(arch_dir).join("bin").join("clang-cl.exe");
899 if clang_cl.exists()
900 && execute_command(clang_cl.as_os_str(), &["--version".as_ref()]).status
901 {
902 emit_warning(format!("Found clang-cl at: {}", clang_cl.display()));
903 return Some(clang_cl.into_os_string());
904 }
905 }
906 break;
907 }
908 }
909
910 None
911 }
912
913 fn test_clang_cl_command() -> bool {
914 find_clang_cl().is_some()
915 }
916
917 fn prepare_cargo_cfg() {
918 if cfg!(clippy) {
919 println!("cargo:rustc-check-cfg=cfg(use_bindgen_pregenerated)");
920 println!("cargo:rustc-check-cfg=cfg(aarch64_linux_android)");
921 println!("cargo:rustc-check-cfg=cfg(aarch64_apple_darwin)");
922 println!("cargo:rustc-check-cfg=cfg(aarch64_pc_windows_msvc)");
923 println!("cargo:rustc-check-cfg=cfg(aarch64_unknown_linux_gnu)");
924 println!("cargo:rustc-check-cfg=cfg(aarch64_unknown_linux_musl)");
925 println!("cargo:rustc-check-cfg=cfg(cpu_jitter_entropy)");
926 println!("cargo:rustc-check-cfg=cfg(i686_pc_windows_msvc)");
927 println!("cargo:rustc-check-cfg=cfg(i686_unknown_linux_gnu)");
928 println!("cargo:rustc-check-cfg=cfg(riscv64gc_unknown_linux_gnu)");
929 println!("cargo:rustc-check-cfg=cfg(x86_64_apple_darwin)");
930 println!("cargo:rustc-check-cfg=cfg(x86_64_pc_windows_gnu)");
931 println!("cargo:rustc-check-cfg=cfg(x86_64_pc_windows_msvc)");
932 println!("cargo:rustc-check-cfg=cfg(x86_64_unknown_linux_gnu)");
933 println!("cargo:rustc-check-cfg=cfg(x86_64_unknown_linux_musl)");
934 println!("cargo:rustc-check-cfg=cfg(universal)");
935 println!("cargo:rustc-check-cfg=cfg(universal_no_u1)");
936 println!("cargo:rustc-check-cfg=cfg(universal_no_u1_prefixed)");
937 println!("cargo:rustc-check-cfg=cfg(universal_prefixed)");
938 }
939 }
940
941 fn is_crt_static() -> bool {
942 let features = cargo_env("CARGO_CFG_TARGET_FEATURE");
943 features.contains("crt-static")
944 }
945
946 #[cfg(any(feature = "bindgen", feature = "fips"))]
947 fn handle_bindgen(manifest_dir: &Path, prefix: &Option<String>) -> bool {
948 if internal_bindgen_supported() && !is_external_bindgen_requested().unwrap_or(false) {
949 emit_warning(format!(
950 "Generating bindings - internal bindgen. Platform: {}",
951 effective_target()
952 ));
953 let gen_bindings_path = out_dir().join("bindings.rs");
954 generate_bindings(manifest_dir, prefix, &gen_bindings_path);
955 emit_rustc_cfg("use_bindgen_pregenerated");
956 true
957 } else {
958 false
959 }
960 }
961
962 #[cfg(not(any(feature = "bindgen", feature = "fips")))]
963 fn handle_bindgen(_manifest_dir: &Path, _prefix: &Option<String>) -> bool {
964 false
965 }
966
967 fn canonicalized_manifest_dir() -> PathBuf {
968 let manifest_dir = current_dir();
969 let manifest_dir = dunce::canonicalize(Path::new(&manifest_dir)).unwrap();
970 #[cfg(windows)]
971 let manifest_dir = to_short_path(&manifest_dir);
972 manifest_dir
973 }
974
975 #[cfg(not(test))]
976 fn main() {
977 initialize();
978 prepare_cargo_cfg();
979
980 let manifest_dir = canonicalized_manifest_dir();
981 let prefix = (!is_no_prefix()).then(prefix_string);
982
983 let builder = get_builder(&prefix, &manifest_dir, &out_dir());
984 emit_warning(format!("Building with: {}", builder.name()));
985 emit_warning(format!("Symbol Prefix: {prefix:?}"));
986
987 builder.check_dependencies().unwrap();
988
989 #[allow(unused_assignments)]
990 let mut bindings_available = false;
991 emit_warning(format!("Target platform: '{}'", target()));
992 if is_pregenerating_bindings() {
993 #[cfg(any(feature = "bindgen", feature = "fips"))]
994 {
995 let src_bindings_path = Path::new(&manifest_dir)
996 .join("src")
997 .join(format!("{}.rs", target_platform_prefix("crypto")));
998 if is_external_bindgen_requested().unwrap_or(false) {
999 assert!(
1000 !is_pregenerating_bindings(),
1001 "Pregenerated bindings not supported using external bindgen.",
1002 );
1003 invoke_external_bindgen(&manifest_dir, &prefix, &src_bindings_path).unwrap();
1004 } else {
1005 generate_src_bindings(&manifest_dir, &prefix, &src_bindings_path);
1006 }
1007 bindings_available = true;
1008 }
1009 } else if is_bindgen_required() {
1010 assert!(
1011 use_no_u1_bindings() != Some(true),
1012 "Bindgen currently cannot generate prefixed bindings w/o the \\x01 prefix.",
1013 );
1014 emit_warning("######");
1015 emit_warning(
1016 "If bindgen is unable to locate a header file, use the \
1017 BINDGEN_EXTRA_CLANG_ARGS environment variable to specify additional include paths.",
1018 );
1019 emit_warning(
1020 "See: https://github.com/rust-lang/rust-bindgen?tab=readme-ov-file#environment-variables",
1021 );
1022 emit_warning("######");
1023 let aws_lc_crypto_dir = Path::new(&manifest_dir).join("aws-lc").join("crypto");
1024 if !aws_lc_crypto_dir.exists() {
1025 emit_warning("######");
1026 emit_warning("###### WARNING: MISSING GIT SUBMODULE ######");
1027 emit_warning(format!(
1028 " -- Did you initialize the repo's git submodules? Unable to find crypto directory: {}.",
1029 aws_lc_crypto_dir.display()
1030 ));
1031 emit_warning(" -- run 'git submodule update --init --recursive' to initialize.");
1032 emit_warning("######");
1033 emit_warning("######");
1034 }
1035 bindings_available = handle_bindgen(&manifest_dir, &prefix);
1036 } else {
1037 bindings_available = true;
1038 }
1039
1040 if !bindings_available {
1041 if cfg!(feature = "ssl") {
1042 emit_warning(
1043 "External bindgen required, but external bindgen unable to produce SSL bindings.",
1044 );
1045 } else {
1046 assert!(
1047 use_no_u1_bindings() != Some(true),
1048 "Bindgen currently cannot generate prefixed bindings w/o the \\x01 prefix.",
1049 );
1050 let gen_bindings_path = out_dir().join("bindings.rs");
1051 let result = invoke_external_bindgen(&manifest_dir, &prefix, &gen_bindings_path);
1052 match result {
1053 Ok(()) => {
1054 emit_rustc_cfg("use_bindgen_pregenerated");
1055 bindings_available = true;
1056 }
1057 Err(msg) => eprintln!("Failure invoking external bindgen! {msg}"),
1058 }
1059 }
1060 }
1061
1062 assert!(
1063 bindings_available,
1064 "aws-lc-sys build failed. Please enable the 'bindgen' feature on aws-lc-rs or aws-lc-sys.\
1065 For more information, see the aws-lc-rs User Guide: https://aws.github.io/aws-lc-rs/index.html"
1066 );
1067 builder.build().unwrap();
1068
1069 // MinGW win7 targets use the BCryptGenRandom path (AWSLC_WINDOWS_7_COMPAT),
1070 // which requires linking against bcrypt. MinGW ignores the MSVC
1071 // `#pragma comment(lib, "bcrypt.lib")` in the source, so we link explicitly.
1072 // See: https://github.com/aws/aws-lc/pull/3239
1073 if target().contains("-win7-windows-gnu") {
1074 println!("cargo:rustc-link-lib=bcrypt");
1075 }
1076
1077 println!(
1078 "cargo:include={}",
1079 setup_include_paths(&out_dir(), &manifest_dir).display()
1080 );
1081
1082 // export the artifact names
1083 println!("cargo:libcrypto={}_crypto", prefix_string());
1084 if cfg!(feature = "ssl") {
1085 println!("cargo:libssl={}_ssl", prefix_string());
1086 }
1087
1088 println!("cargo:conf={}", OSSL_CONF_DEFINES.join(","));
1089
1090 println!("cargo:rerun-if-changed=builder/");
1091 println!("cargo:rerun-if-changed=aws-lc/");
1092 }
1093
1094 fn setup_include_paths(out_dir: &Path, manifest_dir: &Path) -> PathBuf {
1095 let mut include_paths = vec![
1096 get_rust_include_path(manifest_dir),
1097 get_generated_include_path(manifest_dir),
1098 get_aws_lc_include_path(manifest_dir),
1099 ];
1100
1101 if let Some(extra_paths) = get_env_includes_path() {
1102 include_paths.extend(extra_paths);
1103 }
1104
1105 let include_dir = out_dir.join("include");
1106 std::fs::create_dir_all(&include_dir).unwrap();
1107
1108 // iterate over all the include paths and copy them into the final output
1109 for path in include_paths {
1110 for child in std::fs::read_dir(path).into_iter().flatten().flatten() {
1111 if child.path().is_file() {
1112 std::fs::copy(
1113 child.path(),
1114 include_dir.join(child.path().file_name().unwrap()),
1115 )
1116 .expect("Failed to copy include file during build setup");
1117 continue;
1118 }
1119
1120 // prefer the earliest paths
1121 let options = fs_extra::dir::CopyOptions::new()
1122 .skip_exist(true)
1123 .copy_inside(true);
1124 fs_extra::dir::copy(child.path(), &include_dir, &options)
1125 .expect("Failed to copy include directory during build setup");
1126 }
1127 }
1128
1129 include_dir
1130 }
1131
1132 #[derive(Default)]
1133 #[allow(dead_code)]
1134 pub(crate) struct BindingOptions {
1135 pub build_prefix: Option<String>,
1136 pub include_ssl: bool,
1137 pub disable_prelude: bool,
1138 }
1139
1140 impl Debug for BindingOptions {
1141 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1142 f.debug_struct("BindingOptions")
1143 .field("build_prefix", &self.build_prefix)
1144 .field("include_ssl", &self.include_ssl)
1145 .field("disable_prelude", &self.disable_prelude)
1146 .finish()
1147 }
1148 }
1149
1150 fn verify_bindgen() -> Result<(), String> {
1151 if !is_external_bindgen_requested().unwrap_or(true) {
1152 return Err("external bindgen usage prevented by SYS_EXTERNAL_BINDGEN=0".to_string());
1153 }
1154
1155 let result = execute_command("bindgen".as_ref(), &["--version".as_ref()]);
1156 if !result.status {
1157 if result.executed {
1158 eprintln!(
1159 "bindgen-cli exited with an error status:\nSTDOUT: {}\n\nSTDERR: {}",
1160 result.stdout, result.stderr
1161 );
1162 } else {
1163 eprintln!(
1164 "Consider installing the bindgen-cli: \
1165 `cargo install --force --locked bindgen-cli`\
1166 \n\
1167 See our User Guide for more information about bindgen:\
1168 https://aws.github.io/aws-lc-rs/index.html"
1169 );
1170 }
1171 return Err("External bindgen command failed.".to_string());
1172 }
1173 let mut major_version: u32 = 0;
1174 let mut minor_version: u32 = 0;
1175 let mut patch_version: u32 = 0;
1176 let bindgen_version = result.stdout.split(' ').nth(1);
1177 if let Some(version) = bindgen_version {
1178 let version_parts: Vec<&str> = version.trim().split('.').collect();
1179 if version_parts.len() == 3 {
1180 major_version = version_parts[0].parse::<u32>().unwrap_or(0);
1181 minor_version = version_parts[1].parse::<u32>().unwrap_or(0);
1182 patch_version = version_parts[2].parse::<u32>().unwrap_or(0);
1183 }
1184 }
1185 // We currently expect to support all bindgen versions >= 0.69.5
1186 if major_version == 0 && (minor_version < 69 || (minor_version == 69 && patch_version < 5)) {
1187 eprintln!(
1188 "bindgen-cli was used. Detected version was: \
1189 {major_version}.{minor_version}.{patch_version} \n\
1190 Consider upgrading : \
1191 `cargo install --force --locked bindgen-cli`\
1192 \n\
1193 See our User Guide for more information about bindgen:\
1194 https://aws.github.io/aws-lc-rs/index.html"
1195 );
1196 }
1197 Ok(())
1198 }
1199
1200 const PRELUDE: &str = r"
1201 #![allow(
1202 clippy::cast_lossless,
1203 clippy::cast_possible_truncation,
1204 clippy::cast_possible_wrap,
1205 clippy::default_trait_access,
1206 clippy::doc_markdown,
1207 clippy::missing_safety_doc,
1208 clippy::must_use_candidate,
1209 clippy::not_unsafe_ptr_arg_deref,
1210 clippy::ptr_as_ptr,
1211 clippy::ptr_offset_with_cast,
1212 clippy::pub_underscore_fields,
1213 clippy::semicolon_if_nothing_returned,
1214 clippy::too_many_lines,
1215 clippy::unreadable_literal,
1216 clippy::used_underscore_binding,
1217 clippy::useless_transmute,
1218 dead_code,
1219 improper_ctypes,
1220 non_camel_case_types,
1221 non_snake_case,
1222 non_upper_case_globals,
1223 unpredictable_function_pointer_comparisons,
1224 unused_imports
1225 )]
1226 ";
1227
1228 fn invoke_external_bindgen(
1229 manifest_dir: &Path,
1230 prefix: &Option<String>,
1231 gen_bindings_path: &Path,
1232 ) -> Result<(), String> {
1233 verify_bindgen()?;
1234
1235 emit_warning(format!(
1236 "Generating bindings - external bindgen. Platform: {}",
1237 effective_target()
1238 ));
1239
1240 let _guard_target = EnvGuard::new("TARGET", effective_target());
1241
1242 let options = BindingOptions {
1243 // We collect the symbols w/o the prefix added
1244 build_prefix: None,
1245 include_ssl: false,
1246 disable_prelude: true,
1247 };
1248
1249 let clang_args = prepare_clang_args(manifest_dir, &options);
1250 let header = get_rust_include_path(manifest_dir)
1251 .join("rust_wrapper.h")
1252 .display()
1253 .to_string();
1254
1255 let sym_prefix: String;
1256 let mut bindgen_params = vec![];
1257 if let Some(prefix_str) = prefix {
1258 sym_prefix = if target_os().to_lowercase() == "macos"
1259 || target_os().to_lowercase() == "ios"
1260 || target_os().to_lowercase() == "tvos"
1261 || (target_os().to_lowercase() == "windows" && target_arch() == "x86")
1262 {
1263 format!("_{prefix_str}_")
1264 } else {
1265 format!("{prefix_str}_")
1266 };
1267 bindgen_params.extend(vec!["--prefix-link-name", sym_prefix.as_str()]);
1268 }
1269
1270 // These flags needs to be kept in sync with the setup in bindgen::prepare_bindings_builder
1271 // If `bindgen-cli` makes backwards incompatible changes, we will update the parameters below
1272 // to conform with the most recent release. We will guide consumers to likewise use the
1273 // latest version of bindgen-cli.
1274 bindgen_params.extend(vec![
1275 "--allowlist-file",
1276 r".*(/|\\)openssl((/|\\)[^/\\]+)+\.h",
1277 "--allowlist-file",
1278 r".*(/|\\)rust_wrapper\.h",
1279 "--rustified-enum",
1280 r"point_conversion_form_t",
1281 "--default-macro-constant-type",
1282 r"signed",
1283 "--with-derive-default",
1284 "--with-derive-partialeq",
1285 "--with-derive-eq",
1286 "--raw-line",
1287 COPYRIGHT,
1288 "--generate",
1289 "functions,types,vars,methods,constructors,destructors",
1290 header.as_str(),
1291 "--rust-target",
1292 r"1.70",
1293 "--output",
1294 gen_bindings_path.to_str().unwrap(),
1295 "--formatter",
1296 r"rustfmt",
1297 ]);
1298 if !options.disable_prelude {
1299 bindgen_params.extend(["--raw-line", PRELUDE]);
1300 }
1301 bindgen_params.push("--");
1302
1303 for x in &clang_args {
1304 bindgen_params.push(x.as_str());
1305 }
1306 let cmd_params: Vec<OsString> = bindgen_params.iter().map(OsString::from).collect();
1307 let cmd_params: Vec<&OsStr> = cmd_params.iter().map(OsString::as_os_str).collect();
1308
1309 let result = execute_command("bindgen".as_ref(), cmd_params.as_ref());
1310 if !result.status {
1311 return Err(format!(
1312 "\n\n\
1313 bindgen-PARAMS: {}\n\
1314 bindgen-STDOUT: {}\n\
1315 bindgen-STDERR: {}",
1316 bindgen_params.join(" "),
1317 result.stdout.as_ref(),
1318 result.stderr.as_ref()
1319 ));
1320 }
1321 Ok(())
1322 }
1323
1324 fn add_header_include_path(args: &mut Vec<String>, path: String) {
1325 args.push("-I".to_string());
1326 args.push(path);
1327 }
1328
1329 fn prepare_clang_args(manifest_dir: &Path, options: &BindingOptions) -> Vec<String> {
1330 let mut clang_args: Vec<String> = Vec::new();
1331
1332 add_header_include_path(
1333 &mut clang_args,
1334 get_rust_include_path(manifest_dir).display().to_string(),
1335 );
1336
1337 if options.build_prefix.is_some() {
1338 // NOTE: It's possible that the prefix embedded in the header files doesn't match the prefix
1339 // specified. This only happens when the version number as changed in Cargo.toml, but the
1340 // new headers have not yet been generated.
1341 add_header_include_path(
1342 &mut clang_args,
1343 get_generated_include_path(manifest_dir)
1344 .display()
1345 .to_string(),
1346 );
1347 }
1348
1349 add_header_include_path(
1350 &mut clang_args,
1351 get_aws_lc_include_path(manifest_dir).display().to_string(),
1352 );
1353
1354 if let Some(include_paths) = get_env_includes_path() {
1355 for path in include_paths {
1356 add_header_include_path(&mut clang_args, path.display().to_string());
1357 }
1358 }
1359
1360 clang_args
1361 }
1362
1363 const COPYRIGHT: &str = r"
1364 // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
1365 // SPDX-License-Identifier: Apache-2.0 OR ISC
1366 ";
1367
1368 // =============================================================================
1369 // Tests - run via: rustc --test builder/main.rs --edition 2021 -o /tmp/builder_test && /tmp/builder_test
1370 // Or via the Makefile target: make test-builder
1371 // =============================================================================
1372
1373 #[cfg(test)]
1374 mod tests {
1375 use super::*;
1376
1377 // -------------------------------------------------------------------------
1378 // parse_to_bool tests
1379 // -------------------------------------------------------------------------
1380
1381 #[test]
1382 fn test_parse_to_bool_true_values() {
1383 assert_eq!(parse_to_bool("1"), Some(true));
1384 assert_eq!(parse_to_bool("2"), Some(true));
1385 assert_eq!(parse_to_bool("9"), Some(true));
1386 assert_eq!(parse_to_bool("ON"), Some(true));
1387 assert_eq!(parse_to_bool("on"), Some(true));
1388 assert_eq!(parse_to_bool("On"), Some(true));
1389 assert_eq!(parse_to_bool("YES"), Some(true));
1390 assert_eq!(parse_to_bool("yes"), Some(true));
1391 assert_eq!(parse_to_bool("TRUE"), Some(true));
1392 assert_eq!(parse_to_bool("true"), Some(true));
1393 assert_eq!(parse_to_bool("y"), Some(true));
1394 assert_eq!(parse_to_bool("Y"), Some(true));
1395 assert_eq!(parse_to_bool("t"), Some(true));
1396 assert_eq!(parse_to_bool("T"), Some(true));
1397 }
1398
1399 #[test]
1400 fn test_parse_to_bool_false_values() {
1401 assert_eq!(parse_to_bool("0"), Some(false));
1402 assert_eq!(parse_to_bool("OFF"), Some(false));
1403 assert_eq!(parse_to_bool("off"), Some(false));
1404 assert_eq!(parse_to_bool("NO"), Some(false));
1405 assert_eq!(parse_to_bool("no"), Some(false));
1406 assert_eq!(parse_to_bool("FALSE"), Some(false));
1407 assert_eq!(parse_to_bool("false"), Some(false));
1408 assert_eq!(parse_to_bool("n"), Some(false));
1409 assert_eq!(parse_to_bool("N"), Some(false));
1410 assert_eq!(parse_to_bool("f"), Some(false));
1411 assert_eq!(parse_to_bool("F"), Some(false));
1412 }
1413
1414 #[test]
1415 fn test_parse_to_bool_none_values() {
1416 assert_eq!(parse_to_bool(""), None);
1417 assert_eq!(parse_to_bool("invalid"), None);
1418 assert_eq!(parse_to_bool("maybe"), None);
1419 assert_eq!(parse_to_bool(" "), None);
1420 }
1421
1422 // -------------------------------------------------------------------------
1423 // OutputLib tests
1424 // -------------------------------------------------------------------------
1425
1426 #[test]
1427 fn test_output_lib_crypto_libname_with_prefix() {
1428 let prefix = Some("test_prefix".to_string());
1429 let name = OutputLib::Crypto.libname(&prefix);
1430 assert_eq!(name, "test_prefix_crypto");
1431 }
1432
1433 #[test]
1434 fn test_output_lib_crypto_libname_without_prefix() {
1435 let name = OutputLib::Crypto.libname(&None);
1436 assert_eq!(name, "crypto");
1437 }
1438
1439 #[test]
1440 fn test_output_lib_ssl_libname_with_prefix() {
1441 let prefix = Some("my_prefix".to_string());
1442 let name = OutputLib::Ssl.libname(&prefix);
1443 assert_eq!(name, "my_prefix_ssl");
1444 }
1445
1446 #[test]
1447 fn test_output_lib_ssl_libname_without_prefix() {
1448 let name = OutputLib::Ssl.libname(&None);
1449 assert_eq!(name, "ssl");
1450 }
1451
1452 // -------------------------------------------------------------------------
1453 // OutputLibType tests
1454 // -------------------------------------------------------------------------
1455
1456 #[test]
1457 fn test_output_lib_type_rust_lib_type() {
1458 assert_eq!(OutputLibType::Static.rust_lib_type(), "static");
1459 assert_eq!(OutputLibType::Dynamic.rust_lib_type(), "dylib");
1460 }
1461
1462 // -------------------------------------------------------------------------
1463 // Version/Prefix tests
1464 // -------------------------------------------------------------------------
1465
1466 #[test]
1467 fn test_version_constant_exists() {
1468 assert!(!VERSION.is_empty(), "VERSION should not be empty");
1469 }
1470 }