Debian Codegraph @

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

raw
1 // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
2 // SPDX-License-Identifier: Apache-2.0 OR ISC
3
4 use crate::cc_builder::CcBuilder;
5 use crate::OutputLib::{Crypto, Ssl};
6 use crate::{
7 allow_prebuilt_nasm, cargo_env, effective_target, emit_warning, execute_command,
8 get_crate_cflags, is_crt_static, is_fips_build, is_no_asm, is_no_pregenerated_src,
9 optional_env, optional_env_optional_crate_target, sanitizer, set_env, set_env_for_target,
10 should_build_jitter_entropy, target, target_arch, target_env, target_os, test_clang_cl_command,
11 test_nasm_command, use_prebuilt_nasm, OutputLibType,
12 };
13 use std::collections::HashMap;
14 use std::env;
15 use std::ffi::OsString;
16 use std::path::{Path, PathBuf};
17 use std::str::FromStr;
18
19 /// Strip LTO-related flags from a CFLAGS string. LTO flags interfere with the
20 /// FIPS delocator pipeline, which compiles C to assembly (`-S`) and processes it
21 /// with a Go tool. The combination of `-S` and `-flto` causes GCC to produce
22 /// GIMPLE-annotated output that the delocator cannot handle. Additionally, LTO
23 /// object files mixed with hand-written assembly in static libraries can cause
24 /// linker errors (e.g. `R_X86_64_32` relocations incompatible with PIE).
25 /// See also: aws-lc `CMakeLists.txt` which disables assembly when LTO is active.
26 fn strip_lto_flags(cflags: &str) -> String {
27 cflags
28 .split_whitespace()
29 .filter(|flag| {
30 !flag.starts_with("-flto")
31 && *flag != "-ffat-lto-objects"
32 && *flag != "-fno-fat-lto-objects"
33 })
34 .collect::<Vec<_>>()
35 .join(" ")
36 }
37
38 pub(crate) struct CmakeBuilder {
39 manifest_dir: PathBuf,
40 out_dir: PathBuf,
41 build_prefix: Option<String>,
42 output_lib_type: OutputLibType,
43 }
44
45 fn test_prebuilt_nasm_script(script_path: &Path) -> bool {
46 // Call with no args - both scripts will exit with error, but we only care if they can execute
47 execute_command(script_path.as_os_str(), &[]).executed
48 }
49
50 fn find_cmake_command() -> Option<OsString> {
51 if let Some(cmake) = optional_env_optional_crate_target("CMAKE") {
52 emit_warning(format!("CMAKE environment variable set: {}", cmake.clone()));
53 if execute_command(cmake.as_ref(), &["--version".as_ref()]).status {
54 Some(cmake.into())
55 } else {
56 None
57 }
58 } else if execute_command("cmake3".as_ref(), &["--version".as_ref()]).status {
59 Some("cmake3".into())
60 } else if execute_command("cmake".as_ref(), &["--version".as_ref()]).status {
61 Some("cmake".into())
62 } else {
63 None
64 }
65 }
66
67 impl CmakeBuilder {
68 pub(crate) fn new(
69 manifest_dir: PathBuf,
70 out_dir: PathBuf,
71 build_prefix: Option<String>,
72 output_lib_type: OutputLibType,
73 ) -> Self {
74 Self {
75 manifest_dir,
76 out_dir,
77 build_prefix,
78 output_lib_type,
79 }
80 }
81
82 fn artifact_output_dir(&self) -> PathBuf {
83 self.out_dir.join("build").join("artifacts")
84 }
85
86 fn get_cmake_config(&self) -> cmake::Config {
87 cmake::Config::new(&self.manifest_dir)
88 }
89
90 fn apply_universal_build_options<'a>(
91 &self,
92 cmake_cfg: &'a mut cmake::Config,
93 ) -> &'a cmake::Config {
94 // Use the compiler options identified by CcBuilder
95 let cc_builder = CcBuilder::new(
96 self.manifest_dir.clone(),
97 self.out_dir.clone(),
98 self.build_prefix.clone(),
99 self.output_lib_type,
100 );
101 let cc_build = cc::Build::new();
102 let (is_like_msvc, build_options) =
103 cc_builder.collect_universal_build_options(&cc_build, true);
104 for option in &build_options {
105 option.apply_cmake(cmake_cfg, is_like_msvc);
106 }
107 cmake_cfg
108 }
109
110 const GOCACHE_DIR_NAME: &'static str = "go-cache";
111
112 #[allow(clippy::too_many_lines)]
113 fn prepare_cmake_build(&self) -> cmake::Config {
114 if is_fips_build() {
115 unsafe {
116 env::set_var("GOFLAGS", "-buildvcs=false");
117 }
118 if env::var("GOCACHE").is_err() {
119 unsafe {
120 env::set_var(
121 "GOCACHE",
122 self.out_dir.join(Self::GOCACHE_DIR_NAME).as_os_str(),
123 );
124 }
125 }
126 }
127
128 let mut cmake_cfg = self.get_cmake_config();
129 if let Some(generator) = optional_env_optional_crate_target("CMAKE_GENERATOR") {
130 set_env("CMAKE_GENERATOR", generator);
131 }
132
133 if OutputLibType::default() == OutputLibType::Dynamic {
134 cmake_cfg.define("BUILD_SHARED_LIBS", "1");
135 if is_fips_build() {
136 // The default flags include `-ffunction-sections` that can result in
137 // dead code elimination dropping functions.
138 cmake_cfg.no_default_flags(true);
139 }
140 } else {
141 cmake_cfg.define("BUILD_SHARED_LIBS", "0");
142 }
143
144 if let Some(prefix) = &self.build_prefix {
145 cmake_cfg.define("BORINGSSL_PREFIX", format!("{prefix}_"));
146 let include_path = self.manifest_dir.join("generated-include");
147 cmake_cfg.define(
148 "BORINGSSL_PREFIX_HEADERS",
149 include_path.display().to_string(),
150 );
151 }
152
153 // Build flags that minimize our crate size.
154 cmake_cfg.define("BUILD_TESTING", "OFF");
155 cmake_cfg.define("BUILD_TOOL", "OFF");
156 cmake_cfg.define("ENABLE_SOURCE_MODIFICATION", "OFF");
157 if cfg!(feature = "ssl") {
158 cmake_cfg.define("BUILD_LIBSSL", "ON");
159 } else {
160 cmake_cfg.define("BUILD_LIBSSL", "OFF");
161 }
162 if is_fips_build() {
163 cmake_cfg.define("FIPS", "1");
164 } else {
165 if is_no_pregenerated_src() {
166 // Go and Perl will be required.
167 cmake_cfg.define("DISABLE_PERL", "OFF");
168 cmake_cfg.define("DISABLE_GO", "OFF");
169 } else {
170 // Build flags that minimize our dependencies.
171 cmake_cfg.define("DISABLE_PERL", "ON");
172 cmake_cfg.define("DISABLE_GO", "ON");
173 }
174 if !should_build_jitter_entropy() {
175 cmake_cfg.define("DISABLE_CPU_JITTER_ENTROPY", "ON");
176 }
177
178 if target_env() == "ohos" {
179 Self::configure_open_harmony(&mut cmake_cfg);
180 }
181 }
182
183 if is_no_asm() {
184 let opt_level = cargo_env("OPT_LEVEL");
185 if opt_level == "0" {
186 cmake_cfg.define("OPENSSL_NO_ASM", "1");
187 } else {
188 panic!("AWS_LC_SYS_NO_ASM only allowed for debug builds!")
189 }
190 }
191
192 Self::configure_sanitizer(&mut cmake_cfg);
193
194 if let Some(cflags) = get_crate_cflags() {
195 let cflags = if is_fips_build() {
196 strip_lto_flags(&cflags)
197 } else {
198 cflags
199 };
200 // Set both the target-specific and base CFLAGS. cmake-rs reads
201 // the base CFLAGS env var directly, so we must override it too.
202 set_env_for_target("CFLAGS", &cflags);
203 set_env("CFLAGS", &cflags);
204 }
205
206 // cmake-rs has logic that strips Optimization/Debug options that are passed via CFLAGS:
207 // https://github.com/rust-lang/cmake-rs/issues/240
208 // This breaks build configurations that generate warnings when optimizations
209 // are disabled.
210 Self::preserve_cflag_optimization_flags(&mut cmake_cfg);
211
212 if target_os() == "windows" {
213 if is_fips_build() {
214 let opt_level = cargo_env("OPT_LEVEL");
215 let build_type = if opt_level.eq("0") || opt_level.eq("1") || opt_level.eq("2") {
216 "RELWITHDEBINFO"
217 } else {
218 "RELEASE"
219 };
220 cmake_cfg.define("CMAKE_BUILD_TYPE", build_type);
221 } else if use_prebuilt_nasm() {
222 self.configure_prebuilt_nasm(&mut cmake_cfg);
223 }
224 if target_env().as_str() == "msvc" {
225 let mut msvcrt = String::from_str("MultiThreaded").unwrap();
226 if is_crt_static() {
227 cmake_cfg.static_crt(true);
228 // When using static CRT on Windows MSVC, ignore missing PDB file warnings
229 // The static CRT libraries reference PDB files from Microsoft's build servers
230 // which are not available.
231 println!("cargo:rustc-link-arg=/ignore:4099");
232 } else {
233 msvcrt.push_str("DLL");
234 }
235 cmake_cfg.define("CMAKE_MSVC_RUNTIME_LIBRARY", msvcrt.as_str());
236 }
237 }
238
239 // Allow environment to specify CMake toolchain.
240 if let Some(toolchain) = optional_env_optional_crate_target("CMAKE_TOOLCHAIN_FILE") {
241 set_env_for_target("CMAKE_TOOLCHAIN_FILE", toolchain);
242
243 return cmake_cfg;
244 }
245 // We only consider compiler CFLAGS when no cmake toolchain is set
246 self.apply_universal_build_options(&mut cmake_cfg);
247
248 // See issue: https://github.com/aws/aws-lc-rs/issues/453
249 if target_os() == "windows" {
250 self.configure_windows(&mut cmake_cfg);
251 }
252
253 // If the build environment vendor is Apple
254 #[cfg(target_vendor = "apple")]
255 {
256 if target_arch() == "aarch64" {
257 cmake_cfg.define("CMAKE_OSX_ARCHITECTURES", "arm64");
258 cmake_cfg.define("CMAKE_SYSTEM_PROCESSOR", "arm64");
259 }
260 if target_arch() == "x86_64" {
261 cmake_cfg.define("CMAKE_OSX_ARCHITECTURES", "x86_64");
262 cmake_cfg.define("CMAKE_SYSTEM_PROCESSOR", "x86_64");
263 }
264 if target_os().trim() == "ios" {
265 cmake_cfg.define("CMAKE_SYSTEM_NAME", "iOS");
266 if effective_target().ends_with("-ios-sim") || target_arch() == "x86_64" {
267 cmake_cfg.define("CMAKE_OSX_SYSROOT", "iphonesimulator");
268 } else {
269 cmake_cfg.define("CMAKE_OSX_SYSROOT", "iphoneos");
270 }
271 cmake_cfg.define("CMAKE_THREAD_LIBS_INIT", "-lpthread");
272 }
273 if target_os().trim() == "macos" {
274 cmake_cfg.define("CMAKE_SYSTEM_NAME", "Darwin");
275 cmake_cfg.define("CMAKE_OSX_SYSROOT", "macosx");
276 }
277 if target_os().trim() == "tvos" {
278 cmake_cfg.define("CMAKE_SYSTEM_NAME", "tvOS");
279 if effective_target().ends_with("-tvos-sim") || target_arch() == "x86_64" {
280 cmake_cfg.define("CMAKE_OSX_SYSROOT", "appletvsimulator");
281 } else {
282 cmake_cfg.define("CMAKE_OSX_SYSROOT", "appletvos");
283 }
284 }
285 }
286
287 if target_os() == "android" {
288 self.configure_android(&mut cmake_cfg);
289 }
290
291 cmake_cfg
292 }
293
294 fn preserve_cflag_optimization_flags(cmake_cfg: &mut cmake::Config) {
295 if let Some(cflags) = get_crate_cflags() {
296 let split = cflags.split_whitespace();
297 for arg in split {
298 if arg.starts_with("-O") || arg.starts_with("/O") {
299 emit_warning(format!("Preserving optimization flag: {arg}"));
300 cmake_cfg.cflag(arg);
301 }
302 }
303 }
304 }
305
306 #[allow(clippy::unused_self)]
307 fn select_prebuilt_nasm_script(&self) -> PathBuf {
308 let sh_script = self.manifest_dir.join("builder").join("prebuilt-nasm.sh");
309 let bat_script = self.manifest_dir.join("builder").join("prebuilt-nasm.bat");
310
311 // Test .sh first (more universal - works in MSYS2, WSL, native Unix)
312 if test_prebuilt_nasm_script(&sh_script) {
313 emit_warning("Selected prebuilt-nasm.sh (shell script can execute)");
314 sh_script
315 } else if test_prebuilt_nasm_script(&bat_script) {
316 emit_warning(
317 "Selected prebuilt-nasm.bat (batch script can execute, shell script cannot)",
318 );
319 bat_script
320 } else {
321 // Neither script could be verified as executable. This can happen in sandboxed or
322 // restricted build environments where trial execution is blocked. We fall back to
323 // selecting a script based on the host OS, which matches the behavior prior to
324 // execution-based detection. If this fallback is incorrect, the build will fail
325 // when CMake attempts to invoke the selected script.
326 let fallback_script = if cfg!(target_os = "windows") {
327 bat_script
328 } else {
329 sh_script
330 };
331 emit_warning(format!(
332 "WARNING: Neither prebuilt-nasm.sh nor prebuilt-nasm.bat could be verified as \
333 executable. Falling back to target-based selection: {}. If the build fails \
334 during assembly, verify that the selected script is appropriate for your \
335 build environment.",
336 fallback_script.file_name().unwrap().to_str().unwrap()
337 ));
338 fallback_script
339 }
340 }
341
342 #[allow(clippy::unused_self)]
343 fn configure_android(&self, _cmake_cfg: &mut cmake::Config) {
344 // If we leave CMAKE_SYSTEM_PROCESSOR unset, then cmake-rs should handle properly setting
345 // CMAKE_SYSTEM_NAME and CMAKE_SYSTEM_PROCESSOR:
346 // https://github.com/rust-lang/cmake-rs/blob/b689783b5448966e810d515c798465f2e0ab56fd/src/lib.rs#L450-L499
347
348 // Log relevant environment variables.
349 if let Some(value) = optional_env_optional_crate_target("ANDROID_NDK_ROOT") {
350 set_env("ANDROID_NDK_ROOT", value);
351 } else {
352 emit_warning("ANDROID_NDK_ROOT not set.");
353 }
354 if let Some(value) = optional_env_optional_crate_target("ANDROID_NDK") {
355 set_env("ANDROID_NDK", value);
356 } else {
357 emit_warning("ANDROID_NDK not set.");
358 }
359 if let Some(value) = optional_env_optional_crate_target("ANDROID_STANDALONE_TOOLCHAIN") {
360 set_env("ANDROID_STANDALONE_TOOLCHAIN", value);
361 } else {
362 emit_warning("ANDROID_STANDALONE_TOOLCHAIN not set.");
363 }
364 }
365
366 #[allow(clippy::unused_self)]
367 fn configure_windows(&self, cmake_cfg: &mut cmake::Config) {
368 if is_fips_build() {
369 cmake_cfg.generator("Ninja");
370 let env_map = self
371 .collect_vcvarsall_bat()
372 .map_err(|x| panic!("{}", x))
373 .unwrap();
374 for (key, value) in env_map {
375 cmake_cfg.env(key, value);
376 }
377 }
378
379 match (target_env().as_str(), target_arch().as_str()) {
380 ("msvc", "aarch64") => {
381 // If CMAKE_GENERATOR is either not set or not set to "Ninja"
382 let cmake_generator = optional_env("CMAKE_GENERATOR");
383 if cmake_generator.is_none() || cmake_generator.unwrap().to_lowercase() != "ninja" {
384 // The following is not supported by the Ninja generator
385 cmake_cfg.generator_toolset(format!(
386 "ClangCL{}",
387 if cfg!(target_arch = "x86_64") {
388 ",host=x64"
389 } else {
390 ""
391 }
392 ));
393 cmake_cfg.define("CMAKE_GENERATOR_PLATFORM", "ARM64");
394 }
395 cmake_cfg.define("CMAKE_SYSTEM_NAME", "Windows");
396 cmake_cfg.define("CMAKE_SYSTEM_PROCESSOR", "ARM64");
397 }
398 ("msvc", _) => {
399 // No-op
400 }
401 (_, arch) => {
402 cmake_cfg.define("CMAKE_SYSTEM_NAME", "Windows");
403 cmake_cfg.define("CMAKE_SYSTEM_PROCESSOR", arch);
404 }
405 }
406
407 // Workaround for win7-windows-gnu targets: the upstream C source gates the
408 // Win7 compat path with `!defined(__MINGW32__)`. CMakeLists.txt already sets
409 // _WIN32_WINNT for MinGW, but we must force AWSLC_WINDOWS_7_COMPAT until the
410 // upstream fix lands: https://github.com/aws/aws-lc/pull/3239
411 if target().contains("-win7-windows-gnu") {
412 cmake_cfg.cflag("-DAWSLC_WINDOWS_7_COMPAT");
413 }
414 }
415
416 /// Returns the architecture argument for `vcvarsall.bat`.
417 ///
418 /// In a Cargo build-script, `cfg!(target_arch)` is the **host** architecture
419 /// (the machine running the build), while `target_arch()` (backed by
420 /// `CARGO_CFG_TARGET_ARCH`) is the **target** architecture we are compiling for.
421 ///
422 /// `vcvarsall.bat` accepts a single token that encodes both:
423 /// - native : `x64`, `arm64`, `x86`
424 /// - cross : `<host>_<target>`, e.g. `x64_arm64`
425 fn vcvarsall_arch() -> &'static str {
426 let target = target_arch();
427 match (
428 cfg!(target_arch = "x86_64"),
429 cfg!(target_arch = "aarch64"),
430 target.as_str(),
431 ) {
432 // Host x64
433 (true, _, "x86_64") => "x64",
434 (true, _, "aarch64") => "x64_arm64",
435 (true, _, "x86") => "x64_x86",
436 // Host arm64
437 (_, true, "aarch64") => "arm64",
438 (_, true, "x86_64") => "arm64_x64",
439 (_, true, "x86") => "arm64_x86",
440 // Fallback
441 _ => "x64",
442 }
443 }
444
445 fn collect_vcvarsall_bat(&self) -> Result<HashMap<String, String>, String> {
446 let mut map: HashMap<String, String> = HashMap::new();
447 let script_path = self.manifest_dir.join("builder").join("printenv.bat");
448 let arch = OsString::from(Self::vcvarsall_arch());
449 let result = execute_command(script_path.as_os_str(), &[arch.as_os_str()]);
450 if !result.status {
451 eprintln!("{}", result.stdout);
452 return Err("Failed to run vcvarsall.bat.".to_owned());
453 }
454 eprintln!("{}", result.stdout);
455 let lines = result.stdout.lines();
456 for line in lines {
457 if let Some((var, val)) = line.split_once('=') {
458 map.insert(var.to_string(), val.to_string());
459 }
460 }
461 Ok(map)
462 }
463
464 fn configure_prebuilt_nasm(&self, cmake_cfg: &mut cmake::Config) {
465 emit_warning("!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!");
466 emit_warning("!!! Using pre-built NASM binaries !!!");
467 emit_warning("!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!");
468
469 let script_path = self.select_prebuilt_nasm_script();
470 let script_path = script_path.display().to_string();
471 let script_path = script_path.replace('\\', "/");
472
473 cmake_cfg.define("CMAKE_ASM_NASM_COMPILER", script_path.as_str());
474 // Without the following definition, the build fails with a message similar to the one
475 // reported here: https://gitlab.kitware.com/cmake/cmake/-/issues/19453
476 // The variables below were found in the associated fix:
477 // https://gitlab.kitware.com/cmake/cmake/-/merge_requests/4257/diffs
478 cmake_cfg.define(
479 "CMAKE_ASM_NASM_COMPILE_OPTIONS_MSVC_RUNTIME_LIBRARY_MultiThreaded",
480 "",
481 );
482 cmake_cfg.define(
483 "CMAKE_ASM_NASM_COMPILE_OPTIONS_MSVC_RUNTIME_LIBRARY_MultiThreadedDLL",
484 "",
485 );
486 cmake_cfg.define(
487 "CMAKE_ASM_NASM_COMPILE_OPTIONS_MSVC_RUNTIME_LIBRARY_MultiThreadedDebug",
488 "",
489 );
490 cmake_cfg.define(
491 "CMAKE_ASM_NASM_COMPILE_OPTIONS_MSVC_RUNTIME_LIBRARY_MultiThreadedDebugDLL",
492 "",
493 );
494 cmake_cfg.define(
495 "CMAKE_ASM_NASM_COMPILE_OPTIONS_MSVC_DEBUG_INFORMATION_FORMAT_ProgramDatabase",
496 "",
497 );
498 }
499
500 /// Configure the `CMake` build for sanitizer instrumentation.
501 ///
502 /// Resolves the active sanitizer from either the `asan` Cargo feature flag
503 /// (kept for backward compatibility) or the `AWS_LC_SYS_SANITIZER` /
504 /// `AWS_LC_FIPS_SYS_SANITIZER` environment variable (preferred). Supported
505 /// values: `asan`, `msan`, `tsan`.
506 fn configure_sanitizer(cmake_cfg: &mut cmake::Config) {
507 let feature_sanitizer = if cfg!(feature = "asan") {
508 Some("asan")
509 } else {
510 None
511 };
512 let env_sanitizer = sanitizer();
513 let env_sanitizer = env_sanitizer.as_deref();
514
515 let active_sanitizer = match (feature_sanitizer, env_sanitizer) {
516 (Some(f), Some(e)) if f != e => {
517 panic!(
518 "Conflicting sanitizer configuration: feature flag '{f}' and \
519 AWS_LC_SYS_SANITIZER='{e}'. Remove one to resolve the conflict."
520 );
521 }
522 (Some(f), _) => Some(f),
523 (_, Some(e)) => Some(e),
524 _ => None,
525 };
526
527 if let Some(san) = active_sanitizer {
528 set_env_for_target("CC", "clang");
529 set_env_for_target("CXX", "clang++");
530
531 match san {
532 "asan" => {
533 cmake_cfg.define("ASAN", "1");
534 }
535 "msan" => {
536 // AWS-LC's CMakeLists.txt correctly skips the FIPS
537 // delocator when MSAN is set, but bcm.c guards the
538 // integrity-test symbols with `#if !defined(OPENSSL_ASAN)`
539 // only — it does not check OPENSSL_MSAN. Until the
540 // upstream C guard is broadened, MSAN + FIPS will produce
541 // undefined-symbol link errors for BORINGSSL_bcm_text_*.
542 assert!(
543 !is_fips_build(),
544 "MemorySanitizer is not supported for FIPS builds. \
545 The FIPS integrity check in bcm.c lacks an \
546 OPENSSL_MSAN guard, causing undefined-symbol link \
547 errors (BORINGSSL_bcm_text_start/end/hash)."
548 );
549 cmake_cfg.define("MSAN", "1");
550 }
551 "tsan" => {
552 cmake_cfg.define("TSAN", "1");
553 // AWS-LC's CMakeLists.txt defines BORINGSSL_DISPATCH_TEST for
554 // non-FIPS, non-release builds. That macro enables non-atomic
555 // writes to a global BORINGSSL_function_hit[] array from ~15
556 // dispatch points (C and assembly), which TSAN flags as data
557 // races. The writes are benign (idempotent store of 1), but
558 // suppressing every function name is impractical. Force the C
559 // library to build in Release mode so the macro is never
560 // defined. This matches AWS-LC's own sanitizer CI, which
561 // always uses -DCMAKE_BUILD_TYPE=Release.
562 cmake_cfg.profile("Release");
563 }
564 other => {
565 panic!("Unsupported sanitizer: '{other}'. Supported values: asan, msan, tsan")
566 }
567 }
568 }
569 }
570
571 fn configure_open_harmony(cmake_cfg: &mut cmake::Config) {
572 let mut cflags = vec!["-Wno-unused-command-line-argument"];
573 let mut asmflags = vec![];
574
575 // If a toolchain is not specified by the environment
576 if optional_env_optional_crate_target("CMAKE_TOOLCHAIN_FILE").is_none() {
577 if let Ok(ndk) = env::var("OHOS_NDK_HOME") {
578 set_env_for_target(
579 "CMAKE_TOOLCHAIN_FILE",
580 format!("{ndk}/native/build/cmake/ohos.toolchain.cmake"),
581 );
582 } else if let Ok(sdk) = env::var("OHOS_SDK_NATIVE") {
583 set_env_for_target(
584 "CMAKE_TOOLCHAIN_FILE",
585 format!("{sdk}/build/cmake/ohos.toolchain.cmake"),
586 );
587 } else {
588 emit_warning(
589 "Neither OHOS_NDK_HOME nor OHOS_SDK_NATIVE are set! No toolchain found.",
590 );
591 }
592 }
593
594 match effective_target().as_str() {
595 "aarch64-unknown-linux-ohos" => {
596 cmake_cfg.define("OHOS_ARCH", "arm64-v8a");
597 }
598 "armv7-unknown-linux-ohos" => {
599 const ARM7_FLAGS: [&str; 6] = [
600 "-march=armv7-a",
601 "-mfloat-abi=softfp",
602 "-mtune=generic-armv7-a",
603 "-mthumb",
604 "-mfpu=neon",
605 "-DHAVE_NEON",
606 ];
607 cflags.extend(ARM7_FLAGS);
608 asmflags.extend(ARM7_FLAGS);
609 cmake_cfg.define("OHOS_ARCH", "armeabi-v7a");
610 }
611 "x86_64-unknown-linux-ohos" => {
612 const X86_64_FLAGS: [&str; 3] = ["-msse4.1", "-DHAVE_NEON_X86", "-DHAVE_NEON"];
613 cflags.extend(X86_64_FLAGS);
614 asmflags.extend(X86_64_FLAGS);
615 cmake_cfg.define("OHOS_ARCH", "x86_64");
616 }
617 ohos_target => {
618 emit_warning(format!("Target: {ohos_target} is not support yet!").as_str());
619 }
620 }
621 cmake_cfg
622 .cflag(cflags.join(" ").as_str())
623 .cxxflag(cflags.join(" ").as_str())
624 .asmflag(asmflags.join(" ").as_str());
625 }
626
627 fn build_library(&self) -> PathBuf {
628 self.prepare_cmake_build()
629 .configure_arg("--no-warn-unused-cli")
630 .build()
631 }
632 }
633
634 impl crate::Builder for CmakeBuilder {
635 fn check_dependencies(&self) -> Result<(), String> {
636 let mut missing_dependency = false;
637 if target_os() == "windows" && target_arch() == "x86_64" {
638 if is_no_asm() && Some(true) == allow_prebuilt_nasm() {
639 eprintln!(
640 "Build environment has both `AWS_LC_SYS_PREBUILT_NASM` and `AWS_LC_SYS_NO_ASM` set.\
641 Please remove one of these environment variables.
642 See User Guide: https://aws.github.io/aws-lc-rs/index.html"
643 );
644 }
645 if !is_no_asm() && !test_nasm_command() && !use_prebuilt_nasm() {
646 eprintln!(
647 "Consider installing NASM or setting `AWS_LC_SYS_PREBUILT_NASM` in the build environment.\
648 See User Guide: https://aws.github.io/aws-lc-rs/index.html"
649 );
650 eprintln!("Missing dependency: nasm");
651 missing_dependency = true;
652 }
653 }
654 if target_os() == "windows"
655 && target_arch() == "aarch64"
656 && target_env() == "msvc"
657 && !test_clang_cl_command()
658 {
659 eprintln!("Missing dependency: clang-cl");
660 missing_dependency = true;
661 }
662 if let Some(cmake_cmd) = find_cmake_command() {
663 unsafe {
664 env::set_var("CMAKE", cmake_cmd);
665 }
666 } else {
667 eprintln!("Missing dependency: cmake");
668 missing_dependency = true;
669 }
670
671 if missing_dependency {
672 return Err("Required build dependency is missing. Halting build.".to_owned());
673 }
674
675 Ok(())
676 }
677 fn build(&self) -> Result<(), String> {
678 self.build_library();
679
680 println!(
681 "cargo:rustc-link-search=native={}",
682 self.artifact_output_dir().display()
683 );
684
685 println!(
686 "cargo:rustc-link-lib={}={}",
687 self.output_lib_type.rust_lib_type(),
688 Crypto.libname(&self.build_prefix)
689 );
690
691 if cfg!(feature = "ssl") {
692 println!(
693 "cargo:rustc-link-lib={}={}",
694 self.output_lib_type.rust_lib_type(),
695 Ssl.libname(&self.build_prefix)
696 );
697 }
698
699 Ok(())
700 }
701
702 fn name(&self) -> &'static str {
703 "CMake"
704 }
705 }
706
707 #[cfg(test)]
708 mod tests {
709 use super::strip_lto_flags;
710
711 #[test]
712 fn test_strip_lto_flags() {
713 // RPM-style CFLAGS with -flto=auto and -ffat-lto-objects
714 let input = "-O2 -ftree-vectorize -flto=auto -ffat-lto-objects -fexceptions -g -fPIC";
715 assert_eq!(
716 strip_lto_flags(input),
717 "-O2 -ftree-vectorize -fexceptions -g -fPIC"
718 );
719
720 // Various LTO flag forms
721 assert_eq!(strip_lto_flags("-flto -O2"), "-O2");
722 assert_eq!(strip_lto_flags("-flto=thin -O2"), "-O2");
723 assert_eq!(strip_lto_flags("-flto=full -O2"), "-O2");
724 assert_eq!(strip_lto_flags("-flto=4 -O2"), "-O2");
725 assert_eq!(strip_lto_flags("-fno-fat-lto-objects -O2"), "-O2");
726
727 // No LTO flags - passthrough
728 let no_lto = "-O2 -fPIC -g";
729 assert_eq!(strip_lto_flags(no_lto), no_lto);
730
731 // Empty input
732 assert_eq!(strip_lto_flags(""), "");
733 }
734 }