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