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.os != "vita"
2131 && target.arch != "wasm32"
2132 && target.arch != "wasm64",
2133 ) {
2134 cmd.push_cc_arg("-fPIC".into());
2135 // PLT only applies if code is compiled with PIC support,
2136 // and only for ELF targets.
2137 if (target.os == "linux" || target.os == "android")
2138 && !self.use_plt.unwrap_or(true)
2139 {
2140 cmd.push_cc_arg("-fno-plt".into());
2141 }
2142 }
2143 if target.arch == "wasm32" || target.arch == "wasm64" {
2144 // WASI does not support exceptions yet.
2145 // https://github.com/WebAssembly/exception-handling
2146 //
2147 // `rustc` also defaults to (currently) disable exceptions
2148 // on all WASM targets:
2149 // <https://github.com/rust-lang/rust/blob/1.82.0/compiler/rustc_target/src/spec/base/wasm.rs#L72-L77>
2150 cmd.push_cc_arg("-fno-exceptions".into());
2151 }
2152
2153 if target.os == "wasi" {
2154 // Link clang sysroot
2155 if let Ok(wasi_sysroot) = self.wasi_sysroot() {
2156 cmd.push_cc_arg(
2157 format!("--sysroot={}", Path::new(&wasi_sysroot).display()).into(),
2158 );
2159 }
2160
2161 // FIXME(madsmtm): Read from `target_features` instead?
2162 if raw_target.contains("threads") {
2163 cmd.push_cc_arg("-pthread".into());
2164 }
2165 }
2166
2167 if target.os == "nto" {
2168 // Select the target with `-V`, see qcc documentation:
2169 // QNX 7.1: https://www.qnx.com/developers/docs/7.1/index.html#com.qnx.doc.neutrino.utilities/topic/q/qcc.html
2170 // QNX 8.0: https://www.qnx.com/developers/docs/8.0/com.qnx.doc.neutrino.utilities/topic/q/qcc.html
2171 // This assumes qcc/q++ as compiler, which is currently the only supported compiler for QNX.
2172 // See for details: https://github.com/rust-lang/cc-rs/pull/1319
2173 let arg = match target.full_arch {
2174 "x86" | "i586" => "-Vgcc_ntox86_cxx",
2175 "aarch64" => "-Vgcc_ntoaarch64le_cxx",
2176 "x86_64" => "-Vgcc_ntox86_64_cxx",
2177 _ => {
2178 return Err(Error::new(
2179 ErrorKind::InvalidTarget,
2180 format!("Unknown architecture for Neutrino QNX: {}", target.arch),
2181 ))
2182 }
2183 };
2184 cmd.push_cc_arg(arg.into());
2185 }
2186 }
2187 }
2188
2189 if self.get_debug() {
2190 if self.cuda {
2191 // NVCC debug flag
2192 cmd.args.push("-G".into());
2193 }
2194 let family = cmd.family;
2195 family.add_debug_flags(
2196 cmd,
2197 self.get_debug_str().as_deref().unwrap_or_default(),
2198 self.get_dwarf_version(),
2199 );
2200 }
2201
2202 if self.get_force_frame_pointer() {
2203 let family = cmd.family;
2204 family.add_force_frame_pointer(cmd);
2205 }
2206
2207 if !cmd.is_like_msvc() {
2208 if target.arch == "x86" {
2209 cmd.args.push("-m32".into());
2210 } else if target.abi == "x32" {
2211 cmd.args.push("-mx32".into());
2212 } else if target.os == "aix" {
2213 if cmd.family == ToolFamily::Gnu {
2214 cmd.args.push("-maix64".into());
2215 } else {
2216 cmd.args.push("-m64".into());
2217 }
2218 } else if target.arch == "x86_64" || target.arch == "powerpc64" {
2219 cmd.args.push("-m64".into());
2220 }
2221 }
2222
2223 // Target flags
2224 match cmd.family {
2225 ToolFamily::Clang { .. } => {
2226 if !(cmd.has_internal_target_arg
2227 || (target.os == "android"
2228 && android_clang_compiler_uses_target_arg_internally(&cmd.path)))
2229 {
2230 if target.os == "freebsd" {
2231 // FreeBSD only supports C++11 and above when compiling against libc++
2232 // (available from FreeBSD 10 onwards). Under FreeBSD, clang uses libc++ by
2233 // default on FreeBSD 10 and newer unless `--target` is manually passed to
2234 // the compiler, in which case its default behavior differs:
2235 // * If --target=xxx-unknown-freebsdX(.Y) is specified and X is greater than
2236 // or equal to 10, clang++ uses libc++
2237 // * If --target=xxx-unknown-freebsd is specified (without a version),
2238 // clang++ cannot assume libc++ is available and reverts to a default of
2239 // libstdc++ (this behavior was changed in llvm 14).
2240 //
2241 // This breaks C++11 (or greater) builds if targeting FreeBSD with the
2242 // generic xxx-unknown-freebsd target on clang 13 or below *without*
2243 // explicitly specifying that libc++ should be used.
2244 // When cross-compiling, we can't infer from the rust/cargo target name
2245 // which major version of FreeBSD we are targeting, so we need to make sure
2246 // that libc++ is used (unless the user has explicitly specified otherwise).
2247 // There's no compelling reason to use a different approach when compiling
2248 // natively.
2249 if self.cpp && self.cpp_set_stdlib.is_none() {
2250 cmd.push_cc_arg("-stdlib=libc++".into());
2251 }
2252 } else if target.arch == "wasm32" && target.os == "linux" {
2253 for x in &[
2254 "atomics",
2255 "bulk-memory",
2256 "mutable-globals",
2257 "sign-ext",
2258 "exception-handling",
2259 ] {
2260 cmd.push_cc_arg(format!("-m{x}").into());
2261 }
2262 for x in &["wasm-exceptions", "declspec"] {
2263 cmd.push_cc_arg(format!("-f{x}").into());
2264 }
2265 let musl_sysroot = self.wasm_musl_sysroot().unwrap();
2266 cmd.push_cc_arg(
2267 format!("--sysroot={}", Path::new(&musl_sysroot).display()).into(),
2268 );
2269 cmd.push_cc_arg("-pthread".into());
2270 }
2271 // Pass `--target` with the LLVM target to configure Clang for cross-compiling.
2272 //
2273 // This is **required** for cross-compilation, as it's the only flag that
2274 // consistently forces Clang to change the "toolchain" that is responsible for
2275 // parsing target-specific flags:
2276 // https://github.com/rust-lang/cc-rs/issues/1388
2277 // https://github.com/llvm/llvm-project/blob/llvmorg-19.1.7/clang/lib/Driver/Driver.cpp#L1359-L1360
2278 // https://github.com/llvm/llvm-project/blob/llvmorg-19.1.7/clang/lib/Driver/Driver.cpp#L6347-L6532
2279 //
2280 // This can be confusing, because on e.g. host macOS, you can usually get by
2281 // with `-arch` and `-mtargetos=`. But that only works because the _default_
2282 // toolchain is `Darwin`, which enables parsing of darwin-specific options.
2283 //
2284 // NOTE: In the past, we passed the deployment version in here on all Apple
2285 // targets, but versioned targets were found to have poor compatibility with
2286 // older versions of Clang, especially when it comes to configuration files:
2287 // https://github.com/rust-lang/cc-rs/issues/1278
2288 //
2289 // So instead, we pass the deployment target with `-m*-version-min=`, and only
2290 // pass it here on visionOS and Mac Catalyst where that option does not exist:
2291 // https://github.com/rust-lang/cc-rs/issues/1383
2292 let version = if target.os == "visionos" || target.env == "macabi" {
2293 Some(self.apple_deployment_target(target))
2294 } else {
2295 None
2296 };
2297
2298 let clang_target =
2299 target.llvm_target(&self.get_raw_target()?, version.as_deref());
2300 cmd.push_cc_arg(format!("--target={clang_target}").into());
2301 }
2302 }
2303 ToolFamily::Msvc { clang_cl } => {
2304 // This is an undocumented flag from MSVC but helps with making
2305 // builds more reproducible by avoiding putting timestamps into
2306 // files.
2307 cmd.push_cc_arg("-Brepro".into());
2308
2309 if clang_cl {
2310 cmd.push_cc_arg(
2311 format!(
2312 "--target={}",
2313 target.llvm_target(&self.get_raw_target()?, None)
2314 )
2315 .into(),
2316 );
2317
2318 if target.arch == "x86" {
2319 // See
2320 // <https://learn.microsoft.com/en-us/cpp/build/reference/arch-x86?view=msvc-170>.
2321 //
2322 // NOTE: Rust officially supported Windows targets all require SSE2 as part
2323 // of baseline target features.
2324 //
2325 // NOTE: The same applies for STL. See: -
2326 // <https://github.com/microsoft/STL/issues/3922>, and -
2327 // <https://github.com/microsoft/STL/pull/4741>.
2328 cmd.push_cc_arg("-arch:SSE2".into());
2329 }
2330 } else if target.full_arch == "i586" {
2331 cmd.push_cc_arg("-arch:IA32".into());
2332 } else if target.full_arch == "arm64ec" {
2333 cmd.push_cc_arg("-arm64EC".into());
2334 }
2335 // There is a check in corecrt.h that will generate a
2336 // compilation error if
2337 // _ARM_WINAPI_PARTITION_DESKTOP_SDK_AVAILABLE is
2338 // not defined to 1. The check was added in Windows
2339 // 8 days because only store apps were allowed on ARM.
2340 // This changed with the release of Windows 10 IoT Core.
2341 // The check will be going away in future versions of
2342 // the SDK, but for all released versions of the
2343 // Windows SDK it is required.
2344 if target.arch == "arm" {
2345 cmd.args
2346 .push("-D_ARM_WINAPI_PARTITION_DESKTOP_SDK_AVAILABLE=1".into());
2347 }
2348 }
2349 ToolFamily::Gnu => {
2350 if target.vendor == "kmc" {
2351 cmd.args.push("-finput-charset=utf-8".into());
2352 }
2353
2354 if self.static_flag.is_none() {
2355 let features = self.getenv("CARGO_CFG_TARGET_FEATURE");
2356 let features = features.as_deref().unwrap_or_default();
2357 if features.to_string_lossy().contains("crt-static") {
2358 cmd.args.push("-static".into());
2359 }
2360 }
2361
2362 // armv7 targets get to use armv7 instructions
2363 if (target.full_arch.starts_with("armv7")
2364 || target.full_arch.starts_with("thumbv7"))
2365 && (target.os == "linux" || target.vendor == "kmc")
2366 {
2367 cmd.args.push("-march=armv7-a".into());
2368
2369 if target.abi == "eabihf" {
2370 // lowest common denominator FPU
2371 cmd.args.push("-mfpu=vfpv3-d16".into());
2372 cmd.args.push("-mfloat-abi=hard".into());
2373 }
2374 }
2375
2376 // (x86 Android doesn't say "eabi")
2377 if target.os == "android" && target.full_arch.contains("v7") {
2378 cmd.args.push("-march=armv7-a".into());
2379 cmd.args.push("-mthumb".into());
2380 if !target.full_arch.contains("neon") {
2381 // On android we can guarantee some extra float instructions
2382 // (specified in the android spec online)
2383 // NEON guarantees even more; see below.
2384 cmd.args.push("-mfpu=vfpv3-d16".into());
2385 }
2386 cmd.args.push("-mfloat-abi=softfp".into());
2387 }
2388
2389 if target.full_arch.contains("neon") {
2390 cmd.args.push("-mfpu=neon-vfpv4".into());
2391 }
2392
2393 if target.full_arch == "armv4t" && target.os == "linux" {
2394 cmd.args.push("-march=armv4t".into());
2395 cmd.args.push("-marm".into());
2396 cmd.args.push("-mfloat-abi=soft".into());
2397 }
2398
2399 if target.full_arch == "armv5te" && target.os == "linux" {
2400 cmd.args.push("-march=armv5te".into());
2401 cmd.args.push("-marm".into());
2402 cmd.args.push("-mfloat-abi=soft".into());
2403 }
2404
2405 // For us arm == armv6 by default
2406 if target.full_arch == "arm" && target.os == "linux" {
2407 cmd.args.push("-march=armv6".into());
2408 cmd.args.push("-marm".into());
2409 if target.abi == "eabihf" {
2410 cmd.args.push("-mfpu=vfp".into());
2411 } else {
2412 cmd.args.push("-mfloat-abi=soft".into());
2413 }
2414 }
2415
2416 // Turn codegen down on i586 to avoid some instructions.
2417 if target.full_arch == "i586" && target.os == "linux" {
2418 cmd.args.push("-march=pentium".into());
2419 }
2420
2421 // Set codegen level for i686 correctly
2422 if target.full_arch == "i686" && target.os == "linux" {
2423 cmd.args.push("-march=i686".into());
2424 }
2425
2426 // Looks like `musl-gcc` makes it hard for `-m32` to make its way
2427 // all the way to the linker, so we need to actually instruct the
2428 // linker that we're generating 32-bit executables as well. This'll
2429 // typically only be used for build scripts which transitively use
2430 // these flags that try to compile executables.
2431 if target.arch == "x86" && target.env == "musl" {
2432 cmd.args.push("-Wl,-melf_i386".into());
2433 }
2434
2435 if target.arch == "arm" && target.os == "none" && target.abi == "eabihf" {
2436 cmd.args.push("-mfloat-abi=hard".into())
2437 }
2438 if target.full_arch.starts_with("thumb") {
2439 cmd.args.push("-mthumb".into());
2440 }
2441 if target.full_arch.starts_with("thumbv6m") {
2442 cmd.args.push("-march=armv6s-m".into());
2443 }
2444 if target.full_arch.starts_with("thumbv7em") {
2445 cmd.args.push("-march=armv7e-m".into());
2446
2447 if target.abi == "eabihf" {
2448 cmd.args.push("-mfpu=fpv4-sp-d16".into())
2449 }
2450 }
2451 if target.full_arch.starts_with("thumbv7m") {
2452 cmd.args.push("-march=armv7-m".into());
2453 }
2454 if target.full_arch.starts_with("thumbv8m.base") {
2455 cmd.args.push("-march=armv8-m.base".into());
2456 }
2457 if target.full_arch.starts_with("thumbv8m.main") {
2458 cmd.args.push("-march=armv8-m.main".into());
2459
2460 if target.abi == "eabihf" {
2461 cmd.args.push("-mfpu=fpv5-sp-d16".into())
2462 }
2463 }
2464 if target.full_arch.starts_with("armebv7r") | target.full_arch.starts_with("armv7r")
2465 {
2466 if target.full_arch.starts_with("armeb") {
2467 cmd.args.push("-mbig-endian".into());
2468 } else {
2469 cmd.args.push("-mlittle-endian".into());
2470 }
2471
2472 // ARM mode
2473 cmd.args.push("-marm".into());
2474
2475 // R Profile
2476 cmd.args.push("-march=armv7-r".into());
2477
2478 if target.abi == "eabihf" {
2479 // lowest common denominator FPU
2480 // (see Cortex-R4 technical reference manual)
2481 cmd.args.push("-mfpu=vfpv3-d16".into())
2482 }
2483 }
2484 if target.full_arch.starts_with("armv7a") {
2485 cmd.args.push("-march=armv7-a".into());
2486
2487 if target.abi == "eabihf" {
2488 // lowest common denominator FPU
2489 cmd.args.push("-mfpu=vfpv3-d16".into());
2490 }
2491 }
2492 if target.arch == "riscv32" || target.arch == "riscv64" {
2493 // get the 32i/32imac/32imc/64gc/64imac/... part
2494 let arch = &target.full_arch[5..];
2495 if arch.starts_with("64") {
2496 if matches!(target.os, "linux" | "freebsd" | "netbsd") {
2497 cmd.args.push(("-march=rv64gc").into());
2498 cmd.args.push("-mabi=lp64d".into());
2499 } else {
2500 cmd.args.push(("-march=rv".to_owned() + arch).into());
2501 cmd.args.push("-mabi=lp64".into());
2502 }
2503 } else if arch.starts_with("32") {
2504 if target.os == "linux" {
2505 cmd.args.push(("-march=rv32gc").into());
2506 cmd.args.push("-mabi=ilp32d".into());
2507 } else {
2508 cmd.args.push(("-march=rv".to_owned() + arch).into());
2509 cmd.args.push("-mabi=ilp32".into());
2510 }
2511 } else {
2512 cmd.args.push("-mcmodel=medany".into());
2513 }
2514 }
2515 }
2516 }
2517
2518 if raw_target == "wasm32v1-none" {
2519 // `wasm32v1-none` target only exists in `rustc`, so we need to change the compilation flags:
2520 // https://doc.rust-lang.org/rustc/platform-support/wasm32v1-none.html
2521 cmd.push_cc_arg("-mcpu=mvp".into());
2522 cmd.push_cc_arg("-mmutable-globals".into());
2523 }
2524
2525 if target.os == "solaris" || target.os == "illumos" {
2526 // On Solaris and illumos, multi-threaded C programs must be built with `_REENTRANT`
2527 // defined. This configures headers to define APIs appropriately for multi-threaded
2528 // use. This is documented in threads(7), see also https://illumos.org/man/7/threads.
2529 //
2530 // If C code is compiled without multi-threading support but does use multiple threads,
2531 // incorrect behavior may result. One extreme example is that on some systems the
2532 // global errno may be at the same address as the process' first thread's errno; errno
2533 // clobbering may occur to disastrous effect. Conversely, if _REENTRANT is defined
2534 // while it is not actually needed, system headers may define some APIs suboptimally
2535 // but will not result in incorrect behavior. Other code *should* be reasonable under
2536 // such conditions.
2537 //
2538 // We're typically building C code to eventually link into a Rust program. Many Rust
2539 // programs are multi-threaded in some form. So, set the flag by default.
2540 cmd.args.push("-D_REENTRANT".into());
2541 }
2542
2543 if target.vendor == "apple" {
2544 self.apple_flags(cmd)?;
2545 }
2546
2547 if self.static_flag.unwrap_or(false) {
2548 cmd.args.push("-static".into());
2549 }
2550 if self.shared_flag.unwrap_or(false) {
2551 cmd.args.push("-shared".into());
2552 }
2553
2554 if self.cpp {
2555 match (self.cpp_set_stdlib.as_ref(), cmd.family) {
2556 (None, _) => {}
2557 (Some(stdlib), ToolFamily::Gnu) | (Some(stdlib), ToolFamily::Clang { .. }) => {
2558 cmd.push_cc_arg(format!("-stdlib=lib{stdlib}").into());
2559 }
2560 _ => {
2561 self.cargo_output.print_warning(&format_args!("cpp_set_stdlib is specified, but the {:?} compiler does not support this option, ignored", cmd.family));
2562 }
2563 }
2564 }
2565
2566 Ok(())
2567 }
2568
2569 fn add_inherited_rustflags(
2570 &self,
2571 cmd: &mut Tool,
2572 target: &TargetInfo<'_>,
2573 ) -> Result<(), Error> {
2574 let env_os = match self.getenv("CARGO_ENCODED_RUSTFLAGS") {
2575 Some(env) => env,
2576 // No encoded RUSTFLAGS -> nothing to do
2577 None => return Ok(()),
2578 };
2579
2580 let env = env_os.to_string_lossy();
2581 let codegen_flags = RustcCodegenFlags::parse(&env)?;
2582 codegen_flags.cc_flags(self, cmd, target);
2583 Ok(())
2584 }
2585
2586 fn msvc_macro_assembler(&self) -> Result<Command, Error> {
2587 let target = self.get_target()?;
2588 let tool = match target.arch {
2589 "x86_64" => "ml64.exe",
2590 "arm" => "armasm.exe",
2591 "aarch64" | "arm64ec" => "armasm64.exe",
2592 _ => "ml.exe",
2593 };
2594 let mut cmd = self
2595 .find_msvc_tools_find(&target, tool)
2596 .unwrap_or_else(|| self.cmd(tool));
2597 cmd.arg("-nologo"); // undocumented, yet working with armasm[64]
2598 for directory in self.include_directories.iter() {
2599 cmd.arg("-I").arg(&**directory);
2600 }
2601 if is_arm(&target) {
2602 if self.get_debug() {
2603 cmd.arg("-g");
2604 }
2605
2606 if target.arch == "arm64ec" {
2607 cmd.args(["-machine", "ARM64EC"]);
2608 }
2609
2610 for (key, value) in self.definitions.iter() {
2611 cmd.arg("-PreDefine");
2612 if let Some(ref value) = *value {
2613 if let Ok(i) = value.parse::<i32>() {
2614 cmd.arg(format!("{key} SETA {i}"));
2615 } else if value.starts_with('"') && value.ends_with('"') {
2616 cmd.arg(format!("{key} SETS {value}"));
2617 } else {
2618 cmd.arg(format!("{key} SETS \"{value}\""));
2619 }
2620 } else {
2621 cmd.arg(format!("{} SETL {}", key, "{TRUE}"));
2622 }
2623 }
2624 } else {
2625 if self.get_debug() {
2626 cmd.arg("-Zi");
2627 }
2628
2629 for (key, value) in self.definitions.iter() {
2630 if let Some(ref value) = *value {
2631 cmd.arg(format!("-D{key}={value}"));
2632 } else {
2633 cmd.arg(format!("-D{key}"));
2634 }
2635 }
2636 }
2637
2638 if target.arch == "x86" {
2639 cmd.arg("-safeseh");
2640 }
2641
2642 Ok(cmd)
2643 }
2644
2645 fn assemble(&self, lib_name: &str, dst: &Path, objs: &[Object]) -> Result<(), Error> {
2646 // Delete the destination if it exists as we want to
2647 // create on the first iteration instead of appending.
2648 let _ = fs::remove_file(dst);
2649
2650 // Add objects to the archive in limited-length batches. This helps keep
2651 // the length of the command line within a reasonable length to avoid
2652 // blowing system limits on limiting platforms like Windows.
2653 let objs: Vec<_> = objs
2654 .iter()
2655 .map(|o| o.dst.as_path())
2656 .chain(self.objects.iter().map(std::ops::Deref::deref))
2657 .collect();
2658 for chunk in objs.chunks(100) {
2659 self.assemble_progressive(dst, chunk)?;
2660 }
2661
2662 if self.cuda && self.cuda_file_count() > 0 {
2663 // Link the device-side code and add it to the target library,
2664 // so that non-CUDA linker can link the final binary.
2665
2666 let out_dir = self.get_out_dir()?;
2667 let dlink = out_dir.join(lib_name.to_owned() + "_dlink.o");
2668 let mut nvcc = self.get_compiler().to_command();
2669 nvcc.arg("--device-link").arg("-o").arg(&dlink).arg(dst);
2670 run(&mut nvcc, &self.cargo_output)?;
2671 self.assemble_progressive(dst, &[dlink.as_path()])?;
2672 }
2673
2674 let target = self.get_target()?;
2675 if target.env == "msvc" {
2676 // The Rust compiler will look for libfoo.a and foo.lib, but the
2677 // MSVC linker will also be passed foo.lib, so be sure that both
2678 // exist for now.
2679
2680 let lib_dst = dst.with_file_name(format!("{lib_name}.lib"));
2681 let _ = fs::remove_file(&lib_dst);
2682 match fs::hard_link(dst, &lib_dst).or_else(|_| {
2683 // if hard-link fails, just copy (ignoring the number of bytes written)
2684 fs::copy(dst, &lib_dst).map(|_| ())
2685 }) {
2686 Ok(_) => (),
2687 Err(_) => {
2688 return Err(Error::new(
2689 ErrorKind::IOError,
2690 "Could not copy or create a hard-link to the generated lib file.",
2691 ));
2692 }
2693 };
2694 } else {
2695 // Non-msvc targets (those using `ar`) need a separate step to add
2696 // the symbol table to archives since our construction command of
2697 // `cq` doesn't add it for us.
2698 let mut ar = self.try_get_archiver()?;
2699
2700 // NOTE: We add `s` even if flags were passed using $ARFLAGS/ar_flag, because `s`
2701 // here represents a _mode_, not an arbitrary flag. Further discussion of this choice
2702 // can be seen in https://github.com/rust-lang/cc-rs/pull/763.
2703 run(ar.arg("s").arg(dst), &self.cargo_output)?;
2704 }
2705
2706 Ok(())
2707 }
2708
2709 fn assemble_progressive(&self, dst: &Path, objs: &[&Path]) -> Result<(), Error> {
2710 let target = self.get_target()?;
2711
2712 let (mut cmd, program, any_flags) = self.try_get_archiver_and_flags()?;
2713 if target.env == "msvc" && !program.to_string_lossy().contains("llvm-ar") {
2714 // NOTE: -out: here is an I/O flag, and so must be included even if $ARFLAGS/ar_flag is
2715 // in use. -nologo on the other hand is just a regular flag, and one that we'll skip if
2716 // the caller has explicitly dictated the flags they want. See
2717 // https://github.com/rust-lang/cc-rs/pull/763 for further discussion.
2718 let mut out = OsString::from("-out:");
2719 out.push(dst);
2720 cmd.arg(out);
2721 if !any_flags {
2722 cmd.arg("-nologo");
2723 }
2724 // If the library file already exists, add the library name
2725 // as an argument to let lib.exe know we are appending the objs.
2726 if dst.exists() {
2727 cmd.arg(dst);
2728 }
2729 cmd.args(objs);
2730 run(&mut cmd, &self.cargo_output)?;
2731 } else {
2732 // Set an environment variable to tell the OSX archiver to ensure
2733 // that all dates listed in the archive are zero, improving
2734 // determinism of builds. AFAIK there's not really official
2735 // documentation of this but there's a lot of references to it if
2736 // you search google.
2737 //
2738 // You can reproduce this locally on a mac with:
2739 //
2740 // $ touch foo.c
2741 // $ cc -c foo.c -o foo.o
2742 //
2743 // # Notice that these two checksums are different
2744 // $ ar crus libfoo1.a foo.o && sleep 2 && ar crus libfoo2.a foo.o
2745 // $ md5sum libfoo*.a
2746 //
2747 // # Notice that these two checksums are the same
2748 // $ export ZERO_AR_DATE=1
2749 // $ ar crus libfoo1.a foo.o && sleep 2 && touch foo.o && ar crus libfoo2.a foo.o
2750 // $ md5sum libfoo*.a
2751 //
2752 // In any case if this doesn't end up getting read, it shouldn't
2753 // cause that many issues!
2754 cmd.env("ZERO_AR_DATE", "1");
2755
2756 // NOTE: We add cq here regardless of whether $ARFLAGS/ar_flag have been used because
2757 // it dictates the _mode_ ar runs in, which the setter of $ARFLAGS/ar_flag can't
2758 // dictate. See https://github.com/rust-lang/cc-rs/pull/763 for further discussion.
2759 run(cmd.arg("cq").arg(dst).args(objs), &self.cargo_output)?;
2760 }
2761
2762 Ok(())
2763 }
2764
2765 fn apple_flags(&self, cmd: &mut Tool) -> Result<(), Error> {
2766 let target = self.get_target()?;
2767
2768 // This is a Darwin/Apple-specific flag that works both on GCC and Clang, but it is only
2769 // necessary on GCC since we specify `-target` on Clang.
2770 // https://gcc.gnu.org/onlinedocs/gcc/Darwin-Options.html#:~:text=arch
2771 // https://clang.llvm.org/docs/CommandGuide/clang.html#cmdoption-arch
2772 if cmd.is_like_gnu() {
2773 let arch = map_darwin_target_from_rust_to_compiler_architecture(&target);
2774 cmd.args.push("-arch".into());
2775 cmd.args.push(arch.into());
2776 }
2777
2778 // Pass the deployment target via `-mmacosx-version-min=`, `-miphoneos-version-min=` and
2779 // similar. Also necessary on GCC, as it forces a compilation error if the compiler is not
2780 // configured for Darwin: https://gcc.gnu.org/onlinedocs/gcc/Darwin-Options.html
2781 //
2782 // On visionOS and Mac Catalyst, there is no -m*-version-min= flag:
2783 // https://github.com/llvm/llvm-project/issues/88271
2784 // And the workaround to use `-mtargetos=` cannot be used with the `--target` flag that we
2785 // otherwise specify. So we avoid emitting that, and put the version in `--target` instead.
2786 if cmd.is_like_gnu() || !(target.os == "visionos" || target.env == "macabi") {
2787 let min_version = self.apple_deployment_target(&target);
2788 cmd.args
2789 .push(target.apple_version_flag(&min_version).into());
2790 }
2791
2792 // AppleClang sometimes requires sysroot even on macOS
2793 if cmd.is_xctoolchain_clang() || target.os != "macos" {
2794 self.cargo_output.print_metadata(&format_args!(
2795 "Detecting {:?} SDK path for {}",
2796 target.os,
2797 target.apple_sdk_name(),
2798 ));
2799 let sdk_path = self.apple_sdk_root(&target)?;
2800
2801 cmd.args.push("-isysroot".into());
2802 cmd.args.push(OsStr::new(&sdk_path).to_owned());
2803 cmd.env
2804 .push(("SDKROOT".into(), OsStr::new(&sdk_path).to_owned()));
2805
2806 if target.env == "macabi" {
2807 // Mac Catalyst uses the macOS SDK, but to compile against and
2808 // link to iOS-specific frameworks, we should have the support
2809 // library stubs in the include and library search path.
2810 let ios_support = Path::new(&sdk_path).join("System/iOSSupport");
2811
2812 cmd.args.extend([
2813 // Header search path
2814 OsString::from("-isystem"),
2815 ios_support.join("usr/include").into(),
2816 // Framework header search path
2817 OsString::from("-iframework"),
2818 ios_support.join("System/Library/Frameworks").into(),
2819 // Library search path
2820 {
2821 let mut s = OsString::from("-L");
2822 s.push(ios_support.join("usr/lib"));
2823 s
2824 },
2825 // Framework linker search path
2826 {
2827 // Technically, we _could_ avoid emitting `-F`, as
2828 // `-iframework` implies it, but let's keep it in for
2829 // clarity.
2830 let mut s = OsString::from("-F");
2831 s.push(ios_support.join("System/Library/Frameworks"));
2832 s
2833 },
2834 ]);
2835 }
2836 }
2837
2838 Ok(())
2839 }
2840
2841 fn cmd<P: AsRef<OsStr>>(&self, prog: P) -> Command {
2842 let mut cmd = Command::new(prog);
2843 for (a, b) in self.env.iter() {
2844 cmd.env(a, b);
2845 }
2846 cmd
2847 }
2848
2849 fn prefer_clang(&self) -> bool {
2850 if let Some(env) = self.getenv("CARGO_ENCODED_RUSTFLAGS") {
2851 env.to_string_lossy().contains("linker-plugin-lto")
2852 } else {
2853 false
2854 }
2855 }
2856
2857 fn get_base_compiler(&self) -> Result<Tool, Error> {
2858 let out_dir = self.get_out_dir().ok();
2859 let out_dir = out_dir.as_deref();
2860
2861 if let Some(c) = &self.compiler {
2862 return Ok(Tool::new(
2863 (**c).to_owned(),
2864 &self.build_cache.cached_compiler_family,
2865 &self.cargo_output,
2866 out_dir,
2867 ));
2868 }
2869 let target = self.get_target()?;
2870 let raw_target = self.get_raw_target()?;
2871
2872 let msvc = if self.prefer_clang_cl_over_msvc {
2873 "clang-cl.exe"
2874 } else {
2875 "cl.exe"
2876 };
2877
2878 let (env, gnu, traditional, clang) = if self.cpp {
2879 ("CXX", "g++", "c++", "clang++")
2880 } else {
2881 ("CC", "gcc", "cc", "clang")
2882 };
2883
2884 let fallback = Cow::Borrowed(Path::new(traditional));
2885 let default = if cfg!(target_os = "solaris") || cfg!(target_os = "illumos") {
2886 // On historical Solaris systems, "cc" may have been Sun Studio, which
2887 // is not flag-compatible with "gcc". This history casts a long shadow,
2888 // and many modern illumos distributions today ship GCC as "gcc" without
2889 // also making it available as "cc".
2890 Cow::Borrowed(Path::new(gnu))
2891 } else if self.prefer_clang() {
2892 self.which(Path::new(clang), None)
2893 .map(Cow::Owned)
2894 .unwrap_or(fallback)
2895 } else {
2896 fallback
2897 };
2898
2899 let cl_exe = self.find_msvc_tools_find_tool(&target, msvc);
2900
2901 let tool_opt: Option<Tool> = self
2902 .env_tool(env)
2903 .map(|(tool, wrapper, args)| {
2904 // Chop off leading/trailing whitespace to work around
2905 // semi-buggy build scripts which are shared in
2906 // makefiles/configure scripts (where spaces are far more
2907 // lenient)
2908 let mut t = Tool::with_args(
2909 tool,
2910 args.clone(),
2911 &self.build_cache.cached_compiler_family,
2912 &self.cargo_output,
2913 out_dir,
2914 );
2915 if let Some(cc_wrapper) = wrapper {
2916 t.cc_wrapper_path = Some(Path::new(&cc_wrapper).to_owned());
2917 }
2918 for arg in args {
2919 t.cc_wrapper_args.push(arg.into());
2920 }
2921 t
2922 })
2923 .or_else(|| {
2924 if target.os == "emscripten" {
2925 let tool = if self.cpp { "em++" } else { "emcc" };
2926 // Windows uses bat file so we have to be a bit more specific
2927 if cfg!(windows) {
2928 let mut t = Tool::with_family(
2929 PathBuf::from("cmd"),
2930 ToolFamily::Clang { zig_cc: false },
2931 );
2932 t.args.push("/c".into());
2933 t.args.push(format!("{tool}.bat").into());
2934 Some(t)
2935 } else {
2936 Some(Tool::new(
2937 PathBuf::from(tool),
2938 &self.build_cache.cached_compiler_family,
2939 &self.cargo_output,
2940 out_dir,
2941 ))
2942 }
2943 } else {
2944 None
2945 }
2946 })
2947 .or_else(|| cl_exe.clone());
2948
2949 let tool = match tool_opt {
2950 Some(t) => t,
2951 None => {
2952 let compiler: PathBuf = if cfg!(windows) && target.os == "windows" {
2953 if target.env == "msvc" {
2954 msvc.into()
2955 } else {
2956 let cc = if target.abi == "llvm" { clang } else { gnu };
2957 format!("{cc}.exe").into()
2958 }
2959 } else if target.os == "ios"
2960 || target.os == "watchos"
2961 || target.os == "tvos"
2962 || target.os == "visionos"
2963 {
2964 clang.into()
2965 } else if target.os == "android" {
2966 autodetect_android_compiler(&raw_target, gnu, clang)
2967 } else if target.os == "cloudabi" {
2968 format!(
2969 "{}-{}-{}-{}",
2970 target.full_arch, target.vendor, target.os, traditional
2971 )
2972 .into()
2973 } else if target.os == "wasi" {
2974 self.autodetect_wasi_compiler(&raw_target, clang)
2975 } else if target.arch == "wasm32" || target.arch == "wasm64" {
2976 // Compiling WASM is not currently supported by GCC, so
2977 // let's default to Clang.
2978 clang.into()
2979 } else if target.os == "vxworks" {
2980 if self.cpp { "wr-c++" } else { "wr-cc" }.into()
2981 } else if target.arch == "arm" && target.vendor == "kmc" {
2982 format!("arm-kmc-eabi-{gnu}").into()
2983 } else if target.arch == "aarch64" && target.vendor == "kmc" {
2984 format!("aarch64-kmc-elf-{gnu}").into()
2985 } else if target.os == "nto" {
2986 // See for details: https://github.com/rust-lang/cc-rs/pull/1319
2987 if self.cpp { "q++" } else { "qcc" }.into()
2988 } else if self.get_is_cross_compile()? {
2989 let prefix = self.prefix_for_target(&raw_target);
2990 match prefix {
2991 Some(prefix) => {
2992 let cc = if target.abi == "llvm" { clang } else { gnu };
2993 format!("{prefix}-{cc}").into()
2994 }
2995 None => default.into(),
2996 }
2997 } else {
2998 default.into()
2999 };
3000
3001 let mut t = Tool::new(
3002 compiler,
3003 &self.build_cache.cached_compiler_family,
3004 &self.cargo_output,
3005 out_dir,
3006 );
3007 if let Some(cc_wrapper) = self.rustc_wrapper_fallback() {
3008 t.cc_wrapper_path = Some(Path::new(&cc_wrapper).to_owned());
3009 }
3010 t
3011 }
3012 };
3013
3014 let mut tool = if self.cuda {
3015 assert!(
3016 tool.args.is_empty(),
3017 "CUDA compilation currently assumes empty pre-existing args"
3018 );
3019 let nvcc = match self.getenv_with_target_prefixes("NVCC") {
3020 Err(_) => PathBuf::from("nvcc"),
3021 Ok(nvcc) => PathBuf::from(&*nvcc),
3022 };
3023 let mut nvcc_tool = Tool::with_features(
3024 nvcc,
3025 vec![],
3026 self.cuda,
3027 &self.build_cache.cached_compiler_family,
3028 &self.cargo_output,
3029 out_dir,
3030 );
3031 if self.ccbin {
3032 nvcc_tool
3033 .args
3034 .push(format!("-ccbin={}", tool.path.display()).into());
3035 }
3036 if let Some(cc_wrapper) = self.rustc_wrapper_fallback() {
3037 nvcc_tool.cc_wrapper_path = Some(Path::new(&cc_wrapper).to_owned());
3038 }
3039 nvcc_tool.family = tool.family;
3040 nvcc_tool
3041 } else {
3042 tool
3043 };
3044
3045 // New "standalone" C/C++ cross-compiler executables from recent Android NDK
3046 // are just shell scripts that call main clang binary (from Android NDK) with
3047 // proper `--target` argument.
3048 //
3049 // For example, armv7a-linux-androideabi16-clang passes
3050 // `--target=armv7a-linux-androideabi16` to clang.
3051 //
3052 // As the shell script calls the main clang binary, the command line limit length
3053 // on Windows is restricted to around 8k characters instead of around 32k characters.
3054 // To remove this limit, we call the main clang binary directly and construct the
3055 // `--target=` ourselves.
3056 if cfg!(windows) && android_clang_compiler_uses_target_arg_internally(&tool.path) {
3057 if let Some(path) = tool.path.file_name() {
3058 let file_name = path.to_str().unwrap().to_owned();
3059 let (target, clang) = file_name.split_at(file_name.rfind('-').unwrap());
3060
3061 tool.has_internal_target_arg = true;
3062 tool.path.set_file_name(clang.trim_start_matches('-'));
3063 tool.path.set_extension("exe");
3064 tool.args.push(format!("--target={target}").into());
3065
3066 // Additionally, shell scripts for target i686-linux-android versions 16 to 24
3067 // pass the `mstackrealign` option so we do that here as well.
3068 if target.contains("i686-linux-android") {
3069 let (_, version) = target.split_at(target.rfind('d').unwrap() + 1);
3070 if let Ok(version) = version.parse::<u32>() {
3071 if version > 15 && version < 25 {
3072 tool.args.push("-mstackrealign".into());
3073 }
3074 }
3075 }
3076 };
3077 }
3078
3079 // Under cross-compilation scenarios, llvm-mingw's clang executable is just a
3080 // wrapper script that calls the actual clang binary with a suitable `--target`
3081 // argument, much like the Android NDK case outlined above. Passing a target
3082 // argument ourselves in this case will result in an error, as they expect
3083 // targets like `x86_64-w64-mingw32`, and we can't always set such a target
3084 // string because it is specific to this MinGW cross-compilation toolchain.
3085 //
3086 // For example, the following command will always fail due to using an unsuitable
3087 // `--target` argument we'd otherwise pass:
3088 // $ /opt/llvm-mingw-20250613-ucrt-ubuntu-22.04-x86_64/bin/x86_64-w64-mingw32-clang --target=x86_64-pc-windows-gnu dummy.c
3089 //
3090 // Code reference:
3091 // https://github.com/mstorsjo/llvm-mingw/blob/a1f6413e5c21fd74b64137b56167f4fba500d1d8/wrappers/clang-target-wrapper.sh#L31
3092 if !cfg!(windows) && target.os == "windows" && is_llvm_mingw_wrapper(&tool.path) {
3093 tool.has_internal_target_arg = true;
3094 }
3095
3096 // If we found `cl.exe` in our environment, the tool we're returning is
3097 // an MSVC-like tool, *and* no env vars were set then set env vars for
3098 // the tool that we're returning.
3099 //
3100 // Env vars are needed for things like `link.exe` being put into PATH as
3101 // well as header include paths sometimes. These paths are automatically
3102 // included by default but if the `CC` or `CXX` env vars are set these
3103 // won't be used. This'll ensure that when the env vars are used to
3104 // configure for invocations like `clang-cl` we still get a "works out
3105 // of the box" experience.
3106 if let Some(cl_exe) = cl_exe {
3107 if tool.family == (ToolFamily::Msvc { clang_cl: true })
3108 && tool.env.is_empty()
3109 && target.env == "msvc"
3110 {
3111 for (k, v) in cl_exe.env.iter() {
3112 tool.env.push((k.to_owned(), v.to_owned()));
3113 }
3114 }
3115 }
3116
3117 if target.env == "msvc" && tool.family == ToolFamily::Gnu {
3118 self.cargo_output
3119 .print_warning(&"GNU compiler is not supported for this target");
3120 }
3121
3122 Ok(tool)
3123 }
3124
3125 /// Returns a fallback `cc_compiler_wrapper` by introspecting `RUSTC_WRAPPER`
3126 fn rustc_wrapper_fallback(&self) -> Option<Arc<OsStr>> {
3127 // No explicit CC wrapper was detected, but check if RUSTC_WRAPPER
3128 // is defined and is a build accelerator that is compatible with
3129 // C/C++ compilers (e.g. sccache)
3130 const VALID_WRAPPERS: &[&str] = &["sccache", "cachepot", "buildcache"];
3131
3132 let rustc_wrapper = self.getenv("RUSTC_WRAPPER")?;
3133 let wrapper_path = Path::new(&rustc_wrapper);
3134 let wrapper_stem = wrapper_path.file_stem()?;
3135
3136 if VALID_WRAPPERS.contains(&wrapper_stem.to_str()?) {
3137 Some(rustc_wrapper)
3138 } else {
3139 None
3140 }
3141 }
3142
3143 /// Returns compiler path, optional modifier name from whitelist, and arguments vec
3144 fn env_tool(&self, name: &str) -> Option<(PathBuf, Option<Arc<OsStr>>, Vec<String>)> {
3145 let tool = self.getenv_with_target_prefixes(name).ok()?;
3146 let tool = tool.to_string_lossy();
3147 let tool = tool.trim();
3148
3149 if tool.is_empty() {
3150 return None;
3151 }
3152
3153 // If this is an exact path on the filesystem we don't want to do any
3154 // interpretation at all, just pass it on through. This'll hopefully get
3155 // us to support spaces-in-paths.
3156 if let Some(exe) = check_exe(Path::new(tool).into()) {
3157 return Some((exe, self.rustc_wrapper_fallback(), Vec::new()));
3158 }
3159
3160 // Ok now we want to handle a couple of scenarios. We'll assume from
3161 // here on out that spaces are splitting separate arguments. Two major
3162 // features we want to support are:
3163 //
3164 // CC='sccache cc'
3165 //
3166 // aka using `sccache` or any other wrapper/caching-like-thing for
3167 // compilations. We want to know what the actual compiler is still,
3168 // though, because our `Tool` API support introspection of it to see
3169 // what compiler is in use.
3170 //
3171 // additionally we want to support
3172 //
3173 // CC='cc -flag'
3174 //
3175 // where the CC env var is used to also pass default flags to the C
3176 // compiler.
3177 //
3178 // It's true that everything here is a bit of a pain, but apparently if
3179 // you're not literally make or bash then you get a lot of bug reports.
3180 let mut known_wrappers = vec![
3181 "ccache",
3182 "distcc",
3183 "sccache",
3184 "icecc",
3185 "cachepot",
3186 "buildcache",
3187 ];
3188 let custom_wrapper = self.getenv("CC_KNOWN_WRAPPER_CUSTOM");
3189 if custom_wrapper.is_some() {
3190 known_wrappers.push(custom_wrapper.as_deref().unwrap().to_str().unwrap());
3191 }
3192
3193 let mut parts = tool.split_whitespace();
3194 let maybe_wrapper = parts.next()?;
3195
3196 let file_stem = Path::new(maybe_wrapper).file_stem()?.to_str()?;
3197 if known_wrappers.contains(&file_stem) {
3198 if let Some(compiler) = parts.next() {
3199 return Some((
3200 compiler.into(),
3201 Some(Arc::<OsStr>::from(OsStr::new(&maybe_wrapper))),
3202 parts.map(|s| s.to_string()).collect(),
3203 ));
3204 }
3205 }
3206
3207 Some((
3208 maybe_wrapper.into(),
3209 self.rustc_wrapper_fallback(),
3210 parts.map(|s| s.to_string()).collect(),
3211 ))
3212 }
3213
3214 /// Returns the C++ standard library:
3215 /// 1. If [`cpp_link_stdlib`](cc::Build::cpp_link_stdlib) is set, uses its value.
3216 /// 2. Else if the `CXXSTDLIB` environment variable is set, uses its value.
3217 /// 3. Else the default is `c++` for OS X and BSDs, `c++_shared` for Android,
3218 /// `None` for MSVC and `stdc++` for anything else.
3219 fn get_cpp_link_stdlib(&self) -> Result<Option<Cow<'_, Path>>, Error> {
3220 match &self.cpp_link_stdlib {
3221 Some(s) => Ok(s.as_deref().map(Path::new).map(Cow::Borrowed)),
3222 None => {
3223 if let Ok(stdlib) = self.getenv_with_target_prefixes("CXXSTDLIB") {
3224 if stdlib.is_empty() {
3225 Ok(None)
3226 } else {
3227 Ok(Some(Cow::Owned(Path::new(&stdlib).to_owned())))
3228 }
3229 } else {
3230 let target = self.get_target()?;
3231 if target.env == "msvc" {
3232 Ok(None)
3233 } else if target.vendor == "apple"
3234 || target.os == "freebsd"
3235 || target.os == "openbsd"
3236 || target.os == "aix"
3237 || (target.os == "linux" && target.env == "ohos")
3238 || target.os == "wasi"
3239 {
3240 Ok(Some(Cow::Borrowed(Path::new("c++"))))
3241 } else if target.os == "android" {
3242 Ok(Some(Cow::Borrowed(Path::new("c++_shared"))))
3243 } else {
3244 Ok(Some(Cow::Borrowed(Path::new("stdc++"))))
3245 }
3246 }
3247 }
3248 }
3249 }
3250
3251 /// Get the archiver (ar) that's in use for this configuration.
3252 ///
3253 /// You can use [`Command::get_program`] to get just the path to the command.
3254 ///
3255 /// This method will take into account all configuration such as debug
3256 /// information, optimization level, include directories, defines, etc.
3257 /// Additionally, the compiler binary in use follows the standard
3258 /// conventions for this path, e.g. looking at the explicitly set compiler,
3259 /// environment variables (a number of which are inspected here), and then
3260 /// falling back to the default configuration.
3261 ///
3262 /// # Panics
3263 ///
3264 /// Panics if an error occurred while determining the architecture.
3265 pub fn get_archiver(&self) -> Command {
3266 match self.try_get_archiver() {
3267 Ok(tool) => tool,
3268 Err(e) => fail(&e.message),
3269 }
3270 }
3271
3272 /// Get the archiver that's in use for this configuration.
3273 ///
3274 /// This will return a result instead of panicking;
3275 /// see [`Self::get_archiver`] for the complete description.
3276 pub fn try_get_archiver(&self) -> Result<Command, Error> {
3277 Ok(self.try_get_archiver_and_flags()?.0)
3278 }
3279
3280 fn try_get_archiver_and_flags(&self) -> Result<(Command, PathBuf, bool), Error> {
3281 let (mut cmd, name) = self.get_base_archiver()?;
3282 let mut any_flags = false;
3283 if let Some(flags) = self.envflags("ARFLAGS")? {
3284 any_flags = true;
3285 cmd.args(flags);
3286 }
3287 for flag in &self.ar_flags {
3288 any_flags = true;
3289 cmd.arg(&**flag);
3290 }
3291 Ok((cmd, name, any_flags))
3292 }
3293
3294 fn get_base_archiver(&self) -> Result<(Command, PathBuf), Error> {
3295 if let Some(ref a) = self.archiver {
3296 let archiver = &**a;
3297 return Ok((self.cmd(archiver), archiver.into()));
3298 }
3299
3300 self.get_base_archiver_variant("AR", "ar")
3301 }
3302
3303 /// Get the ranlib that's in use for this configuration.
3304 ///
3305 /// You can use [`Command::get_program`] to get just the path to the command.
3306 ///
3307 /// This method will take into account all configuration such as debug
3308 /// information, optimization level, include directories, defines, etc.
3309 /// Additionally, the compiler binary in use follows the standard
3310 /// conventions for this path, e.g. looking at the explicitly set compiler,
3311 /// environment variables (a number of which are inspected here), and then
3312 /// falling back to the default configuration.
3313 ///
3314 /// # Panics
3315 ///
3316 /// Panics if an error occurred while determining the architecture.
3317 pub fn get_ranlib(&self) -> Command {
3318 match self.try_get_ranlib() {
3319 Ok(tool) => tool,
3320 Err(e) => fail(&e.message),
3321 }
3322 }
3323
3324 /// Get the ranlib that's in use for this configuration.
3325 ///
3326 /// This will return a result instead of panicking;
3327 /// see [`Self::get_ranlib`] for the complete description.
3328 pub fn try_get_ranlib(&self) -> Result<Command, Error> {
3329 let mut cmd = self.get_base_ranlib()?;
3330 if let Some(flags) = self.envflags("RANLIBFLAGS")? {
3331 cmd.args(flags);
3332 }
3333 Ok(cmd)
3334 }
3335
3336 fn get_base_ranlib(&self) -> Result<Command, Error> {
3337 if let Some(ref r) = self.ranlib {
3338 return Ok(self.cmd(&**r));
3339 }
3340
3341 Ok(self.get_base_archiver_variant("RANLIB", "ranlib")?.0)
3342 }
3343
3344 fn get_base_archiver_variant(
3345 &self,
3346 env: &str,
3347 tool: &str,
3348 ) -> Result<(Command, PathBuf), Error> {
3349 let target = self.get_target()?;
3350 let mut name = PathBuf::new();
3351 let tool_opt: Option<Command> = self
3352 .env_tool(env)
3353 .map(|(tool, _wrapper, args)| {
3354 name.clone_from(&tool);
3355 let mut cmd = self.cmd(tool);
3356 cmd.args(args);
3357 cmd
3358 })
3359 .or_else(|| {
3360 if target.os == "emscripten" {
3361 // Windows use bat files so we have to be a bit more specific
3362 if cfg!(windows) {
3363 let mut cmd = self.cmd("cmd");
3364 name = format!("em{tool}.bat").into();
3365 cmd.arg("/c").arg(&name);
3366 Some(cmd)
3367 } else {
3368 name = format!("em{tool}").into();
3369 Some(self.cmd(&name))
3370 }
3371 } else if target.arch == "wasm32" || target.arch == "wasm64" {
3372 // Formally speaking one should be able to use this approach,
3373 // parsing -print-search-dirs output, to cover all clang targets,
3374 // including Android SDKs and other cross-compilation scenarios...
3375 // And even extend it to gcc targets by searching for "ar" instead
3376 // of "llvm-ar"...
3377 let compiler = self.get_base_compiler().ok()?;
3378 if compiler.is_like_clang() {
3379 name = format!("llvm-{tool}").into();
3380 self.search_programs(&compiler.path, &name, &self.cargo_output)
3381 .map(|name| self.cmd(name))
3382 } else {
3383 None
3384 }
3385 } else {
3386 None
3387 }
3388 });
3389
3390 let tool = match tool_opt {
3391 Some(t) => t,
3392 None => {
3393 if target.os == "android" {
3394 name = format!("llvm-{tool}").into();
3395 match Command::new(&name).arg("--version").status() {
3396 Ok(status) if status.success() => (),
3397 _ => {
3398 // FIXME: Use parsed target.
3399 let raw_target = self.get_raw_target()?;
3400 name = format!("{}-{}", raw_target.replace("armv7", "arm"), tool).into()
3401 }
3402 }
3403 self.cmd(&name)
3404 } else if target.env == "msvc" {
3405 // NOTE: There isn't really a ranlib on msvc, so arguably we should return
3406 // `None` somehow here. But in general, callers will already have to be aware
3407 // of not running ranlib on Windows anyway, so it feels okay to return lib.exe
3408 // here.
3409
3410 let compiler = self.get_base_compiler()?;
3411 let lib = if compiler.family == (ToolFamily::Msvc { clang_cl: true }) {
3412 self.search_programs(
3413 &compiler.path,
3414 Path::new("llvm-lib"),
3415 &self.cargo_output,
3416 )
3417 .or_else(|| {
3418 // See if there is 'llvm-lib' next to 'clang-cl'
3419 if let Some(mut cmd) = self.which(&compiler.path, None) {
3420 cmd.pop();
3421 cmd.push("llvm-lib");
3422 self.which(&cmd, None)
3423 } else {
3424 None
3425 }
3426 })
3427 } else {
3428 None
3429 };
3430
3431 if let Some(lib) = lib {
3432 name = lib;
3433 self.cmd(&name)
3434 } else {
3435 name = PathBuf::from("lib.exe");
3436 let mut cmd = match self.find_msvc_tools_find(&target, "lib.exe") {
3437 Some(t) => t,
3438 None => self.cmd("lib.exe"),
3439 };
3440 if target.full_arch == "arm64ec" {
3441 cmd.arg("/machine:arm64ec");
3442 }
3443 cmd
3444 }
3445 } else if target.os == "illumos" {
3446 // The default 'ar' on illumos uses a non-standard flags,
3447 // but the OS comes bundled with a GNU-compatible variant.
3448 //
3449 // Use the GNU-variant to match other Unix systems.
3450 name = format!("g{tool}").into();
3451 self.cmd(&name)
3452 } else if target.os == "vxworks" {
3453 name = format!("wr-{tool}").into();
3454 self.cmd(&name)
3455 } else if target.os == "nto" {
3456 // Ref: https://www.qnx.com/developers/docs/8.0/com.qnx.doc.neutrino.utilities/topic/a/ar.html
3457 name = match target.full_arch {
3458 "i586" => format!("ntox86-{tool}").into(),
3459 "x86" | "aarch64" | "x86_64" => {
3460 format!("nto{}-{}", target.arch, tool).into()
3461 }
3462 _ => {
3463 return Err(Error::new(
3464 ErrorKind::InvalidTarget,
3465 format!("Unknown architecture for Neutrino QNX: {}", target.arch),
3466 ))
3467 }
3468 };
3469 self.cmd(&name)
3470 } else if self.get_is_cross_compile()? {
3471 match self.prefix_for_target(&self.get_raw_target()?) {
3472 Some(prefix) => {
3473 // GCC uses $target-gcc-ar, whereas binutils uses $target-ar -- try both.
3474 // Prefer -ar if it exists, as builds of `-gcc-ar` have been observed to be
3475 // outright broken (such as when targeting freebsd with `--disable-lto`
3476 // toolchain where the archiver attempts to load the LTO plugin anyway but
3477 // fails to find one).
3478 //
3479 // The same applies to ranlib.
3480 let chosen = ["", "-gcc"]
3481 .iter()
3482 .filter_map(|infix| {
3483 let target_p = format!("{prefix}{infix}-{tool}");
3484 let status = Command::new(&target_p)
3485 .arg("--version")
3486 .stdin(Stdio::null())
3487 .stdout(Stdio::null())
3488 .stderr(Stdio::null())
3489 .status()
3490 .ok()?;
3491 status.success().then_some(target_p)
3492 })
3493 .next()
3494 .unwrap_or_else(|| tool.to_string());
3495 name = chosen.into();
3496 self.cmd(&name)
3497 }
3498 None => {
3499 name = tool.into();
3500 self.cmd(&name)
3501 }
3502 }
3503 } else {
3504 name = tool.into();
3505 self.cmd(&name)
3506 }
3507 }
3508 };
3509
3510 Ok((tool, name))
3511 }
3512
3513 // FIXME: Use parsed target instead of raw target.
3514 fn prefix_for_target(&self, target: &str) -> Option<Cow<'static, str>> {
3515 // CROSS_COMPILE is of the form: "arm-linux-gnueabi-"
3516 self.getenv("CROSS_COMPILE")
3517 .as_deref()
3518 .map(|s| s.to_string_lossy().trim_end_matches('-').to_owned())
3519 .map(Cow::Owned)
3520 .or_else(|| {
3521 // Put aside RUSTC_LINKER's prefix to be used as second choice, after CROSS_COMPILE
3522 self.getenv("RUSTC_LINKER").and_then(|var| {
3523 var.to_string_lossy()
3524 .strip_suffix("-gcc")
3525 .map(str::to_string)
3526 .map(Cow::Owned)
3527 })
3528 })
3529 .or_else(|| {
3530 match target {
3531 // Note: there is no `aarch64-pc-windows-gnu` target, only `-gnullvm`
3532 "aarch64-pc-windows-gnullvm" => Some("aarch64-w64-mingw32"),
3533 "aarch64-uwp-windows-gnu" => Some("aarch64-w64-mingw32"),
3534 "aarch64-unknown-helenos" => Some("aarch64-helenos"),
3535 "aarch64-unknown-linux-gnu" => Some("aarch64-linux-gnu"),
3536 "aarch64-unknown-linux-musl" => Some("aarch64-linux-musl"),
3537 "aarch64-unknown-netbsd" => Some("aarch64--netbsd"),
3538 "arm-unknown-linux-gnueabi" => Some("arm-linux-gnueabi"),
3539 "armv4t-unknown-linux-gnueabi" => Some("arm-linux-gnueabi"),
3540 "armv5te-unknown-helenos-eabi" => Some("arm-helenos"),
3541 "armv5te-unknown-linux-gnueabi" => Some("arm-linux-gnueabi"),
3542 "armv5te-unknown-linux-musleabi" => Some("arm-linux-gnueabi"),
3543 "arm-unknown-linux-gnueabihf" => Some("arm-linux-gnueabihf"),
3544 "arm-unknown-linux-musleabi" => Some("arm-linux-musleabi"),
3545 "arm-unknown-linux-musleabihf" => Some("arm-linux-musleabihf"),
3546 "arm-unknown-netbsd-eabi" => Some("arm--netbsdelf-eabi"),
3547 "armv6-unknown-netbsd-eabihf" => Some("armv6--netbsdelf-eabihf"),
3548 "armv7-unknown-linux-gnueabi" => Some("arm-linux-gnueabi"),
3549 "armv7-unknown-linux-gnueabihf" => Some("arm-linux-gnueabihf"),
3550 "armv7-unknown-linux-musleabihf" => Some("arm-linux-musleabihf"),
3551 "armv7neon-unknown-linux-gnueabihf" => Some("arm-linux-gnueabihf"),
3552 "armv7neon-unknown-linux-musleabihf" => Some("arm-linux-musleabihf"),
3553 "thumbv7-unknown-linux-gnueabihf" => Some("arm-linux-gnueabihf"),
3554 "thumbv7-unknown-linux-musleabihf" => Some("arm-linux-musleabihf"),
3555 "thumbv7neon-unknown-linux-gnueabihf" => Some("arm-linux-gnueabihf"),
3556 "thumbv7neon-unknown-linux-musleabihf" => Some("arm-linux-musleabihf"),
3557 "armv7-unknown-netbsd-eabihf" => Some("armv7--netbsdelf-eabihf"),
3558 "hexagon-unknown-linux-musl" => Some("hexagon-linux-musl"),
3559 "i586-unknown-linux-musl" => Some("musl"),
3560 "i686-pc-windows-gnu" => Some("i686-w64-mingw32"),
3561 "i686-pc-windows-gnullvm" => Some("i686-w64-mingw32"),
3562 "i686-uwp-windows-gnu" => Some("i686-w64-mingw32"),
3563 "i686-unknown-helenos" => Some("i686-helenos"),
3564 "i686-unknown-linux-gnu" => self.find_working_gnu_prefix(&[
3565 "i686-linux-gnu",
3566 "x86_64-linux-gnu", // transparently support gcc-multilib
3567 ]), // explicit None if not found, so caller knows to fall back
3568 "i686-unknown-linux-musl" => Some("musl"),
3569 "i686-unknown-netbsd" => Some("i486--netbsdelf"),
3570 "loongarch64-unknown-linux-gnu" => Some("loongarch64-linux-gnu"),
3571 "m68k-unknown-linux-gnu" => Some("m68k-linux-gnu"),
3572 "mips-unknown-linux-gnu" => Some("mips-linux-gnu"),
3573 "mips-unknown-linux-musl" => Some("mips-linux-musl"),
3574 "mipsel-unknown-linux-gnu" => Some("mipsel-linux-gnu"),
3575 "mipsel-unknown-linux-musl" => Some("mipsel-linux-musl"),
3576 "mips64-unknown-linux-gnuabi64" => Some("mips64-linux-gnuabi64"),
3577 "mips64el-unknown-linux-gnuabi64" => Some("mips64el-linux-gnuabi64"),
3578 "mipsisa32r6-unknown-linux-gnu" => Some("mipsisa32r6-linux-gnu"),
3579 "mipsisa32r6el-unknown-linux-gnu" => Some("mipsisa32r6el-linux-gnu"),
3580 "mipsisa64r6-unknown-linux-gnuabi64" => Some("mipsisa64r6-linux-gnuabi64"),
3581 "mipsisa64r6el-unknown-linux-gnuabi64" => Some("mipsisa64r6el-linux-gnuabi64"),
3582 "powerpc-unknown-helenos" => Some("ppc-helenos"),
3583 "powerpc-unknown-linux-gnu" => Some("powerpc-linux-gnu"),
3584 "powerpc-unknown-linux-gnuspe" => Some("powerpc-linux-gnuspe"),
3585 "powerpc-unknown-netbsd" => Some("powerpc--netbsd"),
3586 "powerpc64-unknown-linux-gnu" => Some("powerpc64-linux-gnu"),
3587 "powerpc64le-unknown-linux-gnu" => Some("powerpc64le-linux-gnu"),
3588 "riscv32i-unknown-none-elf" => self.find_working_gnu_prefix(&[
3589 "riscv32-unknown-elf",
3590 "riscv64-unknown-elf",
3591 "riscv-none-embed",
3592 ]),
3593 "riscv32im-unknown-none-elf" => self.find_working_gnu_prefix(&[
3594 "riscv32-unknown-elf",
3595 "riscv64-unknown-elf",
3596 "riscv-none-embed",
3597 ]),
3598 "riscv32imac-esp-espidf" => Some("riscv32-esp-elf"),
3599 "riscv32imac-unknown-none-elf" => self.find_working_gnu_prefix(&[
3600 "riscv32-unknown-elf",
3601 "riscv64-unknown-elf",
3602 "riscv-none-embed",
3603 ]),
3604 "riscv32imafc-unknown-none-elf" => self.find_working_gnu_prefix(&[
3605 "riscv32-unknown-elf",
3606 "riscv64-unknown-elf",
3607 "riscv-none-embed",
3608 ]),
3609 "riscv32imac-unknown-xous-elf" => self.find_working_gnu_prefix(&[
3610 "riscv32-unknown-elf",
3611 "riscv64-unknown-elf",
3612 "riscv-none-embed",
3613 ]),
3614 "riscv32imc-esp-espidf" => Some("riscv32-esp-elf"),
3615 "riscv32imc-unknown-none-elf" => self.find_working_gnu_prefix(&[
3616 "riscv32-unknown-elf",
3617 "riscv64-unknown-elf",
3618 "riscv-none-embed",
3619 ]),
3620 "riscv64gc-unknown-none-elf" => self.find_working_gnu_prefix(&[
3621 "riscv64-unknown-elf",
3622 "riscv32-unknown-elf",
3623 "riscv-none-embed",
3624 ]),
3625 "riscv64imac-unknown-none-elf" => self.find_working_gnu_prefix(&[
3626 "riscv64-unknown-elf",
3627 "riscv32-unknown-elf",
3628 "riscv-none-embed",
3629 ]),
3630 "riscv64gc-unknown-linux-gnu" => Some("riscv64-linux-gnu"),
3631 "riscv64a23-unknown-linux-gnu" => Some("riscv64-linux-gnu"),
3632 "riscv32gc-unknown-linux-gnu" => Some("riscv32-linux-gnu"),
3633 "riscv64gc-unknown-linux-musl" => Some("riscv64-linux-musl"),
3634 "riscv32gc-unknown-linux-musl" => Some("riscv32-linux-musl"),
3635 "riscv64gc-unknown-netbsd" => Some("riscv64--netbsd"),
3636 "s390x-unknown-linux-gnu" => Some("s390x-linux-gnu"),
3637 "sparc-unknown-linux-gnu" => Some("sparc-linux-gnu"),
3638 "sparc64-unknown-helenos" => Some("sparc64-helenos"),
3639 "sparc64-unknown-linux-gnu" => Some("sparc64-linux-gnu"),
3640 "sparc64-unknown-netbsd" => Some("sparc64--netbsd"),
3641 "sparcv9-sun-solaris" => Some("sparcv9-sun-solaris"),
3642 "armv7a-none-eabi" => Some("arm-none-eabi"),
3643 "armv7a-none-eabihf" => Some("arm-none-eabi"),
3644 "armebv7r-none-eabi" => Some("arm-none-eabi"),
3645 "armebv7r-none-eabihf" => Some("arm-none-eabi"),
3646 "armv7r-none-eabi" => Some("arm-none-eabi"),
3647 "armv7r-none-eabihf" => Some("arm-none-eabi"),
3648 "armv8r-none-eabihf" => Some("arm-none-eabi"),
3649 "thumbv6m-none-eabi" => Some("arm-none-eabi"),
3650 "thumbv7em-none-eabi" => Some("arm-none-eabi"),
3651 "thumbv7em-none-eabihf" => Some("arm-none-eabi"),
3652 "thumbv7m-none-eabi" => Some("arm-none-eabi"),
3653 "thumbv8m.base-none-eabi" => Some("arm-none-eabi"),
3654 "thumbv8m.main-none-eabi" => Some("arm-none-eabi"),
3655 "thumbv8m.main-none-eabihf" => Some("arm-none-eabi"),
3656 "x86_64-pc-windows-gnu" => Some("x86_64-w64-mingw32"),
3657 "x86_64-pc-windows-gnullvm" => Some("x86_64-w64-mingw32"),
3658 "x86_64-uwp-windows-gnu" => Some("x86_64-w64-mingw32"),
3659 "x86_64-rumprun-netbsd" => Some("x86_64-rumprun-netbsd"),
3660 "x86_64-unknown-helenos" => Some("amd64-helenos"),
3661 "x86_64-unknown-linux-gnu" => self.find_working_gnu_prefix(&[
3662 "x86_64-linux-gnu", // rustfmt wrap
3663 ]), // explicit None if not found, so caller knows to fall back
3664 "x86_64-unknown-linux-musl" => {
3665 self.find_working_gnu_prefix(&["x86_64-linux-musl", "musl"])
3666 }
3667 "x86_64-unknown-netbsd" => Some("x86_64--netbsd"),
3668 "xtensa-esp32-espidf"
3669 | "xtensa-esp32-none-elf"
3670 | "xtensa-esp32s2-espidf"
3671 | "xtensa-esp32s2-none-elf"
3672 | "xtensa-esp32s3-espidf"
3673 | "xtensa-esp32s3-none-elf" => Some("xtensa-esp-elf"),
3674 _ => None,
3675 }
3676 .map(Cow::Borrowed)
3677 })
3678 }
3679
3680 /// Some platforms have multiple, compatible, canonical prefixes. Look through
3681 /// each possible prefix for a compiler that exists and return it. The prefixes
3682 /// should be ordered from most-likely to least-likely.
3683 fn find_working_gnu_prefix(&self, prefixes: &[&'static str]) -> Option<&'static str> {
3684 let suffix = if self.cpp { "-g++" } else { "-gcc" };
3685 let extension = std::env::consts::EXE_SUFFIX;
3686
3687 // Loop through PATH entries searching for each toolchain. This ensures that we
3688 // are more likely to discover the toolchain early on, because chances are good
3689 // that the desired toolchain is in one of the higher-priority paths.
3690 self.getenv("PATH")
3691 .as_ref()
3692 .and_then(|path_entries| {
3693 env::split_paths(path_entries).find_map(|path_entry| {
3694 for prefix in prefixes {
3695 let target_compiler = format!("{prefix}{suffix}{extension}");
3696 if path_entry.join(&target_compiler).exists() {
3697 return Some(prefix);
3698 }
3699 }
3700 None
3701 })
3702 })
3703 .copied()
3704 // If no toolchain was found, provide the first toolchain that was passed in.
3705 // This toolchain has been shown not to exist, however it will appear in the
3706 // error that is shown to the user which should make it easier to search for
3707 // where it should be obtained.
3708 .or_else(|| prefixes.first().copied())
3709 }
3710
3711 fn get_target(&self) -> Result<TargetInfo<'_>, Error> {
3712 match &self.target {
3713 Some(t) if Some(&**t) != self.getenv_unwrap_str("TARGET").ok().as_deref() => {
3714 TargetInfo::from_rustc_target(t)
3715 }
3716 // Fetch target information from environment if not set, or if the
3717 // target was the same as the TARGET environment variable, in
3718 // case the user did `build.target(&env::var("TARGET").unwrap())`.
3719 _ => self
3720 .build_cache
3721 .target_info_parser
3722 .parse_from_cargo_environment_variables(),
3723 }
3724 }
3725
3726 fn get_raw_target(&self) -> Result<Cow<'_, str>, Error> {
3727 match &self.target {
3728 Some(t) => Ok(Cow::Borrowed(t)),
3729 None => self.getenv_unwrap_str("TARGET").map(Cow::Owned),
3730 }
3731 }
3732
3733 fn get_is_cross_compile(&self) -> Result<bool, Error> {
3734 let target = self.get_raw_target()?;
3735 let host: Cow<'_, str> = match &self.host {
3736 Some(h) => Cow::Borrowed(h),
3737 None => Cow::Owned(self.getenv_unwrap_str("HOST")?),
3738 };
3739 Ok(host != target)
3740 }
3741
3742 fn get_opt_level(&self) -> Result<Cow<'_, str>, Error> {
3743 match &self.opt_level {
3744 Some(ol) => Ok(Cow::Borrowed(ol)),
3745 None => self.getenv_unwrap_str("OPT_LEVEL").map(Cow::Owned),
3746 }
3747 }
3748
3749 /// Returns true if *any* debug info is enabled.
3750 ///
3751 /// [`get_debug_str`] provides more detail.
3752 fn get_debug(&self) -> bool {
3753 match self.get_debug_str() {
3754 Err(_) => false,
3755 Ok(d) => match &*d {
3756 // From https://doc.rust-lang.org/cargo/reference/profiles.html#debug
3757 "" | "0" | "false" | "none" => false,
3758 _ => true,
3759 },
3760 }
3761 }
3762
3763 fn get_debug_str(&self) -> Result<Cow<'_, str>, Error> {
3764 match &self.debug {
3765 Some(d) => Ok(Cow::Borrowed(d)),
3766 None => self.getenv_unwrap_str("DEBUG").map(Cow::Owned),
3767 }
3768 }
3769
3770 fn get_shell_escaped_flags(&self) -> bool {
3771 self.shell_escaped_flags
3772 .unwrap_or_else(|| self.getenv_boolean("CC_SHELL_ESCAPED_FLAGS"))
3773 }
3774
3775 fn get_dwarf_version(&self) -> Option<u32> {
3776 // Tentatively matches the DWARF version defaults as of rustc 1.62.
3777 let target = self.get_target().ok()?;
3778 if matches!(
3779 target.os,
3780 "android" | "dragonfly" | "freebsd" | "netbsd" | "openbsd"
3781 ) || target.vendor == "apple"
3782 || (target.os == "windows" && target.env == "gnu")
3783 {
3784 Some(2)
3785 } else if target.os == "linux" {
3786 Some(4)
3787 } else {
3788 None
3789 }
3790 }
3791
3792 fn get_force_frame_pointer(&self) -> bool {
3793 self.force_frame_pointer.unwrap_or_else(|| self.get_debug())
3794 }
3795
3796 fn get_out_dir(&self) -> Result<Cow<'_, Path>, Error> {
3797 match &self.out_dir {
3798 Some(p) => Ok(Cow::Borrowed(&**p)),
3799 None => self
3800 .getenv("OUT_DIR")
3801 .as_deref()
3802 .map(PathBuf::from)
3803 .map(Cow::Owned)
3804 .ok_or_else(|| {
3805 Error::new(
3806 ErrorKind::EnvVarNotFound,
3807 "Environment variable OUT_DIR not defined.",
3808 )
3809 }),
3810 }
3811 }
3812
3813 #[allow(clippy::disallowed_methods)]
3814 fn getenv(&self, v: &str) -> Option<Arc<OsStr>> {
3815 // Returns true for environment variables cargo sets for build scripts:
3816 // https://doc.rust-lang.org/cargo/reference/environment-variables.html#environment-variables-cargo-sets-for-build-scripts
3817 //
3818 // This handles more of the vars than we actually use (it tries to check
3819 // complete-ish set), just to avoid needing maintenance if/when new
3820 // calls to `getenv`/`getenv_unwrap` are added.
3821 fn provided_by_cargo(envvar: &str) -> bool {
3822 match envvar {
3823 v if v.starts_with("CARGO") || v.starts_with("RUSTC") => true,
3824 "HOST" | "TARGET" | "RUSTDOC" | "OUT_DIR" | "OPT_LEVEL" | "DEBUG" | "PROFILE"
3825 | "NUM_JOBS" | "RUSTFLAGS" => true,
3826 _ => false,
3827 }
3828 }
3829 if let Some(val) = self.build_cache.env_cache.read().unwrap().get(v).cloned() {
3830 return val;
3831 }
3832 // Excluding `PATH` prevents spurious rebuilds on Windows, see
3833 // <https://github.com/rust-lang/cc-rs/pull/1215> for details.
3834 if self.emit_rerun_if_env_changed && !provided_by_cargo(v) && v != "PATH" {
3835 self.cargo_output
3836 .print_metadata(&format_args!("cargo:rerun-if-env-changed={v}"));
3837 }
3838 let r = self
3839 .env
3840 .iter()
3841 .find(|(k, _)| k.as_ref() == v)
3842 .map(|(_, value)| value.clone())
3843 .or_else(|| env::var_os(v).map(Arc::from));
3844 self.cargo_output.print_metadata(&format_args!(
3845 "{} = {}",
3846 v,
3847 OptionOsStrDisplay(r.as_deref())
3848 ));
3849 self.build_cache
3850 .env_cache
3851 .write()
3852 .unwrap()
3853 .insert(v.into(), r.clone());
3854 r
3855 }
3856
3857 /// get boolean flag that is either true or false
3858 fn getenv_boolean(&self, v: &str) -> bool {
3859 match self.getenv(v) {
3860 Some(s) => &*s != "0" && &*s != "false" && !s.is_empty(),
3861 None => false,
3862 }
3863 }
3864
3865 fn getenv_unwrap(&self, v: &str) -> Result<Arc<OsStr>, Error> {
3866 match self.getenv(v) {
3867 Some(s) => Ok(s),
3868 None => Err(Error::new(
3869 ErrorKind::EnvVarNotFound,
3870 format!("Environment variable {v} not defined."),
3871 )),
3872 }
3873 }
3874
3875 fn getenv_unwrap_str(&self, v: &str) -> Result<String, Error> {
3876 let env = self.getenv_unwrap(v)?;
3877 env.to_str().map(String::from).ok_or_else(|| {
3878 Error::new(
3879 ErrorKind::EnvVarNotFound,
3880 format!("Environment variable {v} is not valid utf-8."),
3881 )
3882 })
3883 }
3884
3885 /// The list of environment variables to check for a given env, in order of priority.
3886 fn target_envs(&self, env: &str) -> Result<[String; 4], Error> {
3887 let target = self.get_raw_target()?;
3888 let kind = if self.get_is_cross_compile()? {
3889 "TARGET"
3890 } else {
3891 "HOST"
3892 };
3893 let target_u = target.replace(['-', '.'], "_");
3894
3895 Ok([
3896 format!("{env}_{target}"),
3897 format!("{env}_{target_u}"),
3898 format!("{kind}_{env}"),
3899 env.to_string(),
3900 ])
3901 }
3902
3903 /// Get a single-valued environment variable with target variants.
3904 fn getenv_with_target_prefixes(&self, env: &str) -> Result<Arc<OsStr>, Error> {
3905 // Take from first environment variable in the environment.
3906 let res = self
3907 .target_envs(env)?
3908 .iter()
3909 .filter_map(|env| self.getenv(env))
3910 .next();
3911
3912 match res {
3913 Some(res) => Ok(res),
3914 None => Err(Error::new(
3915 ErrorKind::EnvVarNotFound,
3916 format!("could not find environment variable {env}"),
3917 )),
3918 }
3919 }
3920
3921 /// Get values from CFLAGS-style environment variable.
3922 fn envflags(&self, env: &str) -> Result<Option<Vec<String>>, Error> {
3923 // Collect from all environment variables, in reverse order as in
3924 // `getenv_with_target_prefixes` precedence (so that `CFLAGS_$TARGET`
3925 // can override flags in `TARGET_CFLAGS`, which overrides those in
3926 // `CFLAGS`).
3927 let mut any_set = false;
3928 let mut res = vec![];
3929 for env in self.target_envs(env)?.iter().rev() {
3930 if let Some(var) = self.getenv(env) {
3931 any_set = true;
3932
3933 let var = var.to_string_lossy();
3934 if self.get_shell_escaped_flags() {
3935 res.extend(Shlex::new(&var));
3936 } else {
3937 res.extend(var.split_ascii_whitespace().map(ToString::to_string));
3938 }
3939 }
3940 }
3941
3942 Ok(if any_set { Some(res) } else { None })
3943 }
3944
3945 fn fix_env_for_apple_os(&self, cmd: &mut Command) -> Result<(), Error> {
3946 let target = self.get_target()?;
3947 if cfg!(target_os = "macos") && target.os == "macos" {
3948 // Additionally, `IPHONEOS_DEPLOYMENT_TARGET` must not be set when using the Xcode linker at
3949 // "/Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/ld",
3950 // although this is apparently ignored when using the linker at "/usr/bin/ld".
3951 cmd.env_remove("IPHONEOS_DEPLOYMENT_TARGET");
3952 }
3953 Ok(())
3954 }
3955
3956 fn apple_sdk_root_inner(&self, sdk: &str) -> Result<Arc<OsStr>, Error> {
3957 // Code copied from rustc's compiler/rustc_codegen_ssa/src/back/link.rs.
3958 if let Some(sdkroot) = self.getenv("SDKROOT") {
3959 let p = Path::new(&sdkroot);
3960 let does_sdkroot_contain = |strings: &[&str]| {
3961 let sdkroot_str = p.to_string_lossy();
3962 strings.iter().any(|s| sdkroot_str.contains(s))
3963 };
3964 match sdk {
3965 // Ignore `SDKROOT` if it's clearly set for the wrong platform.
3966 "appletvos"
3967 if does_sdkroot_contain(&["TVSimulator.platform", "MacOSX.platform"]) => {}
3968 "appletvsimulator"
3969 if does_sdkroot_contain(&["TVOS.platform", "MacOSX.platform"]) => {}
3970 "iphoneos"
3971 if does_sdkroot_contain(&["iPhoneSimulator.platform", "MacOSX.platform"]) => {}
3972 "iphonesimulator"
3973 if does_sdkroot_contain(&["iPhoneOS.platform", "MacOSX.platform"]) => {}
3974 "macosx10.15"
3975 if does_sdkroot_contain(&["iPhoneOS.platform", "iPhoneSimulator.platform"]) => {
3976 }
3977 "watchos"
3978 if does_sdkroot_contain(&["WatchSimulator.platform", "MacOSX.platform"]) => {}
3979 "watchsimulator"
3980 if does_sdkroot_contain(&["WatchOS.platform", "MacOSX.platform"]) => {}
3981 "xros" if does_sdkroot_contain(&["XRSimulator.platform", "MacOSX.platform"]) => {}
3982 "xrsimulator" if does_sdkroot_contain(&["XROS.platform", "MacOSX.platform"]) => {}
3983 // Ignore `SDKROOT` if it's not a valid path.
3984 _ if !p.is_absolute() || p == Path::new("/") || !p.exists() => {}
3985 _ => return Ok(sdkroot),
3986 }
3987 }
3988
3989 let sdk_path = run_output(
3990 self.cmd("xcrun")
3991 .arg("--show-sdk-path")
3992 .arg("--sdk")
3993 .arg(sdk),
3994 &self.cargo_output,
3995 )?;
3996
3997 let sdk_path = match String::from_utf8(sdk_path) {
3998 Ok(p) => p,
3999 Err(_) => {
4000 return Err(Error::new(
4001 ErrorKind::IOError,
4002 "Unable to determine Apple SDK path.",
4003 ));
4004 }
4005 };
4006 Ok(Arc::from(OsStr::new(sdk_path.trim())))
4007 }
4008
4009 fn apple_sdk_root(&self, target: &TargetInfo<'_>) -> Result<Arc<OsStr>, Error> {
4010 let sdk = target.apple_sdk_name();
4011
4012 if let Some(ret) = self
4013 .build_cache
4014 .apple_sdk_root_cache
4015 .read()
4016 .expect("apple_sdk_root_cache lock failed")
4017 .get(sdk)
4018 .cloned()
4019 {
4020 return Ok(ret);
4021 }
4022 let sdk_path = self.apple_sdk_root_inner(sdk)?;
4023 self.build_cache
4024 .apple_sdk_root_cache
4025 .write()
4026 .expect("apple_sdk_root_cache lock failed")
4027 .insert(sdk.into(), sdk_path.clone());
4028 Ok(sdk_path)
4029 }
4030
4031 fn apple_deployment_target(&self, target: &TargetInfo<'_>) -> Arc<str> {
4032 let sdk = target.apple_sdk_name();
4033 if let Some(ret) = self
4034 .build_cache
4035 .apple_versions_cache
4036 .read()
4037 .expect("apple_versions_cache lock failed")
4038 .get(sdk)
4039 .cloned()
4040 {
4041 return ret;
4042 }
4043
4044 let default_deployment_from_sdk = || -> Option<Arc<str>> {
4045 let version = run_output(
4046 self.cmd("xcrun")
4047 .arg("--show-sdk-version")
4048 .arg("--sdk")
4049 .arg(sdk),
4050 &self.cargo_output,
4051 )
4052 .ok()?;
4053
4054 Some(Arc::from(std::str::from_utf8(&version).ok()?.trim()))
4055 };
4056
4057 let deployment_from_env = |name: &str| -> Option<Arc<str>> {
4058 // note that self.env isn't hit in production codepaths, its mostly just for tests which don't
4059 // set the real env
4060 self.env
4061 .iter()
4062 .find(|(k, _)| &**k == OsStr::new(name))
4063 .map(|(_, v)| v)
4064 .cloned()
4065 .or_else(|| self.getenv(name))?
4066 .to_str()
4067 .map(Arc::from)
4068 };
4069
4070 // Determines if the acquired deployment target is too low to support modern C++ on some Apple platform.
4071 //
4072 // 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.
4073 // If a `cc`` config wants to use C++, we round up to these versions as the baseline.
4074 let maybe_cpp_version_baseline = |deployment_target_ver: Arc<str>| -> Option<Arc<str>> {
4075 if !self.cpp {
4076 return Some(deployment_target_ver);
4077 }
4078
4079 let mut deployment_target = deployment_target_ver
4080 .split('.')
4081 .map(|v| v.parse::<u32>().expect("integer version"));
4082
4083 match target.os {
4084 "macos" => {
4085 let major = deployment_target.next().unwrap_or(0);
4086 let minor = deployment_target.next().unwrap_or(0);
4087
4088 // If below 10.9, we ignore it and let the SDK's target definitions handle it.
4089 if major == 10 && minor < 9 {
4090 self.cargo_output.print_warning(&format_args!(
4091 "macOS deployment target ({deployment_target_ver}) too low, it will be increased"
4092 ));
4093 return None;
4094 }
4095 }
4096 "ios" => {
4097 let major = deployment_target.next().unwrap_or(0);
4098
4099 // If below 10.7, we ignore it and let the SDK's target definitions handle it.
4100 if major < 7 {
4101 self.cargo_output.print_warning(&format_args!(
4102 "iOS deployment target ({deployment_target_ver}) too low, it will be increased"
4103 ));
4104 return None;
4105 }
4106 }
4107 // watchOS, tvOS, visionOS, and others are all new enough that libc++ is their baseline.
4108 _ => {}
4109 }
4110
4111 // If the deployment target met or exceeded the C++ baseline
4112 Some(deployment_target_ver)
4113 };
4114
4115 // The hardcoded minimums here are subject to change in a future compiler release,
4116 // and only exist as last resort fallbacks. Don't consider them stable.
4117 // `cc` doesn't use rustc's `--print deployment-target`` because the compiler's defaults
4118 // don't align well with Apple's SDKs and other third-party libraries that require ~generally~ higher
4119 // deployment targets. rustc isn't interested in those by default though so its fine to be different here.
4120 //
4121 // If no explicit target is passed, `cc` defaults to the current Xcode SDK's `DefaultDeploymentTarget` for better
4122 // compatibility. This is also the crate's historical behavior and what has become a relied-on value.
4123 //
4124 // The ordering of env -> XCode SDK -> old rustc defaults is intentional for performance when using
4125 // an explicit target.
4126 let version: Arc<str> = match target.os {
4127 "macos" => deployment_from_env("MACOSX_DEPLOYMENT_TARGET")
4128 .and_then(maybe_cpp_version_baseline)
4129 .or_else(default_deployment_from_sdk)
4130 .unwrap_or_else(|| {
4131 if target.arch == "aarch64" {
4132 "11.0".into()
4133 } else {
4134 let default: Arc<str> = Arc::from("10.7");
4135 maybe_cpp_version_baseline(default.clone()).unwrap_or(default)
4136 }
4137 }),
4138
4139 "ios" => deployment_from_env("IPHONEOS_DEPLOYMENT_TARGET")
4140 .and_then(maybe_cpp_version_baseline)
4141 .or_else(default_deployment_from_sdk)
4142 .unwrap_or_else(|| "7.0".into()),
4143
4144 "watchos" => deployment_from_env("WATCHOS_DEPLOYMENT_TARGET")
4145 .or_else(default_deployment_from_sdk)
4146 .unwrap_or_else(|| "5.0".into()),
4147
4148 "tvos" => deployment_from_env("TVOS_DEPLOYMENT_TARGET")
4149 .or_else(default_deployment_from_sdk)
4150 .unwrap_or_else(|| "9.0".into()),
4151
4152 "visionos" => deployment_from_env("XROS_DEPLOYMENT_TARGET")
4153 .or_else(default_deployment_from_sdk)
4154 .unwrap_or_else(|| "1.0".into()),
4155
4156 os => unreachable!("unknown Apple OS: {}", os),
4157 };
4158
4159 self.build_cache
4160 .apple_versions_cache
4161 .write()
4162 .expect("apple_versions_cache lock failed")
4163 .insert(sdk.into(), version.clone());
4164
4165 version
4166 }
4167
4168 fn wasm_musl_sysroot(&self) -> Result<Arc<OsStr>, Error> {
4169 if let Some(musl_sysroot_path) = self.getenv("WASM_MUSL_SYSROOT") {
4170 Ok(musl_sysroot_path)
4171 } else {
4172 Err(Error::new(
4173 ErrorKind::EnvVarNotFound,
4174 "Environment variable WASM_MUSL_SYSROOT not defined for wasm32. Download sysroot from GitHub & setup environment variable MUSL_SYSROOT targeting the folder.",
4175 ))
4176 }
4177 }
4178
4179 fn wasi_sysroot(&self) -> Result<Arc<OsStr>, Error> {
4180 if let Some(wasi_sysroot_path) = self.getenv("WASI_SYSROOT") {
4181 Ok(wasi_sysroot_path)
4182 } else {
4183 Err(Error::new(
4184 ErrorKind::EnvVarNotFound,
4185 "Environment variable WASI_SYSROOT not defined. Download sysroot from GitHub & setup environment variable WASI_SYSROOT targeting the folder.",
4186 ))
4187 }
4188 }
4189
4190 fn cuda_file_count(&self) -> usize {
4191 self.files
4192 .iter()
4193 .filter(|file| file.extension() == Some(OsStr::new("cu")))
4194 .count()
4195 }
4196
4197 fn which(&self, tool: &Path, path_entries: Option<&OsStr>) -> Option<PathBuf> {
4198 // Loop through PATH entries searching for the |tool|.
4199 let find_exe_in_path = |path_entries: &OsStr| -> Option<PathBuf> {
4200 env::split_paths(path_entries).find_map(|path_entry| check_exe(path_entry.join(tool)))
4201 };
4202
4203 // If |tool| is not just one "word," assume it's an actual path...
4204 if tool.components().count() > 1 {
4205 check_exe(PathBuf::from(tool))
4206 } else {
4207 path_entries
4208 .and_then(find_exe_in_path)
4209 .or_else(|| find_exe_in_path(&self.getenv("PATH")?))
4210 }
4211 }
4212
4213 /// search for |prog| on 'programs' path in '|cc| --print-search-dirs' output
4214 fn search_programs(
4215 &self,
4216 cc: &Path,
4217 prog: &Path,
4218 cargo_output: &CargoOutput,
4219 ) -> Option<PathBuf> {
4220 let search_dirs = run_output(
4221 self.cmd(cc).arg("--print-search-dirs"),
4222 // this doesn't concern the compilation so we always want to show warnings.
4223 cargo_output,
4224 )
4225 .ok()?;
4226 // clang driver appears to be forcing UTF-8 output even on Windows,
4227 // hence from_utf8 is assumed to be usable in all cases.
4228 let search_dirs = std::str::from_utf8(&search_dirs).ok()?;
4229 for dirs in search_dirs.split(['\r', '\n']) {
4230 if let Some(path) = dirs.strip_prefix("programs: =") {
4231 return self.which(prog, Some(OsStr::new(path)));
4232 }
4233 }
4234 None
4235 }
4236
4237 fn find_msvc_tools_find(&self, target: &TargetInfo<'_>, tool: &str) -> Option<Command> {
4238 self.find_msvc_tools_find_tool(target, tool)
4239 .map(|c| c.to_command())
4240 }
4241
4242 fn find_msvc_tools_find_tool(&self, target: &TargetInfo<'_>, tool: &str) -> Option<Tool> {
4243 struct BuildEnvGetter<'s>(&'s Build);
4244
4245 impl ::find_msvc_tools::EnvGetter for BuildEnvGetter<'_> {
4246 fn get_env(&self, name: &str) -> Option<::find_msvc_tools::Env> {
4247 self.0.getenv(name).map(::find_msvc_tools::Env::Arced)
4248 }
4249 }
4250
4251 if target.env != "msvc" {
4252 return None;
4253 }
4254
4255 ::find_msvc_tools::find_tool_with_env(target.full_arch, tool, &BuildEnvGetter(self))
4256 .map(Tool::from_find_msvc_tools)
4257 }
4258
4259 /// Compiling for WASI targets typically uses the [wasi-sdk] project and
4260 /// installations of wasi-sdk are typically indicated with the
4261 /// `WASI_SDK_PATH` environment variable. Check to see if that environment
4262 /// variable exists, and check to see if an appropriate compiler is located
4263 /// there. If that all passes then use that compiler by default, but
4264 /// otherwise fall back to whatever the clang default is since gcc doesn't
4265 /// have support for compiling to wasm.
4266 ///
4267 /// [wasi-sdk]: https://github.com/WebAssembly/wasi-sdk
4268 fn autodetect_wasi_compiler(&self, raw_target: &str, clang: &str) -> PathBuf {
4269 if let Some(path) = self.getenv("WASI_SDK_PATH") {
4270 let target_clang = Path::new(&path)
4271 .join("bin")
4272 .join(format!("{raw_target}-clang"));
4273 if let Some(path) = self.which(&target_clang, None) {
4274 return path;
4275 }
4276 }
4277
4278 clang.into()
4279 }
4280}
4281
4282impl Default for Build {
4283 fn default() -> Build {
4284 Build::new()
4285 }
4286}
4287
4288fn fail(s: &str) -> ! {
4289 eprintln!("\n\nerror occurred in cc-rs: {s}\n\n");
4290 std::process::exit(1);
4291}
4292
4293// Use by default minimum available API level
4294// See note about naming here
4295// https://android.googlesource.com/platform/ndk/+/refs/heads/ndk-release-r21/docs/BuildSystemMaintainers.md#Clang
4296static NEW_STANDALONE_ANDROID_COMPILERS: [&str; 4] = [
4297 "aarch64-linux-android21-clang",
4298 "armv7a-linux-androideabi16-clang",
4299 "i686-linux-android16-clang",
4300 "x86_64-linux-android21-clang",
4301];
4302
4303// New "standalone" C/C++ cross-compiler executables from recent Android NDK
4304// are just shell scripts that call main clang binary (from Android NDK) with
4305// proper `--target` argument.
4306//
4307// For example, armv7a-linux-androideabi16-clang passes
4308// `--target=armv7a-linux-androideabi16` to clang.
4309// So to construct proper command line check if
4310// `--target` argument would be passed or not to clang
4311fn android_clang_compiler_uses_target_arg_internally(clang_path: &Path) -> bool {
4312 if let Some(filename) = clang_path.file_name() {
4313 if let Some(filename_str) = filename.to_str() {
4314 if let Some(idx) = filename_str.rfind('-') {
4315 return filename_str.split_at(idx).0.contains("android");
4316 }
4317 }
4318 }
4319 false
4320}
4321
4322fn is_llvm_mingw_wrapper(clang_path: &Path) -> bool {
4323 if let Some(filename) = clang_path
4324 .file_name()
4325 .and_then(|file_name| file_name.to_str())
4326 {
4327 filename.ends_with("-w64-mingw32-clang") || filename.ends_with("-w64-mingw32-clang++")
4328 } else {
4329 false
4330 }
4331}
4332
4333// FIXME: Use parsed target.
4334fn autodetect_android_compiler(raw_target: &str, gnu: &str, clang: &str) -> PathBuf {
4335 let new_clang_key = match raw_target {
4336 "aarch64-linux-android" => Some("aarch64"),
4337 "armv7-linux-androideabi" => Some("armv7a"),
4338 "i686-linux-android" => Some("i686"),
4339 "x86_64-linux-android" => Some("x86_64"),
4340 _ => None,
4341 };
4342
4343 let new_clang = new_clang_key
4344 .map(|key| {
4345 NEW_STANDALONE_ANDROID_COMPILERS
4346 .iter()
4347 .find(|x| x.starts_with(key))
4348 })
4349 .unwrap_or(None);
4350
4351 if let Some(new_clang) = new_clang {
4352 if Command::new(new_clang).output().is_ok() {
4353 return (*new_clang).into();
4354 }
4355 }
4356
4357 let target = raw_target
4358 .replace("armv7neon", "arm")
4359 .replace("armv7", "arm")
4360 .replace("thumbv7neon", "arm")
4361 .replace("thumbv7", "arm");
4362 let gnu_compiler = format!("{target}-{gnu}");
4363 let clang_compiler = format!("{target}-{clang}");
4364
4365 // On Windows, the Android clang compiler is provided as a `.cmd` file instead
4366 // of a `.exe` file. `std::process::Command` won't run `.cmd` files unless the
4367 // `.cmd` is explicitly appended to the command name, so we do that here.
4368 let clang_compiler_cmd = format!("{target}-{clang}.cmd");
4369
4370 // Check if gnu compiler is present
4371 // if not, use clang
4372 if Command::new(&gnu_compiler).output().is_ok() {
4373 gnu_compiler
4374 } else if cfg!(windows) && Command::new(&clang_compiler_cmd).output().is_ok() {
4375 clang_compiler_cmd
4376 } else {
4377 clang_compiler
4378 }
4379 .into()
4380}
4381
4382// Rust and clang/cc don't agree on how to name the target.
4383fn map_darwin_target_from_rust_to_compiler_architecture<'a>(target: &TargetInfo<'a>) -> &'a str {
4384 match target.full_arch {
4385 "aarch64" => "arm64",
4386 "arm64_32" => "arm64_32",
4387 "arm64e" => "arm64e",
4388 "armv7k" => "armv7k",
4389 "armv7s" => "armv7s",
4390 "i386" => "i386",
4391 "i686" => "i386",
4392 "powerpc" => "ppc",
4393 "powerpc64" => "ppc64",
4394 "x86_64" => "x86_64",
4395 "x86_64h" => "x86_64h",
4396 arch => arch,
4397 }
4398}
4399
4400fn is_arm(target: &TargetInfo<'_>) -> bool {
4401 matches!(target.arch, "aarch64" | "arm64ec" | "arm")
4402}
4403
4404#[derive(Clone, Copy, PartialEq)]
4405enum AsmFileExt {
4406 /// `.asm` files. On MSVC targets, we assume these should be passed to MASM
4407 /// (`ml{,64}.exe`).
4408 DotAsm,
4409 /// `.s` or `.S` files, which do not have the special handling on MSVC targets.
4410 DotS,
4411}
4412
4413impl AsmFileExt {
4414 fn from_path(file: &Path) -> Option<Self> {
4415 if let Some(ext) = file.extension() {
4416 if let Some(ext) = ext.to_str() {
4417 let ext = ext.to_lowercase();
4418 match &*ext {
4419 "asm" => return Some(AsmFileExt::DotAsm),
4420 "s" => return Some(AsmFileExt::DotS),
4421 _ => return None,
4422 }
4423 }
4424 }
4425 None
4426 }
4427}
4428
4429/// Returns true if `cc` has been disabled by `CC_FORCE_DISABLE`.
4430fn is_disabled() -> bool {
4431 static CACHE: AtomicU8 = AtomicU8::new(0);
4432
4433 let val = CACHE.load(Relaxed);
4434 // We manually cache the environment var, since we need it in some places
4435 // where we don't have access to a `Build` instance.
4436 #[allow(clippy::disallowed_methods)]
4437 fn compute_is_disabled() -> bool {
4438 match std::env::var_os("CC_FORCE_DISABLE") {
4439 // Not set? Not disabled.
4440 None => false,
4441 // Respect `CC_FORCE_DISABLE=0` and some simple synonyms, otherwise
4442 // we're disabled. This intentionally includes `CC_FORCE_DISABLE=""`
4443 Some(v) => &*v != "0" && &*v != "false" && &*v != "no",
4444 }
4445 }
4446 match val {
4447 2 => true,
4448 1 => false,
4449 0 => {
4450 let truth = compute_is_disabled();
4451 let encoded_truth = if truth { 2u8 } else { 1 };
4452 // Use compare_exchange to avoid race condition
4453 let _ = CACHE.compare_exchange(0, encoded_truth, Relaxed, Relaxed);
4454 truth
4455 }
4456 _ => unreachable!(),
4457 }
4458}
4459
4460/// Automates the `if is_disabled() { return error }` check and ensures
4461/// we produce a consistent error message for it.
4462fn check_disabled() -> Result<(), Error> {
4463 if is_disabled() {
4464 return Err(Error::new(
4465 ErrorKind::Disabled,
4466 "the `cc` crate's functionality has been disabled by the `CC_FORCE_DISABLE` environment variable.",
4467 ));
4468 }
4469 Ok(())
4470}
4471
4472fn check_exe(mut exe: PathBuf) -> Option<PathBuf> {
4473 let exe_ext = std::env::consts::EXE_EXTENSION;
4474 let check = exe.exists() || (!exe_ext.is_empty() && exe.set_extension(exe_ext) && exe.exists());
4475 check.then_some(exe)
4476}
4477
4478#[cfg(test)]
4479mod tests {
4480 use super::*;
4481
4482 #[test]
4483 fn test_android_clang_compiler_uses_target_arg_internally() {
4484 for version in 16..21 {
4485 assert!(android_clang_compiler_uses_target_arg_internally(
4486 &PathBuf::from(format!("armv7a-linux-androideabi{}-clang", version))
4487 ));
4488 assert!(android_clang_compiler_uses_target_arg_internally(
4489 &PathBuf::from(format!("armv7a-linux-androideabi{}-clang++", version))
4490 ));
4491 }
4492 assert!(!android_clang_compiler_uses_target_arg_internally(
4493 &PathBuf::from("clang-i686-linux-android")
4494 ));
4495 assert!(!android_clang_compiler_uses_target_arg_internally(
4496 &PathBuf::from("clang")
4497 ));
4498 assert!(!android_clang_compiler_uses_target_arg_internally(
4499 &PathBuf::from("clang++")
4500 ));
4501 }
4502}