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