[go: up one dir, main page]

cc/
lib.rs

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