cc/lib.rs
1//! A library for [Cargo build scripts](https://doc.rust-lang.org/cargo/reference/build-scripts.html)
2//! to compile a set of C/C++/assembly/CUDA files into a static archive for Cargo
3//! to link into the crate being built. This crate does not compile code itself;
4//! it calls out to the default compiler for the platform. This crate will
5//! automatically detect situations such as cross compilation and
6//! [various environment variables](#external-configuration-via-environment-variables) and will build code appropriately.
7//!
8//! # Example
9//!
10//! First, you'll want to both add a build script for your crate (`build.rs`) and
11//! also add this crate to your `Cargo.toml` via:
12//!
13//! ```toml
14//! [build-dependencies]
15//! cc = "1.0"
16//! ```
17//!
18//! Next up, you'll want to write a build script like so:
19//!
20//! ```rust,no_run
21//! // build.rs
22//! cc::Build::new()
23//! .file("foo.c")
24//! .file("bar.c")
25//! .compile("foo");
26//! ```
27//!
28//! And that's it! Running `cargo build` should take care of the rest and your Rust
29//! application will now have the C files `foo.c` and `bar.c` compiled into a file
30//! named `libfoo.a`. If the C files contain
31//!
32//! ```c
33//! void foo_function(void) { ... }
34//! ```
35//!
36//! and
37//!
38//! ```c
39//! int32_t bar_function(int32_t x) { ... }
40//! ```
41//!
42//! you can call them from Rust by declaring them in
43//! your Rust code like so:
44//!
45//! ```rust,no_run
46//! extern "C" {
47//! fn foo_function();
48//! fn bar_function(x: i32) -> i32;
49//! }
50//!
51//! pub fn call() {
52//! unsafe {
53//! foo_function();
54//! bar_function(42);
55//! }
56//! }
57//!
58//! fn main() {
59//! call();
60//! }
61//! ```
62//!
63//! See [the Rustonomicon](https://doc.rust-lang.org/nomicon/ffi.html) for more details.
64//!
65//! # External configuration via environment variables
66//!
67//! To control the programs and flags used for building, the builder can set a
68//! number of different environment variables.
69//!
70//! * `CFLAGS` - a series of space separated flags passed to compilers. Note that
71//! individual flags cannot currently contain spaces, so doing
72//! something like: `-L=foo\ bar` is not possible.
73//! * `CC` - the actual C compiler used. Note that this is used as an exact
74//! executable name, so (for example) no extra flags can be passed inside
75//! this variable, and the builder must ensure that there aren't any
76//! trailing spaces. This compiler must understand the `-c` flag. For
77//! certain `TARGET`s, it also is assumed to know about other flags (most
78//! common is `-fPIC`).
79//! * `AR` - the `ar` (archiver) executable to use to build the static library.
80//! * `CRATE_CC_NO_DEFAULTS` - the default compiler flags may cause conflicts in
81//! some cross compiling scenarios. Setting this variable
82//! will disable the generation of default compiler
83//! flags.
84//! * `CC_ENABLE_DEBUG_OUTPUT` - if set, compiler command invocations and exit codes will
85//! be logged to stdout. This is useful for debugging build script issues, but can be
86//! overly verbose for normal use.
87//! * `CC_SHELL_ESCAPED_FLAGS` - if set, `*FLAGS` will be parsed as if they were shell
88//! arguments (similar to `make` and `cmake`) rather than splitting them on each space.
89//! For example, with `CFLAGS='a "b c"'`, the compiler will be invoked with 2 arguments -
90//! `a` and `b c` - rather than 3: `a`, `"b` and `c"`.
91//! * `CXX...` - see [C++ Support](#c-support).
92//!
93//! Furthermore, projects using this crate may specify custom environment variables
94//! to be inspected, for example via the `Build::try_flags_from_environment`
95//! function. Consult the project’s own documentation or its use of the `cc` crate
96//! for any additional variables it may use.
97//!
98//! Each of these variables can also be supplied with certain prefixes and suffixes,
99//! in the following prioritized order:
100//!
101//! 1. `<var>_<target>` - for example, `CC_x86_64-unknown-linux-gnu`
102//! 2. `<var>_<target_with_underscores>` - for example, `CC_x86_64_unknown_linux_gnu`
103//! 3. `<build-kind>_<var>` - for example, `HOST_CC` or `TARGET_CFLAGS`
104//! 4. `<var>` - a plain `CC`, `AR` as above.
105//!
106//! If none of these variables exist, cc-rs uses built-in defaults.
107//!
108//! In addition to the above optional environment variables, `cc-rs` has some
109//! functions with hard requirements on some variables supplied by [cargo's
110//! build-script driver][cargo] that it has the `TARGET`, `OUT_DIR`, `OPT_LEVEL`,
111//! and `HOST` variables.
112//!
113//! [cargo]: https://doc.rust-lang.org/cargo/reference/build-scripts.html#inputs-to-the-build-script
114//!
115//! # Optional features
116//!
117//! ## Parallel
118//!
119//! Currently cc-rs supports parallel compilation (think `make -jN`) but this
120//! feature is turned off by default. To enable cc-rs to compile C/C++ in parallel,
121//! you can change your dependency to:
122//!
123//! ```toml
124//! [build-dependencies]
125//! cc = { version = "1.0", features = ["parallel"] }
126//! ```
127//!
128//! By default cc-rs will limit parallelism to `$NUM_JOBS`, or if not present it
129//! will limit it to the number of cpus on the machine. If you are using cargo,
130//! use `-jN` option of `build`, `test` and `run` commands as `$NUM_JOBS`
131//! is supplied by cargo.
132//!
133//! # Compile-time Requirements
134//!
135//! To work properly this crate needs access to a C compiler when the build script
136//! is being run. This crate does not ship a C compiler with it. The compiler
137//! required varies per platform, but there are three broad categories:
138//!
139//! * Unix platforms require `cc` to be the C compiler. This can be found by
140//! installing cc/clang on Linux distributions and Xcode on macOS, for example.
141//! * Windows platforms targeting MSVC (e.g. your target triple ends in `-msvc`)
142//! require Visual Studio to be installed. `cc-rs` attempts to locate it, and
143//! if it fails, `cl.exe` is expected to be available in `PATH`. This can be
144//! set up by running the appropriate developer tools shell.
145//! * Windows platforms targeting MinGW (e.g. your target triple ends in `-gnu`)
146//! require `cc` to be available in `PATH`. We recommend the
147//! [MinGW-w64](https://www.mingw-w64.org/) distribution.
148//! You may also acquire it via
149//! [MSYS2](https://www.msys2.org/), as explained [here][msys2-help]. Make sure
150//! to install the appropriate architecture corresponding to your installation of
151//! rustc. GCC from older [MinGW](http://www.mingw.org/) project is compatible
152//! only with 32-bit rust compiler.
153//!
154//! [msys2-help]: https://github.com/rust-lang/rust/blob/master/INSTALL.md#building-on-windows
155//!
156//! # C++ support
157//!
158//! `cc-rs` supports C++ libraries compilation by using the `cpp` method on
159//! `Build`:
160//!
161//! ```rust,no_run
162//! cc::Build::new()
163//! .cpp(true) // Switch to C++ library compilation.
164//! .file("foo.cpp")
165//! .compile("foo");
166//! ```
167//!
168//! For C++ libraries, the `CXX` and `CXXFLAGS` environment variables are used instead of `CC` and `CFLAGS`.
169//!
170//! The C++ standard library may be linked to the crate target. By default it's `libc++` for macOS, FreeBSD, and OpenBSD, `libc++_shared` for Android, nothing for MSVC, and `libstdc++` for anything else. It can be changed in one of two ways:
171//!
172//! 1. by using the `cpp_link_stdlib` method on `Build`:
173//! ```rust,no_run
174//! cc::Build::new()
175//! .cpp(true)
176//! .file("foo.cpp")
177//! .cpp_link_stdlib("stdc++") // use libstdc++
178//! .compile("foo");
179//! ```
180//! 2. by setting the `CXXSTDLIB` environment variable.
181//!
182//! In particular, for Android you may want to [use `c++_static` if you have at most one shared library](https://developer.android.com/ndk/guides/cpp-support).
183//!
184//! Remember that C++ does name mangling so `extern "C"` might be required to enable Rust linker to find your functions.
185//!
186//! # CUDA C++ support
187//!
188//! `cc-rs` also supports compiling CUDA C++ libraries by using the `cuda` method
189//! on `Build`:
190//!
191//! ```rust,no_run
192//! cc::Build::new()
193//! // Switch to CUDA C++ library compilation using NVCC.
194//! .cuda(true)
195//! .cudart("static")
196//! // Generate code for Maxwell (GTX 970, 980, 980 Ti, Titan X).
197//! .flag("-gencode").flag("arch=compute_52,code=sm_52")
198//! // Generate code for Maxwell (Jetson TX1).
199//! .flag("-gencode").flag("arch=compute_53,code=sm_53")
200//! // Generate code for Pascal (GTX 1070, 1080, 1080 Ti, Titan Xp).
201//! .flag("-gencode").flag("arch=compute_61,code=sm_61")
202//! // Generate code for Pascal (Tesla P100).
203//! .flag("-gencode").flag("arch=compute_60,code=sm_60")
204//! // Generate code for Pascal (Jetson TX2).
205//! .flag("-gencode").flag("arch=compute_62,code=sm_62")
206//! // Generate code in parallel
207//! .flag("-t0")
208//! .file("bar.cu")
209//! .compile("bar");
210//! ```
211
212#![doc(html_root_url = "https://docs.rs/cc/1.0")]
213#![deny(warnings)]
214#![deny(missing_docs)]
215#![deny(clippy::disallowed_methods)]
216#![warn(clippy::doc_markdown)]
217
218use std::borrow::Cow;
219use std::collections::HashMap;
220use std::env;
221use std::ffi::{OsStr, OsString};
222use std::fmt::{self, Display};
223use std::fs;
224use std::io::{self, Write};
225use std::path::{Component, Path, PathBuf};
226#[cfg(feature = "parallel")]
227use std::process::Child;
228use std::process::Command;
229use std::sync::{Arc, RwLock};
230
231use shlex::Shlex;
232
233#[cfg(feature = "parallel")]
234mod parallel;
235mod target;
236mod windows;
237use self::target::TargetInfo;
238// Regardless of whether this should be in this crate's public API,
239// it has been since 2015, so don't break it.
240pub use windows::find_tools as windows_registry;
241
242mod command_helpers;
243use command_helpers::*;
244
245mod tool;
246pub use tool::Tool;
247use tool::ToolFamily;
248
249mod tempfile;
250
251mod utilities;
252use utilities::*;
253
254#[derive(Debug, Eq, PartialEq, Hash)]
255struct CompilerFlag {
256 compiler: Box<Path>,
257 flag: Box<OsStr>,
258}
259
260type Env = Option<Arc<OsStr>>;
261
262#[derive(Debug, Default)]
263struct BuildCache {
264 env_cache: RwLock<HashMap<Box<str>, Env>>,
265 apple_sdk_root_cache: RwLock<HashMap<Box<str>, Arc<OsStr>>>,
266 apple_versions_cache: RwLock<HashMap<Box<str>, Arc<str>>>,
267 cached_compiler_family: RwLock<HashMap<Box<Path>, ToolFamily>>,
268 known_flag_support_status_cache: RwLock<HashMap<CompilerFlag, bool>>,
269 target_info_parser: target::TargetInfoParser,
270}
271
272/// A builder for compilation of a native library.
273///
274/// A `Build` is the main type of the `cc` crate and is used to control all the
275/// various configuration options and such of a compile. You'll find more
276/// documentation on each method itself.
277#[derive(Clone, Debug)]
278pub struct Build {
279 include_directories: Vec<Arc<Path>>,
280 definitions: Vec<(Arc<str>, Option<Arc<str>>)>,
281 objects: Vec<Arc<Path>>,
282 flags: Vec<Arc<OsStr>>,
283 flags_supported: Vec<Arc<OsStr>>,
284 ar_flags: Vec<Arc<OsStr>>,
285 asm_flags: Vec<Arc<OsStr>>,
286 no_default_flags: bool,
287 files: Vec<Arc<Path>>,
288 cpp: bool,
289 cpp_link_stdlib: Option<Option<Arc<str>>>,
290 cpp_set_stdlib: Option<Arc<str>>,
291 cuda: bool,
292 cudart: Option<Arc<str>>,
293 ccbin: bool,
294 std: Option<Arc<str>>,
295 target: Option<Arc<str>>,
296 /// The host compiler.
297 ///
298 /// Try to not access this directly, and instead prefer `cfg!(...)`.
299 host: Option<Arc<str>>,
300 out_dir: Option<Arc<Path>>,
301 opt_level: Option<Arc<str>>,
302 debug: Option<bool>,
303 force_frame_pointer: Option<bool>,
304 env: Vec<(Arc<OsStr>, Arc<OsStr>)>,
305 compiler: Option<Arc<Path>>,
306 archiver: Option<Arc<Path>>,
307 ranlib: Option<Arc<Path>>,
308 cargo_output: CargoOutput,
309 link_lib_modifiers: Vec<Arc<OsStr>>,
310 pic: Option<bool>,
311 use_plt: Option<bool>,
312 static_crt: Option<bool>,
313 shared_flag: Option<bool>,
314 static_flag: Option<bool>,
315 warnings_into_errors: bool,
316 warnings: Option<bool>,
317 extra_warnings: Option<bool>,
318 emit_rerun_if_env_changed: bool,
319 shell_escaped_flags: Option<bool>,
320 build_cache: Arc<BuildCache>,
321}
322
323/// Represents the types of errors that may occur while using cc-rs.
324#[derive(Clone, Debug)]
325enum ErrorKind {
326 /// Error occurred while performing I/O.
327 IOError,
328 /// Environment variable not found, with the var in question as extra info.
329 EnvVarNotFound,
330 /// Error occurred while using external tools (ie: invocation of compiler).
331 ToolExecError,
332 /// Error occurred due to missing external tools.
333 ToolNotFound,
334 /// One of the function arguments failed validation.
335 InvalidArgument,
336 /// No known macro is defined for the compiler when discovering tool family
337 ToolFamilyMacroNotFound,
338 /// Invalid target
339 InvalidTarget,
340 #[cfg(feature = "parallel")]
341 /// jobserver helpthread failure
342 JobserverHelpThreadError,
343}
344
345/// Represents an internal error that occurred, with an explanation.
346#[derive(Clone, Debug)]
347pub struct Error {
348 /// Describes the kind of error that occurred.
349 kind: ErrorKind,
350 /// More explanation of error that occurred.
351 message: Cow<'static, str>,
352}
353
354impl Error {
355 fn new(kind: ErrorKind, message: impl Into<Cow<'static, str>>) -> Error {
356 Error {
357 kind,
358 message: message.into(),
359 }
360 }
361}
362
363impl From<io::Error> for Error {
364 fn from(e: io::Error) -> Error {
365 Error::new(ErrorKind::IOError, format!("{}", e))
366 }
367}
368
369impl Display for Error {
370 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
371 write!(f, "{:?}: {}", self.kind, self.message)
372 }
373}
374
375impl std::error::Error for Error {}
376
377/// Represents an object.
378///
379/// This is a source file -> object file pair.
380#[derive(Clone, Debug)]
381struct Object {
382 src: PathBuf,
383 dst: PathBuf,
384}
385
386impl Object {
387 /// Create a new source file -> object file pair.
388 fn new(src: PathBuf, dst: PathBuf) -> Object {
389 Object { src, dst }
390 }
391}
392
393impl Build {
394 /// Construct a new instance of a blank set of configuration.
395 ///
396 /// This builder is finished with the [`compile`] function.
397 ///
398 /// [`compile`]: struct.Build.html#method.compile
399 pub fn new() -> Build {
400 Build {
401 include_directories: Vec::new(),
402 definitions: Vec::new(),
403 objects: Vec::new(),
404 flags: Vec::new(),
405 flags_supported: Vec::new(),
406 ar_flags: Vec::new(),
407 asm_flags: Vec::new(),
408 no_default_flags: false,
409 files: Vec::new(),
410 shared_flag: None,
411 static_flag: None,
412 cpp: false,
413 cpp_link_stdlib: None,
414 cpp_set_stdlib: None,
415 cuda: false,
416 cudart: None,
417 ccbin: true,
418 std: None,
419 target: None,
420 host: None,
421 out_dir: None,
422 opt_level: None,
423 debug: None,
424 force_frame_pointer: None,
425 env: Vec::new(),
426 compiler: None,
427 archiver: None,
428 ranlib: None,
429 cargo_output: CargoOutput::new(),
430 link_lib_modifiers: Vec::new(),
431 pic: None,
432 use_plt: None,
433 static_crt: None,
434 warnings: None,
435 extra_warnings: None,
436 warnings_into_errors: false,
437 emit_rerun_if_env_changed: true,
438 shell_escaped_flags: None,
439 build_cache: Arc::default(),
440 }
441 }
442
443 /// Add a directory to the `-I` or include path for headers
444 ///
445 /// # Example
446 ///
447 /// ```no_run
448 /// use std::path::Path;
449 ///
450 /// let library_path = Path::new("/path/to/library");
451 ///
452 /// cc::Build::new()
453 /// .file("src/foo.c")
454 /// .include(library_path)
455 /// .include("src")
456 /// .compile("foo");
457 /// ```
458 pub fn include<P: AsRef<Path>>(&mut self, dir: P) -> &mut Build {
459 self.include_directories.push(dir.as_ref().into());
460 self
461 }
462
463 /// Add multiple directories to the `-I` include path.
464 ///
465 /// # Example
466 ///
467 /// ```no_run
468 /// # use std::path::Path;
469 /// # let condition = true;
470 /// #
471 /// let mut extra_dir = None;
472 /// if condition {
473 /// extra_dir = Some(Path::new("/path/to"));
474 /// }
475 ///
476 /// cc::Build::new()
477 /// .file("src/foo.c")
478 /// .includes(extra_dir)
479 /// .compile("foo");
480 /// ```
481 pub fn includes<P>(&mut self, dirs: P) -> &mut Build
482 where
483 P: IntoIterator,
484 P::Item: AsRef<Path>,
485 {
486 for dir in dirs {
487 self.include(dir);
488 }
489 self
490 }
491
492 /// Specify a `-D` variable with an optional value.
493 ///
494 /// # Example
495 ///
496 /// ```no_run
497 /// cc::Build::new()
498 /// .file("src/foo.c")
499 /// .define("FOO", "BAR")
500 /// .define("BAZ", None)
501 /// .compile("foo");
502 /// ```
503 pub fn define<'a, V: Into<Option<&'a str>>>(&mut self, var: &str, val: V) -> &mut Build {
504 self.definitions
505 .push((var.into(), val.into().map(Into::into)));
506 self
507 }
508
509 /// Add an arbitrary object file to link in
510 pub fn object<P: AsRef<Path>>(&mut self, obj: P) -> &mut Build {
511 self.objects.push(obj.as_ref().into());
512 self
513 }
514
515 /// Add arbitrary object files to link in
516 pub fn objects<P>(&mut self, objs: P) -> &mut Build
517 where
518 P: IntoIterator,
519 P::Item: AsRef<Path>,
520 {
521 for obj in objs {
522 self.object(obj);
523 }
524 self
525 }
526
527 /// Add an arbitrary flag to the invocation of the compiler
528 ///
529 /// # Example
530 ///
531 /// ```no_run
532 /// cc::Build::new()
533 /// .file("src/foo.c")
534 /// .flag("-ffunction-sections")
535 /// .compile("foo");
536 /// ```
537 pub fn flag(&mut self, flag: impl AsRef<OsStr>) -> &mut Build {
538 self.flags.push(flag.as_ref().into());
539 self
540 }
541
542 /// Removes a compiler flag that was added by [`Build::flag`].
543 ///
544 /// Will not remove flags added by other means (default flags,
545 /// flags from env, and so on).
546 ///
547 /// # Example
548 /// ```
549 /// cc::Build::new()
550 /// .file("src/foo.c")
551 /// .flag("unwanted_flag")
552 /// .remove_flag("unwanted_flag");
553 /// ```
554
555 pub fn remove_flag(&mut self, flag: &str) -> &mut Build {
556 self.flags.retain(|other_flag| &**other_flag != flag);
557 self
558 }
559
560 /// Add a flag to the invocation of the ar
561 ///
562 /// # Example
563 ///
564 /// ```no_run
565 /// cc::Build::new()
566 /// .file("src/foo.c")
567 /// .file("src/bar.c")
568 /// .ar_flag("/NODEFAULTLIB:libc.dll")
569 /// .compile("foo");
570 /// ```
571 pub fn ar_flag(&mut self, flag: impl AsRef<OsStr>) -> &mut Build {
572 self.ar_flags.push(flag.as_ref().into());
573 self
574 }
575
576 /// Add a flag that will only be used with assembly files.
577 ///
578 /// The flag will be applied to input files with either a `.s` or
579 /// `.asm` extension (case insensitive).
580 ///
581 /// # Example
582 ///
583 /// ```no_run
584 /// cc::Build::new()
585 /// .asm_flag("-Wa,-defsym,abc=1")
586 /// .file("src/foo.S") // The asm flag will be applied here
587 /// .file("src/bar.c") // The asm flag will not be applied here
588 /// .compile("foo");
589 /// ```
590 pub fn asm_flag(&mut self, flag: impl AsRef<OsStr>) -> &mut Build {
591 self.asm_flags.push(flag.as_ref().into());
592 self
593 }
594
595 fn ensure_check_file(&self) -> Result<PathBuf, Error> {
596 let out_dir = self.get_out_dir()?;
597 let src = if self.cuda {
598 assert!(self.cpp);
599 out_dir.join("flag_check.cu")
600 } else if self.cpp {
601 out_dir.join("flag_check.cpp")
602 } else {
603 out_dir.join("flag_check.c")
604 };
605
606 if !src.exists() {
607 let mut f = fs::File::create(&src)?;
608 write!(f, "int main(void) {{ return 0; }}")?;
609 }
610
611 Ok(src)
612 }
613
614 /// Run the compiler to test if it accepts the given flag.
615 ///
616 /// For a convenience method for setting flags conditionally,
617 /// see `flag_if_supported()`.
618 ///
619 /// It may return error if it's unable to run the compiler with a test file
620 /// (e.g. the compiler is missing or a write to the `out_dir` failed).
621 ///
622 /// Note: Once computed, the result of this call is stored in the
623 /// `known_flag_support` field. If `is_flag_supported(flag)`
624 /// is called again, the result will be read from the hash table.
625 pub fn is_flag_supported(&self, flag: impl AsRef<OsStr>) -> Result<bool, Error> {
626 self.is_flag_supported_inner(
627 flag.as_ref(),
628 self.get_base_compiler()?.path(),
629 &self.get_target()?,
630 )
631 }
632
633 fn is_flag_supported_inner(
634 &self,
635 flag: &OsStr,
636 compiler_path: &Path,
637 target: &TargetInfo<'_>,
638 ) -> Result<bool, Error> {
639 let compiler_flag = CompilerFlag {
640 compiler: compiler_path.into(),
641 flag: flag.into(),
642 };
643
644 if let Some(is_supported) = self
645 .build_cache
646 .known_flag_support_status_cache
647 .read()
648 .unwrap()
649 .get(&compiler_flag)
650 .cloned()
651 {
652 return Ok(is_supported);
653 }
654
655 let out_dir = self.get_out_dir()?;
656 let src = self.ensure_check_file()?;
657 let obj = out_dir.join("flag_check");
658
659 let mut compiler = {
660 let mut cfg = Build::new();
661 cfg.flag(flag)
662 .compiler(compiler_path)
663 .cargo_metadata(self.cargo_output.metadata)
664 .opt_level(0)
665 .debug(false)
666 .cpp(self.cpp)
667 .cuda(self.cuda)
668 .emit_rerun_if_env_changed(self.emit_rerun_if_env_changed);
669 if let Some(target) = &self.target {
670 cfg.target(target);
671 }
672 if let Some(host) = &self.host {
673 cfg.host(host);
674 }
675 cfg.try_get_compiler()?
676 };
677
678 // Clang uses stderr for verbose output, which yields a false positive
679 // result if the CFLAGS/CXXFLAGS include -v to aid in debugging.
680 if compiler.family.verbose_stderr() {
681 compiler.remove_arg("-v".into());
682 }
683 if compiler.is_like_clang() {
684 // Avoid reporting that the arg is unsupported just because the
685 // compiler complains that it wasn't used.
686 compiler.push_cc_arg("-Wno-unused-command-line-argument".into());
687 }
688
689 let mut cmd = compiler.to_command();
690 let is_arm = matches!(target.arch, "aarch64" | "arm");
691 let clang = compiler.is_like_clang();
692 let gnu = compiler.family == ToolFamily::Gnu;
693 command_add_output_file(
694 &mut cmd,
695 &obj,
696 CmdAddOutputFileArgs {
697 cuda: self.cuda,
698 is_assembler_msvc: false,
699 msvc: compiler.is_like_msvc(),
700 clang,
701 gnu,
702 is_asm: false,
703 is_arm,
704 },
705 );
706
707 // Checking for compiler flags does not require linking
708 cmd.arg("-c");
709
710 cmd.arg(&src);
711
712 let output = cmd.output()?;
713 let is_supported = output.status.success() && output.stderr.is_empty();
714
715 self.build_cache
716 .known_flag_support_status_cache
717 .write()
718 .unwrap()
719 .insert(compiler_flag, is_supported);
720
721 Ok(is_supported)
722 }
723
724 /// Add an arbitrary flag to the invocation of the compiler if it supports it
725 ///
726 /// # Example
727 ///
728 /// ```no_run
729 /// cc::Build::new()
730 /// .file("src/foo.c")
731 /// .flag_if_supported("-Wlogical-op") // only supported by GCC
732 /// .flag_if_supported("-Wunreachable-code") // only supported by clang
733 /// .compile("foo");
734 /// ```
735 pub fn flag_if_supported(&mut self, flag: impl AsRef<OsStr>) -> &mut Build {
736 self.flags_supported.push(flag.as_ref().into());
737 self
738 }
739
740 /// Add flags from the specified environment variable.
741 ///
742 /// Normally the `cc` crate will consult with the standard set of environment
743 /// variables (such as `CFLAGS` and `CXXFLAGS`) to construct the compiler invocation. Use of
744 /// this method provides additional levers for the end user to use when configuring the build
745 /// process.
746 ///
747 /// Just like the standard variables, this method will search for an environment variable with
748 /// appropriate target prefixes, when appropriate.
749 ///
750 /// # Examples
751 ///
752 /// This method is particularly beneficial in introducing the ability to specify crate-specific
753 /// flags.
754 ///
755 /// ```no_run
756 /// cc::Build::new()
757 /// .file("src/foo.c")
758 /// .try_flags_from_environment(concat!(env!("CARGO_PKG_NAME"), "_CFLAGS"))
759 /// .expect("the environment variable must be specified and UTF-8")
760 /// .compile("foo");
761 /// ```
762 ///
763 pub fn try_flags_from_environment(&mut self, environ_key: &str) -> Result<&mut Build, Error> {
764 let flags = self.envflags(environ_key)?;
765 self.flags.extend(
766 flags
767 .into_iter()
768 .map(|flag| Arc::from(OsString::from(flag).as_os_str())),
769 );
770 Ok(self)
771 }
772
773 /// Set the `-shared` flag.
774 ///
775 /// When enabled, the compiler will produce a shared object which can
776 /// then be linked with other objects to form an executable.
777 ///
778 /// # Example
779 ///
780 /// ```no_run
781 /// cc::Build::new()
782 /// .file("src/foo.c")
783 /// .shared_flag(true)
784 /// .compile("libfoo.so");
785 /// ```
786 pub fn shared_flag(&mut self, shared_flag: bool) -> &mut Build {
787 self.shared_flag = Some(shared_flag);
788 self
789 }
790
791 /// Set the `-static` flag.
792 ///
793 /// When enabled on systems that support dynamic linking, this prevents
794 /// linking with the shared libraries.
795 ///
796 /// # Example
797 ///
798 /// ```no_run
799 /// cc::Build::new()
800 /// .file("src/foo.c")
801 /// .shared_flag(true)
802 /// .static_flag(true)
803 /// .compile("foo");
804 /// ```
805 pub fn static_flag(&mut self, static_flag: bool) -> &mut Build {
806 self.static_flag = Some(static_flag);
807 self
808 }
809
810 /// Disables the generation of default compiler flags. The default compiler
811 /// flags may cause conflicts in some cross compiling scenarios.
812 ///
813 /// Setting the `CRATE_CC_NO_DEFAULTS` environment variable has the same
814 /// effect as setting this to `true`. The presence of the environment
815 /// variable and the value of `no_default_flags` will be OR'd together.
816 pub fn no_default_flags(&mut self, no_default_flags: bool) -> &mut Build {
817 self.no_default_flags = no_default_flags;
818 self
819 }
820
821 /// Add a file which will be compiled
822 pub fn file<P: AsRef<Path>>(&mut self, p: P) -> &mut Build {
823 self.files.push(p.as_ref().into());
824 self
825 }
826
827 /// Add files which will be compiled
828 pub fn files<P>(&mut self, p: P) -> &mut Build
829 where
830 P: IntoIterator,
831 P::Item: AsRef<Path>,
832 {
833 for file in p.into_iter() {
834 self.file(file);
835 }
836 self
837 }
838
839 /// Get the files which will be compiled
840 pub fn get_files(&self) -> impl Iterator<Item = &Path> {
841 self.files.iter().map(AsRef::as_ref)
842 }
843
844 /// Set C++ support.
845 ///
846 /// The other `cpp_*` options will only become active if this is set to
847 /// `true`.
848 ///
849 /// The name of the C++ standard library to link is decided by:
850 /// 1. If [`cpp_link_stdlib`](Build::cpp_link_stdlib) is set, use its value.
851 /// 2. Else if the `CXXSTDLIB` environment variable is set, use its value.
852 /// 3. Else the default is `c++` for OS X and BSDs, `c++_shared` for Android,
853 /// `None` for MSVC and `stdc++` for anything else.
854 pub fn cpp(&mut self, cpp: bool) -> &mut Build {
855 self.cpp = cpp;
856 self
857 }
858
859 /// Set CUDA C++ support.
860 ///
861 /// Enabling CUDA will invoke the CUDA compiler, NVCC. While NVCC accepts
862 /// the most common compiler flags, e.g. `-std=c++17`, some project-specific
863 /// flags might have to be prefixed with "-Xcompiler" flag, for example as
864 /// `.flag("-Xcompiler").flag("-fpermissive")`. See the documentation for
865 /// `nvcc`, the CUDA compiler driver, at <https://docs.nvidia.com/cuda/cuda-compiler-driver-nvcc/>
866 /// for more information.
867 ///
868 /// If enabled, this also implicitly enables C++ support.
869 pub fn cuda(&mut self, cuda: bool) -> &mut Build {
870 self.cuda = cuda;
871 if cuda {
872 self.cpp = true;
873 self.cudart = Some("static".into());
874 }
875 self
876 }
877
878 /// Link CUDA run-time.
879 ///
880 /// This option mimics the `--cudart` NVCC command-line option. Just like
881 /// the original it accepts `{none|shared|static}`, with default being
882 /// `static`. The method has to be invoked after `.cuda(true)`, or not
883 /// at all, if the default is right for the project.
884 pub fn cudart(&mut self, cudart: &str) -> &mut Build {
885 if self.cuda {
886 self.cudart = Some(cudart.into());
887 }
888 self
889 }
890
891 /// Set CUDA host compiler.
892 ///
893 /// By default, a `-ccbin` flag will be passed to NVCC to specify the
894 /// underlying host compiler. The value of `-ccbin` is the same as the
895 /// chosen C++ compiler. This is not always desired, because NVCC might
896 /// not support that compiler. In this case, you can remove the `-ccbin`
897 /// flag so that NVCC will choose the host compiler by itself.
898 pub fn ccbin(&mut self, ccbin: bool) -> &mut Build {
899 self.ccbin = ccbin;
900 self
901 }
902
903 /// Specify the C or C++ language standard version.
904 ///
905 /// These values are common to modern versions of GCC, Clang and MSVC:
906 /// - `c11` for ISO/IEC 9899:2011
907 /// - `c17` for ISO/IEC 9899:2018
908 /// - `c++14` for ISO/IEC 14882:2014
909 /// - `c++17` for ISO/IEC 14882:2017
910 /// - `c++20` for ISO/IEC 14882:2020
911 ///
912 /// Other values have less broad support, e.g. MSVC does not support `c++11`
913 /// (`c++14` is the minimum), `c89` (omit the flag instead) or `c99`.
914 ///
915 /// For compiling C++ code, you should also set `.cpp(true)`.
916 ///
917 /// The default is that no standard flag is passed to the compiler, so the
918 /// language version will be the compiler's default.
919 ///
920 /// # Example
921 ///
922 /// ```no_run
923 /// cc::Build::new()
924 /// .file("src/modern.cpp")
925 /// .cpp(true)
926 /// .std("c++17")
927 /// .compile("modern");
928 /// ```
929 pub fn std(&mut self, std: &str) -> &mut Build {
930 self.std = Some(std.into());
931 self
932 }
933
934 /// Set warnings into errors flag.
935 ///
936 /// Disabled by default.
937 ///
938 /// Warning: turning warnings into errors only make sense
939 /// if you are a developer of the crate using cc-rs.
940 /// Some warnings only appear on some architecture or
941 /// specific version of the compiler. Any user of this crate,
942 /// or any other crate depending on it, could fail during
943 /// compile time.
944 ///
945 /// # Example
946 ///
947 /// ```no_run
948 /// cc::Build::new()
949 /// .file("src/foo.c")
950 /// .warnings_into_errors(true)
951 /// .compile("libfoo.a");
952 /// ```
953 pub fn warnings_into_errors(&mut self, warnings_into_errors: bool) -> &mut Build {
954 self.warnings_into_errors = warnings_into_errors;
955 self
956 }
957
958 /// Set warnings flags.
959 ///
960 /// Adds some flags:
961 /// - "-Wall" for MSVC.
962 /// - "-Wall", "-Wextra" for GNU and Clang.
963 ///
964 /// Enabled by default.
965 ///
966 /// # Example
967 ///
968 /// ```no_run
969 /// cc::Build::new()
970 /// .file("src/foo.c")
971 /// .warnings(false)
972 /// .compile("libfoo.a");
973 /// ```
974 pub fn warnings(&mut self, warnings: bool) -> &mut Build {
975 self.warnings = Some(warnings);
976 self.extra_warnings = Some(warnings);
977 self
978 }
979
980 /// Set extra warnings flags.
981 ///
982 /// Adds some flags:
983 /// - nothing for MSVC.
984 /// - "-Wextra" for GNU and Clang.
985 ///
986 /// Enabled by default.
987 ///
988 /// # Example
989 ///
990 /// ```no_run
991 /// // Disables -Wextra, -Wall remains enabled:
992 /// cc::Build::new()
993 /// .file("src/foo.c")
994 /// .extra_warnings(false)
995 /// .compile("libfoo.a");
996 /// ```
997 pub fn extra_warnings(&mut self, warnings: bool) -> &mut Build {
998 self.extra_warnings = Some(warnings);
999 self
1000 }
1001
1002 /// Set the standard library to link against when compiling with C++
1003 /// support.
1004 ///
1005 /// If the `CXXSTDLIB` environment variable is set, its value will
1006 /// override the default value, but not the value explicitly set by calling
1007 /// this function.
1008 ///
1009 /// A value of `None` indicates that no automatic linking should happen,
1010 /// otherwise cargo will link against the specified library.
1011 ///
1012 /// The given library name must not contain the `lib` prefix.
1013 ///
1014 /// Common values:
1015 /// - `stdc++` for GNU
1016 /// - `c++` for Clang
1017 /// - `c++_shared` or `c++_static` for Android
1018 ///
1019 /// # Example
1020 ///
1021 /// ```no_run
1022 /// cc::Build::new()
1023 /// .file("src/foo.c")
1024 /// .shared_flag(true)
1025 /// .cpp_link_stdlib("stdc++")
1026 /// .compile("libfoo.so");
1027 /// ```
1028 pub fn cpp_link_stdlib<'a, V: Into<Option<&'a str>>>(
1029 &mut self,
1030 cpp_link_stdlib: V,
1031 ) -> &mut Build {
1032 self.cpp_link_stdlib = Some(cpp_link_stdlib.into().map(Arc::from));
1033 self
1034 }
1035
1036 /// Force the C++ compiler to use the specified standard library.
1037 ///
1038 /// Setting this option will automatically set `cpp_link_stdlib` to the same
1039 /// value.
1040 ///
1041 /// The default value of this option is always `None`.
1042 ///
1043 /// This option has no effect when compiling for a Visual Studio based
1044 /// target.
1045 ///
1046 /// This option sets the `-stdlib` flag, which is only supported by some
1047 /// compilers (clang, icc) but not by others (gcc). The library will not
1048 /// detect which compiler is used, as such it is the responsibility of the
1049 /// caller to ensure that this option is only used in conjunction with a
1050 /// compiler which supports the `-stdlib` flag.
1051 ///
1052 /// A value of `None` indicates that no specific C++ standard library should
1053 /// be used, otherwise `-stdlib` is added to the compile invocation.
1054 ///
1055 /// The given library name must not contain the `lib` prefix.
1056 ///
1057 /// Common values:
1058 /// - `stdc++` for GNU
1059 /// - `c++` for Clang
1060 ///
1061 /// # Example
1062 ///
1063 /// ```no_run
1064 /// cc::Build::new()
1065 /// .file("src/foo.c")
1066 /// .cpp_set_stdlib("c++")
1067 /// .compile("libfoo.a");
1068 /// ```
1069 pub fn cpp_set_stdlib<'a, V: Into<Option<&'a str>>>(
1070 &mut self,
1071 cpp_set_stdlib: V,
1072 ) -> &mut Build {
1073 let cpp_set_stdlib = cpp_set_stdlib.into().map(Arc::from);
1074 self.cpp_set_stdlib.clone_from(&cpp_set_stdlib);
1075 self.cpp_link_stdlib = Some(cpp_set_stdlib);
1076 self
1077 }
1078
1079 /// Configures the target this configuration will be compiling for.
1080 ///
1081 /// This option is automatically scraped from the `TARGET` environment
1082 /// variable by build scripts, so it's not required to call this function.
1083 ///
1084 /// # Example
1085 ///
1086 /// ```no_run
1087 /// cc::Build::new()
1088 /// .file("src/foo.c")
1089 /// .target("aarch64-linux-android")
1090 /// .compile("foo");
1091 /// ```
1092 pub fn target(&mut self, target: &str) -> &mut Build {
1093 self.target = Some(target.into());
1094 self
1095 }
1096
1097 /// Configures the host assumed by this configuration.
1098 ///
1099 /// This option is automatically scraped from the `HOST` environment
1100 /// variable by build scripts, so it's not required to call this function.
1101 ///
1102 /// # Example
1103 ///
1104 /// ```no_run
1105 /// cc::Build::new()
1106 /// .file("src/foo.c")
1107 /// .host("arm-linux-gnueabihf")
1108 /// .compile("foo");
1109 /// ```
1110 pub fn host(&mut self, host: &str) -> &mut Build {
1111 self.host = Some(host.into());
1112 self
1113 }
1114
1115 /// Configures the optimization level of the generated object files.
1116 ///
1117 /// This option is automatically scraped from the `OPT_LEVEL` environment
1118 /// variable by build scripts, so it's not required to call this function.
1119 pub fn opt_level(&mut self, opt_level: u32) -> &mut Build {
1120 self.opt_level = Some(opt_level.to_string().into());
1121 self
1122 }
1123
1124 /// Configures the optimization level of the generated object files.
1125 ///
1126 /// This option is automatically scraped from the `OPT_LEVEL` environment
1127 /// variable by build scripts, so it's not required to call this function.
1128 pub fn opt_level_str(&mut self, opt_level: &str) -> &mut Build {
1129 self.opt_level = Some(opt_level.into());
1130 self
1131 }
1132
1133 /// Configures whether the compiler will emit debug information when
1134 /// generating object files.
1135 ///
1136 /// This option is automatically scraped from the `DEBUG` environment
1137 /// variable by build scripts, so it's not required to call this function.
1138 pub fn debug(&mut self, debug: bool) -> &mut Build {
1139 self.debug = Some(debug);
1140 self
1141 }
1142
1143 /// Configures whether the compiler will emit instructions to store
1144 /// frame pointers during codegen.
1145 ///
1146 /// This option is automatically enabled when debug information is emitted.
1147 /// Otherwise the target platform compiler's default will be used.
1148 /// You can use this option to force a specific setting.
1149 pub fn force_frame_pointer(&mut self, force: bool) -> &mut Build {
1150 self.force_frame_pointer = Some(force);
1151 self
1152 }
1153
1154 /// Configures the output directory where all object files and static
1155 /// libraries will be located.
1156 ///
1157 /// This option is automatically scraped from the `OUT_DIR` environment
1158 /// variable by build scripts, so it's not required to call this function.
1159 pub fn out_dir<P: AsRef<Path>>(&mut self, out_dir: P) -> &mut Build {
1160 self.out_dir = Some(out_dir.as_ref().into());
1161 self
1162 }
1163
1164 /// Configures the compiler to be used to produce output.
1165 ///
1166 /// This option is automatically determined from the target platform or a
1167 /// number of environment variables, so it's not required to call this
1168 /// function.
1169 pub fn compiler<P: AsRef<Path>>(&mut self, compiler: P) -> &mut Build {
1170 self.compiler = Some(compiler.as_ref().into());
1171 self
1172 }
1173
1174 /// Configures the tool used to assemble archives.
1175 ///
1176 /// This option is automatically determined from the target platform or a
1177 /// number of environment variables, so it's not required to call this
1178 /// function.
1179 pub fn archiver<P: AsRef<Path>>(&mut self, archiver: P) -> &mut Build {
1180 self.archiver = Some(archiver.as_ref().into());
1181 self
1182 }
1183
1184 /// Configures the tool used to index archives.
1185 ///
1186 /// This option is automatically determined from the target platform or a
1187 /// number of environment variables, so it's not required to call this
1188 /// function.
1189 pub fn ranlib<P: AsRef<Path>>(&mut self, ranlib: P) -> &mut Build {
1190 self.ranlib = Some(ranlib.as_ref().into());
1191 self
1192 }
1193
1194 /// Define whether metadata should be emitted for cargo allowing it to
1195 /// automatically link the binary. Defaults to `true`.
1196 ///
1197 /// The emitted metadata is:
1198 ///
1199 /// - `rustc-link-lib=static=`*compiled lib*
1200 /// - `rustc-link-search=native=`*target folder*
1201 /// - When target is MSVC, the ATL-MFC libs are added via `rustc-link-search=native=`
1202 /// - When C++ is enabled, the C++ stdlib is added via `rustc-link-lib`
1203 /// - If `emit_rerun_if_env_changed` is not `false`, `rerun-if-env-changed=`*env*
1204 ///
1205 pub fn cargo_metadata(&mut self, cargo_metadata: bool) -> &mut Build {
1206 self.cargo_output.metadata = cargo_metadata;
1207 self
1208 }
1209
1210 /// Define whether compile warnings should be emitted for cargo. Defaults to
1211 /// `true`.
1212 ///
1213 /// If disabled, compiler messages will not be printed.
1214 /// Issues unrelated to the compilation will always produce cargo warnings regardless of this setting.
1215 pub fn cargo_warnings(&mut self, cargo_warnings: bool) -> &mut Build {
1216 self.cargo_output.warnings = cargo_warnings;
1217 self
1218 }
1219
1220 /// Define whether debug information should be emitted for cargo. Defaults to whether
1221 /// or not the environment variable `CC_ENABLE_DEBUG_OUTPUT` is set.
1222 ///
1223 /// If enabled, the compiler will emit debug information when generating object files,
1224 /// such as the command invoked and the exit status.
1225 pub fn cargo_debug(&mut self, cargo_debug: bool) -> &mut Build {
1226 self.cargo_output.debug = cargo_debug;
1227 self
1228 }
1229
1230 /// Define whether compiler output (to stdout) should be emitted. Defaults to `true`
1231 /// (forward compiler stdout to this process' stdout)
1232 ///
1233 /// Some compilers emit errors to stdout, so if you *really* need stdout to be clean
1234 /// you should also set this to `false`.
1235 pub fn cargo_output(&mut self, cargo_output: bool) -> &mut Build {
1236 self.cargo_output.output = if cargo_output {
1237 OutputKind::Forward
1238 } else {
1239 OutputKind::Discard
1240 };
1241 self
1242 }
1243
1244 /// Adds a native library modifier that will be added to the
1245 /// `rustc-link-lib=static:MODIFIERS=LIBRARY_NAME` metadata line
1246 /// emitted for cargo if `cargo_metadata` is enabled.
1247 /// See <https://doc.rust-lang.org/rustc/command-line-arguments.html#-l-link-the-generated-crate-to-a-native-library>
1248 /// for the list of modifiers accepted by rustc.
1249 pub fn link_lib_modifier(&mut self, link_lib_modifier: impl AsRef<OsStr>) -> &mut Build {
1250 self.link_lib_modifiers
1251 .push(link_lib_modifier.as_ref().into());
1252 self
1253 }
1254
1255 /// Configures whether the compiler will emit position independent code.
1256 ///
1257 /// This option defaults to `false` for `windows-gnu` and bare metal targets and
1258 /// to `true` for all other targets.
1259 pub fn pic(&mut self, pic: bool) -> &mut Build {
1260 self.pic = Some(pic);
1261 self
1262 }
1263
1264 /// Configures whether the Procedure Linkage Table is used for indirect
1265 /// calls into shared libraries.
1266 ///
1267 /// The PLT is used to provide features like lazy binding, but introduces
1268 /// a small performance loss due to extra pointer indirection. Setting
1269 /// `use_plt` to `false` can provide a small performance increase.
1270 ///
1271 /// Note that skipping the PLT requires a recent version of GCC/Clang.
1272 ///
1273 /// This only applies to ELF targets. It has no effect on other platforms.
1274 pub fn use_plt(&mut self, use_plt: bool) -> &mut Build {
1275 self.use_plt = Some(use_plt);
1276 self
1277 }
1278
1279 /// Define whether metadata should be emitted for cargo to detect environment
1280 /// changes that should trigger a rebuild.
1281 ///
1282 /// NOTE that cc does not emit metadata to detect changes for `PATH`, since it could
1283 /// be changed every comilation yet does not affect the result of compilation
1284 /// (i.e. rust-analyzer adds temporary directory to `PATH`).
1285 ///
1286 /// cc in general, has no way detecting changes to compiler, as there are so many ways to
1287 /// change it and sidestep the detection, for example the compiler might be wrapped in a script
1288 /// so detecting change of the file, or using checksum won't work.
1289 ///
1290 /// We recommend users to decide for themselves, if they want rebuild if the compiler has been upgraded
1291 /// or changed, and how to detect that.
1292 ///
1293 /// This has no effect if the `cargo_metadata` option is `false`.
1294 ///
1295 /// This option defaults to `true`.
1296 pub fn emit_rerun_if_env_changed(&mut self, emit_rerun_if_env_changed: bool) -> &mut Build {
1297 self.emit_rerun_if_env_changed = emit_rerun_if_env_changed;
1298 self
1299 }
1300
1301 /// Configures whether the /MT flag or the /MD flag will be passed to msvc build tools.
1302 ///
1303 /// This option defaults to `false`, and affect only msvc targets.
1304 pub fn static_crt(&mut self, static_crt: bool) -> &mut Build {
1305 self.static_crt = Some(static_crt);
1306 self
1307 }
1308
1309 /// Configure whether *FLAGS variables are parsed using `shlex`, similarly to `make` and
1310 /// `cmake`.
1311 ///
1312 /// This option defaults to `false`.
1313 pub fn shell_escaped_flags(&mut self, shell_escaped_flags: bool) -> &mut Build {
1314 self.shell_escaped_flags = Some(shell_escaped_flags);
1315 self
1316 }
1317
1318 #[doc(hidden)]
1319 pub fn __set_env<A, B>(&mut self, a: A, b: B) -> &mut Build
1320 where
1321 A: AsRef<OsStr>,
1322 B: AsRef<OsStr>,
1323 {
1324 self.env.push((a.as_ref().into(), b.as_ref().into()));
1325 self
1326 }
1327
1328 /// Run the compiler, generating the file `output`
1329 ///
1330 /// This will return a result instead of panicking; see [`Self::compile()`] for
1331 /// the complete description.
1332 pub fn try_compile(&self, output: &str) -> Result<(), Error> {
1333 let mut output_components = Path::new(output).components();
1334 match (output_components.next(), output_components.next()) {
1335 (Some(Component::Normal(_)), None) => {}
1336 _ => {
1337 return Err(Error::new(
1338 ErrorKind::InvalidArgument,
1339 "argument of `compile` must be a single normal path component",
1340 ));
1341 }
1342 }
1343
1344 let (lib_name, gnu_lib_name) = if output.starts_with("lib") && output.ends_with(".a") {
1345 (&output[3..output.len() - 2], output.to_owned())
1346 } else {
1347 let mut gnu = String::with_capacity(5 + output.len());
1348 gnu.push_str("lib");
1349 gnu.push_str(output);
1350 gnu.push_str(".a");
1351 (output, gnu)
1352 };
1353 let dst = self.get_out_dir()?;
1354
1355 let objects = objects_from_files(&self.files, &dst)?;
1356
1357 self.compile_objects(&objects)?;
1358 self.assemble(lib_name, &dst.join(gnu_lib_name), &objects)?;
1359
1360 let target = self.get_target()?;
1361 if target.env == "msvc" {
1362 let compiler = self.get_base_compiler()?;
1363 let atlmfc_lib = compiler
1364 .env()
1365 .iter()
1366 .find(|&(var, _)| var.as_os_str() == OsStr::new("LIB"))
1367 .and_then(|(_, lib_paths)| {
1368 env::split_paths(lib_paths).find(|path| {
1369 let sub = Path::new("atlmfc/lib");
1370 path.ends_with(sub) || path.parent().map_or(false, |p| p.ends_with(sub))
1371 })
1372 });
1373
1374 if let Some(atlmfc_lib) = atlmfc_lib {
1375 self.cargo_output.print_metadata(&format_args!(
1376 "cargo:rustc-link-search=native={}",
1377 atlmfc_lib.display()
1378 ));
1379 }
1380 }
1381
1382 if self.link_lib_modifiers.is_empty() {
1383 self.cargo_output
1384 .print_metadata(&format_args!("cargo:rustc-link-lib=static={}", lib_name));
1385 } else {
1386 self.cargo_output.print_metadata(&format_args!(
1387 "cargo:rustc-link-lib=static:{}={}",
1388 JoinOsStrs {
1389 slice: &self.link_lib_modifiers,
1390 delimiter: ','
1391 },
1392 lib_name
1393 ));
1394 }
1395 self.cargo_output.print_metadata(&format_args!(
1396 "cargo:rustc-link-search=native={}",
1397 dst.display()
1398 ));
1399
1400 // Add specific C++ libraries, if enabled.
1401 if self.cpp {
1402 if let Some(stdlib) = self.get_cpp_link_stdlib()? {
1403 self.cargo_output
1404 .print_metadata(&format_args!("cargo:rustc-link-lib={}", stdlib.display()));
1405 }
1406 // Link c++ lib from WASI sysroot
1407 if target.os == "wasi" {
1408 if let Ok(wasi_sysroot) = self.wasi_sysroot() {
1409 self.cargo_output.print_metadata(&format_args!(
1410 "cargo:rustc-flags=-L {}/lib/{} -lstatic=c++ -lstatic=c++abi",
1411 Path::new(&wasi_sysroot).display(),
1412 self.get_raw_target()?
1413 ));
1414 }
1415 }
1416 }
1417
1418 let cudart = match &self.cudart {
1419 Some(opt) => opt, // {none|shared|static}
1420 None => "none",
1421 };
1422 if cudart != "none" {
1423 if let Some(nvcc) = self.which(&self.get_compiler().path, None) {
1424 // Try to figure out the -L search path. If it fails,
1425 // it's on user to specify one by passing it through
1426 // RUSTFLAGS environment variable.
1427 let mut libtst = false;
1428 let mut libdir = nvcc;
1429 libdir.pop(); // remove 'nvcc'
1430 libdir.push("..");
1431 if cfg!(target_os = "linux") {
1432 libdir.push("targets");
1433 libdir.push(format!("{}-linux", target.arch));
1434 libdir.push("lib");
1435 libtst = true;
1436 } else if cfg!(target_env = "msvc") {
1437 libdir.push("lib");
1438 match target.arch {
1439 "x86_64" => {
1440 libdir.push("x64");
1441 libtst = true;
1442 }
1443 "x86" => {
1444 libdir.push("Win32");
1445 libtst = true;
1446 }
1447 _ => libtst = false,
1448 }
1449 }
1450 if libtst && libdir.is_dir() {
1451 self.cargo_output.print_metadata(&format_args!(
1452 "cargo:rustc-link-search=native={}",
1453 libdir.to_str().unwrap()
1454 ));
1455 }
1456
1457 // And now the -l flag.
1458 let lib = match cudart {
1459 "shared" => "cudart",
1460 "static" => "cudart_static",
1461 bad => panic!("unsupported cudart option: {}", bad),
1462 };
1463 self.cargo_output
1464 .print_metadata(&format_args!("cargo:rustc-link-lib={}", lib));
1465 }
1466 }
1467
1468 Ok(())
1469 }
1470
1471 /// Run the compiler, generating the file `output`
1472 ///
1473 /// # Library name
1474 ///
1475 /// The `output` string argument determines the file name for the compiled
1476 /// library. The Rust compiler will create an assembly named "lib"+output+".a".
1477 /// MSVC will create a file named output+".lib".
1478 ///
1479 /// The choice of `output` is close to arbitrary, but:
1480 ///
1481 /// - must be nonempty,
1482 /// - must not contain a path separator (`/`),
1483 /// - must be unique across all `compile` invocations made by the same build
1484 /// script.
1485 ///
1486 /// If your build script compiles a single source file, the base name of
1487 /// that source file would usually be reasonable:
1488 ///
1489 /// ```no_run
1490 /// cc::Build::new().file("blobstore.c").compile("blobstore");
1491 /// ```
1492 ///
1493 /// Compiling multiple source files, some people use their crate's name, or
1494 /// their crate's name + "-cc".
1495 ///
1496 /// Otherwise, please use your imagination.
1497 ///
1498 /// For backwards compatibility, if `output` starts with "lib" *and* ends
1499 /// with ".a", a second "lib" prefix and ".a" suffix do not get added on,
1500 /// but this usage is deprecated; please omit `lib` and `.a` in the argument
1501 /// that you pass.
1502 ///
1503 /// # Panics
1504 ///
1505 /// Panics if `output` is not formatted correctly or if one of the underlying
1506 /// compiler commands fails. It can also panic if it fails reading file names
1507 /// or creating directories.
1508 pub fn compile(&self, output: &str) {
1509 if let Err(e) = self.try_compile(output) {
1510 fail(&e.message);
1511 }
1512 }
1513
1514 /// Run the compiler, generating intermediate files, but without linking
1515 /// them into an archive file.
1516 ///
1517 /// This will return a list of compiled object files, in the same order
1518 /// as they were passed in as `file`/`files` methods.
1519 pub fn compile_intermediates(&self) -> Vec<PathBuf> {
1520 match self.try_compile_intermediates() {
1521 Ok(v) => v,
1522 Err(e) => fail(&e.message),
1523 }
1524 }
1525
1526 /// Run the compiler, generating intermediate files, but without linking
1527 /// them into an archive file.
1528 ///
1529 /// This will return a result instead of panicking; see `compile_intermediates()` for the complete description.
1530 pub fn try_compile_intermediates(&self) -> Result<Vec<PathBuf>, Error> {
1531 let dst = self.get_out_dir()?;
1532 let objects = objects_from_files(&self.files, &dst)?;
1533
1534 self.compile_objects(&objects)?;
1535
1536 Ok(objects.into_iter().map(|v| v.dst).collect())
1537 }
1538
1539 #[cfg(feature = "parallel")]
1540 fn compile_objects(&self, objs: &[Object]) -> Result<(), Error> {
1541 use std::cell::Cell;
1542
1543 use parallel::async_executor::{block_on, YieldOnce};
1544
1545 if objs.len() <= 1 {
1546 for obj in objs {
1547 let (mut cmd, name) = self.create_compile_object_cmd(obj)?;
1548 run(&mut cmd, &name, &self.cargo_output)?;
1549 }
1550
1551 return Ok(());
1552 }
1553
1554 // Limit our parallelism globally with a jobserver.
1555 let mut tokens = parallel::job_token::ActiveJobTokenServer::new();
1556
1557 // When compiling objects in parallel we do a few dirty tricks to speed
1558 // things up:
1559 //
1560 // * First is that we use the `jobserver` crate to limit the parallelism
1561 // of this build script. The `jobserver` crate will use a jobserver
1562 // configured by Cargo for build scripts to ensure that parallelism is
1563 // coordinated across C compilations and Rust compilations. Before we
1564 // compile anything we make sure to wait until we acquire a token.
1565 //
1566 // Note that this jobserver is cached globally so we only used one per
1567 // process and only worry about creating it once.
1568 //
1569 // * Next we use spawn the process to actually compile objects in
1570 // parallel after we've acquired a token to perform some work
1571 //
1572 // With all that in mind we compile all objects in a loop here, after we
1573 // acquire the appropriate tokens, Once all objects have been compiled
1574 // we wait on all the processes and propagate the results of compilation.
1575
1576 let pendings = Cell::new(Vec::<(
1577 Command,
1578 Cow<'static, Path>,
1579 KillOnDrop,
1580 parallel::job_token::JobToken,
1581 )>::new());
1582 let is_disconnected = Cell::new(false);
1583 let has_made_progress = Cell::new(false);
1584
1585 let wait_future = async {
1586 let mut error = None;
1587 // Buffer the stdout
1588 let mut stdout = io::BufWriter::with_capacity(128, io::stdout());
1589
1590 loop {
1591 // If the other end of the pipe is already disconnected, then we're not gonna get any new jobs,
1592 // so it doesn't make sense to reuse the tokens; in fact,
1593 // releasing them as soon as possible (once we know that the other end is disconnected) is beneficial.
1594 // Imagine that the last file built takes an hour to finish; in this scenario,
1595 // by not releasing the tokens before that last file is done we would effectively block other processes from
1596 // starting sooner - even though we only need one token for that last file, not N others that were acquired.
1597
1598 let mut pendings_is_empty = false;
1599
1600 cell_update(&pendings, |mut pendings| {
1601 // Try waiting on them.
1602 pendings.retain_mut(|(cmd, program, child, _token)| {
1603 match try_wait_on_child(
1604 cmd,
1605 program,
1606 &mut child.0,
1607 &mut stdout,
1608 &mut child.1,
1609 ) {
1610 Ok(Some(())) => {
1611 // Task done, remove the entry
1612 has_made_progress.set(true);
1613 false
1614 }
1615 Ok(None) => true, // Task still not finished, keep the entry
1616 Err(err) => {
1617 // Task fail, remove the entry.
1618 // Since we can only return one error, log the error to make
1619 // sure users always see all the compilation failures.
1620 has_made_progress.set(true);
1621
1622 if self.cargo_output.warnings {
1623 let _ = writeln!(stdout, "cargo:warning={}", err);
1624 }
1625 error = Some(err);
1626
1627 false
1628 }
1629 }
1630 });
1631 pendings_is_empty = pendings.is_empty();
1632 pendings
1633 });
1634
1635 if pendings_is_empty && is_disconnected.get() {
1636 break if let Some(err) = error {
1637 Err(err)
1638 } else {
1639 Ok(())
1640 };
1641 }
1642
1643 YieldOnce::default().await;
1644 }
1645 };
1646 let spawn_future = async {
1647 for obj in objs {
1648 let (mut cmd, program) = self.create_compile_object_cmd(obj)?;
1649 let token = tokens.acquire().await?;
1650 let mut child = spawn(&mut cmd, &program, &self.cargo_output)?;
1651 let mut stderr_forwarder = StderrForwarder::new(&mut child);
1652 stderr_forwarder.set_non_blocking()?;
1653
1654 cell_update(&pendings, |mut pendings| {
1655 pendings.push((cmd, program, KillOnDrop(child, stderr_forwarder), token));
1656 pendings
1657 });
1658
1659 has_made_progress.set(true);
1660 }
1661 is_disconnected.set(true);
1662
1663 Ok::<_, Error>(())
1664 };
1665
1666 return block_on(wait_future, spawn_future, &has_made_progress);
1667
1668 struct KillOnDrop(Child, StderrForwarder);
1669
1670 impl Drop for KillOnDrop {
1671 fn drop(&mut self) {
1672 let child = &mut self.0;
1673
1674 child.kill().ok();
1675 }
1676 }
1677
1678 fn cell_update<T, F>(cell: &Cell<T>, f: F)
1679 where
1680 T: Default,
1681 F: FnOnce(T) -> T,
1682 {
1683 let old = cell.take();
1684 let new = f(old);
1685 cell.set(new);
1686 }
1687 }
1688
1689 #[cfg(not(feature = "parallel"))]
1690 fn compile_objects(&self, objs: &[Object]) -> Result<(), Error> {
1691 for obj in objs {
1692 let (mut cmd, name) = self.create_compile_object_cmd(obj)?;
1693 run(&mut cmd, &name, &self.cargo_output)?;
1694 }
1695
1696 Ok(())
1697 }
1698
1699 fn create_compile_object_cmd(
1700 &self,
1701 obj: &Object,
1702 ) -> Result<(Command, Cow<'static, Path>), Error> {
1703 let asm_ext = AsmFileExt::from_path(&obj.src);
1704 let is_asm = asm_ext.is_some();
1705 let target = self.get_target()?;
1706 let msvc = target.env == "msvc";
1707 let compiler = self.try_get_compiler()?;
1708 let clang = compiler.is_like_clang();
1709 let gnu = compiler.family == ToolFamily::Gnu;
1710
1711 let is_assembler_msvc = msvc && asm_ext == Some(AsmFileExt::DotAsm);
1712 let (mut cmd, name) = if is_assembler_msvc {
1713 let (cmd, name) = self.msvc_macro_assembler()?;
1714 (cmd, Cow::Borrowed(Path::new(name)))
1715 } else {
1716 let mut cmd = compiler.to_command();
1717 for (a, b) in self.env.iter() {
1718 cmd.env(a, b);
1719 }
1720 (
1721 cmd,
1722 compiler
1723 .path
1724 .file_name()
1725 .ok_or_else(|| Error::new(ErrorKind::IOError, "Failed to get compiler path."))
1726 .map(PathBuf::from)
1727 .map(Cow::Owned)?,
1728 )
1729 };
1730 let is_arm = matches!(target.arch, "aarch64" | "arm");
1731 command_add_output_file(
1732 &mut cmd,
1733 &obj.dst,
1734 CmdAddOutputFileArgs {
1735 cuda: self.cuda,
1736 is_assembler_msvc,
1737 msvc: compiler.is_like_msvc(),
1738 clang,
1739 gnu,
1740 is_asm,
1741 is_arm,
1742 },
1743 );
1744 // armasm and armasm64 don't requrie -c option
1745 if !is_assembler_msvc || !is_arm {
1746 cmd.arg("-c");
1747 }
1748 if self.cuda && self.cuda_file_count() > 1 {
1749 cmd.arg("--device-c");
1750 }
1751 if is_asm {
1752 cmd.args(self.asm_flags.iter().map(std::ops::Deref::deref));
1753 }
1754 if compiler.family == (ToolFamily::Msvc { clang_cl: true }) && !is_assembler_msvc {
1755 // #513: For `clang-cl`, separate flags/options from the input file.
1756 // When cross-compiling macOS -> Windows, this avoids interpreting
1757 // common `/Users/...` paths as the `/U` flag and triggering
1758 // `-Wslash-u-filename` warning.
1759 cmd.arg("--");
1760 }
1761 cmd.arg(&obj.src);
1762 if cfg!(target_os = "macos") {
1763 self.fix_env_for_apple_os(&mut cmd)?;
1764 }
1765
1766 Ok((cmd, name))
1767 }
1768
1769 /// This will return a result instead of panicking; see [`Self::expand()`] for
1770 /// the complete description.
1771 pub fn try_expand(&self) -> Result<Vec<u8>, Error> {
1772 let compiler = self.try_get_compiler()?;
1773 let mut cmd = compiler.to_command();
1774 for (a, b) in self.env.iter() {
1775 cmd.env(a, b);
1776 }
1777 cmd.arg("-E");
1778
1779 assert!(
1780 self.files.len() <= 1,
1781 "Expand may only be called for a single file"
1782 );
1783
1784 let is_asm = self
1785 .files
1786 .iter()
1787 .map(std::ops::Deref::deref)
1788 .find_map(AsmFileExt::from_path)
1789 .is_some();
1790
1791 if compiler.family == (ToolFamily::Msvc { clang_cl: true }) && !is_asm {
1792 // #513: For `clang-cl`, separate flags/options from the input file.
1793 // When cross-compiling macOS -> Windows, this avoids interpreting
1794 // common `/Users/...` paths as the `/U` flag and triggering
1795 // `-Wslash-u-filename` warning.
1796 cmd.arg("--");
1797 }
1798
1799 cmd.args(self.files.iter().map(std::ops::Deref::deref));
1800
1801 let name = compiler
1802 .path
1803 .file_name()
1804 .ok_or_else(|| Error::new(ErrorKind::IOError, "Failed to get compiler path."))?;
1805
1806 run_output(&mut cmd, name, &self.cargo_output)
1807 }
1808
1809 /// Run the compiler, returning the macro-expanded version of the input files.
1810 ///
1811 /// This is only relevant for C and C++ files.
1812 ///
1813 /// # Panics
1814 /// Panics if more than one file is present in the config, or if compiler
1815 /// path has an invalid file name.
1816 ///
1817 /// # Example
1818 /// ```no_run
1819 /// let out = cc::Build::new().file("src/foo.c").expand();
1820 /// ```
1821 pub fn expand(&self) -> Vec<u8> {
1822 match self.try_expand() {
1823 Err(e) => fail(&e.message),
1824 Ok(v) => v,
1825 }
1826 }
1827
1828 /// Get the compiler that's in use for this configuration.
1829 ///
1830 /// This function will return a `Tool` which represents the culmination
1831 /// of this configuration at a snapshot in time. The returned compiler can
1832 /// be inspected (e.g. the path, arguments, environment) to forward along to
1833 /// other tools, or the `to_command` method can be used to invoke the
1834 /// compiler itself.
1835 ///
1836 /// This method will take into account all configuration such as debug
1837 /// information, optimization level, include directories, defines, etc.
1838 /// Additionally, the compiler binary in use follows the standard
1839 /// conventions for this path, e.g. looking at the explicitly set compiler,
1840 /// environment variables (a number of which are inspected here), and then
1841 /// falling back to the default configuration.
1842 ///
1843 /// # Panics
1844 ///
1845 /// Panics if an error occurred while determining the architecture.
1846 pub fn get_compiler(&self) -> Tool {
1847 match self.try_get_compiler() {
1848 Ok(tool) => tool,
1849 Err(e) => fail(&e.message),
1850 }
1851 }
1852
1853 /// Get the compiler that's in use for this configuration.
1854 ///
1855 /// This will return a result instead of panicking; see
1856 /// [`get_compiler()`](Self::get_compiler) for the complete description.
1857 pub fn try_get_compiler(&self) -> Result<Tool, Error> {
1858 let opt_level = self.get_opt_level()?;
1859 let target = self.get_target()?;
1860
1861 let mut cmd = self.get_base_compiler()?;
1862
1863 // Disable default flag generation via `no_default_flags` or environment variable
1864 let no_defaults = self.no_default_flags || self.getenv_boolean("CRATE_CC_NO_DEFAULTS");
1865
1866 if !no_defaults {
1867 self.add_default_flags(&mut cmd, &target, &opt_level)?;
1868 }
1869
1870 if let Some(ref std) = self.std {
1871 let separator = match cmd.family {
1872 ToolFamily::Msvc { .. } => ':',
1873 ToolFamily::Gnu | ToolFamily::Clang { .. } => '=',
1874 };
1875 cmd.push_cc_arg(format!("-std{}{}", separator, std).into());
1876 }
1877
1878 for directory in self.include_directories.iter() {
1879 cmd.args.push("-I".into());
1880 cmd.args.push(directory.as_os_str().into());
1881 }
1882
1883 if let Ok(flags) = self.envflags(if self.cpp { "CXXFLAGS" } else { "CFLAGS" }) {
1884 for arg in flags {
1885 cmd.push_cc_arg(arg.into());
1886 }
1887 }
1888
1889 // If warnings and/or extra_warnings haven't been explicitly set,
1890 // then we set them only if the environment doesn't already have
1891 // CFLAGS/CXXFLAGS, since those variables presumably already contain
1892 // the desired set of warnings flags.
1893
1894 if self.warnings.unwrap_or(!self.has_flags()) {
1895 let wflags = cmd.family.warnings_flags().into();
1896 cmd.push_cc_arg(wflags);
1897 }
1898
1899 if self.extra_warnings.unwrap_or(!self.has_flags()) {
1900 if let Some(wflags) = cmd.family.extra_warnings_flags() {
1901 cmd.push_cc_arg(wflags.into());
1902 }
1903 }
1904
1905 for flag in self.flags.iter() {
1906 cmd.args.push((**flag).into());
1907 }
1908
1909 for flag in self.flags_supported.iter() {
1910 if self
1911 .is_flag_supported_inner(flag, &cmd.path, &target)
1912 .unwrap_or(false)
1913 {
1914 cmd.push_cc_arg((**flag).into());
1915 }
1916 }
1917
1918 for (key, value) in self.definitions.iter() {
1919 if let Some(ref value) = *value {
1920 cmd.args.push(format!("-D{}={}", key, value).into());
1921 } else {
1922 cmd.args.push(format!("-D{}", key).into());
1923 }
1924 }
1925
1926 if self.warnings_into_errors {
1927 let warnings_to_errors_flag = cmd.family.warnings_to_errors_flag().into();
1928 cmd.push_cc_arg(warnings_to_errors_flag);
1929 }
1930
1931 Ok(cmd)
1932 }
1933
1934 fn add_default_flags(
1935 &self,
1936 cmd: &mut Tool,
1937 target: &TargetInfo<'_>,
1938 opt_level: &str,
1939 ) -> Result<(), Error> {
1940 let raw_target = self.get_raw_target()?;
1941 // Non-target flags
1942 // If the flag is not conditioned on target variable, it belongs here :)
1943 match cmd.family {
1944 ToolFamily::Msvc { .. } => {
1945 cmd.push_cc_arg("-nologo".into());
1946
1947 let crt_flag = match self.static_crt {
1948 Some(true) => "-MT",
1949 Some(false) => "-MD",
1950 None => {
1951 let features = self.getenv("CARGO_CFG_TARGET_FEATURE");
1952 let features = features.as_deref().unwrap_or_default();
1953 if features.to_string_lossy().contains("crt-static") {
1954 "-MT"
1955 } else {
1956 "-MD"
1957 }
1958 }
1959 };
1960 cmd.push_cc_arg(crt_flag.into());
1961
1962 match opt_level {
1963 // Msvc uses /O1 to enable all optimizations that minimize code size.
1964 "z" | "s" | "1" => cmd.push_opt_unless_duplicate("-O1".into()),
1965 // -O3 is a valid value for gcc and clang compilers, but not msvc. Cap to /O2.
1966 "2" | "3" => cmd.push_opt_unless_duplicate("-O2".into()),
1967 _ => {}
1968 }
1969 }
1970 ToolFamily::Gnu | ToolFamily::Clang { .. } => {
1971 // arm-linux-androideabi-gcc 4.8 shipped with Android NDK does
1972 // not support '-Oz'
1973 if opt_level == "z" && !cmd.is_like_clang() {
1974 cmd.push_opt_unless_duplicate("-Os".into());
1975 } else {
1976 cmd.push_opt_unless_duplicate(format!("-O{}", opt_level).into());
1977 }
1978
1979 if cmd.is_like_clang() && target.os == "android" {
1980 // For compatibility with code that doesn't use pre-defined `__ANDROID__` macro.
1981 // If compiler used via ndk-build or cmake (officially supported build methods)
1982 // this macros is defined.
1983 // See https://android.googlesource.com/platform/ndk/+/refs/heads/ndk-release-r21/build/cmake/android.toolchain.cmake#456
1984 // https://android.googlesource.com/platform/ndk/+/refs/heads/ndk-release-r21/build/core/build-binary.mk#141
1985 cmd.push_opt_unless_duplicate("-DANDROID".into());
1986 }
1987
1988 if target.os != "ios"
1989 && target.os != "watchos"
1990 && target.os != "tvos"
1991 && target.os != "visionos"
1992 {
1993 cmd.push_cc_arg("-ffunction-sections".into());
1994 cmd.push_cc_arg("-fdata-sections".into());
1995 }
1996 // Disable generation of PIC on bare-metal for now: rust-lld doesn't support this yet
1997 //
1998 // `rustc` also defaults to disable PIC on WASM:
1999 // <https://github.com/rust-lang/rust/blob/1.82.0/compiler/rustc_target/src/spec/base/wasm.rs#L101-L108>
2000 if self.pic.unwrap_or(
2001 target.os != "windows"
2002 && target.os != "none"
2003 && target.os != "uefi"
2004 && target.arch != "wasm32"
2005 && target.arch != "wasm64",
2006 ) {
2007 cmd.push_cc_arg("-fPIC".into());
2008 // PLT only applies if code is compiled with PIC support,
2009 // and only for ELF targets.
2010 if (target.os == "linux" || target.os == "android")
2011 && !self.use_plt.unwrap_or(true)
2012 {
2013 cmd.push_cc_arg("-fno-plt".into());
2014 }
2015 }
2016 if target.arch == "wasm32" || target.arch == "wasm64" {
2017 // WASI does not support exceptions yet.
2018 // https://github.com/WebAssembly/exception-handling
2019 //
2020 // `rustc` also defaults to (currently) disable exceptions
2021 // on all WASM targets:
2022 // <https://github.com/rust-lang/rust/blob/1.82.0/compiler/rustc_target/src/spec/base/wasm.rs#L72-L77>
2023 cmd.push_cc_arg("-fno-exceptions".into());
2024 }
2025
2026 if target.os == "wasi" {
2027 // Link clang sysroot
2028 if let Ok(wasi_sysroot) = self.wasi_sysroot() {
2029 cmd.push_cc_arg(
2030 format!("--sysroot={}", Path::new(&wasi_sysroot).display()).into(),
2031 );
2032 }
2033
2034 // FIXME(madsmtm): Read from `target_features` instead?
2035 if raw_target.contains("threads") {
2036 cmd.push_cc_arg("-pthread".into());
2037 }
2038 }
2039 }
2040 }
2041
2042 if self.get_debug() {
2043 if self.cuda {
2044 // NVCC debug flag
2045 cmd.args.push("-G".into());
2046 }
2047 let family = cmd.family;
2048 family.add_debug_flags(cmd, self.get_dwarf_version());
2049 }
2050
2051 if self.get_force_frame_pointer() {
2052 let family = cmd.family;
2053 family.add_force_frame_pointer(cmd);
2054 }
2055
2056 if !cmd.is_like_msvc() {
2057 if target.arch == "x86" {
2058 cmd.args.push("-m32".into());
2059 } else if target.abi == "x32" {
2060 cmd.args.push("-mx32".into());
2061 } else if target.arch == "x86_64" || target.arch == "powerpc64" {
2062 cmd.args.push("-m64".into());
2063 }
2064 }
2065
2066 // Target flags
2067 match cmd.family {
2068 ToolFamily::Clang { .. } => {
2069 if !(cmd.has_internal_target_arg
2070 || (target.os == "android"
2071 && android_clang_compiler_uses_target_arg_internally(&cmd.path)))
2072 {
2073 if target.os == "freebsd" {
2074 // FreeBSD only supports C++11 and above when compiling against libc++
2075 // (available from FreeBSD 10 onwards). Under FreeBSD, clang uses libc++ by
2076 // default on FreeBSD 10 and newer unless `--target` is manually passed to
2077 // the compiler, in which case its default behavior differs:
2078 // * If --target=xxx-unknown-freebsdX(.Y) is specified and X is greater than
2079 // or equal to 10, clang++ uses libc++
2080 // * If --target=xxx-unknown-freebsd is specified (without a version),
2081 // clang++ cannot assume libc++ is available and reverts to a default of
2082 // libstdc++ (this behavior was changed in llvm 14).
2083 //
2084 // This breaks C++11 (or greater) builds if targeting FreeBSD with the
2085 // generic xxx-unknown-freebsd triple on clang 13 or below *without*
2086 // explicitly specifying that libc++ should be used.
2087 // When cross-compiling, we can't infer from the rust/cargo target triple
2088 // which major version of FreeBSD we are targeting, so we need to make sure
2089 // that libc++ is used (unless the user has explicitly specified otherwise).
2090 // There's no compelling reason to use a different approach when compiling
2091 // natively.
2092 if self.cpp && self.cpp_set_stdlib.is_none() {
2093 cmd.push_cc_arg("-stdlib=libc++".into());
2094 }
2095 }
2096
2097 // Add version information to the target.
2098 let llvm_target = if target.vendor == "apple" {
2099 let deployment_target = self.apple_deployment_target(target);
2100 target.versioned_llvm_target(Some(&deployment_target))
2101 } else {
2102 target.versioned_llvm_target(None)
2103 };
2104
2105 // Pass `--target` with the LLVM target to properly
2106 // configure Clang even when cross-compiling.
2107 cmd.push_cc_arg(format!("--target={llvm_target}").into());
2108 }
2109 }
2110 ToolFamily::Msvc { clang_cl } => {
2111 // This is an undocumented flag from MSVC but helps with making
2112 // builds more reproducible by avoiding putting timestamps into
2113 // files.
2114 cmd.push_cc_arg("-Brepro".into());
2115
2116 if clang_cl {
2117 if target.arch == "x86_64" {
2118 cmd.push_cc_arg("-m64".into());
2119 } else if target.arch == "x86" {
2120 cmd.push_cc_arg("-m32".into());
2121 cmd.push_cc_arg("-arch:IA32".into());
2122 } else {
2123 let llvm_target = target.versioned_llvm_target(None);
2124 cmd.push_cc_arg(format!("--target={llvm_target}").into());
2125 }
2126 } else if target.full_arch == "i586" {
2127 cmd.push_cc_arg("-arch:IA32".into());
2128 } else if target.full_arch == "arm64ec" {
2129 cmd.push_cc_arg("-arm64EC".into());
2130 }
2131 // There is a check in corecrt.h that will generate a
2132 // compilation error if
2133 // _ARM_WINAPI_PARTITION_DESKTOP_SDK_AVAILABLE is
2134 // not defined to 1. The check was added in Windows
2135 // 8 days because only store apps were allowed on ARM.
2136 // This changed with the release of Windows 10 IoT Core.
2137 // The check will be going away in future versions of
2138 // the SDK, but for all released versions of the
2139 // Windows SDK it is required.
2140 if target.arch == "arm" {
2141 cmd.args
2142 .push("-D_ARM_WINAPI_PARTITION_DESKTOP_SDK_AVAILABLE=1".into());
2143 }
2144 }
2145 ToolFamily::Gnu => {
2146 if target.vendor == "apple" {
2147 let arch = map_darwin_target_from_rust_to_compiler_architecture(target);
2148 cmd.args.push("-arch".into());
2149 cmd.args.push(arch.into());
2150 }
2151
2152 if target.vendor == "kmc" {
2153 cmd.args.push("-finput-charset=utf-8".into());
2154 }
2155
2156 if self.static_flag.is_none() {
2157 let features = self.getenv("CARGO_CFG_TARGET_FEATURE");
2158 let features = features.as_deref().unwrap_or_default();
2159 if features.to_string_lossy().contains("crt-static") {
2160 cmd.args.push("-static".into());
2161 }
2162 }
2163
2164 // armv7 targets get to use armv7 instructions
2165 if (target.full_arch.starts_with("armv7")
2166 || target.full_arch.starts_with("thumbv7"))
2167 && (target.os == "linux" || target.vendor == "kmc")
2168 {
2169 cmd.args.push("-march=armv7-a".into());
2170
2171 if target.abi == "eabihf" {
2172 // lowest common denominator FPU
2173 cmd.args.push("-mfpu=vfpv3-d16".into());
2174 }
2175 }
2176
2177 // (x86 Android doesn't say "eabi")
2178 if target.os == "android" && target.full_arch.contains("v7") {
2179 cmd.args.push("-march=armv7-a".into());
2180 cmd.args.push("-mthumb".into());
2181 if !target.full_arch.contains("neon") {
2182 // On android we can guarantee some extra float instructions
2183 // (specified in the android spec online)
2184 // NEON guarantees even more; see below.
2185 cmd.args.push("-mfpu=vfpv3-d16".into());
2186 }
2187 cmd.args.push("-mfloat-abi=softfp".into());
2188 }
2189
2190 if target.full_arch.contains("neon") {
2191 cmd.args.push("-mfpu=neon-vfpv4".into());
2192 }
2193
2194 if target.full_arch == "armv4t" && target.os == "linux" {
2195 cmd.args.push("-march=armv4t".into());
2196 cmd.args.push("-marm".into());
2197 cmd.args.push("-mfloat-abi=soft".into());
2198 }
2199
2200 if target.full_arch == "armv5te" && target.os == "linux" {
2201 cmd.args.push("-march=armv5te".into());
2202 cmd.args.push("-marm".into());
2203 cmd.args.push("-mfloat-abi=soft".into());
2204 }
2205
2206 // For us arm == armv6 by default
2207 if target.full_arch == "arm" && target.os == "linux" {
2208 cmd.args.push("-march=armv6".into());
2209 cmd.args.push("-marm".into());
2210 if target.abi == "eabihf" {
2211 cmd.args.push("-mfpu=vfp".into());
2212 } else {
2213 cmd.args.push("-mfloat-abi=soft".into());
2214 }
2215 }
2216
2217 // Turn codegen down on i586 to avoid some instructions.
2218 if target.full_arch == "i586" && target.os == "linux" {
2219 cmd.args.push("-march=pentium".into());
2220 }
2221
2222 // Set codegen level for i686 correctly
2223 if target.full_arch == "i686" && target.os == "linux" {
2224 cmd.args.push("-march=i686".into());
2225 }
2226
2227 // Looks like `musl-gcc` makes it hard for `-m32` to make its way
2228 // all the way to the linker, so we need to actually instruct the
2229 // linker that we're generating 32-bit executables as well. This'll
2230 // typically only be used for build scripts which transitively use
2231 // these flags that try to compile executables.
2232 if target.arch == "x86" && target.env == "musl" {
2233 cmd.args.push("-Wl,-melf_i386".into());
2234 }
2235
2236 if target.arch == "arm" && target.os == "none" && target.abi == "eabihf" {
2237 cmd.args.push("-mfloat-abi=hard".into())
2238 }
2239 if target.full_arch.starts_with("thumb") {
2240 cmd.args.push("-mthumb".into());
2241 }
2242 if target.full_arch.starts_with("thumbv6m") {
2243 cmd.args.push("-march=armv6s-m".into());
2244 }
2245 if target.full_arch.starts_with("thumbv7em") {
2246 cmd.args.push("-march=armv7e-m".into());
2247
2248 if target.abi == "eabihf" {
2249 cmd.args.push("-mfpu=fpv4-sp-d16".into())
2250 }
2251 }
2252 if target.full_arch.starts_with("thumbv7m") {
2253 cmd.args.push("-march=armv7-m".into());
2254 }
2255 if target.full_arch.starts_with("thumbv8m.base") {
2256 cmd.args.push("-march=armv8-m.base".into());
2257 }
2258 if target.full_arch.starts_with("thumbv8m.main") {
2259 cmd.args.push("-march=armv8-m.main".into());
2260
2261 if target.abi == "eabihf" {
2262 cmd.args.push("-mfpu=fpv5-sp-d16".into())
2263 }
2264 }
2265 if target.full_arch.starts_with("armebv7r") | target.full_arch.starts_with("armv7r")
2266 {
2267 if target.full_arch.starts_with("armeb") {
2268 cmd.args.push("-mbig-endian".into());
2269 } else {
2270 cmd.args.push("-mlittle-endian".into());
2271 }
2272
2273 // ARM mode
2274 cmd.args.push("-marm".into());
2275
2276 // R Profile
2277 cmd.args.push("-march=armv7-r".into());
2278
2279 if target.abi == "eabihf" {
2280 // lowest common denominator FPU
2281 // (see Cortex-R4 technical reference manual)
2282 cmd.args.push("-mfpu=vfpv3-d16".into())
2283 }
2284 }
2285 if target.full_arch.starts_with("armv7a") {
2286 cmd.args.push("-march=armv7-a".into());
2287
2288 if target.abi == "eabihf" {
2289 // lowest common denominator FPU
2290 cmd.args.push("-mfpu=vfpv3-d16".into());
2291 }
2292 }
2293 if target.arch == "riscv32" || target.arch == "riscv64" {
2294 // get the 32i/32imac/32imc/64gc/64imac/... part
2295 let arch = &target.full_arch[5..];
2296 if arch.starts_with("64") {
2297 if matches!(target.os, "linux" | "freebsd" | "netbsd") {
2298 cmd.args.push(("-march=rv64gc").into());
2299 cmd.args.push("-mabi=lp64d".into());
2300 } else {
2301 cmd.args.push(("-march=rv".to_owned() + arch).into());
2302 cmd.args.push("-mabi=lp64".into());
2303 }
2304 } else if arch.starts_with("32") {
2305 if target.os == "linux" {
2306 cmd.args.push(("-march=rv32gc").into());
2307 cmd.args.push("-mabi=ilp32d".into());
2308 } else {
2309 cmd.args.push(("-march=rv".to_owned() + arch).into());
2310 cmd.args.push("-mabi=ilp32".into());
2311 }
2312 } else {
2313 cmd.args.push("-mcmodel=medany".into());
2314 }
2315 }
2316 }
2317 }
2318
2319 if target.vendor == "apple" {
2320 self.apple_flags(cmd)?;
2321 }
2322
2323 if self.static_flag.unwrap_or(false) {
2324 cmd.args.push("-static".into());
2325 }
2326 if self.shared_flag.unwrap_or(false) {
2327 cmd.args.push("-shared".into());
2328 }
2329
2330 if self.cpp {
2331 match (self.cpp_set_stdlib.as_ref(), cmd.family) {
2332 (None, _) => {}
2333 (Some(stdlib), ToolFamily::Gnu) | (Some(stdlib), ToolFamily::Clang { .. }) => {
2334 cmd.push_cc_arg(format!("-stdlib=lib{}", stdlib).into());
2335 }
2336 _ => {
2337 self.cargo_output.print_warning(&format_args!("cpp_set_stdlib is specified, but the {:?} compiler does not support this option, ignored", cmd.family));
2338 }
2339 }
2340 }
2341
2342 Ok(())
2343 }
2344
2345 fn has_flags(&self) -> bool {
2346 let flags_env_var_name = if self.cpp { "CXXFLAGS" } else { "CFLAGS" };
2347 let flags_env_var_value = self.getenv_with_target_prefixes(flags_env_var_name);
2348 flags_env_var_value.is_ok()
2349 }
2350
2351 fn msvc_macro_assembler(&self) -> Result<(Command, &'static str), Error> {
2352 let target = self.get_target()?;
2353 let tool = if target.arch == "x86_64" {
2354 "ml64.exe"
2355 } else if target.arch == "arm" {
2356 "armasm.exe"
2357 } else if target.arch == "aarch64" {
2358 "armasm64.exe"
2359 } else {
2360 "ml.exe"
2361 };
2362 let mut cmd = self
2363 .windows_registry_find(&target, tool)
2364 .unwrap_or_else(|| self.cmd(tool));
2365 cmd.arg("-nologo"); // undocumented, yet working with armasm[64]
2366 for directory in self.include_directories.iter() {
2367 cmd.arg("-I").arg(&**directory);
2368 }
2369 if target.arch == "aarch64" || target.arch == "arm" {
2370 if self.get_debug() {
2371 cmd.arg("-g");
2372 }
2373
2374 for (key, value) in self.definitions.iter() {
2375 cmd.arg("-PreDefine");
2376 if let Some(ref value) = *value {
2377 if let Ok(i) = value.parse::<i32>() {
2378 cmd.arg(format!("{} SETA {}", key, i));
2379 } else if value.starts_with('"') && value.ends_with('"') {
2380 cmd.arg(format!("{} SETS {}", key, value));
2381 } else {
2382 cmd.arg(format!("{} SETS \"{}\"", key, value));
2383 }
2384 } else {
2385 cmd.arg(format!("{} SETL {}", key, "{TRUE}"));
2386 }
2387 }
2388 } else {
2389 if self.get_debug() {
2390 cmd.arg("-Zi");
2391 }
2392
2393 for (key, value) in self.definitions.iter() {
2394 if let Some(ref value) = *value {
2395 cmd.arg(format!("-D{}={}", key, value));
2396 } else {
2397 cmd.arg(format!("-D{}", key));
2398 }
2399 }
2400 }
2401
2402 if target.arch == "x86" {
2403 cmd.arg("-safeseh");
2404 }
2405
2406 Ok((cmd, tool))
2407 }
2408
2409 fn assemble(&self, lib_name: &str, dst: &Path, objs: &[Object]) -> Result<(), Error> {
2410 // Delete the destination if it exists as we want to
2411 // create on the first iteration instead of appending.
2412 let _ = fs::remove_file(dst);
2413
2414 // Add objects to the archive in limited-length batches. This helps keep
2415 // the length of the command line within a reasonable length to avoid
2416 // blowing system limits on limiting platforms like Windows.
2417 let objs: Vec<_> = objs
2418 .iter()
2419 .map(|o| o.dst.as_path())
2420 .chain(self.objects.iter().map(std::ops::Deref::deref))
2421 .collect();
2422 for chunk in objs.chunks(100) {
2423 self.assemble_progressive(dst, chunk)?;
2424 }
2425
2426 if self.cuda && self.cuda_file_count() > 0 {
2427 // Link the device-side code and add it to the target library,
2428 // so that non-CUDA linker can link the final binary.
2429
2430 let out_dir = self.get_out_dir()?;
2431 let dlink = out_dir.join(lib_name.to_owned() + "_dlink.o");
2432 let mut nvcc = self.get_compiler().to_command();
2433 nvcc.arg("--device-link").arg("-o").arg(&dlink).arg(dst);
2434 run(&mut nvcc, "nvcc", &self.cargo_output)?;
2435 self.assemble_progressive(dst, &[dlink.as_path()])?;
2436 }
2437
2438 let target = self.get_target()?;
2439 if target.env == "msvc" {
2440 // The Rust compiler will look for libfoo.a and foo.lib, but the
2441 // MSVC linker will also be passed foo.lib, so be sure that both
2442 // exist for now.
2443
2444 let lib_dst = dst.with_file_name(format!("{}.lib", lib_name));
2445 let _ = fs::remove_file(&lib_dst);
2446 match fs::hard_link(dst, &lib_dst).or_else(|_| {
2447 // if hard-link fails, just copy (ignoring the number of bytes written)
2448 fs::copy(dst, &lib_dst).map(|_| ())
2449 }) {
2450 Ok(_) => (),
2451 Err(_) => {
2452 return Err(Error::new(
2453 ErrorKind::IOError,
2454 "Could not copy or create a hard-link to the generated lib file.",
2455 ));
2456 }
2457 };
2458 } else {
2459 // Non-msvc targets (those using `ar`) need a separate step to add
2460 // the symbol table to archives since our construction command of
2461 // `cq` doesn't add it for us.
2462 let (mut ar, cmd, _any_flags) = self.get_ar()?;
2463
2464 // NOTE: We add `s` even if flags were passed using $ARFLAGS/ar_flag, because `s`
2465 // here represents a _mode_, not an arbitrary flag. Further discussion of this choice
2466 // can be seen in https://github.com/rust-lang/cc-rs/pull/763.
2467 run(ar.arg("s").arg(dst), &cmd, &self.cargo_output)?;
2468 }
2469
2470 Ok(())
2471 }
2472
2473 fn assemble_progressive(&self, dst: &Path, objs: &[&Path]) -> Result<(), Error> {
2474 let target = self.get_target()?;
2475
2476 let (mut cmd, program, any_flags) = self.get_ar()?;
2477 if target.env == "msvc" && !program.to_string_lossy().contains("llvm-ar") {
2478 // NOTE: -out: here is an I/O flag, and so must be included even if $ARFLAGS/ar_flag is
2479 // in use. -nologo on the other hand is just a regular flag, and one that we'll skip if
2480 // the caller has explicitly dictated the flags they want. See
2481 // https://github.com/rust-lang/cc-rs/pull/763 for further discussion.
2482 let mut out = OsString::from("-out:");
2483 out.push(dst);
2484 cmd.arg(out);
2485 if !any_flags {
2486 cmd.arg("-nologo");
2487 }
2488 // If the library file already exists, add the library name
2489 // as an argument to let lib.exe know we are appending the objs.
2490 if dst.exists() {
2491 cmd.arg(dst);
2492 }
2493 cmd.args(objs);
2494 run(&mut cmd, &program, &self.cargo_output)?;
2495 } else {
2496 // Set an environment variable to tell the OSX archiver to ensure
2497 // that all dates listed in the archive are zero, improving
2498 // determinism of builds. AFAIK there's not really official
2499 // documentation of this but there's a lot of references to it if
2500 // you search google.
2501 //
2502 // You can reproduce this locally on a mac with:
2503 //
2504 // $ touch foo.c
2505 // $ cc -c foo.c -o foo.o
2506 //
2507 // # Notice that these two checksums are different
2508 // $ ar crus libfoo1.a foo.o && sleep 2 && ar crus libfoo2.a foo.o
2509 // $ md5sum libfoo*.a
2510 //
2511 // # Notice that these two checksums are the same
2512 // $ export ZERO_AR_DATE=1
2513 // $ ar crus libfoo1.a foo.o && sleep 2 && touch foo.o && ar crus libfoo2.a foo.o
2514 // $ md5sum libfoo*.a
2515 //
2516 // In any case if this doesn't end up getting read, it shouldn't
2517 // cause that many issues!
2518 cmd.env("ZERO_AR_DATE", "1");
2519
2520 // NOTE: We add cq here regardless of whether $ARFLAGS/ar_flag have been used because
2521 // it dictates the _mode_ ar runs in, which the setter of $ARFLAGS/ar_flag can't
2522 // dictate. See https://github.com/rust-lang/cc-rs/pull/763 for further discussion.
2523 run(
2524 cmd.arg("cq").arg(dst).args(objs),
2525 &program,
2526 &self.cargo_output,
2527 )?;
2528 }
2529
2530 Ok(())
2531 }
2532
2533 fn apple_flags(&self, cmd: &mut Tool) -> Result<(), Error> {
2534 let target = self.get_target()?;
2535
2536 // If the compiler is Clang, then we've already specifed the target
2537 // information (including the deployment target) with the `--target`
2538 // option, so we don't need to do anything further here.
2539 //
2540 // If the compiler is GCC, then we need to specify
2541 // `-mmacosx-version-min` to set the deployment target, as well
2542 // as to say that the target OS is macOS.
2543 //
2544 // NOTE: GCC does not support `-miphoneos-version-min=` etc. (because
2545 // it does not support iOS in general), but we specify them anyhow in
2546 // case we actually have a Clang-like compiler disguised as a GNU-like
2547 // compiler, or in case GCC adds support for these in the future.
2548 if !cmd.is_like_clang() {
2549 let min_version = self.apple_deployment_target(&target);
2550 cmd.args
2551 .push(target.apple_version_flag(&min_version).into());
2552 }
2553
2554 // AppleClang sometimes requires sysroot even on macOS
2555 if cmd.is_xctoolchain_clang() || target.os != "macos" {
2556 self.cargo_output.print_metadata(&format_args!(
2557 "Detecting {:?} SDK path for {}",
2558 target.os,
2559 target.apple_sdk_name(),
2560 ));
2561 let sdk_path = self.apple_sdk_root(&target)?;
2562
2563 cmd.args.push("-isysroot".into());
2564 cmd.args.push(OsStr::new(&sdk_path).to_owned());
2565
2566 if target.abi == "macabi" {
2567 // Mac Catalyst uses the macOS SDK, but to compile against and
2568 // link to iOS-specific frameworks, we should have the support
2569 // library stubs in the include and library search path.
2570 let ios_support = Path::new(&sdk_path).join("System/iOSSupport");
2571
2572 cmd.args.extend([
2573 // Header search path
2574 OsString::from("-isystem"),
2575 ios_support.join("usr/include").into(),
2576 // Framework header search path
2577 OsString::from("-iframework"),
2578 ios_support.join("System/Library/Frameworks").into(),
2579 // Library search path
2580 {
2581 let mut s = OsString::from("-L");
2582 s.push(ios_support.join("usr/lib"));
2583 s
2584 },
2585 // Framework linker search path
2586 {
2587 // Technically, we _could_ avoid emitting `-F`, as
2588 // `-iframework` implies it, but let's keep it in for
2589 // clarity.
2590 let mut s = OsString::from("-F");
2591 s.push(ios_support.join("System/Library/Frameworks"));
2592 s
2593 },
2594 ]);
2595 }
2596 }
2597
2598 Ok(())
2599 }
2600
2601 fn cmd<P: AsRef<OsStr>>(&self, prog: P) -> Command {
2602 let mut cmd = Command::new(prog);
2603 for (a, b) in self.env.iter() {
2604 cmd.env(a, b);
2605 }
2606 cmd
2607 }
2608
2609 fn get_base_compiler(&self) -> Result<Tool, Error> {
2610 let out_dir = self.get_out_dir().ok();
2611 let out_dir = out_dir.as_deref();
2612
2613 if let Some(c) = &self.compiler {
2614 return Ok(Tool::new(
2615 (**c).to_owned(),
2616 &self.build_cache.cached_compiler_family,
2617 &self.cargo_output,
2618 out_dir,
2619 ));
2620 }
2621 let target = self.get_target()?;
2622 let raw_target = self.get_raw_target()?;
2623 let (env, msvc, gnu, traditional, clang) = if self.cpp {
2624 ("CXX", "cl.exe", "g++", "c++", "clang++")
2625 } else {
2626 ("CC", "cl.exe", "gcc", "cc", "clang")
2627 };
2628
2629 // On historical Solaris systems, "cc" may have been Sun Studio, which
2630 // is not flag-compatible with "gcc". This history casts a long shadow,
2631 // and many modern illumos distributions today ship GCC as "gcc" without
2632 // also making it available as "cc".
2633 let default = if cfg!(target_os = "solaris") || cfg!(target_os = "illumos") {
2634 gnu
2635 } else {
2636 traditional
2637 };
2638
2639 let cl_exe = self.windows_registry_find_tool(&target, "cl.exe");
2640
2641 let tool_opt: Option<Tool> = self
2642 .env_tool(env)
2643 .map(|(tool, wrapper, args)| {
2644 // find the driver mode, if any
2645 const DRIVER_MODE: &str = "--driver-mode=";
2646 let driver_mode = args
2647 .iter()
2648 .find(|a| a.starts_with(DRIVER_MODE))
2649 .map(|a| &a[DRIVER_MODE.len()..]);
2650 // Chop off leading/trailing whitespace to work around
2651 // semi-buggy build scripts which are shared in
2652 // makefiles/configure scripts (where spaces are far more
2653 // lenient)
2654 let mut t = Tool::with_clang_driver(
2655 tool,
2656 driver_mode,
2657 &self.build_cache.cached_compiler_family,
2658 &self.cargo_output,
2659 out_dir,
2660 );
2661 if let Some(cc_wrapper) = wrapper {
2662 t.cc_wrapper_path = Some(Path::new(&cc_wrapper).to_owned());
2663 }
2664 for arg in args {
2665 t.cc_wrapper_args.push(arg.into());
2666 }
2667 t
2668 })
2669 .or_else(|| {
2670 if target.os == "emscripten" {
2671 let tool = if self.cpp { "em++" } else { "emcc" };
2672 // Windows uses bat file so we have to be a bit more specific
2673 if cfg!(windows) {
2674 let mut t = Tool::with_family(
2675 PathBuf::from("cmd"),
2676 ToolFamily::Clang { zig_cc: false },
2677 );
2678 t.args.push("/c".into());
2679 t.args.push(format!("{}.bat", tool).into());
2680 Some(t)
2681 } else {
2682 Some(Tool::new(
2683 PathBuf::from(tool),
2684 &self.build_cache.cached_compiler_family,
2685 &self.cargo_output,
2686 out_dir,
2687 ))
2688 }
2689 } else {
2690 None
2691 }
2692 })
2693 .or_else(|| cl_exe.clone());
2694
2695 let tool = match tool_opt {
2696 Some(t) => t,
2697 None => {
2698 let compiler = if cfg!(windows) && target.os == "windows" {
2699 if target.env == "msvc" {
2700 msvc.to_string()
2701 } else {
2702 let cc = if target.abi == "llvm" { clang } else { gnu };
2703 format!("{}.exe", cc)
2704 }
2705 } else if target.os == "ios"
2706 || target.os == "watchos"
2707 || target.os == "tvos"
2708 || target.os == "visionos"
2709 {
2710 clang.to_string()
2711 } else if target.os == "android" {
2712 autodetect_android_compiler(&raw_target, gnu, clang)
2713 } else if target.os == "cloudabi" {
2714 format!(
2715 "{}-{}-{}-{}",
2716 target.full_arch, target.vendor, target.os, traditional
2717 )
2718 } else if target.arch == "wasm32" || target.arch == "wasm64" {
2719 // Compiling WASM is not currently supported by GCC, so
2720 // let's default to Clang.
2721 clang.to_string()
2722 } else if target.os == "vxworks" {
2723 if self.cpp {
2724 "wr-c++".to_string()
2725 } else {
2726 "wr-cc".to_string()
2727 }
2728 } else if target.arch == "arm" && target.vendor == "kmc" {
2729 format!("arm-kmc-eabi-{}", gnu)
2730 } else if target.arch == "aarch64" && target.vendor == "kmc" {
2731 format!("aarch64-kmc-elf-{}", gnu)
2732 } else if self.get_is_cross_compile()? {
2733 let prefix = self.prefix_for_target(&raw_target);
2734 match prefix {
2735 Some(prefix) => {
2736 let cc = if target.abi == "llvm" { clang } else { gnu };
2737 format!("{}-{}", prefix, cc)
2738 }
2739 None => default.to_string(),
2740 }
2741 } else {
2742 default.to_string()
2743 };
2744
2745 let mut t = Tool::new(
2746 PathBuf::from(compiler),
2747 &self.build_cache.cached_compiler_family,
2748 &self.cargo_output,
2749 out_dir,
2750 );
2751 if let Some(cc_wrapper) = self.rustc_wrapper_fallback() {
2752 t.cc_wrapper_path = Some(Path::new(&cc_wrapper).to_owned());
2753 }
2754 t
2755 }
2756 };
2757
2758 let mut tool = if self.cuda {
2759 assert!(
2760 tool.args.is_empty(),
2761 "CUDA compilation currently assumes empty pre-existing args"
2762 );
2763 let nvcc = match self.getenv_with_target_prefixes("NVCC") {
2764 Err(_) => PathBuf::from("nvcc"),
2765 Ok(nvcc) => PathBuf::from(&*nvcc),
2766 };
2767 let mut nvcc_tool = Tool::with_features(
2768 nvcc,
2769 None,
2770 self.cuda,
2771 &self.build_cache.cached_compiler_family,
2772 &self.cargo_output,
2773 out_dir,
2774 );
2775 if self.ccbin {
2776 nvcc_tool
2777 .args
2778 .push(format!("-ccbin={}", tool.path.display()).into());
2779 }
2780 nvcc_tool.family = tool.family;
2781 nvcc_tool
2782 } else {
2783 tool
2784 };
2785
2786 // New "standalone" C/C++ cross-compiler executables from recent Android NDK
2787 // are just shell scripts that call main clang binary (from Android NDK) with
2788 // proper `--target` argument.
2789 //
2790 // For example, armv7a-linux-androideabi16-clang passes
2791 // `--target=armv7a-linux-androideabi16` to clang.
2792 //
2793 // As the shell script calls the main clang binary, the command line limit length
2794 // on Windows is restricted to around 8k characters instead of around 32k characters.
2795 // To remove this limit, we call the main clang binary directly and construct the
2796 // `--target=` ourselves.
2797 if cfg!(windows) && android_clang_compiler_uses_target_arg_internally(&tool.path) {
2798 if let Some(path) = tool.path.file_name() {
2799 let file_name = path.to_str().unwrap().to_owned();
2800 let (target, clang) = file_name.split_at(file_name.rfind('-').unwrap());
2801
2802 tool.has_internal_target_arg = true;
2803 tool.path.set_file_name(clang.trim_start_matches('-'));
2804 tool.path.set_extension("exe");
2805 tool.args.push(format!("--target={}", target).into());
2806
2807 // Additionally, shell scripts for target i686-linux-android versions 16 to 24
2808 // pass the `mstackrealign` option so we do that here as well.
2809 if target.contains("i686-linux-android") {
2810 let (_, version) = target.split_at(target.rfind('d').unwrap() + 1);
2811 if let Ok(version) = version.parse::<u32>() {
2812 if version > 15 && version < 25 {
2813 tool.args.push("-mstackrealign".into());
2814 }
2815 }
2816 }
2817 };
2818 }
2819
2820 // If we found `cl.exe` in our environment, the tool we're returning is
2821 // an MSVC-like tool, *and* no env vars were set then set env vars for
2822 // the tool that we're returning.
2823 //
2824 // Env vars are needed for things like `link.exe` being put into PATH as
2825 // well as header include paths sometimes. These paths are automatically
2826 // included by default but if the `CC` or `CXX` env vars are set these
2827 // won't be used. This'll ensure that when the env vars are used to
2828 // configure for invocations like `clang-cl` we still get a "works out
2829 // of the box" experience.
2830 if let Some(cl_exe) = cl_exe {
2831 if tool.family == (ToolFamily::Msvc { clang_cl: true })
2832 && tool.env.is_empty()
2833 && target.env == "msvc"
2834 {
2835 for (k, v) in cl_exe.env.iter() {
2836 tool.env.push((k.to_owned(), v.to_owned()));
2837 }
2838 }
2839 }
2840
2841 if target.env == "msvc" && tool.family == ToolFamily::Gnu {
2842 self.cargo_output
2843 .print_warning(&"GNU compiler is not supported for this target");
2844 }
2845
2846 Ok(tool)
2847 }
2848
2849 /// Returns a fallback `cc_compiler_wrapper` by introspecting `RUSTC_WRAPPER`
2850 fn rustc_wrapper_fallback(&self) -> Option<Arc<OsStr>> {
2851 // No explicit CC wrapper was detected, but check if RUSTC_WRAPPER
2852 // is defined and is a build accelerator that is compatible with
2853 // C/C++ compilers (e.g. sccache)
2854 const VALID_WRAPPERS: &[&str] = &["sccache", "cachepot", "buildcache"];
2855
2856 let rustc_wrapper = self.getenv("RUSTC_WRAPPER")?;
2857 let wrapper_path = Path::new(&rustc_wrapper);
2858 let wrapper_stem = wrapper_path.file_stem()?;
2859
2860 if VALID_WRAPPERS.contains(&wrapper_stem.to_str()?) {
2861 Some(rustc_wrapper)
2862 } else {
2863 None
2864 }
2865 }
2866
2867 /// Returns compiler path, optional modifier name from whitelist, and arguments vec
2868 fn env_tool(&self, name: &str) -> Option<(PathBuf, Option<Arc<OsStr>>, Vec<String>)> {
2869 let tool = self.getenv_with_target_prefixes(name).ok()?;
2870 let tool = tool.to_string_lossy();
2871 let tool = tool.trim();
2872
2873 if tool.is_empty() {
2874 return None;
2875 }
2876
2877 // If this is an exact path on the filesystem we don't want to do any
2878 // interpretation at all, just pass it on through. This'll hopefully get
2879 // us to support spaces-in-paths.
2880 if Path::new(tool).exists() {
2881 return Some((
2882 PathBuf::from(tool),
2883 self.rustc_wrapper_fallback(),
2884 Vec::new(),
2885 ));
2886 }
2887
2888 // Ok now we want to handle a couple of scenarios. We'll assume from
2889 // here on out that spaces are splitting separate arguments. Two major
2890 // features we want to support are:
2891 //
2892 // CC='sccache cc'
2893 //
2894 // aka using `sccache` or any other wrapper/caching-like-thing for
2895 // compilations. We want to know what the actual compiler is still,
2896 // though, because our `Tool` API support introspection of it to see
2897 // what compiler is in use.
2898 //
2899 // additionally we want to support
2900 //
2901 // CC='cc -flag'
2902 //
2903 // where the CC env var is used to also pass default flags to the C
2904 // compiler.
2905 //
2906 // It's true that everything here is a bit of a pain, but apparently if
2907 // you're not literally make or bash then you get a lot of bug reports.
2908 let mut known_wrappers = vec![
2909 "ccache",
2910 "distcc",
2911 "sccache",
2912 "icecc",
2913 "cachepot",
2914 "buildcache",
2915 ];
2916 let custom_wrapper = self.getenv("CC_KNOWN_WRAPPER_CUSTOM");
2917 if custom_wrapper.is_some() {
2918 known_wrappers.push(custom_wrapper.as_deref().unwrap().to_str().unwrap());
2919 }
2920
2921 let mut parts = tool.split_whitespace();
2922 let maybe_wrapper = match parts.next() {
2923 Some(s) => s,
2924 None => return None,
2925 };
2926
2927 let file_stem = Path::new(maybe_wrapper).file_stem()?.to_str()?;
2928 if known_wrappers.contains(&file_stem) {
2929 if let Some(compiler) = parts.next() {
2930 return Some((
2931 compiler.into(),
2932 Some(Arc::<OsStr>::from(OsStr::new(&maybe_wrapper))),
2933 parts.map(|s| s.to_string()).collect(),
2934 ));
2935 }
2936 }
2937
2938 Some((
2939 maybe_wrapper.into(),
2940 self.rustc_wrapper_fallback(),
2941 parts.map(|s| s.to_string()).collect(),
2942 ))
2943 }
2944
2945 /// Returns the C++ standard library:
2946 /// 1. If [`cpp_link_stdlib`](cc::Build::cpp_link_stdlib) is set, uses its value.
2947 /// 2. Else if the `CXXSTDLIB` environment variable is set, uses its value.
2948 /// 3. Else the default is `c++` for OS X and BSDs, `c++_shared` for Android,
2949 /// `None` for MSVC and `stdc++` for anything else.
2950 fn get_cpp_link_stdlib(&self) -> Result<Option<Cow<'_, Path>>, Error> {
2951 match &self.cpp_link_stdlib {
2952 Some(s) => Ok(s.as_deref().map(Path::new).map(Cow::Borrowed)),
2953 None => {
2954 if let Ok(stdlib) = self.getenv_with_target_prefixes("CXXSTDLIB") {
2955 if stdlib.is_empty() {
2956 Ok(None)
2957 } else {
2958 Ok(Some(Cow::Owned(Path::new(&stdlib).to_owned())))
2959 }
2960 } else {
2961 let target = self.get_target()?;
2962 if target.env == "msvc" {
2963 Ok(None)
2964 } else if target.vendor == "apple"
2965 || target.os == "freebsd"
2966 || target.os == "openbsd"
2967 || target.os == "aix"
2968 || (target.os == "linux" && target.env == "ohos")
2969 || target.os == "wasi"
2970 {
2971 Ok(Some(Cow::Borrowed(Path::new("c++"))))
2972 } else if target.os == "android" {
2973 Ok(Some(Cow::Borrowed(Path::new("c++_shared"))))
2974 } else {
2975 Ok(Some(Cow::Borrowed(Path::new("stdc++"))))
2976 }
2977 }
2978 }
2979 }
2980 }
2981
2982 fn get_ar(&self) -> Result<(Command, PathBuf, bool), Error> {
2983 self.try_get_archiver_and_flags()
2984 }
2985
2986 /// Get the archiver (ar) that's in use for this configuration.
2987 ///
2988 /// You can use [`Command::get_program`] to get just the path to the command.
2989 ///
2990 /// This method will take into account all configuration such as debug
2991 /// information, optimization level, include directories, defines, etc.
2992 /// Additionally, the compiler binary in use follows the standard
2993 /// conventions for this path, e.g. looking at the explicitly set compiler,
2994 /// environment variables (a number of which are inspected here), and then
2995 /// falling back to the default configuration.
2996 ///
2997 /// # Panics
2998 ///
2999 /// Panics if an error occurred while determining the architecture.
3000 pub fn get_archiver(&self) -> Command {
3001 match self.try_get_archiver() {
3002 Ok(tool) => tool,
3003 Err(e) => fail(&e.message),
3004 }
3005 }
3006
3007 /// Get the archiver that's in use for this configuration.
3008 ///
3009 /// This will return a result instead of panicking;
3010 /// see [`Self::get_archiver`] for the complete description.
3011 pub fn try_get_archiver(&self) -> Result<Command, Error> {
3012 Ok(self.try_get_archiver_and_flags()?.0)
3013 }
3014
3015 fn try_get_archiver_and_flags(&self) -> Result<(Command, PathBuf, bool), Error> {
3016 let (mut cmd, name) = self.get_base_archiver()?;
3017 let mut any_flags = false;
3018 if let Ok(flags) = self.envflags("ARFLAGS") {
3019 any_flags |= !flags.is_empty();
3020 cmd.args(flags);
3021 }
3022 for flag in &self.ar_flags {
3023 any_flags = true;
3024 cmd.arg(&**flag);
3025 }
3026 Ok((cmd, name, any_flags))
3027 }
3028
3029 fn get_base_archiver(&self) -> Result<(Command, PathBuf), Error> {
3030 if let Some(ref a) = self.archiver {
3031 let archiver = &**a;
3032 return Ok((self.cmd(archiver), archiver.into()));
3033 }
3034
3035 self.get_base_archiver_variant("AR", "ar")
3036 }
3037
3038 /// Get the ranlib that's in use for this configuration.
3039 ///
3040 /// You can use [`Command::get_program`] to get just the path to the command.
3041 ///
3042 /// This method will take into account all configuration such as debug
3043 /// information, optimization level, include directories, defines, etc.
3044 /// Additionally, the compiler binary in use follows the standard
3045 /// conventions for this path, e.g. looking at the explicitly set compiler,
3046 /// environment variables (a number of which are inspected here), and then
3047 /// falling back to the default configuration.
3048 ///
3049 /// # Panics
3050 ///
3051 /// Panics if an error occurred while determining the architecture.
3052 pub fn get_ranlib(&self) -> Command {
3053 match self.try_get_ranlib() {
3054 Ok(tool) => tool,
3055 Err(e) => fail(&e.message),
3056 }
3057 }
3058
3059 /// Get the ranlib that's in use for this configuration.
3060 ///
3061 /// This will return a result instead of panicking;
3062 /// see [`Self::get_ranlib`] for the complete description.
3063 pub fn try_get_ranlib(&self) -> Result<Command, Error> {
3064 let mut cmd = self.get_base_ranlib()?;
3065 if let Ok(flags) = self.envflags("RANLIBFLAGS") {
3066 cmd.args(flags);
3067 }
3068 Ok(cmd)
3069 }
3070
3071 fn get_base_ranlib(&self) -> Result<Command, Error> {
3072 if let Some(ref r) = self.ranlib {
3073 return Ok(self.cmd(&**r));
3074 }
3075
3076 Ok(self.get_base_archiver_variant("RANLIB", "ranlib")?.0)
3077 }
3078
3079 fn get_base_archiver_variant(
3080 &self,
3081 env: &str,
3082 tool: &str,
3083 ) -> Result<(Command, PathBuf), Error> {
3084 let target = self.get_target()?;
3085 let mut name = PathBuf::new();
3086 let tool_opt: Option<Command> = self
3087 .env_tool(env)
3088 .map(|(tool, _wrapper, args)| {
3089 name.clone_from(&tool);
3090 let mut cmd = self.cmd(tool);
3091 cmd.args(args);
3092 cmd
3093 })
3094 .or_else(|| {
3095 if target.os == "emscripten" {
3096 // Windows use bat files so we have to be a bit more specific
3097 if cfg!(windows) {
3098 let mut cmd = self.cmd("cmd");
3099 name = format!("em{}.bat", tool).into();
3100 cmd.arg("/c").arg(&name);
3101 Some(cmd)
3102 } else {
3103 name = format!("em{}", tool).into();
3104 Some(self.cmd(&name))
3105 }
3106 } else if target.arch == "wasm32" || target.arch == "wasm64" {
3107 // Formally speaking one should be able to use this approach,
3108 // parsing -print-search-dirs output, to cover all clang targets,
3109 // including Android SDKs and other cross-compilation scenarios...
3110 // And even extend it to gcc targets by searching for "ar" instead
3111 // of "llvm-ar"...
3112 let compiler = self.get_base_compiler().ok()?;
3113 if compiler.is_like_clang() {
3114 name = format!("llvm-{}", tool).into();
3115 self.search_programs(
3116 &mut self.cmd(&compiler.path),
3117 &name,
3118 &self.cargo_output,
3119 )
3120 .map(|name| self.cmd(name))
3121 } else {
3122 None
3123 }
3124 } else {
3125 None
3126 }
3127 });
3128
3129 let default = tool.to_string();
3130 let tool = match tool_opt {
3131 Some(t) => t,
3132 None => {
3133 if target.os == "android" {
3134 name = format!("llvm-{}", tool).into();
3135 match Command::new(&name).arg("--version").status() {
3136 Ok(status) if status.success() => (),
3137 _ => {
3138 // FIXME: Use parsed target.
3139 let raw_target = self.get_raw_target()?;
3140 name = format!("{}-{}", raw_target.replace("armv7", "arm"), tool).into()
3141 }
3142 }
3143 self.cmd(&name)
3144 } else if target.env == "msvc" {
3145 // NOTE: There isn't really a ranlib on msvc, so arguably we should return
3146 // `None` somehow here. But in general, callers will already have to be aware
3147 // of not running ranlib on Windows anyway, so it feels okay to return lib.exe
3148 // here.
3149
3150 let compiler = self.get_base_compiler()?;
3151 let mut lib = String::new();
3152 if compiler.family == (ToolFamily::Msvc { clang_cl: true }) {
3153 // See if there is 'llvm-lib' next to 'clang-cl'
3154 // Another possibility could be to see if there is 'clang'
3155 // next to 'clang-cl' and use 'search_programs()' to locate
3156 // 'llvm-lib'. This is because 'clang-cl' doesn't support
3157 // the -print-search-dirs option.
3158 if let Some(mut cmd) = self.which(&compiler.path, None) {
3159 cmd.pop();
3160 cmd.push("llvm-lib.exe");
3161 if let Some(llvm_lib) = self.which(&cmd, None) {
3162 llvm_lib.to_str().unwrap().clone_into(&mut lib);
3163 }
3164 }
3165 }
3166
3167 if lib.is_empty() {
3168 name = PathBuf::from("lib.exe");
3169 let mut cmd = match self.windows_registry_find(&target, "lib.exe") {
3170 Some(t) => t,
3171 None => self.cmd("lib.exe"),
3172 };
3173 if target.full_arch == "arm64ec" {
3174 cmd.arg("/machine:arm64ec");
3175 }
3176 cmd
3177 } else {
3178 name = lib.into();
3179 self.cmd(&name)
3180 }
3181 } else if target.os == "illumos" {
3182 // The default 'ar' on illumos uses a non-standard flags,
3183 // but the OS comes bundled with a GNU-compatible variant.
3184 //
3185 // Use the GNU-variant to match other Unix systems.
3186 name = format!("g{}", tool).into();
3187 self.cmd(&name)
3188 } else if self.get_is_cross_compile()? {
3189 match self.prefix_for_target(&self.get_raw_target()?) {
3190 Some(p) => {
3191 // GCC uses $target-gcc-ar, whereas binutils uses $target-ar -- try both.
3192 // Prefer -ar if it exists, as builds of `-gcc-ar` have been observed to be
3193 // outright broken (such as when targeting freebsd with `--disable-lto`
3194 // toolchain where the archiver attempts to load the LTO plugin anyway but
3195 // fails to find one).
3196 //
3197 // The same applies to ranlib.
3198 let mut chosen = default;
3199 for &infix in &["", "-gcc"] {
3200 let target_p = format!("{}{}-{}", p, infix, tool);
3201 if Command::new(&target_p).output().is_ok() {
3202 chosen = target_p;
3203 break;
3204 }
3205 }
3206 name = chosen.into();
3207 self.cmd(&name)
3208 }
3209 None => {
3210 name = default.into();
3211 self.cmd(&name)
3212 }
3213 }
3214 } else {
3215 name = default.into();
3216 self.cmd(&name)
3217 }
3218 }
3219 };
3220
3221 Ok((tool, name))
3222 }
3223
3224 // FIXME: Use parsed target instead of raw target.
3225 fn prefix_for_target(&self, target: &str) -> Option<Cow<'static, str>> {
3226 // CROSS_COMPILE is of the form: "arm-linux-gnueabi-"
3227 self.getenv("CROSS_COMPILE")
3228 .as_deref()
3229 .map(|s| s.to_string_lossy().trim_end_matches('-').to_owned())
3230 .map(Cow::Owned)
3231 .or_else(|| {
3232 // Put aside RUSTC_LINKER's prefix to be used as second choice, after CROSS_COMPILE
3233 self.getenv("RUSTC_LINKER").and_then(|var| {
3234 var.to_string_lossy()
3235 .strip_suffix("-gcc")
3236 .map(str::to_string)
3237 .map(Cow::Owned)
3238 })
3239 })
3240 .or_else(|| {
3241 match target {
3242 // Note: there is no `aarch64-pc-windows-gnu` target, only `-gnullvm`
3243 "aarch64-pc-windows-gnullvm" => Some("aarch64-w64-mingw32"),
3244 "aarch64-uwp-windows-gnu" => Some("aarch64-w64-mingw32"),
3245 "aarch64-unknown-linux-gnu" => Some("aarch64-linux-gnu"),
3246 "aarch64-unknown-linux-musl" => Some("aarch64-linux-musl"),
3247 "aarch64-unknown-netbsd" => Some("aarch64--netbsd"),
3248 "arm-unknown-linux-gnueabi" => Some("arm-linux-gnueabi"),
3249 "armv4t-unknown-linux-gnueabi" => Some("arm-linux-gnueabi"),
3250 "armv5te-unknown-linux-gnueabi" => Some("arm-linux-gnueabi"),
3251 "armv5te-unknown-linux-musleabi" => Some("arm-linux-gnueabi"),
3252 "arm-unknown-linux-gnueabihf" => Some("arm-linux-gnueabihf"),
3253 "arm-unknown-linux-musleabi" => Some("arm-linux-musleabi"),
3254 "arm-unknown-linux-musleabihf" => Some("arm-linux-musleabihf"),
3255 "arm-unknown-netbsd-eabi" => Some("arm--netbsdelf-eabi"),
3256 "armv6-unknown-netbsd-eabihf" => Some("armv6--netbsdelf-eabihf"),
3257 "armv7-unknown-linux-gnueabi" => Some("arm-linux-gnueabi"),
3258 "armv7-unknown-linux-gnueabihf" => Some("arm-linux-gnueabihf"),
3259 "armv7-unknown-linux-musleabihf" => Some("arm-linux-musleabihf"),
3260 "armv7neon-unknown-linux-gnueabihf" => Some("arm-linux-gnueabihf"),
3261 "armv7neon-unknown-linux-musleabihf" => Some("arm-linux-musleabihf"),
3262 "thumbv7-unknown-linux-gnueabihf" => Some("arm-linux-gnueabihf"),
3263 "thumbv7-unknown-linux-musleabihf" => Some("arm-linux-musleabihf"),
3264 "thumbv7neon-unknown-linux-gnueabihf" => Some("arm-linux-gnueabihf"),
3265 "thumbv7neon-unknown-linux-musleabihf" => Some("arm-linux-musleabihf"),
3266 "armv7-unknown-netbsd-eabihf" => Some("armv7--netbsdelf-eabihf"),
3267 "hexagon-unknown-linux-musl" => Some("hexagon-linux-musl"),
3268 "i586-unknown-linux-musl" => Some("musl"),
3269 "i686-pc-windows-gnu" => Some("i686-w64-mingw32"),
3270 "i686-pc-windows-gnullvm" => Some("i686-w64-mingw32"),
3271 "i686-uwp-windows-gnu" => Some("i686-w64-mingw32"),
3272 "i686-unknown-linux-gnu" => self.find_working_gnu_prefix(&[
3273 "i686-linux-gnu",
3274 "x86_64-linux-gnu", // transparently support gcc-multilib
3275 ]), // explicit None if not found, so caller knows to fall back
3276 "i686-unknown-linux-musl" => Some("musl"),
3277 "i686-unknown-netbsd" => Some("i486--netbsdelf"),
3278 "loongarch64-unknown-linux-gnu" => Some("loongarch64-linux-gnu"),
3279 "mips-unknown-linux-gnu" => Some("mips-linux-gnu"),
3280 "mips-unknown-linux-musl" => Some("mips-linux-musl"),
3281 "mipsel-unknown-linux-gnu" => Some("mipsel-linux-gnu"),
3282 "mipsel-unknown-linux-musl" => Some("mipsel-linux-musl"),
3283 "mips64-unknown-linux-gnuabi64" => Some("mips64-linux-gnuabi64"),
3284 "mips64el-unknown-linux-gnuabi64" => Some("mips64el-linux-gnuabi64"),
3285 "mipsisa32r6-unknown-linux-gnu" => Some("mipsisa32r6-linux-gnu"),
3286 "mipsisa32r6el-unknown-linux-gnu" => Some("mipsisa32r6el-linux-gnu"),
3287 "mipsisa64r6-unknown-linux-gnuabi64" => Some("mipsisa64r6-linux-gnuabi64"),
3288 "mipsisa64r6el-unknown-linux-gnuabi64" => Some("mipsisa64r6el-linux-gnuabi64"),
3289 "powerpc-unknown-linux-gnu" => Some("powerpc-linux-gnu"),
3290 "powerpc-unknown-linux-gnuspe" => Some("powerpc-linux-gnuspe"),
3291 "powerpc-unknown-netbsd" => Some("powerpc--netbsd"),
3292 "powerpc64-unknown-linux-gnu" => Some("powerpc-linux-gnu"),
3293 "powerpc64le-unknown-linux-gnu" => Some("powerpc64le-linux-gnu"),
3294 "riscv32i-unknown-none-elf" => self.find_working_gnu_prefix(&[
3295 "riscv32-unknown-elf",
3296 "riscv64-unknown-elf",
3297 "riscv-none-embed",
3298 ]),
3299 "riscv32imac-esp-espidf" => Some("riscv32-esp-elf"),
3300 "riscv32imac-unknown-none-elf" => self.find_working_gnu_prefix(&[
3301 "riscv32-unknown-elf",
3302 "riscv64-unknown-elf",
3303 "riscv-none-embed",
3304 ]),
3305 "riscv32imac-unknown-xous-elf" => self.find_working_gnu_prefix(&[
3306 "riscv32-unknown-elf",
3307 "riscv64-unknown-elf",
3308 "riscv-none-embed",
3309 ]),
3310 "riscv32imc-esp-espidf" => Some("riscv32-esp-elf"),
3311 "riscv32imc-unknown-none-elf" => self.find_working_gnu_prefix(&[
3312 "riscv32-unknown-elf",
3313 "riscv64-unknown-elf",
3314 "riscv-none-embed",
3315 ]),
3316 "riscv64gc-unknown-none-elf" => self.find_working_gnu_prefix(&[
3317 "riscv64-unknown-elf",
3318 "riscv32-unknown-elf",
3319 "riscv-none-embed",
3320 ]),
3321 "riscv64imac-unknown-none-elf" => self.find_working_gnu_prefix(&[
3322 "riscv64-unknown-elf",
3323 "riscv32-unknown-elf",
3324 "riscv-none-embed",
3325 ]),
3326 "riscv64gc-unknown-linux-gnu" => Some("riscv64-linux-gnu"),
3327 "riscv32gc-unknown-linux-gnu" => Some("riscv32-linux-gnu"),
3328 "riscv64gc-unknown-linux-musl" => Some("riscv64-linux-musl"),
3329 "riscv32gc-unknown-linux-musl" => Some("riscv32-linux-musl"),
3330 "riscv64gc-unknown-netbsd" => Some("riscv64--netbsd"),
3331 "s390x-unknown-linux-gnu" => Some("s390x-linux-gnu"),
3332 "sparc-unknown-linux-gnu" => Some("sparc-linux-gnu"),
3333 "sparc64-unknown-linux-gnu" => Some("sparc64-linux-gnu"),
3334 "sparc64-unknown-netbsd" => Some("sparc64--netbsd"),
3335 "sparcv9-sun-solaris" => Some("sparcv9-sun-solaris"),
3336 "armv7a-none-eabi" => Some("arm-none-eabi"),
3337 "armv7a-none-eabihf" => Some("arm-none-eabi"),
3338 "armebv7r-none-eabi" => Some("arm-none-eabi"),
3339 "armebv7r-none-eabihf" => Some("arm-none-eabi"),
3340 "armv7r-none-eabi" => Some("arm-none-eabi"),
3341 "armv7r-none-eabihf" => Some("arm-none-eabi"),
3342 "armv8r-none-eabihf" => Some("arm-none-eabi"),
3343 "thumbv6m-none-eabi" => Some("arm-none-eabi"),
3344 "thumbv7em-none-eabi" => Some("arm-none-eabi"),
3345 "thumbv7em-none-eabihf" => Some("arm-none-eabi"),
3346 "thumbv7m-none-eabi" => Some("arm-none-eabi"),
3347 "thumbv8m.base-none-eabi" => Some("arm-none-eabi"),
3348 "thumbv8m.main-none-eabi" => Some("arm-none-eabi"),
3349 "thumbv8m.main-none-eabihf" => Some("arm-none-eabi"),
3350 "x86_64-pc-windows-gnu" => Some("x86_64-w64-mingw32"),
3351 "x86_64-pc-windows-gnullvm" => Some("x86_64-w64-mingw32"),
3352 "x86_64-uwp-windows-gnu" => Some("x86_64-w64-mingw32"),
3353 "x86_64-rumprun-netbsd" => Some("x86_64-rumprun-netbsd"),
3354 "x86_64-unknown-linux-gnu" => self.find_working_gnu_prefix(&[
3355 "x86_64-linux-gnu", // rustfmt wrap
3356 ]), // explicit None if not found, so caller knows to fall back
3357 "x86_64-unknown-linux-musl" => Some("musl"),
3358 "x86_64-unknown-netbsd" => Some("x86_64--netbsd"),
3359 _ => None,
3360 }
3361 .map(Cow::Borrowed)
3362 })
3363 }
3364
3365 /// Some platforms have multiple, compatible, canonical prefixes. Look through
3366 /// each possible prefix for a compiler that exists and return it. The prefixes
3367 /// should be ordered from most-likely to least-likely.
3368 fn find_working_gnu_prefix(&self, prefixes: &[&'static str]) -> Option<&'static str> {
3369 let suffix = if self.cpp { "-g++" } else { "-gcc" };
3370 let extension = std::env::consts::EXE_SUFFIX;
3371
3372 // Loop through PATH entries searching for each toolchain. This ensures that we
3373 // are more likely to discover the toolchain early on, because chances are good
3374 // that the desired toolchain is in one of the higher-priority paths.
3375 self.getenv("PATH")
3376 .as_ref()
3377 .and_then(|path_entries| {
3378 env::split_paths(path_entries).find_map(|path_entry| {
3379 for prefix in prefixes {
3380 let target_compiler = format!("{}{}{}", prefix, suffix, extension);
3381 if path_entry.join(&target_compiler).exists() {
3382 return Some(prefix);
3383 }
3384 }
3385 None
3386 })
3387 })
3388 .copied()
3389 // If no toolchain was found, provide the first toolchain that was passed in.
3390 // This toolchain has been shown not to exist, however it will appear in the
3391 // error that is shown to the user which should make it easier to search for
3392 // where it should be obtained.
3393 .or_else(|| prefixes.first().copied())
3394 }
3395
3396 fn get_target(&self) -> Result<TargetInfo<'_>, Error> {
3397 match &self.target {
3398 Some(t) => t.parse(),
3399 None => self
3400 .build_cache
3401 .target_info_parser
3402 .parse_from_cargo_environment_variables(),
3403 }
3404 }
3405
3406 fn get_raw_target(&self) -> Result<Cow<'_, str>, Error> {
3407 match &self.target {
3408 Some(t) => Ok(Cow::Borrowed(t)),
3409 None => self.getenv_unwrap_str("TARGET").map(Cow::Owned),
3410 }
3411 }
3412
3413 fn get_is_cross_compile(&self) -> Result<bool, Error> {
3414 let target = self.get_raw_target()?;
3415 let host: Cow<'_, str> = match &self.host {
3416 Some(h) => Cow::Borrowed(h),
3417 None => Cow::Owned(self.getenv_unwrap_str("HOST")?),
3418 };
3419 Ok(host != target)
3420 }
3421
3422 fn get_opt_level(&self) -> Result<Cow<'_, str>, Error> {
3423 match &self.opt_level {
3424 Some(ol) => Ok(Cow::Borrowed(ol)),
3425 None => self.getenv_unwrap_str("OPT_LEVEL").map(Cow::Owned),
3426 }
3427 }
3428
3429 fn get_debug(&self) -> bool {
3430 self.debug.unwrap_or_else(|| self.getenv_boolean("DEBUG"))
3431 }
3432
3433 fn get_shell_escaped_flags(&self) -> bool {
3434 self.shell_escaped_flags
3435 .unwrap_or_else(|| self.getenv_boolean("CC_SHELL_ESCAPED_FLAGS"))
3436 }
3437
3438 fn get_dwarf_version(&self) -> Option<u32> {
3439 // Tentatively matches the DWARF version defaults as of rustc 1.62.
3440 let target = self.get_target().ok()?;
3441 if matches!(
3442 target.os,
3443 "android" | "dragonfly" | "freebsd" | "netbsd" | "openbsd"
3444 ) || target.vendor == "apple"
3445 || (target.os == "windows" && target.env == "gnu")
3446 {
3447 Some(2)
3448 } else if target.os == "linux" {
3449 Some(4)
3450 } else {
3451 None
3452 }
3453 }
3454
3455 fn get_force_frame_pointer(&self) -> bool {
3456 self.force_frame_pointer.unwrap_or_else(|| self.get_debug())
3457 }
3458
3459 fn get_out_dir(&self) -> Result<Cow<'_, Path>, Error> {
3460 match &self.out_dir {
3461 Some(p) => Ok(Cow::Borrowed(&**p)),
3462 None => self
3463 .getenv("OUT_DIR")
3464 .as_deref()
3465 .map(PathBuf::from)
3466 .map(Cow::Owned)
3467 .ok_or_else(|| {
3468 Error::new(
3469 ErrorKind::EnvVarNotFound,
3470 "Environment variable OUT_DIR not defined.",
3471 )
3472 }),
3473 }
3474 }
3475
3476 #[allow(clippy::disallowed_methods)]
3477 fn getenv(&self, v: &str) -> Option<Arc<OsStr>> {
3478 // Returns true for environment variables cargo sets for build scripts:
3479 // https://doc.rust-lang.org/cargo/reference/environment-variables.html#environment-variables-cargo-sets-for-build-scripts
3480 //
3481 // This handles more of the vars than we actually use (it tries to check
3482 // complete-ish set), just to avoid needing maintenance if/when new
3483 // calls to `getenv`/`getenv_unwrap` are added.
3484 fn provided_by_cargo(envvar: &str) -> bool {
3485 match envvar {
3486 v if v.starts_with("CARGO") || v.starts_with("RUSTC") => true,
3487 "HOST" | "TARGET" | "RUSTDOC" | "OUT_DIR" | "OPT_LEVEL" | "DEBUG" | "PROFILE"
3488 | "NUM_JOBS" | "RUSTFLAGS" => true,
3489 _ => false,
3490 }
3491 }
3492 if let Some(val) = self.build_cache.env_cache.read().unwrap().get(v).cloned() {
3493 return val;
3494 }
3495 // Excluding `PATH` prevents spurious rebuilds on Windows, see
3496 // <https://github.com/rust-lang/cc-rs/pull/1215> for details.
3497 if self.emit_rerun_if_env_changed && !provided_by_cargo(v) && v != "PATH" {
3498 self.cargo_output
3499 .print_metadata(&format_args!("cargo:rerun-if-env-changed={}", v));
3500 }
3501 let r = env::var_os(v).map(Arc::from);
3502 self.cargo_output.print_metadata(&format_args!(
3503 "{} = {}",
3504 v,
3505 OptionOsStrDisplay(r.as_deref())
3506 ));
3507 self.build_cache
3508 .env_cache
3509 .write()
3510 .unwrap()
3511 .insert(v.into(), r.clone());
3512 r
3513 }
3514
3515 /// get boolean flag that is either true or false
3516 fn getenv_boolean(&self, v: &str) -> bool {
3517 match self.getenv(v) {
3518 Some(s) => &*s != "0" && &*s != "false" && !s.is_empty(),
3519 None => false,
3520 }
3521 }
3522
3523 fn getenv_unwrap(&self, v: &str) -> Result<Arc<OsStr>, Error> {
3524 match self.getenv(v) {
3525 Some(s) => Ok(s),
3526 None => Err(Error::new(
3527 ErrorKind::EnvVarNotFound,
3528 format!("Environment variable {} not defined.", v),
3529 )),
3530 }
3531 }
3532
3533 fn getenv_unwrap_str(&self, v: &str) -> Result<String, Error> {
3534 let env = self.getenv_unwrap(v)?;
3535 env.to_str().map(String::from).ok_or_else(|| {
3536 Error::new(
3537 ErrorKind::EnvVarNotFound,
3538 format!("Environment variable {} is not valid utf-8.", v),
3539 )
3540 })
3541 }
3542
3543 fn getenv_with_target_prefixes(&self, var_base: &str) -> Result<Arc<OsStr>, Error> {
3544 let target = self.get_raw_target()?;
3545 let kind = if self.get_is_cross_compile()? {
3546 "TARGET"
3547 } else {
3548 "HOST"
3549 };
3550 let target_u = target.replace('-', "_");
3551 let res = self
3552 .getenv(&format!("{}_{}", var_base, target))
3553 .or_else(|| self.getenv(&format!("{}_{}", var_base, target_u)))
3554 .or_else(|| self.getenv(&format!("{}_{}", kind, var_base)))
3555 .or_else(|| self.getenv(var_base));
3556
3557 match res {
3558 Some(res) => Ok(res),
3559 None => Err(Error::new(
3560 ErrorKind::EnvVarNotFound,
3561 format!("Could not find environment variable {}.", var_base),
3562 )),
3563 }
3564 }
3565
3566 fn envflags(&self, name: &str) -> Result<Vec<String>, Error> {
3567 let env_os = self.getenv_with_target_prefixes(name)?;
3568 let env = env_os.to_string_lossy();
3569
3570 if self.get_shell_escaped_flags() {
3571 Ok(Shlex::new(&env).collect())
3572 } else {
3573 Ok(env
3574 .split_ascii_whitespace()
3575 .map(ToString::to_string)
3576 .collect())
3577 }
3578 }
3579
3580 fn fix_env_for_apple_os(&self, cmd: &mut Command) -> Result<(), Error> {
3581 let target = self.get_target()?;
3582 if cfg!(target_os = "macos") && target.os == "macos" {
3583 // Additionally, `IPHONEOS_DEPLOYMENT_TARGET` must not be set when using the Xcode linker at
3584 // "/Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/ld",
3585 // although this is apparently ignored when using the linker at "/usr/bin/ld".
3586 cmd.env_remove("IPHONEOS_DEPLOYMENT_TARGET");
3587 }
3588 Ok(())
3589 }
3590
3591 fn apple_sdk_root_inner(&self, sdk: &str) -> Result<Arc<OsStr>, Error> {
3592 // Code copied from rustc's compiler/rustc_codegen_ssa/src/back/link.rs.
3593 if let Some(sdkroot) = self.getenv("SDKROOT") {
3594 let p = Path::new(&sdkroot);
3595 let does_sdkroot_contain = |strings: &[&str]| {
3596 let sdkroot_str = p.to_string_lossy();
3597 strings.iter().any(|s| sdkroot_str.contains(s))
3598 };
3599 match sdk {
3600 // Ignore `SDKROOT` if it's clearly set for the wrong platform.
3601 "appletvos"
3602 if does_sdkroot_contain(&["TVSimulator.platform", "MacOSX.platform"]) => {}
3603 "appletvsimulator"
3604 if does_sdkroot_contain(&["TVOS.platform", "MacOSX.platform"]) => {}
3605 "iphoneos"
3606 if does_sdkroot_contain(&["iPhoneSimulator.platform", "MacOSX.platform"]) => {}
3607 "iphonesimulator"
3608 if does_sdkroot_contain(&["iPhoneOS.platform", "MacOSX.platform"]) => {}
3609 "macosx10.15"
3610 if does_sdkroot_contain(&["iPhoneOS.platform", "iPhoneSimulator.platform"]) => {
3611 }
3612 "watchos"
3613 if does_sdkroot_contain(&["WatchSimulator.platform", "MacOSX.platform"]) => {}
3614 "watchsimulator"
3615 if does_sdkroot_contain(&["WatchOS.platform", "MacOSX.platform"]) => {}
3616 "xros" if does_sdkroot_contain(&["XRSimulator.platform", "MacOSX.platform"]) => {}
3617 "xrsimulator" if does_sdkroot_contain(&["XROS.platform", "MacOSX.platform"]) => {}
3618 // Ignore `SDKROOT` if it's not a valid path.
3619 _ if !p.is_absolute() || p == Path::new("/") || !p.exists() => {}
3620 _ => return Ok(sdkroot),
3621 }
3622 }
3623
3624 let sdk_path = run_output(
3625 self.cmd("xcrun")
3626 .arg("--show-sdk-path")
3627 .arg("--sdk")
3628 .arg(sdk),
3629 "xcrun",
3630 &self.cargo_output,
3631 )?;
3632
3633 let sdk_path = match String::from_utf8(sdk_path) {
3634 Ok(p) => p,
3635 Err(_) => {
3636 return Err(Error::new(
3637 ErrorKind::IOError,
3638 "Unable to determine Apple SDK path.",
3639 ));
3640 }
3641 };
3642 Ok(Arc::from(OsStr::new(sdk_path.trim())))
3643 }
3644
3645 fn apple_sdk_root(&self, target: &TargetInfo) -> Result<Arc<OsStr>, Error> {
3646 let sdk = target.apple_sdk_name();
3647
3648 if let Some(ret) = self
3649 .build_cache
3650 .apple_sdk_root_cache
3651 .read()
3652 .expect("apple_sdk_root_cache lock failed")
3653 .get(sdk)
3654 .cloned()
3655 {
3656 return Ok(ret);
3657 }
3658 let sdk_path = self.apple_sdk_root_inner(sdk)?;
3659 self.build_cache
3660 .apple_sdk_root_cache
3661 .write()
3662 .expect("apple_sdk_root_cache lock failed")
3663 .insert(sdk.into(), sdk_path.clone());
3664 Ok(sdk_path)
3665 }
3666
3667 fn apple_deployment_target(&self, target: &TargetInfo<'_>) -> Arc<str> {
3668 let sdk = target.apple_sdk_name();
3669 if let Some(ret) = self
3670 .build_cache
3671 .apple_versions_cache
3672 .read()
3673 .expect("apple_versions_cache lock failed")
3674 .get(sdk)
3675 .cloned()
3676 {
3677 return ret;
3678 }
3679
3680 let default_deployment_from_sdk = || -> Option<Arc<str>> {
3681 let version = run_output(
3682 self.cmd("xcrun")
3683 .arg("--show-sdk-version")
3684 .arg("--sdk")
3685 .arg(sdk),
3686 "xcrun",
3687 &self.cargo_output,
3688 )
3689 .ok()?;
3690
3691 Some(Arc::from(std::str::from_utf8(&version).ok()?.trim()))
3692 };
3693
3694 let deployment_from_env = |name: &str| -> Option<Arc<str>> {
3695 // note that self.env isn't hit in production codepaths, its mostly just for tests which don't
3696 // set the real env
3697 self.env
3698 .iter()
3699 .find(|(k, _)| &**k == OsStr::new(name))
3700 .map(|(_, v)| v)
3701 .cloned()
3702 .or_else(|| self.getenv(name))?
3703 .to_str()
3704 .map(Arc::from)
3705 };
3706
3707 // Determines if the acquired deployment target is too low to support modern C++ on some Apple platform.
3708 //
3709 // A long time ago they used libstdc++, but since macOS 10.9 and iOS 7 libc++ has been the library the SDKs provide to link against.
3710 // If a `cc`` config wants to use C++, we round up to these versions as the baseline.
3711 let maybe_cpp_version_baseline = |deployment_target_ver: Arc<str>| -> Option<Arc<str>> {
3712 if !self.cpp {
3713 return Some(deployment_target_ver);
3714 }
3715
3716 let mut deployment_target = deployment_target_ver
3717 .split('.')
3718 .map(|v| v.parse::<u32>().expect("integer version"));
3719
3720 match target.os {
3721 "macos" => {
3722 let major = deployment_target.next().unwrap_or(0);
3723 let minor = deployment_target.next().unwrap_or(0);
3724
3725 // If below 10.9, we ignore it and let the SDK's target definitions handle it.
3726 if major == 10 && minor < 9 {
3727 self.cargo_output.print_warning(&format_args!(
3728 "macOS deployment target ({}) too low, it will be increased",
3729 deployment_target_ver
3730 ));
3731 return None;
3732 }
3733 }
3734 "ios" => {
3735 let major = deployment_target.next().unwrap_or(0);
3736
3737 // If below 10.7, we ignore it and let the SDK's target definitions handle it.
3738 if major < 7 {
3739 self.cargo_output.print_warning(&format_args!(
3740 "iOS deployment target ({}) too low, it will be increased",
3741 deployment_target_ver
3742 ));
3743 return None;
3744 }
3745 }
3746 // watchOS, tvOS, visionOS, and others are all new enough that libc++ is their baseline.
3747 _ => {}
3748 }
3749
3750 // If the deployment target met or exceeded the C++ baseline
3751 Some(deployment_target_ver)
3752 };
3753
3754 // The hardcoded minimums here are subject to change in a future compiler release,
3755 // and only exist as last resort fallbacks. Don't consider them stable.
3756 // `cc` doesn't use rustc's `--print deployment-target`` because the compiler's defaults
3757 // don't align well with Apple's SDKs and other third-party libraries that require ~generally~ higher
3758 // deployment targets. rustc isn't interested in those by default though so its fine to be different here.
3759 //
3760 // If no explicit target is passed, `cc` defaults to the current Xcode SDK's `DefaultDeploymentTarget` for better
3761 // compatibility. This is also the crate's historical behavior and what has become a relied-on value.
3762 //
3763 // The ordering of env -> XCode SDK -> old rustc defaults is intentional for performance when using
3764 // an explicit target.
3765 let version: Arc<str> = match target.os {
3766 "macos" => deployment_from_env("MACOSX_DEPLOYMENT_TARGET")
3767 .and_then(maybe_cpp_version_baseline)
3768 .or_else(default_deployment_from_sdk)
3769 .unwrap_or_else(|| {
3770 if target.arch == "aarch64" {
3771 "11.0".into()
3772 } else {
3773 let default: Arc<str> = Arc::from("10.7");
3774 maybe_cpp_version_baseline(default.clone()).unwrap_or(default)
3775 }
3776 }),
3777
3778 "ios" => deployment_from_env("IPHONEOS_DEPLOYMENT_TARGET")
3779 .and_then(maybe_cpp_version_baseline)
3780 .or_else(default_deployment_from_sdk)
3781 .unwrap_or_else(|| "7.0".into()),
3782
3783 "watchos" => deployment_from_env("WATCHOS_DEPLOYMENT_TARGET")
3784 .or_else(default_deployment_from_sdk)
3785 .unwrap_or_else(|| "5.0".into()),
3786
3787 "tvos" => deployment_from_env("TVOS_DEPLOYMENT_TARGET")
3788 .or_else(default_deployment_from_sdk)
3789 .unwrap_or_else(|| "9.0".into()),
3790
3791 "visionos" => deployment_from_env("XROS_DEPLOYMENT_TARGET")
3792 .or_else(default_deployment_from_sdk)
3793 .unwrap_or_else(|| "1.0".into()),
3794
3795 os => unreachable!("unknown Apple OS: {}", os),
3796 };
3797
3798 self.build_cache
3799 .apple_versions_cache
3800 .write()
3801 .expect("apple_versions_cache lock failed")
3802 .insert(sdk.into(), version.clone());
3803
3804 version
3805 }
3806
3807 fn wasi_sysroot(&self) -> Result<Arc<OsStr>, Error> {
3808 if let Some(wasi_sysroot_path) = self.getenv("WASI_SYSROOT") {
3809 Ok(wasi_sysroot_path)
3810 } else {
3811 Err(Error::new(
3812 ErrorKind::EnvVarNotFound,
3813 "Environment variable WASI_SYSROOT not defined. Download sysroot from GitHub & setup environment variable WASI_SYSROOT targeting the folder.",
3814 ))
3815 }
3816 }
3817
3818 fn cuda_file_count(&self) -> usize {
3819 self.files
3820 .iter()
3821 .filter(|file| file.extension() == Some(OsStr::new("cu")))
3822 .count()
3823 }
3824
3825 fn which(&self, tool: &Path, path_entries: Option<&OsStr>) -> Option<PathBuf> {
3826 fn check_exe(mut exe: PathBuf) -> Option<PathBuf> {
3827 let exe_ext = std::env::consts::EXE_EXTENSION;
3828 let check =
3829 exe.exists() || (!exe_ext.is_empty() && exe.set_extension(exe_ext) && exe.exists());
3830 check.then_some(exe)
3831 }
3832
3833 // Loop through PATH entries searching for the |tool|.
3834 let find_exe_in_path = |path_entries: &OsStr| -> Option<PathBuf> {
3835 env::split_paths(path_entries).find_map(|path_entry| check_exe(path_entry.join(tool)))
3836 };
3837
3838 // If |tool| is not just one "word," assume it's an actual path...
3839 if tool.components().count() > 1 {
3840 check_exe(PathBuf::from(tool))
3841 } else {
3842 path_entries
3843 .and_then(find_exe_in_path)
3844 .or_else(|| find_exe_in_path(&self.getenv("PATH")?))
3845 }
3846 }
3847
3848 /// search for |prog| on 'programs' path in '|cc| -print-search-dirs' output
3849 fn search_programs(
3850 &self,
3851 cc: &mut Command,
3852 prog: &Path,
3853 cargo_output: &CargoOutput,
3854 ) -> Option<PathBuf> {
3855 let search_dirs = run_output(
3856 cc.arg("-print-search-dirs"),
3857 "cc",
3858 // this doesn't concern the compilation so we always want to show warnings.
3859 cargo_output,
3860 )
3861 .ok()?;
3862 // clang driver appears to be forcing UTF-8 output even on Windows,
3863 // hence from_utf8 is assumed to be usable in all cases.
3864 let search_dirs = std::str::from_utf8(&search_dirs).ok()?;
3865 for dirs in search_dirs.split(['\r', '\n']) {
3866 if let Some(path) = dirs.strip_prefix("programs: =") {
3867 return self.which(prog, Some(OsStr::new(path)));
3868 }
3869 }
3870 None
3871 }
3872
3873 fn windows_registry_find(&self, target: &TargetInfo<'_>, tool: &str) -> Option<Command> {
3874 self.windows_registry_find_tool(target, tool)
3875 .map(|c| c.to_command())
3876 }
3877
3878 fn windows_registry_find_tool(&self, target: &TargetInfo<'_>, tool: &str) -> Option<Tool> {
3879 struct BuildEnvGetter<'s>(&'s Build);
3880
3881 impl windows_registry::EnvGetter for BuildEnvGetter<'_> {
3882 fn get_env(&self, name: &str) -> Option<windows_registry::Env> {
3883 self.0.getenv(name).map(windows_registry::Env::Arced)
3884 }
3885 }
3886
3887 if target.env != "msvc" {
3888 return None;
3889 }
3890
3891 windows_registry::find_tool_inner(target.full_arch, tool, &BuildEnvGetter(self))
3892 }
3893}
3894
3895impl Default for Build {
3896 fn default() -> Build {
3897 Build::new()
3898 }
3899}
3900
3901fn fail(s: &str) -> ! {
3902 eprintln!("\n\nerror occurred: {}\n\n", s);
3903 std::process::exit(1);
3904}
3905
3906// Use by default minimum available API level
3907// See note about naming here
3908// https://android.googlesource.com/platform/ndk/+/refs/heads/ndk-release-r21/docs/BuildSystemMaintainers.md#Clang
3909static NEW_STANDALONE_ANDROID_COMPILERS: [&str; 4] = [
3910 "aarch64-linux-android21-clang",
3911 "armv7a-linux-androideabi16-clang",
3912 "i686-linux-android16-clang",
3913 "x86_64-linux-android21-clang",
3914];
3915
3916// New "standalone" C/C++ cross-compiler executables from recent Android NDK
3917// are just shell scripts that call main clang binary (from Android NDK) with
3918// proper `--target` argument.
3919//
3920// For example, armv7a-linux-androideabi16-clang passes
3921// `--target=armv7a-linux-androideabi16` to clang.
3922// So to construct proper command line check if
3923// `--target` argument would be passed or not to clang
3924fn android_clang_compiler_uses_target_arg_internally(clang_path: &Path) -> bool {
3925 if let Some(filename) = clang_path.file_name() {
3926 if let Some(filename_str) = filename.to_str() {
3927 if let Some(idx) = filename_str.rfind('-') {
3928 return filename_str.split_at(idx).0.contains("android");
3929 }
3930 }
3931 }
3932 false
3933}
3934
3935// FIXME: Use parsed target.
3936fn autodetect_android_compiler(raw_target: &str, gnu: &str, clang: &str) -> String {
3937 let new_clang_key = match raw_target {
3938 "aarch64-linux-android" => Some("aarch64"),
3939 "armv7-linux-androideabi" => Some("armv7a"),
3940 "i686-linux-android" => Some("i686"),
3941 "x86_64-linux-android" => Some("x86_64"),
3942 _ => None,
3943 };
3944
3945 let new_clang = new_clang_key
3946 .map(|key| {
3947 NEW_STANDALONE_ANDROID_COMPILERS
3948 .iter()
3949 .find(|x| x.starts_with(key))
3950 })
3951 .unwrap_or(None);
3952
3953 if let Some(new_clang) = new_clang {
3954 if Command::new(new_clang).output().is_ok() {
3955 return (*new_clang).into();
3956 }
3957 }
3958
3959 let target = raw_target
3960 .replace("armv7neon", "arm")
3961 .replace("armv7", "arm")
3962 .replace("thumbv7neon", "arm")
3963 .replace("thumbv7", "arm");
3964 let gnu_compiler = format!("{}-{}", target, gnu);
3965 let clang_compiler = format!("{}-{}", target, clang);
3966
3967 // On Windows, the Android clang compiler is provided as a `.cmd` file instead
3968 // of a `.exe` file. `std::process::Command` won't run `.cmd` files unless the
3969 // `.cmd` is explicitly appended to the command name, so we do that here.
3970 let clang_compiler_cmd = format!("{}-{}.cmd", target, clang);
3971
3972 // Check if gnu compiler is present
3973 // if not, use clang
3974 if Command::new(&gnu_compiler).output().is_ok() {
3975 gnu_compiler
3976 } else if cfg!(windows) && Command::new(&clang_compiler_cmd).output().is_ok() {
3977 clang_compiler_cmd
3978 } else {
3979 clang_compiler
3980 }
3981}
3982
3983// Rust and clang/cc don't agree on how to name the target.
3984fn map_darwin_target_from_rust_to_compiler_architecture<'a>(target: &TargetInfo<'a>) -> &'a str {
3985 match target.full_arch {
3986 "aarch64" => "arm64",
3987 "arm64_32" => "arm64_32",
3988 "arm64e" => "arm64e",
3989 "armv7k" => "armv7k",
3990 "armv7s" => "armv7s",
3991 "i386" => "i386",
3992 "i686" => "i386",
3993 "powerpc" => "ppc",
3994 "powerpc64" => "ppc64",
3995 "x86_64" => "x86_64",
3996 "x86_64h" => "x86_64h",
3997 arch => arch,
3998 }
3999}
4000
4001#[derive(Clone, Copy, PartialEq)]
4002enum AsmFileExt {
4003 /// `.asm` files. On MSVC targets, we assume these should be passed to MASM
4004 /// (`ml{,64}.exe`).
4005 DotAsm,
4006 /// `.s` or `.S` files, which do not have the special handling on MSVC targets.
4007 DotS,
4008}
4009
4010impl AsmFileExt {
4011 fn from_path(file: &Path) -> Option<Self> {
4012 if let Some(ext) = file.extension() {
4013 if let Some(ext) = ext.to_str() {
4014 let ext = ext.to_lowercase();
4015 match &*ext {
4016 "asm" => return Some(AsmFileExt::DotAsm),
4017 "s" => return Some(AsmFileExt::DotS),
4018 _ => return None,
4019 }
4020 }
4021 }
4022 None
4023 }
4024}
4025
4026#[cfg(test)]
4027mod tests {
4028 use super::*;
4029
4030 #[test]
4031 fn test_android_clang_compiler_uses_target_arg_internally() {
4032 for version in 16..21 {
4033 assert!(android_clang_compiler_uses_target_arg_internally(
4034 &PathBuf::from(format!("armv7a-linux-androideabi{}-clang", version))
4035 ));
4036 assert!(android_clang_compiler_uses_target_arg_internally(
4037 &PathBuf::from(format!("armv7a-linux-androideabi{}-clang++", version))
4038 ));
4039 }
4040 assert!(!android_clang_compiler_uses_target_arg_internally(
4041 &PathBuf::from("clang-i686-linux-android")
4042 ));
4043 assert!(!android_clang_compiler_uses_target_arg_internally(
4044 &PathBuf::from("clang")
4045 ));
4046 assert!(!android_clang_compiler_uses_target_arg_internally(
4047 &PathBuf::from("clang++")
4048 ));
4049 }
4050}