[go: up one dir, main page]

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