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