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