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