cc/
lib.rs

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