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 name 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 name 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, Stdio};
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 command_add_output_file(
1341 &mut cmd,
1342 &obj,
1343 CmdAddOutputFileArgs {
1344 cuda: self.cuda,
1345 is_assembler_msvc: false,
1346 msvc: compiler.is_like_msvc(),
1347 clang: compiler.is_like_clang(),
1348 gnu: compiler.is_like_gnu(),
1349 is_asm: false,
1350 is_arm,
1351 },
1352 );
1353
1354 if compiler.supports_path_delimiter() {
1355 cmd.arg("--");
1356 }
1357
1358 cmd.arg(&src);
1359
1360 if compiler.is_like_msvc() {
1361 // On MSVC we need to make sure the LIB directory is included
1362 // so the CRT can be found.
1363 for (key, value) in &tool.env {
1364 if key == "LIB" {
1365 cmd.env("LIB", value);
1366 break;
1367 }
1368 }
1369 }
1370
1371 let output = cmd.current_dir(out_dir).output()?;
1372 let is_supported = output.status.success() && output.stderr.is_empty();
1373
1374 self.build_cache
1375 .known_flag_support_status_cache
1376 .write()
1377 .unwrap()
1378 .insert(compiler_flag, is_supported);
1379
1380 Ok(is_supported)
1381 }
1382
1383 /// Run the compiler, generating the file `output`
1384 ///
1385 /// This will return a result instead of panicking; see [`Self::compile()`] for
1386 /// the complete description.
1387 pub fn try_compile(&self, output: &str) -> Result<(), Error> {
1388 let mut output_components = Path::new(output).components();
1389 match (output_components.next(), output_components.next()) {
1390 (Some(Component::Normal(_)), None) => {}
1391 _ => {
1392 return Err(Error::new(
1393 ErrorKind::InvalidArgument,
1394 "argument of `compile` must be a single normal path component",
1395 ));
1396 }
1397 }
1398
1399 let (lib_name, gnu_lib_name) = if output.starts_with("lib") && output.ends_with(".a") {
1400 (&output[3..output.len() - 2], output.to_owned())
1401 } else {
1402 let mut gnu = String::with_capacity(5 + output.len());
1403 gnu.push_str("lib");
1404 gnu.push_str(output);
1405 gnu.push_str(".a");
1406 (output, gnu)
1407 };
1408 let dst = self.get_out_dir()?;
1409
1410 let objects = objects_from_files(&self.files, &dst)?;
1411
1412 self.compile_objects(&objects)?;
1413 self.assemble(lib_name, &dst.join(gnu_lib_name), &objects)?;
1414
1415 let target = self.get_target()?;
1416 if target.env == "msvc" {
1417 let compiler = self.get_base_compiler()?;
1418 let atlmfc_lib = compiler
1419 .env()
1420 .iter()
1421 .find(|&(var, _)| var.as_os_str() == OsStr::new("LIB"))
1422 .and_then(|(_, lib_paths)| {
1423 env::split_paths(lib_paths).find(|path| {
1424 let sub = Path::new("atlmfc/lib");
1425 path.ends_with(sub) || path.parent().map_or(false, |p| p.ends_with(sub))
1426 })
1427 });
1428
1429 if let Some(atlmfc_lib) = atlmfc_lib {
1430 self.cargo_output.print_metadata(&format_args!(
1431 "cargo:rustc-link-search=native={}",
1432 atlmfc_lib.display()
1433 ));
1434 }
1435 }
1436
1437 if self.link_lib_modifiers.is_empty() {
1438 self.cargo_output
1439 .print_metadata(&format_args!("cargo:rustc-link-lib=static={}", lib_name));
1440 } else {
1441 self.cargo_output.print_metadata(&format_args!(
1442 "cargo:rustc-link-lib=static:{}={}",
1443 JoinOsStrs {
1444 slice: &self.link_lib_modifiers,
1445 delimiter: ','
1446 },
1447 lib_name
1448 ));
1449 }
1450 self.cargo_output.print_metadata(&format_args!(
1451 "cargo:rustc-link-search=native={}",
1452 dst.display()
1453 ));
1454
1455 // Add specific C++ libraries, if enabled.
1456 if self.cpp {
1457 if let Some(stdlib) = self.get_cpp_link_stdlib()? {
1458 self.cargo_output
1459 .print_metadata(&format_args!("cargo:rustc-link-lib={}", stdlib.display()));
1460 }
1461 // Link c++ lib from WASI sysroot
1462 if target.arch == "wasm32" {
1463 if target.os == "wasi" {
1464 if let Ok(wasi_sysroot) = self.wasi_sysroot() {
1465 self.cargo_output.print_metadata(&format_args!(
1466 "cargo:rustc-flags=-L {}/lib/{} -lstatic=c++ -lstatic=c++abi",
1467 Path::new(&wasi_sysroot).display(),
1468 self.get_raw_target()?
1469 ));
1470 }
1471 } else if target.os == "linux" {
1472 let musl_sysroot = self.wasm_musl_sysroot().unwrap();
1473 self.cargo_output.print_metadata(&format_args!(
1474 "cargo:rustc-flags=-L {}/lib -lstatic=c++ -lstatic=c++abi",
1475 Path::new(&musl_sysroot).display(),
1476 ));
1477 }
1478 }
1479 }
1480
1481 let cudart = match &self.cudart {
1482 Some(opt) => opt, // {none|shared|static}
1483 None => "none",
1484 };
1485 if cudart != "none" {
1486 if let Some(nvcc) = self.which(&self.get_compiler().path, None) {
1487 // Try to figure out the -L search path. If it fails,
1488 // it's on user to specify one by passing it through
1489 // RUSTFLAGS environment variable.
1490 let mut libtst = false;
1491 let mut libdir = nvcc;
1492 libdir.pop(); // remove 'nvcc'
1493 libdir.push("..");
1494 if cfg!(target_os = "linux") {
1495 libdir.push("targets");
1496 libdir.push(format!("{}-linux", target.arch));
1497 libdir.push("lib");
1498 libtst = true;
1499 } else if cfg!(target_env = "msvc") {
1500 libdir.push("lib");
1501 match target.arch {
1502 "x86_64" => {
1503 libdir.push("x64");
1504 libtst = true;
1505 }
1506 "x86" => {
1507 libdir.push("Win32");
1508 libtst = true;
1509 }
1510 _ => libtst = false,
1511 }
1512 }
1513 if libtst && libdir.is_dir() {
1514 self.cargo_output.print_metadata(&format_args!(
1515 "cargo:rustc-link-search=native={}",
1516 libdir.to_str().unwrap()
1517 ));
1518 }
1519
1520 // And now the -l flag.
1521 let lib = match cudart {
1522 "shared" => "cudart",
1523 "static" => "cudart_static",
1524 bad => panic!("unsupported cudart option: {}", bad),
1525 };
1526 self.cargo_output
1527 .print_metadata(&format_args!("cargo:rustc-link-lib={}", lib));
1528 }
1529 }
1530
1531 Ok(())
1532 }
1533
1534 /// Run the compiler, generating the file `output`
1535 ///
1536 /// # Library name
1537 ///
1538 /// The `output` string argument determines the file name for the compiled
1539 /// library. The Rust compiler will create an assembly named "lib"+output+".a".
1540 /// MSVC will create a file named output+".lib".
1541 ///
1542 /// The choice of `output` is close to arbitrary, but:
1543 ///
1544 /// - must be nonempty,
1545 /// - must not contain a path separator (`/`),
1546 /// - must be unique across all `compile` invocations made by the same build
1547 /// script.
1548 ///
1549 /// If your build script compiles a single source file, the base name of
1550 /// that source file would usually be reasonable:
1551 ///
1552 /// ```no_run
1553 /// cc::Build::new().file("blobstore.c").compile("blobstore");
1554 /// ```
1555 ///
1556 /// Compiling multiple source files, some people use their crate's name, or
1557 /// their crate's name + "-cc".
1558 ///
1559 /// Otherwise, please use your imagination.
1560 ///
1561 /// For backwards compatibility, if `output` starts with "lib" *and* ends
1562 /// with ".a", a second "lib" prefix and ".a" suffix do not get added on,
1563 /// but this usage is deprecated; please omit `lib` and `.a` in the argument
1564 /// that you pass.
1565 ///
1566 /// # Panics
1567 ///
1568 /// Panics if `output` is not formatted correctly or if one of the underlying
1569 /// compiler commands fails. It can also panic if it fails reading file names
1570 /// or creating directories.
1571 pub fn compile(&self, output: &str) {
1572 if let Err(e) = self.try_compile(output) {
1573 fail(&e.message);
1574 }
1575 }
1576
1577 /// Run the compiler, generating intermediate files, but without linking
1578 /// them into an archive file.
1579 ///
1580 /// This will return a list of compiled object files, in the same order
1581 /// as they were passed in as `file`/`files` methods.
1582 pub fn compile_intermediates(&self) -> Vec<PathBuf> {
1583 match self.try_compile_intermediates() {
1584 Ok(v) => v,
1585 Err(e) => fail(&e.message),
1586 }
1587 }
1588
1589 /// Run the compiler, generating intermediate files, but without linking
1590 /// them into an archive file.
1591 ///
1592 /// This will return a result instead of panicking; see `compile_intermediates()` for the complete description.
1593 pub fn try_compile_intermediates(&self) -> Result<Vec<PathBuf>, Error> {
1594 let dst = self.get_out_dir()?;
1595 let objects = objects_from_files(&self.files, &dst)?;
1596
1597 self.compile_objects(&objects)?;
1598
1599 Ok(objects.into_iter().map(|v| v.dst).collect())
1600 }
1601
1602 #[cfg(feature = "parallel")]
1603 fn compile_objects(&self, objs: &[Object]) -> Result<(), Error> {
1604 use std::cell::Cell;
1605
1606 use parallel::async_executor::{block_on, YieldOnce};
1607
1608 check_disabled()?;
1609
1610 if objs.len() <= 1 {
1611 for obj in objs {
1612 let mut cmd = self.create_compile_object_cmd(obj)?;
1613 run(&mut cmd, &self.cargo_output)?;
1614 }
1615
1616 return Ok(());
1617 }
1618
1619 // Limit our parallelism globally with a jobserver.
1620 let mut tokens = parallel::job_token::ActiveJobTokenServer::new();
1621
1622 // When compiling objects in parallel we do a few dirty tricks to speed
1623 // things up:
1624 //
1625 // * First is that we use the `jobserver` crate to limit the parallelism
1626 // of this build script. The `jobserver` crate will use a jobserver
1627 // configured by Cargo for build scripts to ensure that parallelism is
1628 // coordinated across C compilations and Rust compilations. Before we
1629 // compile anything we make sure to wait until we acquire a token.
1630 //
1631 // Note that this jobserver is cached globally so we only used one per
1632 // process and only worry about creating it once.
1633 //
1634 // * Next we use spawn the process to actually compile objects in
1635 // parallel after we've acquired a token to perform some work
1636 //
1637 // With all that in mind we compile all objects in a loop here, after we
1638 // acquire the appropriate tokens, Once all objects have been compiled
1639 // we wait on all the processes and propagate the results of compilation.
1640
1641 let pendings =
1642 Cell::new(Vec::<(Command, KillOnDrop, parallel::job_token::JobToken)>::new());
1643 let is_disconnected = Cell::new(false);
1644 let has_made_progress = Cell::new(false);
1645
1646 let wait_future = async {
1647 let mut error = None;
1648 // Buffer the stdout
1649 let mut stdout = io::BufWriter::with_capacity(128, io::stdout());
1650
1651 loop {
1652 // If the other end of the pipe is already disconnected, then we're not gonna get any new jobs,
1653 // so it doesn't make sense to reuse the tokens; in fact,
1654 // releasing them as soon as possible (once we know that the other end is disconnected) is beneficial.
1655 // Imagine that the last file built takes an hour to finish; in this scenario,
1656 // by not releasing the tokens before that last file is done we would effectively block other processes from
1657 // starting sooner - even though we only need one token for that last file, not N others that were acquired.
1658
1659 let mut pendings_is_empty = false;
1660
1661 cell_update(&pendings, |mut pendings| {
1662 // Try waiting on them.
1663 pendings.retain_mut(|(cmd, child, _token)| {
1664 match try_wait_on_child(cmd, &mut child.0, &mut stdout, &mut child.1) {
1665 Ok(Some(())) => {
1666 // Task done, remove the entry
1667 has_made_progress.set(true);
1668 false
1669 }
1670 Ok(None) => true, // Task still not finished, keep the entry
1671 Err(err) => {
1672 // Task fail, remove the entry.
1673 // Since we can only return one error, log the error to make
1674 // sure users always see all the compilation failures.
1675 has_made_progress.set(true);
1676
1677 if self.cargo_output.warnings {
1678 let _ = writeln!(stdout, "cargo:warning={}", err);
1679 }
1680 error = Some(err);
1681
1682 false
1683 }
1684 }
1685 });
1686 pendings_is_empty = pendings.is_empty();
1687 pendings
1688 });
1689
1690 if pendings_is_empty && is_disconnected.get() {
1691 break if let Some(err) = error {
1692 Err(err)
1693 } else {
1694 Ok(())
1695 };
1696 }
1697
1698 YieldOnce::default().await;
1699 }
1700 };
1701 let spawn_future = async {
1702 for obj in objs {
1703 let mut cmd = self.create_compile_object_cmd(obj)?;
1704 let token = tokens.acquire().await?;
1705 let mut child = spawn(&mut cmd, &self.cargo_output)?;
1706 let mut stderr_forwarder = StderrForwarder::new(&mut child);
1707 stderr_forwarder.set_non_blocking()?;
1708
1709 cell_update(&pendings, |mut pendings| {
1710 pendings.push((cmd, KillOnDrop(child, stderr_forwarder), token));
1711 pendings
1712 });
1713
1714 has_made_progress.set(true);
1715 }
1716 is_disconnected.set(true);
1717
1718 Ok::<_, Error>(())
1719 };
1720
1721 return block_on(wait_future, spawn_future, &has_made_progress);
1722
1723 struct KillOnDrop(Child, StderrForwarder);
1724
1725 impl Drop for KillOnDrop {
1726 fn drop(&mut self) {
1727 let child = &mut self.0;
1728
1729 child.kill().ok();
1730 }
1731 }
1732
1733 fn cell_update<T, F>(cell: &Cell<T>, f: F)
1734 where
1735 T: Default,
1736 F: FnOnce(T) -> T,
1737 {
1738 let old = cell.take();
1739 let new = f(old);
1740 cell.set(new);
1741 }
1742 }
1743
1744 #[cfg(not(feature = "parallel"))]
1745 fn compile_objects(&self, objs: &[Object]) -> Result<(), Error> {
1746 check_disabled()?;
1747
1748 for obj in objs {
1749 let mut cmd = self.create_compile_object_cmd(obj)?;
1750 run(&mut cmd, &self.cargo_output)?;
1751 }
1752
1753 Ok(())
1754 }
1755
1756 fn create_compile_object_cmd(&self, obj: &Object) -> Result<Command, Error> {
1757 let asm_ext = AsmFileExt::from_path(&obj.src);
1758 let is_asm = asm_ext.is_some();
1759 let target = self.get_target()?;
1760 let msvc = target.env == "msvc";
1761 let compiler = self.try_get_compiler()?;
1762
1763 let is_assembler_msvc = msvc && asm_ext == Some(AsmFileExt::DotAsm);
1764 let mut cmd = if is_assembler_msvc {
1765 self.msvc_macro_assembler()?
1766 } else {
1767 let mut cmd = compiler.to_command();
1768 for (a, b) in self.env.iter() {
1769 cmd.env(a, b);
1770 }
1771 cmd
1772 };
1773 let is_arm = matches!(target.arch, "aarch64" | "arm");
1774 command_add_output_file(
1775 &mut cmd,
1776 &obj.dst,
1777 CmdAddOutputFileArgs {
1778 cuda: self.cuda,
1779 is_assembler_msvc,
1780 msvc: compiler.is_like_msvc(),
1781 clang: compiler.is_like_clang(),
1782 gnu: compiler.is_like_gnu(),
1783 is_asm,
1784 is_arm,
1785 },
1786 );
1787 // armasm and armasm64 don't requrie -c option
1788 if !is_assembler_msvc || !is_arm {
1789 cmd.arg("-c");
1790 }
1791 if self.cuda && self.cuda_file_count() > 1 {
1792 cmd.arg("--device-c");
1793 }
1794 if is_asm {
1795 cmd.args(self.asm_flags.iter().map(std::ops::Deref::deref));
1796 }
1797
1798 if compiler.supports_path_delimiter() && !is_assembler_msvc {
1799 // #513: For `clang-cl`, separate flags/options from the input file.
1800 // When cross-compiling macOS -> Windows, this avoids interpreting
1801 // common `/Users/...` paths as the `/U` flag and triggering
1802 // `-Wslash-u-filename` warning.
1803 cmd.arg("--");
1804 }
1805 cmd.arg(&obj.src);
1806
1807 if cfg!(target_os = "macos") {
1808 self.fix_env_for_apple_os(&mut cmd)?;
1809 }
1810
1811 Ok(cmd)
1812 }
1813
1814 /// This will return a result instead of panicking; see [`Self::expand()`] for
1815 /// the complete description.
1816 pub fn try_expand(&self) -> Result<Vec<u8>, Error> {
1817 let compiler = self.try_get_compiler()?;
1818 let mut cmd = compiler.to_command();
1819 for (a, b) in self.env.iter() {
1820 cmd.env(a, b);
1821 }
1822 cmd.arg("-E");
1823
1824 assert!(
1825 self.files.len() <= 1,
1826 "Expand may only be called for a single file"
1827 );
1828
1829 let is_asm = self
1830 .files
1831 .iter()
1832 .map(std::ops::Deref::deref)
1833 .find_map(AsmFileExt::from_path)
1834 .is_some();
1835
1836 if compiler.family == (ToolFamily::Msvc { clang_cl: true }) && !is_asm {
1837 // #513: For `clang-cl`, separate flags/options from the input file.
1838 // When cross-compiling macOS -> Windows, this avoids interpreting
1839 // common `/Users/...` paths as the `/U` flag and triggering
1840 // `-Wslash-u-filename` warning.
1841 cmd.arg("--");
1842 }
1843
1844 cmd.args(self.files.iter().map(std::ops::Deref::deref));
1845
1846 run_output(&mut cmd, &self.cargo_output)
1847 }
1848
1849 /// Run the compiler, returning the macro-expanded version of the input files.
1850 ///
1851 /// This is only relevant for C and C++ files.
1852 ///
1853 /// # Panics
1854 /// Panics if more than one file is present in the config, or if compiler
1855 /// path has an invalid file name.
1856 ///
1857 /// # Example
1858 /// ```no_run
1859 /// let out = cc::Build::new().file("src/foo.c").expand();
1860 /// ```
1861 pub fn expand(&self) -> Vec<u8> {
1862 match self.try_expand() {
1863 Err(e) => fail(&e.message),
1864 Ok(v) => v,
1865 }
1866 }
1867
1868 /// Get the compiler that's in use for this configuration.
1869 ///
1870 /// This function will return a `Tool` which represents the culmination
1871 /// of this configuration at a snapshot in time. The returned compiler can
1872 /// be inspected (e.g. the path, arguments, environment) to forward along to
1873 /// other tools, or the `to_command` method can be used to invoke the
1874 /// compiler itself.
1875 ///
1876 /// This method will take into account all configuration such as debug
1877 /// information, optimization level, include directories, defines, etc.
1878 /// Additionally, the compiler binary in use follows the standard
1879 /// conventions for this path, e.g. looking at the explicitly set compiler,
1880 /// environment variables (a number of which are inspected here), and then
1881 /// falling back to the default configuration.
1882 ///
1883 /// # Panics
1884 ///
1885 /// Panics if an error occurred while determining the architecture.
1886 pub fn get_compiler(&self) -> Tool {
1887 match self.try_get_compiler() {
1888 Ok(tool) => tool,
1889 Err(e) => fail(&e.message),
1890 }
1891 }
1892
1893 /// Get the compiler that's in use for this configuration.
1894 ///
1895 /// This will return a result instead of panicking; see
1896 /// [`get_compiler()`](Self::get_compiler) for the complete description.
1897 pub fn try_get_compiler(&self) -> Result<Tool, Error> {
1898 let opt_level = self.get_opt_level()?;
1899 let target = self.get_target()?;
1900
1901 let mut cmd = self.get_base_compiler()?;
1902
1903 // The flags below are added in roughly the following order:
1904 // 1. Default flags
1905 // - Controlled by `cc-rs`.
1906 // 2. `rustc`-inherited flags
1907 // - Controlled by `rustc`.
1908 // 3. Builder flags
1909 // - Controlled by the developer using `cc-rs` in e.g. their `build.rs`.
1910 // 4. Environment flags
1911 // - Controlled by the end user.
1912 //
1913 // This is important to allow later flags to override previous ones.
1914
1915 // Copied from <https://github.com/rust-lang/rust/blob/5db81020006d2920fc9c62ffc0f4322f90bffa04/compiler/rustc_codegen_ssa/src/back/linker.rs#L27-L38>
1916 //
1917 // Disables non-English messages from localized linkers.
1918 // Such messages may cause issues with text encoding on Windows
1919 // and prevent inspection of msvc output in case of errors, which we occasionally do.
1920 // This should be acceptable because other messages from rustc are in English anyway,
1921 // and may also be desirable to improve searchability of the compiler diagnostics.
1922 if matches!(cmd.family, ToolFamily::Msvc { clang_cl: false }) {
1923 cmd.env.push(("VSLANG".into(), "1033".into()));
1924 } else {
1925 cmd.env.push(("LC_ALL".into(), "C".into()));
1926 }
1927
1928 // Disable default flag generation via `no_default_flags` or environment variable
1929 let no_defaults = self.no_default_flags || self.getenv_boolean("CRATE_CC_NO_DEFAULTS");
1930 if !no_defaults {
1931 self.add_default_flags(&mut cmd, &target, &opt_level)?;
1932 }
1933
1934 // Specify various flags that are not considered part of the default flags above.
1935 // FIXME(madsmtm): Should these be considered part of the defaults? If no, why not?
1936 if let Some(ref std) = self.std {
1937 let separator = match cmd.family {
1938 ToolFamily::Msvc { .. } => ':',
1939 ToolFamily::Gnu | ToolFamily::Clang { .. } => '=',
1940 };
1941 cmd.push_cc_arg(format!("-std{}{}", separator, std).into());
1942 }
1943 for directory in self.include_directories.iter() {
1944 cmd.args.push("-I".into());
1945 cmd.args.push(directory.as_os_str().into());
1946 }
1947 if self.warnings_into_errors {
1948 let warnings_to_errors_flag = cmd.family.warnings_to_errors_flag().into();
1949 cmd.push_cc_arg(warnings_to_errors_flag);
1950 }
1951
1952 // If warnings and/or extra_warnings haven't been explicitly set,
1953 // then we set them only if the environment doesn't already have
1954 // CFLAGS/CXXFLAGS, since those variables presumably already contain
1955 // the desired set of warnings flags.
1956 let envflags = self.envflags(if self.cpp { "CXXFLAGS" } else { "CFLAGS" })?;
1957 if self.warnings.unwrap_or(envflags.is_none()) {
1958 let wflags = cmd.family.warnings_flags().into();
1959 cmd.push_cc_arg(wflags);
1960 }
1961 if self.extra_warnings.unwrap_or(envflags.is_none()) {
1962 if let Some(wflags) = cmd.family.extra_warnings_flags() {
1963 cmd.push_cc_arg(wflags.into());
1964 }
1965 }
1966
1967 // Add cc flags inherited from matching rustc flags.
1968 if self.inherit_rustflags {
1969 self.add_inherited_rustflags(&mut cmd, &target)?;
1970 }
1971
1972 // Set flags configured in the builder (do this second-to-last, to allow these to override
1973 // everything above).
1974 for flag in self.flags.iter() {
1975 cmd.args.push((**flag).into());
1976 }
1977 for flag in self.flags_supported.iter() {
1978 if self
1979 .is_flag_supported_inner(flag, &cmd, &target)
1980 .unwrap_or(false)
1981 {
1982 cmd.push_cc_arg((**flag).into());
1983 }
1984 }
1985 for (key, value) in self.definitions.iter() {
1986 if let Some(ref value) = *value {
1987 cmd.args.push(format!("-D{}={}", key, value).into());
1988 } else {
1989 cmd.args.push(format!("-D{}", key).into());
1990 }
1991 }
1992
1993 // Set flags from the environment (do this last, to allow these to override everything else).
1994 if let Some(flags) = &envflags {
1995 for arg in flags {
1996 cmd.push_cc_arg(arg.into());
1997 }
1998 }
1999
2000 Ok(cmd)
2001 }
2002
2003 fn add_default_flags(
2004 &self,
2005 cmd: &mut Tool,
2006 target: &TargetInfo<'_>,
2007 opt_level: &str,
2008 ) -> Result<(), Error> {
2009 let raw_target = self.get_raw_target()?;
2010 // Non-target flags
2011 // If the flag is not conditioned on target variable, it belongs here :)
2012 match cmd.family {
2013 ToolFamily::Msvc { .. } => {
2014 cmd.push_cc_arg("-nologo".into());
2015
2016 let crt_flag = match self.static_crt {
2017 Some(true) => "-MT",
2018 Some(false) => "-MD",
2019 None => {
2020 let features = self.getenv("CARGO_CFG_TARGET_FEATURE");
2021 let features = features.as_deref().unwrap_or_default();
2022 if features.to_string_lossy().contains("crt-static") {
2023 "-MT"
2024 } else {
2025 "-MD"
2026 }
2027 }
2028 };
2029 cmd.push_cc_arg(crt_flag.into());
2030
2031 match opt_level {
2032 // Msvc uses /O1 to enable all optimizations that minimize code size.
2033 "z" | "s" | "1" => cmd.push_opt_unless_duplicate("-O1".into()),
2034 // -O3 is a valid value for gcc and clang compilers, but not msvc. Cap to /O2.
2035 "2" | "3" => cmd.push_opt_unless_duplicate("-O2".into()),
2036 _ => {}
2037 }
2038 }
2039 ToolFamily::Gnu | ToolFamily::Clang { .. } => {
2040 // arm-linux-androideabi-gcc 4.8 shipped with Android NDK does
2041 // not support '-Oz'
2042 if opt_level == "z" && !cmd.is_like_clang() {
2043 cmd.push_opt_unless_duplicate("-Os".into());
2044 } else {
2045 cmd.push_opt_unless_duplicate(format!("-O{}", opt_level).into());
2046 }
2047
2048 if cmd.is_like_clang() && target.os == "android" {
2049 // For compatibility with code that doesn't use pre-defined `__ANDROID__` macro.
2050 // If compiler used via ndk-build or cmake (officially supported build methods)
2051 // this macros is defined.
2052 // See https://android.googlesource.com/platform/ndk/+/refs/heads/ndk-release-r21/build/cmake/android.toolchain.cmake#456
2053 // https://android.googlesource.com/platform/ndk/+/refs/heads/ndk-release-r21/build/core/build-binary.mk#141
2054 cmd.push_opt_unless_duplicate("-DANDROID".into());
2055 }
2056
2057 if target.os != "ios"
2058 && target.os != "watchos"
2059 && target.os != "tvos"
2060 && target.os != "visionos"
2061 {
2062 cmd.push_cc_arg("-ffunction-sections".into());
2063 cmd.push_cc_arg("-fdata-sections".into());
2064 }
2065 // Disable generation of PIC on bare-metal for now: rust-lld doesn't support this yet
2066 //
2067 // `rustc` also defaults to disable PIC on WASM:
2068 // <https://github.com/rust-lang/rust/blob/1.82.0/compiler/rustc_target/src/spec/base/wasm.rs#L101-L108>
2069 if self.pic.unwrap_or(
2070 target.os != "windows"
2071 && target.os != "none"
2072 && target.os != "uefi"
2073 && target.arch != "wasm32"
2074 && target.arch != "wasm64",
2075 ) {
2076 cmd.push_cc_arg("-fPIC".into());
2077 // PLT only applies if code is compiled with PIC support,
2078 // and only for ELF targets.
2079 if (target.os == "linux" || target.os == "android")
2080 && !self.use_plt.unwrap_or(true)
2081 {
2082 cmd.push_cc_arg("-fno-plt".into());
2083 }
2084 }
2085 if target.arch == "wasm32" || target.arch == "wasm64" {
2086 // WASI does not support exceptions yet.
2087 // https://github.com/WebAssembly/exception-handling
2088 //
2089 // `rustc` also defaults to (currently) disable exceptions
2090 // on all WASM targets:
2091 // <https://github.com/rust-lang/rust/blob/1.82.0/compiler/rustc_target/src/spec/base/wasm.rs#L72-L77>
2092 cmd.push_cc_arg("-fno-exceptions".into());
2093 }
2094
2095 if target.os == "wasi" {
2096 // Link clang sysroot
2097 if let Ok(wasi_sysroot) = self.wasi_sysroot() {
2098 cmd.push_cc_arg(
2099 format!("--sysroot={}", Path::new(&wasi_sysroot).display()).into(),
2100 );
2101 }
2102
2103 // FIXME(madsmtm): Read from `target_features` instead?
2104 if raw_target.contains("threads") {
2105 cmd.push_cc_arg("-pthread".into());
2106 }
2107 }
2108
2109 if target.os == "nto" {
2110 // Select the target with `-V`, see qcc documentation:
2111 // QNX 7.1: https://www.qnx.com/developers/docs/7.1/index.html#com.qnx.doc.neutrino.utilities/topic/q/qcc.html
2112 // QNX 8.0: https://www.qnx.com/developers/docs/8.0/com.qnx.doc.neutrino.utilities/topic/q/qcc.html
2113 // This assumes qcc/q++ as compiler, which is currently the only supported compiler for QNX.
2114 // See for details: https://github.com/rust-lang/cc-rs/pull/1319
2115 let arg = match target.arch {
2116 "i586" => "-Vgcc_ntox86_cxx",
2117 "aarch64" => "-Vgcc_ntoaarch64le_cxx",
2118 "x86_64" => "-Vgcc_ntox86_64_cxx",
2119 _ => {
2120 return Err(Error::new(
2121 ErrorKind::InvalidTarget,
2122 format!("Unknown architecture for Neutrino QNX: {}", target.arch),
2123 ))
2124 }
2125 };
2126 cmd.push_cc_arg(arg.into());
2127 }
2128 }
2129 }
2130
2131 if self.get_debug() {
2132 if self.cuda {
2133 // NVCC debug flag
2134 cmd.args.push("-G".into());
2135 }
2136 let family = cmd.family;
2137 family.add_debug_flags(cmd, self.get_dwarf_version());
2138 }
2139
2140 if self.get_force_frame_pointer() {
2141 let family = cmd.family;
2142 family.add_force_frame_pointer(cmd);
2143 }
2144
2145 if !cmd.is_like_msvc() {
2146 if target.arch == "x86" {
2147 cmd.args.push("-m32".into());
2148 } else if target.abi == "x32" {
2149 cmd.args.push("-mx32".into());
2150 } else if target.os == "aix" {
2151 if cmd.family == ToolFamily::Gnu {
2152 cmd.args.push("-maix64".into());
2153 } else {
2154 cmd.args.push("-m64".into());
2155 }
2156 } else if target.arch == "x86_64" || target.arch == "powerpc64" {
2157 cmd.args.push("-m64".into());
2158 }
2159 }
2160
2161 // Target flags
2162 match cmd.family {
2163 ToolFamily::Clang { .. } => {
2164 if !(cmd.has_internal_target_arg
2165 || (target.os == "android"
2166 && android_clang_compiler_uses_target_arg_internally(&cmd.path)))
2167 {
2168 if target.os == "freebsd" {
2169 // FreeBSD only supports C++11 and above when compiling against libc++
2170 // (available from FreeBSD 10 onwards). Under FreeBSD, clang uses libc++ by
2171 // default on FreeBSD 10 and newer unless `--target` is manually passed to
2172 // the compiler, in which case its default behavior differs:
2173 // * If --target=xxx-unknown-freebsdX(.Y) is specified and X is greater than
2174 // or equal to 10, clang++ uses libc++
2175 // * If --target=xxx-unknown-freebsd is specified (without a version),
2176 // clang++ cannot assume libc++ is available and reverts to a default of
2177 // libstdc++ (this behavior was changed in llvm 14).
2178 //
2179 // This breaks C++11 (or greater) builds if targeting FreeBSD with the
2180 // generic xxx-unknown-freebsd target on clang 13 or below *without*
2181 // explicitly specifying that libc++ should be used.
2182 // When cross-compiling, we can't infer from the rust/cargo target name
2183 // which major version of FreeBSD we are targeting, so we need to make sure
2184 // that libc++ is used (unless the user has explicitly specified otherwise).
2185 // There's no compelling reason to use a different approach when compiling
2186 // natively.
2187 if self.cpp && self.cpp_set_stdlib.is_none() {
2188 cmd.push_cc_arg("-stdlib=libc++".into());
2189 }
2190 } else if target.arch == "wasm32" && target.os == "linux" {
2191 for x in &[
2192 "atomics",
2193 "bulk-memory",
2194 "mutable-globals",
2195 "sign-ext",
2196 "exception-handling",
2197 ] {
2198 cmd.push_cc_arg(format!("-m{x}").into());
2199 }
2200 for x in &["wasm-exceptions", "declspec"] {
2201 cmd.push_cc_arg(format!("-f{x}").into());
2202 }
2203 let musl_sysroot = self.wasm_musl_sysroot().unwrap();
2204 cmd.push_cc_arg(
2205 format!("--sysroot={}", Path::new(&musl_sysroot).display()).into(),
2206 );
2207 cmd.push_cc_arg("-pthread".into());
2208 }
2209 // Pass `--target` with the LLVM target to configure Clang for cross-compiling.
2210 //
2211 // This is **required** for cross-compilation, as it's the only flag that
2212 // consistently forces Clang to change the "toolchain" that is responsible for
2213 // parsing target-specific flags:
2214 // https://github.com/rust-lang/cc-rs/issues/1388
2215 // https://github.com/llvm/llvm-project/blob/llvmorg-19.1.7/clang/lib/Driver/Driver.cpp#L1359-L1360
2216 // https://github.com/llvm/llvm-project/blob/llvmorg-19.1.7/clang/lib/Driver/Driver.cpp#L6347-L6532
2217 //
2218 // This can be confusing, because on e.g. host macOS, you can usually get by
2219 // with `-arch` and `-mtargetos=`. But that only works because the _default_
2220 // toolchain is `Darwin`, which enables parsing of darwin-specific options.
2221 //
2222 // NOTE: In the past, we passed the deployment version in here on all Apple
2223 // targets, but versioned targets were found to have poor compatibility with
2224 // older versions of Clang, especially when it comes to configuration files:
2225 // https://github.com/rust-lang/cc-rs/issues/1278
2226 //
2227 // So instead, we pass the deployment target with `-m*-version-min=`, and only
2228 // pass it here on visionOS and Mac Catalyst where that option does not exist:
2229 // https://github.com/rust-lang/cc-rs/issues/1383
2230 let version = if target.os == "visionos" || target.abi == "macabi" {
2231 Some(self.apple_deployment_target(target))
2232 } else {
2233 None
2234 };
2235
2236 let clang_target =
2237 target.llvm_target(&self.get_raw_target()?, version.as_deref());
2238 cmd.push_cc_arg(format!("--target={clang_target}").into());
2239 }
2240 }
2241 ToolFamily::Msvc { clang_cl } => {
2242 // This is an undocumented flag from MSVC but helps with making
2243 // builds more reproducible by avoiding putting timestamps into
2244 // files.
2245 cmd.push_cc_arg("-Brepro".into());
2246
2247 if clang_cl {
2248 if target.arch == "x86_64" {
2249 cmd.push_cc_arg("-m64".into());
2250 } else if target.arch == "x86" {
2251 cmd.push_cc_arg("-m32".into());
2252 // See
2253 // <https://learn.microsoft.com/en-us/cpp/build/reference/arch-x86?view=msvc-170>.
2254 //
2255 // NOTE: Rust officially supported Windows targets all require SSE2 as part
2256 // of baseline target features.
2257 //
2258 // NOTE: The same applies for STL. See: -
2259 // <https://github.com/microsoft/STL/issues/3922>, and -
2260 // <https://github.com/microsoft/STL/pull/4741>.
2261 cmd.push_cc_arg("-arch:SSE2".into());
2262 } else {
2263 cmd.push_cc_arg(
2264 format!(
2265 "--target={}",
2266 target.llvm_target(&self.get_raw_target()?, None)
2267 )
2268 .into(),
2269 );
2270 }
2271 } else if target.full_arch == "i586" {
2272 cmd.push_cc_arg("-arch:IA32".into());
2273 } else if target.full_arch == "arm64ec" {
2274 cmd.push_cc_arg("-arm64EC".into());
2275 }
2276 // There is a check in corecrt.h that will generate a
2277 // compilation error if
2278 // _ARM_WINAPI_PARTITION_DESKTOP_SDK_AVAILABLE is
2279 // not defined to 1. The check was added in Windows
2280 // 8 days because only store apps were allowed on ARM.
2281 // This changed with the release of Windows 10 IoT Core.
2282 // The check will be going away in future versions of
2283 // the SDK, but for all released versions of the
2284 // Windows SDK it is required.
2285 if target.arch == "arm" {
2286 cmd.args
2287 .push("-D_ARM_WINAPI_PARTITION_DESKTOP_SDK_AVAILABLE=1".into());
2288 }
2289 }
2290 ToolFamily::Gnu => {
2291 if target.vendor == "kmc" {
2292 cmd.args.push("-finput-charset=utf-8".into());
2293 }
2294
2295 if self.static_flag.is_none() {
2296 let features = self.getenv("CARGO_CFG_TARGET_FEATURE");
2297 let features = features.as_deref().unwrap_or_default();
2298 if features.to_string_lossy().contains("crt-static") {
2299 cmd.args.push("-static".into());
2300 }
2301 }
2302
2303 // armv7 targets get to use armv7 instructions
2304 if (target.full_arch.starts_with("armv7")
2305 || target.full_arch.starts_with("thumbv7"))
2306 && (target.os == "linux" || target.vendor == "kmc")
2307 {
2308 cmd.args.push("-march=armv7-a".into());
2309
2310 if target.abi == "eabihf" {
2311 // lowest common denominator FPU
2312 cmd.args.push("-mfpu=vfpv3-d16".into());
2313 cmd.args.push("-mfloat-abi=hard".into());
2314 }
2315 }
2316
2317 // (x86 Android doesn't say "eabi")
2318 if target.os == "android" && target.full_arch.contains("v7") {
2319 cmd.args.push("-march=armv7-a".into());
2320 cmd.args.push("-mthumb".into());
2321 if !target.full_arch.contains("neon") {
2322 // On android we can guarantee some extra float instructions
2323 // (specified in the android spec online)
2324 // NEON guarantees even more; see below.
2325 cmd.args.push("-mfpu=vfpv3-d16".into());
2326 }
2327 cmd.args.push("-mfloat-abi=softfp".into());
2328 }
2329
2330 if target.full_arch.contains("neon") {
2331 cmd.args.push("-mfpu=neon-vfpv4".into());
2332 }
2333
2334 if target.full_arch == "armv4t" && target.os == "linux" {
2335 cmd.args.push("-march=armv4t".into());
2336 cmd.args.push("-marm".into());
2337 cmd.args.push("-mfloat-abi=soft".into());
2338 }
2339
2340 if target.full_arch == "armv5te" && target.os == "linux" {
2341 cmd.args.push("-march=armv5te".into());
2342 cmd.args.push("-marm".into());
2343 cmd.args.push("-mfloat-abi=soft".into());
2344 }
2345
2346 // For us arm == armv6 by default
2347 if target.full_arch == "arm" && target.os == "linux" {
2348 cmd.args.push("-march=armv6".into());
2349 cmd.args.push("-marm".into());
2350 if target.abi == "eabihf" {
2351 cmd.args.push("-mfpu=vfp".into());
2352 } else {
2353 cmd.args.push("-mfloat-abi=soft".into());
2354 }
2355 }
2356
2357 // Turn codegen down on i586 to avoid some instructions.
2358 if target.full_arch == "i586" && target.os == "linux" {
2359 cmd.args.push("-march=pentium".into());
2360 }
2361
2362 // Set codegen level for i686 correctly
2363 if target.full_arch == "i686" && target.os == "linux" {
2364 cmd.args.push("-march=i686".into());
2365 }
2366
2367 // Looks like `musl-gcc` makes it hard for `-m32` to make its way
2368 // all the way to the linker, so we need to actually instruct the
2369 // linker that we're generating 32-bit executables as well. This'll
2370 // typically only be used for build scripts which transitively use
2371 // these flags that try to compile executables.
2372 if target.arch == "x86" && target.env == "musl" {
2373 cmd.args.push("-Wl,-melf_i386".into());
2374 }
2375
2376 if target.arch == "arm" && target.os == "none" && target.abi == "eabihf" {
2377 cmd.args.push("-mfloat-abi=hard".into())
2378 }
2379 if target.full_arch.starts_with("thumb") {
2380 cmd.args.push("-mthumb".into());
2381 }
2382 if target.full_arch.starts_with("thumbv6m") {
2383 cmd.args.push("-march=armv6s-m".into());
2384 }
2385 if target.full_arch.starts_with("thumbv7em") {
2386 cmd.args.push("-march=armv7e-m".into());
2387
2388 if target.abi == "eabihf" {
2389 cmd.args.push("-mfpu=fpv4-sp-d16".into())
2390 }
2391 }
2392 if target.full_arch.starts_with("thumbv7m") {
2393 cmd.args.push("-march=armv7-m".into());
2394 }
2395 if target.full_arch.starts_with("thumbv8m.base") {
2396 cmd.args.push("-march=armv8-m.base".into());
2397 }
2398 if target.full_arch.starts_with("thumbv8m.main") {
2399 cmd.args.push("-march=armv8-m.main".into());
2400
2401 if target.abi == "eabihf" {
2402 cmd.args.push("-mfpu=fpv5-sp-d16".into())
2403 }
2404 }
2405 if target.full_arch.starts_with("armebv7r") | target.full_arch.starts_with("armv7r")
2406 {
2407 if target.full_arch.starts_with("armeb") {
2408 cmd.args.push("-mbig-endian".into());
2409 } else {
2410 cmd.args.push("-mlittle-endian".into());
2411 }
2412
2413 // ARM mode
2414 cmd.args.push("-marm".into());
2415
2416 // R Profile
2417 cmd.args.push("-march=armv7-r".into());
2418
2419 if target.abi == "eabihf" {
2420 // lowest common denominator FPU
2421 // (see Cortex-R4 technical reference manual)
2422 cmd.args.push("-mfpu=vfpv3-d16".into())
2423 }
2424 }
2425 if target.full_arch.starts_with("armv7a") {
2426 cmd.args.push("-march=armv7-a".into());
2427
2428 if target.abi == "eabihf" {
2429 // lowest common denominator FPU
2430 cmd.args.push("-mfpu=vfpv3-d16".into());
2431 }
2432 }
2433 if target.arch == "riscv32" || target.arch == "riscv64" {
2434 // get the 32i/32imac/32imc/64gc/64imac/... part
2435 let arch = &target.full_arch[5..];
2436 if arch.starts_with("64") {
2437 if matches!(target.os, "linux" | "freebsd" | "netbsd") {
2438 cmd.args.push(("-march=rv64gc").into());
2439 cmd.args.push("-mabi=lp64d".into());
2440 } else {
2441 cmd.args.push(("-march=rv".to_owned() + arch).into());
2442 cmd.args.push("-mabi=lp64".into());
2443 }
2444 } else if arch.starts_with("32") {
2445 if target.os == "linux" {
2446 cmd.args.push(("-march=rv32gc").into());
2447 cmd.args.push("-mabi=ilp32d".into());
2448 } else {
2449 cmd.args.push(("-march=rv".to_owned() + arch).into());
2450 cmd.args.push("-mabi=ilp32".into());
2451 }
2452 } else {
2453 cmd.args.push("-mcmodel=medany".into());
2454 }
2455 }
2456 }
2457 }
2458
2459 if target.vendor == "apple" {
2460 self.apple_flags(cmd)?;
2461 }
2462
2463 if self.static_flag.unwrap_or(false) {
2464 cmd.args.push("-static".into());
2465 }
2466 if self.shared_flag.unwrap_or(false) {
2467 cmd.args.push("-shared".into());
2468 }
2469
2470 if self.cpp {
2471 match (self.cpp_set_stdlib.as_ref(), cmd.family) {
2472 (None, _) => {}
2473 (Some(stdlib), ToolFamily::Gnu) | (Some(stdlib), ToolFamily::Clang { .. }) => {
2474 cmd.push_cc_arg(format!("-stdlib=lib{}", stdlib).into());
2475 }
2476 _ => {
2477 self.cargo_output.print_warning(&format_args!("cpp_set_stdlib is specified, but the {:?} compiler does not support this option, ignored", cmd.family));
2478 }
2479 }
2480 }
2481
2482 Ok(())
2483 }
2484
2485 fn add_inherited_rustflags(
2486 &self,
2487 cmd: &mut Tool,
2488 target: &TargetInfo<'_>,
2489 ) -> Result<(), Error> {
2490 let env_os = match self.getenv("CARGO_ENCODED_RUSTFLAGS") {
2491 Some(env) => env,
2492 // No encoded RUSTFLAGS -> nothing to do
2493 None => return Ok(()),
2494 };
2495
2496 let env = env_os.to_string_lossy();
2497 let codegen_flags = RustcCodegenFlags::parse(&env)?;
2498 codegen_flags.cc_flags(self, cmd, target);
2499 Ok(())
2500 }
2501
2502 fn msvc_macro_assembler(&self) -> Result<Command, Error> {
2503 let target = self.get_target()?;
2504 let tool = if target.arch == "x86_64" {
2505 "ml64.exe"
2506 } else if target.arch == "arm" {
2507 "armasm.exe"
2508 } else if target.arch == "aarch64" {
2509 "armasm64.exe"
2510 } else {
2511 "ml.exe"
2512 };
2513 let mut cmd = self
2514 .windows_registry_find(&target, tool)
2515 .unwrap_or_else(|| self.cmd(tool));
2516 cmd.arg("-nologo"); // undocumented, yet working with armasm[64]
2517 for directory in self.include_directories.iter() {
2518 cmd.arg("-I").arg(&**directory);
2519 }
2520 if target.arch == "aarch64" || target.arch == "arm" {
2521 if self.get_debug() {
2522 cmd.arg("-g");
2523 }
2524
2525 for (key, value) in self.definitions.iter() {
2526 cmd.arg("-PreDefine");
2527 if let Some(ref value) = *value {
2528 if let Ok(i) = value.parse::<i32>() {
2529 cmd.arg(format!("{} SETA {}", key, i));
2530 } else if value.starts_with('"') && value.ends_with('"') {
2531 cmd.arg(format!("{} SETS {}", key, value));
2532 } else {
2533 cmd.arg(format!("{} SETS \"{}\"", key, value));
2534 }
2535 } else {
2536 cmd.arg(format!("{} SETL {}", key, "{TRUE}"));
2537 }
2538 }
2539 } else {
2540 if self.get_debug() {
2541 cmd.arg("-Zi");
2542 }
2543
2544 for (key, value) in self.definitions.iter() {
2545 if let Some(ref value) = *value {
2546 cmd.arg(format!("-D{}={}", key, value));
2547 } else {
2548 cmd.arg(format!("-D{}", key));
2549 }
2550 }
2551 }
2552
2553 if target.arch == "x86" {
2554 cmd.arg("-safeseh");
2555 }
2556
2557 Ok(cmd)
2558 }
2559
2560 fn assemble(&self, lib_name: &str, dst: &Path, objs: &[Object]) -> Result<(), Error> {
2561 // Delete the destination if it exists as we want to
2562 // create on the first iteration instead of appending.
2563 let _ = fs::remove_file(dst);
2564
2565 // Add objects to the archive in limited-length batches. This helps keep
2566 // the length of the command line within a reasonable length to avoid
2567 // blowing system limits on limiting platforms like Windows.
2568 let objs: Vec<_> = objs
2569 .iter()
2570 .map(|o| o.dst.as_path())
2571 .chain(self.objects.iter().map(std::ops::Deref::deref))
2572 .collect();
2573 for chunk in objs.chunks(100) {
2574 self.assemble_progressive(dst, chunk)?;
2575 }
2576
2577 if self.cuda && self.cuda_file_count() > 0 {
2578 // Link the device-side code and add it to the target library,
2579 // so that non-CUDA linker can link the final binary.
2580
2581 let out_dir = self.get_out_dir()?;
2582 let dlink = out_dir.join(lib_name.to_owned() + "_dlink.o");
2583 let mut nvcc = self.get_compiler().to_command();
2584 nvcc.arg("--device-link").arg("-o").arg(&dlink).arg(dst);
2585 run(&mut nvcc, &self.cargo_output)?;
2586 self.assemble_progressive(dst, &[dlink.as_path()])?;
2587 }
2588
2589 let target = self.get_target()?;
2590 if target.env == "msvc" {
2591 // The Rust compiler will look for libfoo.a and foo.lib, but the
2592 // MSVC linker will also be passed foo.lib, so be sure that both
2593 // exist for now.
2594
2595 let lib_dst = dst.with_file_name(format!("{}.lib", lib_name));
2596 let _ = fs::remove_file(&lib_dst);
2597 match fs::hard_link(dst, &lib_dst).or_else(|_| {
2598 // if hard-link fails, just copy (ignoring the number of bytes written)
2599 fs::copy(dst, &lib_dst).map(|_| ())
2600 }) {
2601 Ok(_) => (),
2602 Err(_) => {
2603 return Err(Error::new(
2604 ErrorKind::IOError,
2605 "Could not copy or create a hard-link to the generated lib file.",
2606 ));
2607 }
2608 };
2609 } else {
2610 // Non-msvc targets (those using `ar`) need a separate step to add
2611 // the symbol table to archives since our construction command of
2612 // `cq` doesn't add it for us.
2613 let mut ar = self.try_get_archiver()?;
2614
2615 // NOTE: We add `s` even if flags were passed using $ARFLAGS/ar_flag, because `s`
2616 // here represents a _mode_, not an arbitrary flag. Further discussion of this choice
2617 // can be seen in https://github.com/rust-lang/cc-rs/pull/763.
2618 run(ar.arg("s").arg(dst), &self.cargo_output)?;
2619 }
2620
2621 Ok(())
2622 }
2623
2624 fn assemble_progressive(&self, dst: &Path, objs: &[&Path]) -> Result<(), Error> {
2625 let target = self.get_target()?;
2626
2627 let (mut cmd, program, any_flags) = self.try_get_archiver_and_flags()?;
2628 if target.env == "msvc" && !program.to_string_lossy().contains("llvm-ar") {
2629 // NOTE: -out: here is an I/O flag, and so must be included even if $ARFLAGS/ar_flag is
2630 // in use. -nologo on the other hand is just a regular flag, and one that we'll skip if
2631 // the caller has explicitly dictated the flags they want. See
2632 // https://github.com/rust-lang/cc-rs/pull/763 for further discussion.
2633 let mut out = OsString::from("-out:");
2634 out.push(dst);
2635 cmd.arg(out);
2636 if !any_flags {
2637 cmd.arg("-nologo");
2638 }
2639 // If the library file already exists, add the library name
2640 // as an argument to let lib.exe know we are appending the objs.
2641 if dst.exists() {
2642 cmd.arg(dst);
2643 }
2644 cmd.args(objs);
2645 run(&mut cmd, &self.cargo_output)?;
2646 } else {
2647 // Set an environment variable to tell the OSX archiver to ensure
2648 // that all dates listed in the archive are zero, improving
2649 // determinism of builds. AFAIK there's not really official
2650 // documentation of this but there's a lot of references to it if
2651 // you search google.
2652 //
2653 // You can reproduce this locally on a mac with:
2654 //
2655 // $ touch foo.c
2656 // $ cc -c foo.c -o foo.o
2657 //
2658 // # Notice that these two checksums are different
2659 // $ ar crus libfoo1.a foo.o && sleep 2 && ar crus libfoo2.a foo.o
2660 // $ md5sum libfoo*.a
2661 //
2662 // # Notice that these two checksums are the same
2663 // $ export ZERO_AR_DATE=1
2664 // $ ar crus libfoo1.a foo.o && sleep 2 && touch foo.o && ar crus libfoo2.a foo.o
2665 // $ md5sum libfoo*.a
2666 //
2667 // In any case if this doesn't end up getting read, it shouldn't
2668 // cause that many issues!
2669 cmd.env("ZERO_AR_DATE", "1");
2670
2671 // NOTE: We add cq here regardless of whether $ARFLAGS/ar_flag have been used because
2672 // it dictates the _mode_ ar runs in, which the setter of $ARFLAGS/ar_flag can't
2673 // dictate. See https://github.com/rust-lang/cc-rs/pull/763 for further discussion.
2674 run(cmd.arg("cq").arg(dst).args(objs), &self.cargo_output)?;
2675 }
2676
2677 Ok(())
2678 }
2679
2680 fn apple_flags(&self, cmd: &mut Tool) -> Result<(), Error> {
2681 let target = self.get_target()?;
2682
2683 // This is a Darwin/Apple-specific flag that works both on GCC and Clang, but it is only
2684 // necessary on GCC since we specify `-target` on Clang.
2685 // https://gcc.gnu.org/onlinedocs/gcc/Darwin-Options.html#:~:text=arch
2686 // https://clang.llvm.org/docs/CommandGuide/clang.html#cmdoption-arch
2687 if cmd.is_like_gnu() {
2688 let arch = map_darwin_target_from_rust_to_compiler_architecture(&target);
2689 cmd.args.push("-arch".into());
2690 cmd.args.push(arch.into());
2691 }
2692
2693 // Pass the deployment target via `-mmacosx-version-min=`, `-miphoneos-version-min=` and
2694 // similar. Also necessary on GCC, as it forces a compilation error if the compiler is not
2695 // configured for Darwin: https://gcc.gnu.org/onlinedocs/gcc/Darwin-Options.html
2696 //
2697 // On visionOS and Mac Catalyst, there is no -m*-version-min= flag:
2698 // https://github.com/llvm/llvm-project/issues/88271
2699 // And the workaround to use `-mtargetos=` cannot be used with the `--target` flag that we
2700 // otherwise specify. So we avoid emitting that, and put the version in `--target` instead.
2701 if cmd.is_like_gnu() || !(target.os == "visionos" || target.abi == "macabi") {
2702 let min_version = self.apple_deployment_target(&target);
2703 cmd.args
2704 .push(target.apple_version_flag(&min_version).into());
2705 }
2706
2707 // AppleClang sometimes requires sysroot even on macOS
2708 if cmd.is_xctoolchain_clang() || target.os != "macos" {
2709 self.cargo_output.print_metadata(&format_args!(
2710 "Detecting {:?} SDK path for {}",
2711 target.os,
2712 target.apple_sdk_name(),
2713 ));
2714 let sdk_path = self.apple_sdk_root(&target)?;
2715
2716 cmd.args.push("-isysroot".into());
2717 cmd.args.push(OsStr::new(&sdk_path).to_owned());
2718
2719 if target.abi == "macabi" {
2720 // Mac Catalyst uses the macOS SDK, but to compile against and
2721 // link to iOS-specific frameworks, we should have the support
2722 // library stubs in the include and library search path.
2723 let ios_support = Path::new(&sdk_path).join("System/iOSSupport");
2724
2725 cmd.args.extend([
2726 // Header search path
2727 OsString::from("-isystem"),
2728 ios_support.join("usr/include").into(),
2729 // Framework header search path
2730 OsString::from("-iframework"),
2731 ios_support.join("System/Library/Frameworks").into(),
2732 // Library search path
2733 {
2734 let mut s = OsString::from("-L");
2735 s.push(ios_support.join("usr/lib"));
2736 s
2737 },
2738 // Framework linker search path
2739 {
2740 // Technically, we _could_ avoid emitting `-F`, as
2741 // `-iframework` implies it, but let's keep it in for
2742 // clarity.
2743 let mut s = OsString::from("-F");
2744 s.push(ios_support.join("System/Library/Frameworks"));
2745 s
2746 },
2747 ]);
2748 }
2749 }
2750
2751 Ok(())
2752 }
2753
2754 fn cmd<P: AsRef<OsStr>>(&self, prog: P) -> Command {
2755 let mut cmd = Command::new(prog);
2756 for (a, b) in self.env.iter() {
2757 cmd.env(a, b);
2758 }
2759 cmd
2760 }
2761
2762 fn get_base_compiler(&self) -> Result<Tool, Error> {
2763 let out_dir = self.get_out_dir().ok();
2764 let out_dir = out_dir.as_deref();
2765
2766 if let Some(c) = &self.compiler {
2767 return Ok(Tool::new(
2768 (**c).to_owned(),
2769 &self.build_cache.cached_compiler_family,
2770 &self.cargo_output,
2771 out_dir,
2772 ));
2773 }
2774 let target = self.get_target()?;
2775 let raw_target = self.get_raw_target()?;
2776 let (env, msvc, gnu, traditional, clang) = if self.cpp {
2777 ("CXX", "cl.exe", "g++", "c++", "clang++")
2778 } else {
2779 ("CC", "cl.exe", "gcc", "cc", "clang")
2780 };
2781
2782 // On historical Solaris systems, "cc" may have been Sun Studio, which
2783 // is not flag-compatible with "gcc". This history casts a long shadow,
2784 // and many modern illumos distributions today ship GCC as "gcc" without
2785 // also making it available as "cc".
2786 let default = if cfg!(target_os = "solaris") || cfg!(target_os = "illumos") {
2787 gnu
2788 } else {
2789 traditional
2790 };
2791
2792 let cl_exe = self.windows_registry_find_tool(&target, "cl.exe");
2793
2794 let tool_opt: Option<Tool> = self
2795 .env_tool(env)
2796 .map(|(tool, wrapper, args)| {
2797 // Chop off leading/trailing whitespace to work around
2798 // semi-buggy build scripts which are shared in
2799 // makefiles/configure scripts (where spaces are far more
2800 // lenient)
2801 let mut t = Tool::with_args(
2802 tool,
2803 args.clone(),
2804 &self.build_cache.cached_compiler_family,
2805 &self.cargo_output,
2806 out_dir,
2807 );
2808 if let Some(cc_wrapper) = wrapper {
2809 t.cc_wrapper_path = Some(Path::new(&cc_wrapper).to_owned());
2810 }
2811 for arg in args {
2812 t.cc_wrapper_args.push(arg.into());
2813 }
2814 t
2815 })
2816 .or_else(|| {
2817 if target.os == "emscripten" {
2818 let tool = if self.cpp { "em++" } else { "emcc" };
2819 // Windows uses bat file so we have to be a bit more specific
2820 if cfg!(windows) {
2821 let mut t = Tool::with_family(
2822 PathBuf::from("cmd"),
2823 ToolFamily::Clang { zig_cc: false },
2824 );
2825 t.args.push("/c".into());
2826 t.args.push(format!("{}.bat", tool).into());
2827 Some(t)
2828 } else {
2829 Some(Tool::new(
2830 PathBuf::from(tool),
2831 &self.build_cache.cached_compiler_family,
2832 &self.cargo_output,
2833 out_dir,
2834 ))
2835 }
2836 } else {
2837 None
2838 }
2839 })
2840 .or_else(|| cl_exe.clone());
2841
2842 let tool = match tool_opt {
2843 Some(t) => t,
2844 None => {
2845 let compiler = if cfg!(windows) && target.os == "windows" {
2846 if target.env == "msvc" {
2847 msvc.to_string()
2848 } else {
2849 let cc = if target.abi == "llvm" { clang } else { gnu };
2850 format!("{}.exe", cc)
2851 }
2852 } else if target.os == "ios"
2853 || target.os == "watchos"
2854 || target.os == "tvos"
2855 || target.os == "visionos"
2856 {
2857 clang.to_string()
2858 } else if target.os == "android" {
2859 autodetect_android_compiler(&raw_target, gnu, clang)
2860 } else if target.os == "cloudabi" {
2861 format!(
2862 "{}-{}-{}-{}",
2863 target.full_arch, target.vendor, target.os, traditional
2864 )
2865 } else if target.arch == "wasm32" || target.arch == "wasm64" {
2866 // Compiling WASM is not currently supported by GCC, so
2867 // let's default to Clang.
2868 clang.to_string()
2869 } else if target.os == "vxworks" {
2870 if self.cpp {
2871 "wr-c++".to_string()
2872 } else {
2873 "wr-cc".to_string()
2874 }
2875 } else if target.arch == "arm" && target.vendor == "kmc" {
2876 format!("arm-kmc-eabi-{}", gnu)
2877 } else if target.arch == "aarch64" && target.vendor == "kmc" {
2878 format!("aarch64-kmc-elf-{}", gnu)
2879 } else if target.os == "nto" {
2880 // See for details: https://github.com/rust-lang/cc-rs/pull/1319
2881 if self.cpp {
2882 "q++".to_string()
2883 } else {
2884 "qcc".to_string()
2885 }
2886 } else if self.get_is_cross_compile()? {
2887 let prefix = self.prefix_for_target(&raw_target);
2888 match prefix {
2889 Some(prefix) => {
2890 let cc = if target.abi == "llvm" { clang } else { gnu };
2891 format!("{}-{}", prefix, cc)
2892 }
2893 None => default.to_string(),
2894 }
2895 } else {
2896 default.to_string()
2897 };
2898
2899 let mut t = Tool::new(
2900 PathBuf::from(compiler),
2901 &self.build_cache.cached_compiler_family,
2902 &self.cargo_output,
2903 out_dir,
2904 );
2905 if let Some(cc_wrapper) = self.rustc_wrapper_fallback() {
2906 t.cc_wrapper_path = Some(Path::new(&cc_wrapper).to_owned());
2907 }
2908 t
2909 }
2910 };
2911
2912 let mut tool = if self.cuda {
2913 assert!(
2914 tool.args.is_empty(),
2915 "CUDA compilation currently assumes empty pre-existing args"
2916 );
2917 let nvcc = match self.getenv_with_target_prefixes("NVCC") {
2918 Err(_) => PathBuf::from("nvcc"),
2919 Ok(nvcc) => PathBuf::from(&*nvcc),
2920 };
2921 let mut nvcc_tool = Tool::with_features(
2922 nvcc,
2923 vec![],
2924 self.cuda,
2925 &self.build_cache.cached_compiler_family,
2926 &self.cargo_output,
2927 out_dir,
2928 );
2929 if self.ccbin {
2930 nvcc_tool
2931 .args
2932 .push(format!("-ccbin={}", tool.path.display()).into());
2933 }
2934 if let Some(cc_wrapper) = self.rustc_wrapper_fallback() {
2935 nvcc_tool.cc_wrapper_path = Some(Path::new(&cc_wrapper).to_owned());
2936 }
2937 nvcc_tool.family = tool.family;
2938 nvcc_tool
2939 } else {
2940 tool
2941 };
2942
2943 // New "standalone" C/C++ cross-compiler executables from recent Android NDK
2944 // are just shell scripts that call main clang binary (from Android NDK) with
2945 // proper `--target` argument.
2946 //
2947 // For example, armv7a-linux-androideabi16-clang passes
2948 // `--target=armv7a-linux-androideabi16` to clang.
2949 //
2950 // As the shell script calls the main clang binary, the command line limit length
2951 // on Windows is restricted to around 8k characters instead of around 32k characters.
2952 // To remove this limit, we call the main clang binary directly and construct the
2953 // `--target=` ourselves.
2954 if cfg!(windows) && android_clang_compiler_uses_target_arg_internally(&tool.path) {
2955 if let Some(path) = tool.path.file_name() {
2956 let file_name = path.to_str().unwrap().to_owned();
2957 let (target, clang) = file_name.split_at(file_name.rfind('-').unwrap());
2958
2959 tool.has_internal_target_arg = true;
2960 tool.path.set_file_name(clang.trim_start_matches('-'));
2961 tool.path.set_extension("exe");
2962 tool.args.push(format!("--target={}", target).into());
2963
2964 // Additionally, shell scripts for target i686-linux-android versions 16 to 24
2965 // pass the `mstackrealign` option so we do that here as well.
2966 if target.contains("i686-linux-android") {
2967 let (_, version) = target.split_at(target.rfind('d').unwrap() + 1);
2968 if let Ok(version) = version.parse::<u32>() {
2969 if version > 15 && version < 25 {
2970 tool.args.push("-mstackrealign".into());
2971 }
2972 }
2973 }
2974 };
2975 }
2976
2977 // If we found `cl.exe` in our environment, the tool we're returning is
2978 // an MSVC-like tool, *and* no env vars were set then set env vars for
2979 // the tool that we're returning.
2980 //
2981 // Env vars are needed for things like `link.exe` being put into PATH as
2982 // well as header include paths sometimes. These paths are automatically
2983 // included by default but if the `CC` or `CXX` env vars are set these
2984 // won't be used. This'll ensure that when the env vars are used to
2985 // configure for invocations like `clang-cl` we still get a "works out
2986 // of the box" experience.
2987 if let Some(cl_exe) = cl_exe {
2988 if tool.family == (ToolFamily::Msvc { clang_cl: true })
2989 && tool.env.is_empty()
2990 && target.env == "msvc"
2991 {
2992 for (k, v) in cl_exe.env.iter() {
2993 tool.env.push((k.to_owned(), v.to_owned()));
2994 }
2995 }
2996 }
2997
2998 if target.env == "msvc" && tool.family == ToolFamily::Gnu {
2999 self.cargo_output
3000 .print_warning(&"GNU compiler is not supported for this target");
3001 }
3002
3003 Ok(tool)
3004 }
3005
3006 /// Returns a fallback `cc_compiler_wrapper` by introspecting `RUSTC_WRAPPER`
3007 fn rustc_wrapper_fallback(&self) -> Option<Arc<OsStr>> {
3008 // No explicit CC wrapper was detected, but check if RUSTC_WRAPPER
3009 // is defined and is a build accelerator that is compatible with
3010 // C/C++ compilers (e.g. sccache)
3011 const VALID_WRAPPERS: &[&str] = &["sccache", "cachepot", "buildcache"];
3012
3013 let rustc_wrapper = self.getenv("RUSTC_WRAPPER")?;
3014 let wrapper_path = Path::new(&rustc_wrapper);
3015 let wrapper_stem = wrapper_path.file_stem()?;
3016
3017 if VALID_WRAPPERS.contains(&wrapper_stem.to_str()?) {
3018 Some(rustc_wrapper)
3019 } else {
3020 None
3021 }
3022 }
3023
3024 /// Returns compiler path, optional modifier name from whitelist, and arguments vec
3025 fn env_tool(&self, name: &str) -> Option<(PathBuf, Option<Arc<OsStr>>, Vec<String>)> {
3026 let tool = self.getenv_with_target_prefixes(name).ok()?;
3027 let tool = tool.to_string_lossy();
3028 let tool = tool.trim();
3029
3030 if tool.is_empty() {
3031 return None;
3032 }
3033
3034 // If this is an exact path on the filesystem we don't want to do any
3035 // interpretation at all, just pass it on through. This'll hopefully get
3036 // us to support spaces-in-paths.
3037 if Path::new(tool).exists() {
3038 return Some((
3039 PathBuf::from(tool),
3040 self.rustc_wrapper_fallback(),
3041 Vec::new(),
3042 ));
3043 }
3044
3045 // Ok now we want to handle a couple of scenarios. We'll assume from
3046 // here on out that spaces are splitting separate arguments. Two major
3047 // features we want to support are:
3048 //
3049 // CC='sccache cc'
3050 //
3051 // aka using `sccache` or any other wrapper/caching-like-thing for
3052 // compilations. We want to know what the actual compiler is still,
3053 // though, because our `Tool` API support introspection of it to see
3054 // what compiler is in use.
3055 //
3056 // additionally we want to support
3057 //
3058 // CC='cc -flag'
3059 //
3060 // where the CC env var is used to also pass default flags to the C
3061 // compiler.
3062 //
3063 // It's true that everything here is a bit of a pain, but apparently if
3064 // you're not literally make or bash then you get a lot of bug reports.
3065 let mut known_wrappers = vec![
3066 "ccache",
3067 "distcc",
3068 "sccache",
3069 "icecc",
3070 "cachepot",
3071 "buildcache",
3072 ];
3073 let custom_wrapper = self.getenv("CC_KNOWN_WRAPPER_CUSTOM");
3074 if custom_wrapper.is_some() {
3075 known_wrappers.push(custom_wrapper.as_deref().unwrap().to_str().unwrap());
3076 }
3077
3078 let mut parts = tool.split_whitespace();
3079 let maybe_wrapper = parts.next()?;
3080
3081 let file_stem = Path::new(maybe_wrapper).file_stem()?.to_str()?;
3082 if known_wrappers.contains(&file_stem) {
3083 if let Some(compiler) = parts.next() {
3084 return Some((
3085 compiler.into(),
3086 Some(Arc::<OsStr>::from(OsStr::new(&maybe_wrapper))),
3087 parts.map(|s| s.to_string()).collect(),
3088 ));
3089 }
3090 }
3091
3092 Some((
3093 maybe_wrapper.into(),
3094 self.rustc_wrapper_fallback(),
3095 parts.map(|s| s.to_string()).collect(),
3096 ))
3097 }
3098
3099 /// Returns the C++ standard library:
3100 /// 1. If [`cpp_link_stdlib`](cc::Build::cpp_link_stdlib) is set, uses its value.
3101 /// 2. Else if the `CXXSTDLIB` environment variable is set, uses its value.
3102 /// 3. Else the default is `c++` for OS X and BSDs, `c++_shared` for Android,
3103 /// `None` for MSVC and `stdc++` for anything else.
3104 fn get_cpp_link_stdlib(&self) -> Result<Option<Cow<'_, Path>>, Error> {
3105 match &self.cpp_link_stdlib {
3106 Some(s) => Ok(s.as_deref().map(Path::new).map(Cow::Borrowed)),
3107 None => {
3108 if let Ok(stdlib) = self.getenv_with_target_prefixes("CXXSTDLIB") {
3109 if stdlib.is_empty() {
3110 Ok(None)
3111 } else {
3112 Ok(Some(Cow::Owned(Path::new(&stdlib).to_owned())))
3113 }
3114 } else {
3115 let target = self.get_target()?;
3116 if target.env == "msvc" {
3117 Ok(None)
3118 } else if target.vendor == "apple"
3119 || target.os == "freebsd"
3120 || target.os == "openbsd"
3121 || target.os == "aix"
3122 || (target.os == "linux" && target.env == "ohos")
3123 || target.os == "wasi"
3124 {
3125 Ok(Some(Cow::Borrowed(Path::new("c++"))))
3126 } else if target.os == "android" {
3127 Ok(Some(Cow::Borrowed(Path::new("c++_shared"))))
3128 } else {
3129 Ok(Some(Cow::Borrowed(Path::new("stdc++"))))
3130 }
3131 }
3132 }
3133 }
3134 }
3135
3136 /// Get the archiver (ar) that's in use for this configuration.
3137 ///
3138 /// You can use [`Command::get_program`] to get just the path to the command.
3139 ///
3140 /// This method will take into account all configuration such as debug
3141 /// information, optimization level, include directories, defines, etc.
3142 /// Additionally, the compiler binary in use follows the standard
3143 /// conventions for this path, e.g. looking at the explicitly set compiler,
3144 /// environment variables (a number of which are inspected here), and then
3145 /// falling back to the default configuration.
3146 ///
3147 /// # Panics
3148 ///
3149 /// Panics if an error occurred while determining the architecture.
3150 pub fn get_archiver(&self) -> Command {
3151 match self.try_get_archiver() {
3152 Ok(tool) => tool,
3153 Err(e) => fail(&e.message),
3154 }
3155 }
3156
3157 /// Get the archiver that's in use for this configuration.
3158 ///
3159 /// This will return a result instead of panicking;
3160 /// see [`Self::get_archiver`] for the complete description.
3161 pub fn try_get_archiver(&self) -> Result<Command, Error> {
3162 Ok(self.try_get_archiver_and_flags()?.0)
3163 }
3164
3165 fn try_get_archiver_and_flags(&self) -> Result<(Command, PathBuf, bool), Error> {
3166 let (mut cmd, name) = self.get_base_archiver()?;
3167 let mut any_flags = false;
3168 if let Some(flags) = self.envflags("ARFLAGS")? {
3169 any_flags = true;
3170 cmd.args(flags);
3171 }
3172 for flag in &self.ar_flags {
3173 any_flags = true;
3174 cmd.arg(&**flag);
3175 }
3176 Ok((cmd, name, any_flags))
3177 }
3178
3179 fn get_base_archiver(&self) -> Result<(Command, PathBuf), Error> {
3180 if let Some(ref a) = self.archiver {
3181 let archiver = &**a;
3182 return Ok((self.cmd(archiver), archiver.into()));
3183 }
3184
3185 self.get_base_archiver_variant("AR", "ar")
3186 }
3187
3188 /// Get the ranlib that's in use for this configuration.
3189 ///
3190 /// You can use [`Command::get_program`] to get just the path to the command.
3191 ///
3192 /// This method will take into account all configuration such as debug
3193 /// information, optimization level, include directories, defines, etc.
3194 /// Additionally, the compiler binary in use follows the standard
3195 /// conventions for this path, e.g. looking at the explicitly set compiler,
3196 /// environment variables (a number of which are inspected here), and then
3197 /// falling back to the default configuration.
3198 ///
3199 /// # Panics
3200 ///
3201 /// Panics if an error occurred while determining the architecture.
3202 pub fn get_ranlib(&self) -> Command {
3203 match self.try_get_ranlib() {
3204 Ok(tool) => tool,
3205 Err(e) => fail(&e.message),
3206 }
3207 }
3208
3209 /// Get the ranlib that's in use for this configuration.
3210 ///
3211 /// This will return a result instead of panicking;
3212 /// see [`Self::get_ranlib`] for the complete description.
3213 pub fn try_get_ranlib(&self) -> Result<Command, Error> {
3214 let mut cmd = self.get_base_ranlib()?;
3215 if let Some(flags) = self.envflags("RANLIBFLAGS")? {
3216 cmd.args(flags);
3217 }
3218 Ok(cmd)
3219 }
3220
3221 fn get_base_ranlib(&self) -> Result<Command, Error> {
3222 if let Some(ref r) = self.ranlib {
3223 return Ok(self.cmd(&**r));
3224 }
3225
3226 Ok(self.get_base_archiver_variant("RANLIB", "ranlib")?.0)
3227 }
3228
3229 fn get_base_archiver_variant(
3230 &self,
3231 env: &str,
3232 tool: &str,
3233 ) -> Result<(Command, PathBuf), Error> {
3234 let target = self.get_target()?;
3235 let mut name = PathBuf::new();
3236 let tool_opt: Option<Command> = self
3237 .env_tool(env)
3238 .map(|(tool, _wrapper, args)| {
3239 name.clone_from(&tool);
3240 let mut cmd = self.cmd(tool);
3241 cmd.args(args);
3242 cmd
3243 })
3244 .or_else(|| {
3245 if target.os == "emscripten" {
3246 // Windows use bat files so we have to be a bit more specific
3247 if cfg!(windows) {
3248 let mut cmd = self.cmd("cmd");
3249 name = format!("em{}.bat", tool).into();
3250 cmd.arg("/c").arg(&name);
3251 Some(cmd)
3252 } else {
3253 name = format!("em{}", tool).into();
3254 Some(self.cmd(&name))
3255 }
3256 } else if target.arch == "wasm32" || target.arch == "wasm64" {
3257 // Formally speaking one should be able to use this approach,
3258 // parsing -print-search-dirs output, to cover all clang targets,
3259 // including Android SDKs and other cross-compilation scenarios...
3260 // And even extend it to gcc targets by searching for "ar" instead
3261 // of "llvm-ar"...
3262 let compiler = self.get_base_compiler().ok()?;
3263 if compiler.is_like_clang() {
3264 name = format!("llvm-{}", tool).into();
3265 self.search_programs(
3266 &mut self.cmd(&compiler.path),
3267 &name,
3268 &self.cargo_output,
3269 )
3270 .map(|name| self.cmd(name))
3271 } else {
3272 None
3273 }
3274 } else {
3275 None
3276 }
3277 });
3278
3279 let tool = match tool_opt {
3280 Some(t) => t,
3281 None => {
3282 if target.os == "android" {
3283 name = format!("llvm-{}", tool).into();
3284 match Command::new(&name).arg("--version").status() {
3285 Ok(status) if status.success() => (),
3286 _ => {
3287 // FIXME: Use parsed target.
3288 let raw_target = self.get_raw_target()?;
3289 name = format!("{}-{}", raw_target.replace("armv7", "arm"), tool).into()
3290 }
3291 }
3292 self.cmd(&name)
3293 } else if target.env == "msvc" {
3294 // NOTE: There isn't really a ranlib on msvc, so arguably we should return
3295 // `None` somehow here. But in general, callers will already have to be aware
3296 // of not running ranlib on Windows anyway, so it feels okay to return lib.exe
3297 // here.
3298
3299 let compiler = self.get_base_compiler()?;
3300 let mut lib = String::new();
3301 if compiler.family == (ToolFamily::Msvc { clang_cl: true }) {
3302 // See if there is 'llvm-lib' next to 'clang-cl'
3303 // Another possibility could be to see if there is 'clang'
3304 // next to 'clang-cl' and use 'search_programs()' to locate
3305 // 'llvm-lib'. This is because 'clang-cl' doesn't support
3306 // the -print-search-dirs option.
3307 if let Some(mut cmd) = self.which(&compiler.path, None) {
3308 cmd.pop();
3309 cmd.push("llvm-lib.exe");
3310 if let Some(llvm_lib) = self.which(&cmd, None) {
3311 llvm_lib.to_str().unwrap().clone_into(&mut lib);
3312 }
3313 }
3314 }
3315
3316 if lib.is_empty() {
3317 name = PathBuf::from("lib.exe");
3318 let mut cmd = match self.windows_registry_find(&target, "lib.exe") {
3319 Some(t) => t,
3320 None => self.cmd("lib.exe"),
3321 };
3322 if target.full_arch == "arm64ec" {
3323 cmd.arg("/machine:arm64ec");
3324 }
3325 cmd
3326 } else {
3327 name = lib.into();
3328 self.cmd(&name)
3329 }
3330 } else if target.os == "illumos" {
3331 // The default 'ar' on illumos uses a non-standard flags,
3332 // but the OS comes bundled with a GNU-compatible variant.
3333 //
3334 // Use the GNU-variant to match other Unix systems.
3335 name = format!("g{}", tool).into();
3336 self.cmd(&name)
3337 } else if self.get_is_cross_compile()? {
3338 match self.prefix_for_target(&self.get_raw_target()?) {
3339 Some(prefix) => {
3340 // GCC uses $target-gcc-ar, whereas binutils uses $target-ar -- try both.
3341 // Prefer -ar if it exists, as builds of `-gcc-ar` have been observed to be
3342 // outright broken (such as when targeting freebsd with `--disable-lto`
3343 // toolchain where the archiver attempts to load the LTO plugin anyway but
3344 // fails to find one).
3345 //
3346 // The same applies to ranlib.
3347 let chosen = ["", "-gcc"]
3348 .iter()
3349 .filter_map(|infix| {
3350 let target_p = format!("{prefix}{infix}-{tool}");
3351 let status = Command::new(&target_p)
3352 .arg("--version")
3353 .stdin(Stdio::null())
3354 .stdout(Stdio::null())
3355 .stderr(Stdio::null())
3356 .status()
3357 .ok()?;
3358 status.success().then_some(target_p)
3359 })
3360 .next()
3361 .unwrap_or_else(|| tool.to_string());
3362 name = chosen.into();
3363 self.cmd(&name)
3364 }
3365 None => {
3366 name = tool.into();
3367 self.cmd(&name)
3368 }
3369 }
3370 } else {
3371 name = tool.into();
3372 self.cmd(&name)
3373 }
3374 }
3375 };
3376
3377 Ok((tool, name))
3378 }
3379
3380 // FIXME: Use parsed target instead of raw target.
3381 fn prefix_for_target(&self, target: &str) -> Option<Cow<'static, str>> {
3382 // CROSS_COMPILE is of the form: "arm-linux-gnueabi-"
3383 self.getenv("CROSS_COMPILE")
3384 .as_deref()
3385 .map(|s| s.to_string_lossy().trim_end_matches('-').to_owned())
3386 .map(Cow::Owned)
3387 .or_else(|| {
3388 // Put aside RUSTC_LINKER's prefix to be used as second choice, after CROSS_COMPILE
3389 self.getenv("RUSTC_LINKER").and_then(|var| {
3390 var.to_string_lossy()
3391 .strip_suffix("-gcc")
3392 .map(str::to_string)
3393 .map(Cow::Owned)
3394 })
3395 })
3396 .or_else(|| {
3397 match target {
3398 // Note: there is no `aarch64-pc-windows-gnu` target, only `-gnullvm`
3399 "aarch64-pc-windows-gnullvm" => Some("aarch64-w64-mingw32"),
3400 "aarch64-uwp-windows-gnu" => Some("aarch64-w64-mingw32"),
3401 "aarch64-unknown-linux-gnu" => Some("aarch64-linux-gnu"),
3402 "aarch64-unknown-linux-musl" => Some("aarch64-linux-musl"),
3403 "aarch64-unknown-netbsd" => Some("aarch64--netbsd"),
3404 "arm-unknown-linux-gnueabi" => Some("arm-linux-gnueabi"),
3405 "armv4t-unknown-linux-gnueabi" => Some("arm-linux-gnueabi"),
3406 "armv5te-unknown-linux-gnueabi" => Some("arm-linux-gnueabi"),
3407 "armv5te-unknown-linux-musleabi" => Some("arm-linux-gnueabi"),
3408 "arm-unknown-linux-gnueabihf" => Some("arm-linux-gnueabihf"),
3409 "arm-unknown-linux-musleabi" => Some("arm-linux-musleabi"),
3410 "arm-unknown-linux-musleabihf" => Some("arm-linux-musleabihf"),
3411 "arm-unknown-netbsd-eabi" => Some("arm--netbsdelf-eabi"),
3412 "armv6-unknown-netbsd-eabihf" => Some("armv6--netbsdelf-eabihf"),
3413 "armv7-unknown-linux-gnueabi" => Some("arm-linux-gnueabi"),
3414 "armv7-unknown-linux-gnueabihf" => Some("arm-linux-gnueabihf"),
3415 "armv7-unknown-linux-musleabihf" => Some("arm-linux-musleabihf"),
3416 "armv7neon-unknown-linux-gnueabihf" => Some("arm-linux-gnueabihf"),
3417 "armv7neon-unknown-linux-musleabihf" => Some("arm-linux-musleabihf"),
3418 "thumbv7-unknown-linux-gnueabihf" => Some("arm-linux-gnueabihf"),
3419 "thumbv7-unknown-linux-musleabihf" => Some("arm-linux-musleabihf"),
3420 "thumbv7neon-unknown-linux-gnueabihf" => Some("arm-linux-gnueabihf"),
3421 "thumbv7neon-unknown-linux-musleabihf" => Some("arm-linux-musleabihf"),
3422 "armv7-unknown-netbsd-eabihf" => Some("armv7--netbsdelf-eabihf"),
3423 "hexagon-unknown-linux-musl" => Some("hexagon-linux-musl"),
3424 "i586-unknown-linux-musl" => Some("musl"),
3425 "i686-pc-windows-gnu" => Some("i686-w64-mingw32"),
3426 "i686-pc-windows-gnullvm" => Some("i686-w64-mingw32"),
3427 "i686-uwp-windows-gnu" => Some("i686-w64-mingw32"),
3428 "i686-unknown-linux-gnu" => self.find_working_gnu_prefix(&[
3429 "i686-linux-gnu",
3430 "x86_64-linux-gnu", // transparently support gcc-multilib
3431 ]), // explicit None if not found, so caller knows to fall back
3432 "i686-unknown-linux-musl" => Some("musl"),
3433 "i686-unknown-netbsd" => Some("i486--netbsdelf"),
3434 "loongarch64-unknown-linux-gnu" => Some("loongarch64-linux-gnu"),
3435 "mips-unknown-linux-gnu" => Some("mips-linux-gnu"),
3436 "mips-unknown-linux-musl" => Some("mips-linux-musl"),
3437 "mipsel-unknown-linux-gnu" => Some("mipsel-linux-gnu"),
3438 "mipsel-unknown-linux-musl" => Some("mipsel-linux-musl"),
3439 "mips64-unknown-linux-gnuabi64" => Some("mips64-linux-gnuabi64"),
3440 "mips64el-unknown-linux-gnuabi64" => Some("mips64el-linux-gnuabi64"),
3441 "mipsisa32r6-unknown-linux-gnu" => Some("mipsisa32r6-linux-gnu"),
3442 "mipsisa32r6el-unknown-linux-gnu" => Some("mipsisa32r6el-linux-gnu"),
3443 "mipsisa64r6-unknown-linux-gnuabi64" => Some("mipsisa64r6-linux-gnuabi64"),
3444 "mipsisa64r6el-unknown-linux-gnuabi64" => Some("mipsisa64r6el-linux-gnuabi64"),
3445 "powerpc-unknown-linux-gnu" => Some("powerpc-linux-gnu"),
3446 "powerpc-unknown-linux-gnuspe" => Some("powerpc-linux-gnuspe"),
3447 "powerpc-unknown-netbsd" => Some("powerpc--netbsd"),
3448 "powerpc64-unknown-linux-gnu" => Some("powerpc-linux-gnu"),
3449 "powerpc64le-unknown-linux-gnu" => Some("powerpc64le-linux-gnu"),
3450 "riscv32i-unknown-none-elf" => self.find_working_gnu_prefix(&[
3451 "riscv32-unknown-elf",
3452 "riscv64-unknown-elf",
3453 "riscv-none-embed",
3454 ]),
3455 "riscv32imac-esp-espidf" => Some("riscv32-esp-elf"),
3456 "riscv32imac-unknown-none-elf" => self.find_working_gnu_prefix(&[
3457 "riscv32-unknown-elf",
3458 "riscv64-unknown-elf",
3459 "riscv-none-embed",
3460 ]),
3461 "riscv32imac-unknown-xous-elf" => self.find_working_gnu_prefix(&[
3462 "riscv32-unknown-elf",
3463 "riscv64-unknown-elf",
3464 "riscv-none-embed",
3465 ]),
3466 "riscv32imc-esp-espidf" => Some("riscv32-esp-elf"),
3467 "riscv32imc-unknown-none-elf" => self.find_working_gnu_prefix(&[
3468 "riscv32-unknown-elf",
3469 "riscv64-unknown-elf",
3470 "riscv-none-embed",
3471 ]),
3472 "riscv64gc-unknown-none-elf" => self.find_working_gnu_prefix(&[
3473 "riscv64-unknown-elf",
3474 "riscv32-unknown-elf",
3475 "riscv-none-embed",
3476 ]),
3477 "riscv64imac-unknown-none-elf" => self.find_working_gnu_prefix(&[
3478 "riscv64-unknown-elf",
3479 "riscv32-unknown-elf",
3480 "riscv-none-embed",
3481 ]),
3482 "riscv64gc-unknown-linux-gnu" => Some("riscv64-linux-gnu"),
3483 "riscv32gc-unknown-linux-gnu" => Some("riscv32-linux-gnu"),
3484 "riscv64gc-unknown-linux-musl" => Some("riscv64-linux-musl"),
3485 "riscv32gc-unknown-linux-musl" => Some("riscv32-linux-musl"),
3486 "riscv64gc-unknown-netbsd" => Some("riscv64--netbsd"),
3487 "s390x-unknown-linux-gnu" => Some("s390x-linux-gnu"),
3488 "sparc-unknown-linux-gnu" => Some("sparc-linux-gnu"),
3489 "sparc64-unknown-linux-gnu" => Some("sparc64-linux-gnu"),
3490 "sparc64-unknown-netbsd" => Some("sparc64--netbsd"),
3491 "sparcv9-sun-solaris" => Some("sparcv9-sun-solaris"),
3492 "armv7a-none-eabi" => Some("arm-none-eabi"),
3493 "armv7a-none-eabihf" => Some("arm-none-eabi"),
3494 "armebv7r-none-eabi" => Some("arm-none-eabi"),
3495 "armebv7r-none-eabihf" => Some("arm-none-eabi"),
3496 "armv7r-none-eabi" => Some("arm-none-eabi"),
3497 "armv7r-none-eabihf" => Some("arm-none-eabi"),
3498 "armv8r-none-eabihf" => Some("arm-none-eabi"),
3499 "thumbv6m-none-eabi" => Some("arm-none-eabi"),
3500 "thumbv7em-none-eabi" => Some("arm-none-eabi"),
3501 "thumbv7em-none-eabihf" => Some("arm-none-eabi"),
3502 "thumbv7m-none-eabi" => Some("arm-none-eabi"),
3503 "thumbv8m.base-none-eabi" => Some("arm-none-eabi"),
3504 "thumbv8m.main-none-eabi" => Some("arm-none-eabi"),
3505 "thumbv8m.main-none-eabihf" => Some("arm-none-eabi"),
3506 "x86_64-pc-windows-gnu" => Some("x86_64-w64-mingw32"),
3507 "x86_64-pc-windows-gnullvm" => Some("x86_64-w64-mingw32"),
3508 "x86_64-uwp-windows-gnu" => Some("x86_64-w64-mingw32"),
3509 "x86_64-rumprun-netbsd" => Some("x86_64-rumprun-netbsd"),
3510 "x86_64-unknown-linux-gnu" => self.find_working_gnu_prefix(&[
3511 "x86_64-linux-gnu", // rustfmt wrap
3512 ]), // explicit None if not found, so caller knows to fall back
3513 "x86_64-unknown-linux-musl" => {
3514 self.find_working_gnu_prefix(&["x86_64-linux-musl", "musl"])
3515 }
3516 "x86_64-unknown-netbsd" => Some("x86_64--netbsd"),
3517 _ => None,
3518 }
3519 .map(Cow::Borrowed)
3520 })
3521 }
3522
3523 /// Some platforms have multiple, compatible, canonical prefixes. Look through
3524 /// each possible prefix for a compiler that exists and return it. The prefixes
3525 /// should be ordered from most-likely to least-likely.
3526 fn find_working_gnu_prefix(&self, prefixes: &[&'static str]) -> Option<&'static str> {
3527 let suffix = if self.cpp { "-g++" } else { "-gcc" };
3528 let extension = std::env::consts::EXE_SUFFIX;
3529
3530 // Loop through PATH entries searching for each toolchain. This ensures that we
3531 // are more likely to discover the toolchain early on, because chances are good
3532 // that the desired toolchain is in one of the higher-priority paths.
3533 self.getenv("PATH")
3534 .as_ref()
3535 .and_then(|path_entries| {
3536 env::split_paths(path_entries).find_map(|path_entry| {
3537 for prefix in prefixes {
3538 let target_compiler = format!("{}{}{}", prefix, suffix, extension);
3539 if path_entry.join(&target_compiler).exists() {
3540 return Some(prefix);
3541 }
3542 }
3543 None
3544 })
3545 })
3546 .copied()
3547 // If no toolchain was found, provide the first toolchain that was passed in.
3548 // This toolchain has been shown not to exist, however it will appear in the
3549 // error that is shown to the user which should make it easier to search for
3550 // where it should be obtained.
3551 .or_else(|| prefixes.first().copied())
3552 }
3553
3554 fn get_target(&self) -> Result<TargetInfo<'_>, Error> {
3555 match &self.target {
3556 Some(t) if Some(&**t) != self.getenv_unwrap_str("TARGET").ok().as_deref() => {
3557 TargetInfo::from_rustc_target(t)
3558 }
3559 // Fetch target information from environment if not set, or if the
3560 // target was the same as the TARGET environment variable, in
3561 // case the user did `build.target(&env::var("TARGET").unwrap())`.
3562 _ => self
3563 .build_cache
3564 .target_info_parser
3565 .parse_from_cargo_environment_variables(),
3566 }
3567 }
3568
3569 fn get_raw_target(&self) -> Result<Cow<'_, str>, Error> {
3570 match &self.target {
3571 Some(t) => Ok(Cow::Borrowed(t)),
3572 None => self.getenv_unwrap_str("TARGET").map(Cow::Owned),
3573 }
3574 }
3575
3576 fn get_is_cross_compile(&self) -> Result<bool, Error> {
3577 let target = self.get_raw_target()?;
3578 let host: Cow<'_, str> = match &self.host {
3579 Some(h) => Cow::Borrowed(h),
3580 None => Cow::Owned(self.getenv_unwrap_str("HOST")?),
3581 };
3582 Ok(host != target)
3583 }
3584
3585 fn get_opt_level(&self) -> Result<Cow<'_, str>, Error> {
3586 match &self.opt_level {
3587 Some(ol) => Ok(Cow::Borrowed(ol)),
3588 None => self.getenv_unwrap_str("OPT_LEVEL").map(Cow::Owned),
3589 }
3590 }
3591
3592 fn get_debug(&self) -> bool {
3593 self.debug.unwrap_or_else(|| self.getenv_boolean("DEBUG"))
3594 }
3595
3596 fn get_shell_escaped_flags(&self) -> bool {
3597 self.shell_escaped_flags
3598 .unwrap_or_else(|| self.getenv_boolean("CC_SHELL_ESCAPED_FLAGS"))
3599 }
3600
3601 fn get_dwarf_version(&self) -> Option<u32> {
3602 // Tentatively matches the DWARF version defaults as of rustc 1.62.
3603 let target = self.get_target().ok()?;
3604 if matches!(
3605 target.os,
3606 "android" | "dragonfly" | "freebsd" | "netbsd" | "openbsd"
3607 ) || target.vendor == "apple"
3608 || (target.os == "windows" && target.env == "gnu")
3609 {
3610 Some(2)
3611 } else if target.os == "linux" {
3612 Some(4)
3613 } else {
3614 None
3615 }
3616 }
3617
3618 fn get_force_frame_pointer(&self) -> bool {
3619 self.force_frame_pointer.unwrap_or_else(|| self.get_debug())
3620 }
3621
3622 fn get_out_dir(&self) -> Result<Cow<'_, Path>, Error> {
3623 match &self.out_dir {
3624 Some(p) => Ok(Cow::Borrowed(&**p)),
3625 None => self
3626 .getenv("OUT_DIR")
3627 .as_deref()
3628 .map(PathBuf::from)
3629 .map(Cow::Owned)
3630 .ok_or_else(|| {
3631 Error::new(
3632 ErrorKind::EnvVarNotFound,
3633 "Environment variable OUT_DIR not defined.",
3634 )
3635 }),
3636 }
3637 }
3638
3639 #[allow(clippy::disallowed_methods)]
3640 fn getenv(&self, v: &str) -> Option<Arc<OsStr>> {
3641 // Returns true for environment variables cargo sets for build scripts:
3642 // https://doc.rust-lang.org/cargo/reference/environment-variables.html#environment-variables-cargo-sets-for-build-scripts
3643 //
3644 // This handles more of the vars than we actually use (it tries to check
3645 // complete-ish set), just to avoid needing maintenance if/when new
3646 // calls to `getenv`/`getenv_unwrap` are added.
3647 fn provided_by_cargo(envvar: &str) -> bool {
3648 match envvar {
3649 v if v.starts_with("CARGO") || v.starts_with("RUSTC") => true,
3650 "HOST" | "TARGET" | "RUSTDOC" | "OUT_DIR" | "OPT_LEVEL" | "DEBUG" | "PROFILE"
3651 | "NUM_JOBS" | "RUSTFLAGS" => true,
3652 _ => false,
3653 }
3654 }
3655 if let Some(val) = self.build_cache.env_cache.read().unwrap().get(v).cloned() {
3656 return val;
3657 }
3658 // Excluding `PATH` prevents spurious rebuilds on Windows, see
3659 // <https://github.com/rust-lang/cc-rs/pull/1215> for details.
3660 if self.emit_rerun_if_env_changed && !provided_by_cargo(v) && v != "PATH" {
3661 self.cargo_output
3662 .print_metadata(&format_args!("cargo:rerun-if-env-changed={}", v));
3663 }
3664 let r = env::var_os(v).map(Arc::from);
3665 self.cargo_output.print_metadata(&format_args!(
3666 "{} = {}",
3667 v,
3668 OptionOsStrDisplay(r.as_deref())
3669 ));
3670 self.build_cache
3671 .env_cache
3672 .write()
3673 .unwrap()
3674 .insert(v.into(), r.clone());
3675 r
3676 }
3677
3678 /// get boolean flag that is either true or false
3679 fn getenv_boolean(&self, v: &str) -> bool {
3680 match self.getenv(v) {
3681 Some(s) => &*s != "0" && &*s != "false" && !s.is_empty(),
3682 None => false,
3683 }
3684 }
3685
3686 fn getenv_unwrap(&self, v: &str) -> Result<Arc<OsStr>, Error> {
3687 match self.getenv(v) {
3688 Some(s) => Ok(s),
3689 None => Err(Error::new(
3690 ErrorKind::EnvVarNotFound,
3691 format!("Environment variable {} not defined.", v),
3692 )),
3693 }
3694 }
3695
3696 fn getenv_unwrap_str(&self, v: &str) -> Result<String, Error> {
3697 let env = self.getenv_unwrap(v)?;
3698 env.to_str().map(String::from).ok_or_else(|| {
3699 Error::new(
3700 ErrorKind::EnvVarNotFound,
3701 format!("Environment variable {} is not valid utf-8.", v),
3702 )
3703 })
3704 }
3705
3706 /// The list of environment variables to check for a given env, in order of priority.
3707 fn target_envs(&self, env: &str) -> Result<[String; 4], Error> {
3708 let target = self.get_raw_target()?;
3709 let kind = if self.get_is_cross_compile()? {
3710 "TARGET"
3711 } else {
3712 "HOST"
3713 };
3714 let target_u = target.replace('-', "_");
3715
3716 Ok([
3717 format!("{env}_{target}"),
3718 format!("{env}_{target_u}"),
3719 format!("{kind}_{env}"),
3720 env.to_string(),
3721 ])
3722 }
3723
3724 /// Get a single-valued environment variable with target variants.
3725 fn getenv_with_target_prefixes(&self, env: &str) -> Result<Arc<OsStr>, Error> {
3726 // Take from first environment variable in the environment.
3727 let res = self
3728 .target_envs(env)?
3729 .iter()
3730 .filter_map(|env| self.getenv(env))
3731 .next();
3732
3733 match res {
3734 Some(res) => Ok(res),
3735 None => Err(Error::new(
3736 ErrorKind::EnvVarNotFound,
3737 format!("could not find environment variable {env}"),
3738 )),
3739 }
3740 }
3741
3742 /// Get values from CFLAGS-style environment variable.
3743 fn envflags(&self, env: &str) -> Result<Option<Vec<String>>, Error> {
3744 // Collect from all environment variables, in reverse order as in
3745 // `getenv_with_target_prefixes` precedence (so that `CFLAGS_$TARGET`
3746 // can override flags in `TARGET_CFLAGS`, which overrides those in
3747 // `CFLAGS`).
3748 let mut any_set = false;
3749 let mut res = vec![];
3750 for env in self.target_envs(env)?.iter().rev() {
3751 if let Some(var) = self.getenv(env) {
3752 any_set = true;
3753
3754 let var = var.to_string_lossy();
3755 if self.get_shell_escaped_flags() {
3756 res.extend(Shlex::new(&var));
3757 } else {
3758 res.extend(var.split_ascii_whitespace().map(ToString::to_string));
3759 }
3760 }
3761 }
3762
3763 Ok(if any_set { Some(res) } else { None })
3764 }
3765
3766 fn fix_env_for_apple_os(&self, cmd: &mut Command) -> Result<(), Error> {
3767 let target = self.get_target()?;
3768 if cfg!(target_os = "macos") && target.os == "macos" {
3769 // Additionally, `IPHONEOS_DEPLOYMENT_TARGET` must not be set when using the Xcode linker at
3770 // "/Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/ld",
3771 // although this is apparently ignored when using the linker at "/usr/bin/ld".
3772 cmd.env_remove("IPHONEOS_DEPLOYMENT_TARGET");
3773 }
3774 Ok(())
3775 }
3776
3777 fn apple_sdk_root_inner(&self, sdk: &str) -> Result<Arc<OsStr>, Error> {
3778 // Code copied from rustc's compiler/rustc_codegen_ssa/src/back/link.rs.
3779 if let Some(sdkroot) = self.getenv("SDKROOT") {
3780 let p = Path::new(&sdkroot);
3781 let does_sdkroot_contain = |strings: &[&str]| {
3782 let sdkroot_str = p.to_string_lossy();
3783 strings.iter().any(|s| sdkroot_str.contains(s))
3784 };
3785 match sdk {
3786 // Ignore `SDKROOT` if it's clearly set for the wrong platform.
3787 "appletvos"
3788 if does_sdkroot_contain(&["TVSimulator.platform", "MacOSX.platform"]) => {}
3789 "appletvsimulator"
3790 if does_sdkroot_contain(&["TVOS.platform", "MacOSX.platform"]) => {}
3791 "iphoneos"
3792 if does_sdkroot_contain(&["iPhoneSimulator.platform", "MacOSX.platform"]) => {}
3793 "iphonesimulator"
3794 if does_sdkroot_contain(&["iPhoneOS.platform", "MacOSX.platform"]) => {}
3795 "macosx10.15"
3796 if does_sdkroot_contain(&["iPhoneOS.platform", "iPhoneSimulator.platform"]) => {
3797 }
3798 "watchos"
3799 if does_sdkroot_contain(&["WatchSimulator.platform", "MacOSX.platform"]) => {}
3800 "watchsimulator"
3801 if does_sdkroot_contain(&["WatchOS.platform", "MacOSX.platform"]) => {}
3802 "xros" if does_sdkroot_contain(&["XRSimulator.platform", "MacOSX.platform"]) => {}
3803 "xrsimulator" if does_sdkroot_contain(&["XROS.platform", "MacOSX.platform"]) => {}
3804 // Ignore `SDKROOT` if it's not a valid path.
3805 _ if !p.is_absolute() || p == Path::new("/") || !p.exists() => {}
3806 _ => return Ok(sdkroot),
3807 }
3808 }
3809
3810 let sdk_path = run_output(
3811 self.cmd("xcrun")
3812 .arg("--show-sdk-path")
3813 .arg("--sdk")
3814 .arg(sdk),
3815 &self.cargo_output,
3816 )?;
3817
3818 let sdk_path = match String::from_utf8(sdk_path) {
3819 Ok(p) => p,
3820 Err(_) => {
3821 return Err(Error::new(
3822 ErrorKind::IOError,
3823 "Unable to determine Apple SDK path.",
3824 ));
3825 }
3826 };
3827 Ok(Arc::from(OsStr::new(sdk_path.trim())))
3828 }
3829
3830 fn apple_sdk_root(&self, target: &TargetInfo<'_>) -> Result<Arc<OsStr>, Error> {
3831 let sdk = target.apple_sdk_name();
3832
3833 if let Some(ret) = self
3834 .build_cache
3835 .apple_sdk_root_cache
3836 .read()
3837 .expect("apple_sdk_root_cache lock failed")
3838 .get(sdk)
3839 .cloned()
3840 {
3841 return Ok(ret);
3842 }
3843 let sdk_path = self.apple_sdk_root_inner(sdk)?;
3844 self.build_cache
3845 .apple_sdk_root_cache
3846 .write()
3847 .expect("apple_sdk_root_cache lock failed")
3848 .insert(sdk.into(), sdk_path.clone());
3849 Ok(sdk_path)
3850 }
3851
3852 fn apple_deployment_target(&self, target: &TargetInfo<'_>) -> Arc<str> {
3853 let sdk = target.apple_sdk_name();
3854 if let Some(ret) = self
3855 .build_cache
3856 .apple_versions_cache
3857 .read()
3858 .expect("apple_versions_cache lock failed")
3859 .get(sdk)
3860 .cloned()
3861 {
3862 return ret;
3863 }
3864
3865 let default_deployment_from_sdk = || -> Option<Arc<str>> {
3866 let version = run_output(
3867 self.cmd("xcrun")
3868 .arg("--show-sdk-version")
3869 .arg("--sdk")
3870 .arg(sdk),
3871 &self.cargo_output,
3872 )
3873 .ok()?;
3874
3875 Some(Arc::from(std::str::from_utf8(&version).ok()?.trim()))
3876 };
3877
3878 let deployment_from_env = |name: &str| -> Option<Arc<str>> {
3879 // note that self.env isn't hit in production codepaths, its mostly just for tests which don't
3880 // set the real env
3881 self.env
3882 .iter()
3883 .find(|(k, _)| &**k == OsStr::new(name))
3884 .map(|(_, v)| v)
3885 .cloned()
3886 .or_else(|| self.getenv(name))?
3887 .to_str()
3888 .map(Arc::from)
3889 };
3890
3891 // Determines if the acquired deployment target is too low to support modern C++ on some Apple platform.
3892 //
3893 // 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.
3894 // If a `cc`` config wants to use C++, we round up to these versions as the baseline.
3895 let maybe_cpp_version_baseline = |deployment_target_ver: Arc<str>| -> Option<Arc<str>> {
3896 if !self.cpp {
3897 return Some(deployment_target_ver);
3898 }
3899
3900 let mut deployment_target = deployment_target_ver
3901 .split('.')
3902 .map(|v| v.parse::<u32>().expect("integer version"));
3903
3904 match target.os {
3905 "macos" => {
3906 let major = deployment_target.next().unwrap_or(0);
3907 let minor = deployment_target.next().unwrap_or(0);
3908
3909 // If below 10.9, we ignore it and let the SDK's target definitions handle it.
3910 if major == 10 && minor < 9 {
3911 self.cargo_output.print_warning(&format_args!(
3912 "macOS deployment target ({}) too low, it will be increased",
3913 deployment_target_ver
3914 ));
3915 return None;
3916 }
3917 }
3918 "ios" => {
3919 let major = deployment_target.next().unwrap_or(0);
3920
3921 // If below 10.7, we ignore it and let the SDK's target definitions handle it.
3922 if major < 7 {
3923 self.cargo_output.print_warning(&format_args!(
3924 "iOS deployment target ({}) too low, it will be increased",
3925 deployment_target_ver
3926 ));
3927 return None;
3928 }
3929 }
3930 // watchOS, tvOS, visionOS, and others are all new enough that libc++ is their baseline.
3931 _ => {}
3932 }
3933
3934 // If the deployment target met or exceeded the C++ baseline
3935 Some(deployment_target_ver)
3936 };
3937
3938 // The hardcoded minimums here are subject to change in a future compiler release,
3939 // and only exist as last resort fallbacks. Don't consider them stable.
3940 // `cc` doesn't use rustc's `--print deployment-target`` because the compiler's defaults
3941 // don't align well with Apple's SDKs and other third-party libraries that require ~generally~ higher
3942 // deployment targets. rustc isn't interested in those by default though so its fine to be different here.
3943 //
3944 // If no explicit target is passed, `cc` defaults to the current Xcode SDK's `DefaultDeploymentTarget` for better
3945 // compatibility. This is also the crate's historical behavior and what has become a relied-on value.
3946 //
3947 // The ordering of env -> XCode SDK -> old rustc defaults is intentional for performance when using
3948 // an explicit target.
3949 let version: Arc<str> = match target.os {
3950 "macos" => deployment_from_env("MACOSX_DEPLOYMENT_TARGET")
3951 .and_then(maybe_cpp_version_baseline)
3952 .or_else(default_deployment_from_sdk)
3953 .unwrap_or_else(|| {
3954 if target.arch == "aarch64" {
3955 "11.0".into()
3956 } else {
3957 let default: Arc<str> = Arc::from("10.7");
3958 maybe_cpp_version_baseline(default.clone()).unwrap_or(default)
3959 }
3960 }),
3961
3962 "ios" => deployment_from_env("IPHONEOS_DEPLOYMENT_TARGET")
3963 .and_then(maybe_cpp_version_baseline)
3964 .or_else(default_deployment_from_sdk)
3965 .unwrap_or_else(|| "7.0".into()),
3966
3967 "watchos" => deployment_from_env("WATCHOS_DEPLOYMENT_TARGET")
3968 .or_else(default_deployment_from_sdk)
3969 .unwrap_or_else(|| "5.0".into()),
3970
3971 "tvos" => deployment_from_env("TVOS_DEPLOYMENT_TARGET")
3972 .or_else(default_deployment_from_sdk)
3973 .unwrap_or_else(|| "9.0".into()),
3974
3975 "visionos" => deployment_from_env("XROS_DEPLOYMENT_TARGET")
3976 .or_else(default_deployment_from_sdk)
3977 .unwrap_or_else(|| "1.0".into()),
3978
3979 os => unreachable!("unknown Apple OS: {}", os),
3980 };
3981
3982 self.build_cache
3983 .apple_versions_cache
3984 .write()
3985 .expect("apple_versions_cache lock failed")
3986 .insert(sdk.into(), version.clone());
3987
3988 version
3989 }
3990
3991 fn wasm_musl_sysroot(&self) -> Result<Arc<OsStr>, Error> {
3992 if let Some(musl_sysroot_path) = self.getenv("WASM_MUSL_SYSROOT") {
3993 Ok(musl_sysroot_path)
3994 } else {
3995 Err(Error::new(
3996 ErrorKind::EnvVarNotFound,
3997 "Environment variable WASM_MUSL_SYSROOT not defined for wasm32. Download sysroot from GitHub & setup environment variable MUSL_SYSROOT targeting the folder.",
3998 ))
3999 }
4000 }
4001
4002 fn wasi_sysroot(&self) -> Result<Arc<OsStr>, Error> {
4003 if let Some(wasi_sysroot_path) = self.getenv("WASI_SYSROOT") {
4004 Ok(wasi_sysroot_path)
4005 } else {
4006 Err(Error::new(
4007 ErrorKind::EnvVarNotFound,
4008 "Environment variable WASI_SYSROOT not defined. Download sysroot from GitHub & setup environment variable WASI_SYSROOT targeting the folder.",
4009 ))
4010 }
4011 }
4012
4013 fn cuda_file_count(&self) -> usize {
4014 self.files
4015 .iter()
4016 .filter(|file| file.extension() == Some(OsStr::new("cu")))
4017 .count()
4018 }
4019
4020 fn which(&self, tool: &Path, path_entries: Option<&OsStr>) -> Option<PathBuf> {
4021 fn check_exe(mut exe: PathBuf) -> Option<PathBuf> {
4022 let exe_ext = std::env::consts::EXE_EXTENSION;
4023 let check =
4024 exe.exists() || (!exe_ext.is_empty() && exe.set_extension(exe_ext) && exe.exists());
4025 check.then_some(exe)
4026 }
4027
4028 // Loop through PATH entries searching for the |tool|.
4029 let find_exe_in_path = |path_entries: &OsStr| -> Option<PathBuf> {
4030 env::split_paths(path_entries).find_map(|path_entry| check_exe(path_entry.join(tool)))
4031 };
4032
4033 // If |tool| is not just one "word," assume it's an actual path...
4034 if tool.components().count() > 1 {
4035 check_exe(PathBuf::from(tool))
4036 } else {
4037 path_entries
4038 .and_then(find_exe_in_path)
4039 .or_else(|| find_exe_in_path(&self.getenv("PATH")?))
4040 }
4041 }
4042
4043 /// search for |prog| on 'programs' path in '|cc| -print-search-dirs' output
4044 fn search_programs(
4045 &self,
4046 cc: &mut Command,
4047 prog: &Path,
4048 cargo_output: &CargoOutput,
4049 ) -> Option<PathBuf> {
4050 let search_dirs = run_output(
4051 cc.arg("-print-search-dirs"),
4052 // this doesn't concern the compilation so we always want to show warnings.
4053 cargo_output,
4054 )
4055 .ok()?;
4056 // clang driver appears to be forcing UTF-8 output even on Windows,
4057 // hence from_utf8 is assumed to be usable in all cases.
4058 let search_dirs = std::str::from_utf8(&search_dirs).ok()?;
4059 for dirs in search_dirs.split(['\r', '\n']) {
4060 if let Some(path) = dirs.strip_prefix("programs: =") {
4061 return self.which(prog, Some(OsStr::new(path)));
4062 }
4063 }
4064 None
4065 }
4066
4067 fn windows_registry_find(&self, target: &TargetInfo<'_>, tool: &str) -> Option<Command> {
4068 self.windows_registry_find_tool(target, tool)
4069 .map(|c| c.to_command())
4070 }
4071
4072 fn windows_registry_find_tool(&self, target: &TargetInfo<'_>, tool: &str) -> Option<Tool> {
4073 struct BuildEnvGetter<'s>(&'s Build);
4074
4075 impl windows_registry::EnvGetter for BuildEnvGetter<'_> {
4076 fn get_env(&self, name: &str) -> Option<windows_registry::Env> {
4077 self.0.getenv(name).map(windows_registry::Env::Arced)
4078 }
4079 }
4080
4081 if target.env != "msvc" {
4082 return None;
4083 }
4084
4085 windows_registry::find_tool_inner(target.full_arch, tool, &BuildEnvGetter(self))
4086 }
4087}
4088
4089impl Default for Build {
4090 fn default() -> Build {
4091 Build::new()
4092 }
4093}
4094
4095fn fail(s: &str) -> ! {
4096 eprintln!("\n\nerror occurred in cc-rs: {}\n\n", s);
4097 std::process::exit(1);
4098}
4099
4100// Use by default minimum available API level
4101// See note about naming here
4102// https://android.googlesource.com/platform/ndk/+/refs/heads/ndk-release-r21/docs/BuildSystemMaintainers.md#Clang
4103static NEW_STANDALONE_ANDROID_COMPILERS: [&str; 4] = [
4104 "aarch64-linux-android21-clang",
4105 "armv7a-linux-androideabi16-clang",
4106 "i686-linux-android16-clang",
4107 "x86_64-linux-android21-clang",
4108];
4109
4110// New "standalone" C/C++ cross-compiler executables from recent Android NDK
4111// are just shell scripts that call main clang binary (from Android NDK) with
4112// proper `--target` argument.
4113//
4114// For example, armv7a-linux-androideabi16-clang passes
4115// `--target=armv7a-linux-androideabi16` to clang.
4116// So to construct proper command line check if
4117// `--target` argument would be passed or not to clang
4118fn android_clang_compiler_uses_target_arg_internally(clang_path: &Path) -> bool {
4119 if let Some(filename) = clang_path.file_name() {
4120 if let Some(filename_str) = filename.to_str() {
4121 if let Some(idx) = filename_str.rfind('-') {
4122 return filename_str.split_at(idx).0.contains("android");
4123 }
4124 }
4125 }
4126 false
4127}
4128
4129// FIXME: Use parsed target.
4130fn autodetect_android_compiler(raw_target: &str, gnu: &str, clang: &str) -> String {
4131 let new_clang_key = match raw_target {
4132 "aarch64-linux-android" => Some("aarch64"),
4133 "armv7-linux-androideabi" => Some("armv7a"),
4134 "i686-linux-android" => Some("i686"),
4135 "x86_64-linux-android" => Some("x86_64"),
4136 _ => None,
4137 };
4138
4139 let new_clang = new_clang_key
4140 .map(|key| {
4141 NEW_STANDALONE_ANDROID_COMPILERS
4142 .iter()
4143 .find(|x| x.starts_with(key))
4144 })
4145 .unwrap_or(None);
4146
4147 if let Some(new_clang) = new_clang {
4148 if Command::new(new_clang).output().is_ok() {
4149 return (*new_clang).into();
4150 }
4151 }
4152
4153 let target = raw_target
4154 .replace("armv7neon", "arm")
4155 .replace("armv7", "arm")
4156 .replace("thumbv7neon", "arm")
4157 .replace("thumbv7", "arm");
4158 let gnu_compiler = format!("{}-{}", target, gnu);
4159 let clang_compiler = format!("{}-{}", target, clang);
4160
4161 // On Windows, the Android clang compiler is provided as a `.cmd` file instead
4162 // of a `.exe` file. `std::process::Command` won't run `.cmd` files unless the
4163 // `.cmd` is explicitly appended to the command name, so we do that here.
4164 let clang_compiler_cmd = format!("{}-{}.cmd", target, clang);
4165
4166 // Check if gnu compiler is present
4167 // if not, use clang
4168 if Command::new(&gnu_compiler).output().is_ok() {
4169 gnu_compiler
4170 } else if cfg!(windows) && Command::new(&clang_compiler_cmd).output().is_ok() {
4171 clang_compiler_cmd
4172 } else {
4173 clang_compiler
4174 }
4175}
4176
4177// Rust and clang/cc don't agree on how to name the target.
4178fn map_darwin_target_from_rust_to_compiler_architecture<'a>(target: &TargetInfo<'a>) -> &'a str {
4179 match target.full_arch {
4180 "aarch64" => "arm64",
4181 "arm64_32" => "arm64_32",
4182 "arm64e" => "arm64e",
4183 "armv7k" => "armv7k",
4184 "armv7s" => "armv7s",
4185 "i386" => "i386",
4186 "i686" => "i386",
4187 "powerpc" => "ppc",
4188 "powerpc64" => "ppc64",
4189 "x86_64" => "x86_64",
4190 "x86_64h" => "x86_64h",
4191 arch => arch,
4192 }
4193}
4194
4195#[derive(Clone, Copy, PartialEq)]
4196enum AsmFileExt {
4197 /// `.asm` files. On MSVC targets, we assume these should be passed to MASM
4198 /// (`ml{,64}.exe`).
4199 DotAsm,
4200 /// `.s` or `.S` files, which do not have the special handling on MSVC targets.
4201 DotS,
4202}
4203
4204impl AsmFileExt {
4205 fn from_path(file: &Path) -> Option<Self> {
4206 if let Some(ext) = file.extension() {
4207 if let Some(ext) = ext.to_str() {
4208 let ext = ext.to_lowercase();
4209 match &*ext {
4210 "asm" => return Some(AsmFileExt::DotAsm),
4211 "s" => return Some(AsmFileExt::DotS),
4212 _ => return None,
4213 }
4214 }
4215 }
4216 None
4217 }
4218}
4219
4220/// Returns true if `cc` has been disabled by `CC_FORCE_DISABLE`.
4221fn is_disabled() -> bool {
4222 static CACHE: AtomicU8 = AtomicU8::new(0);
4223
4224 let val = CACHE.load(Relaxed);
4225 // We manually cache the environment var, since we need it in some places
4226 // where we don't have access to a `Build` instance.
4227 #[allow(clippy::disallowed_methods)]
4228 fn compute_is_disabled() -> bool {
4229 match std::env::var_os("CC_FORCE_DISABLE") {
4230 // Not set? Not disabled.
4231 None => false,
4232 // Respect `CC_FORCE_DISABLE=0` and some simple synonyms, otherwise
4233 // we're disabled. This intentionally includes `CC_FORCE_DISABLE=""`
4234 Some(v) => &*v != "0" && &*v != "false" && &*v != "no",
4235 }
4236 }
4237 match val {
4238 2 => true,
4239 1 => false,
4240 0 => {
4241 let truth = compute_is_disabled();
4242 let encoded_truth = if truth { 2u8 } else { 1 };
4243 // Might race against another thread, but we'd both be setting the
4244 // same value so it should be fine.
4245 CACHE.store(encoded_truth, Relaxed);
4246 truth
4247 }
4248 _ => unreachable!(),
4249 }
4250}
4251
4252/// Automates the `if is_disabled() { return error }` check and ensures
4253/// we produce a consistent error message for it.
4254fn check_disabled() -> Result<(), Error> {
4255 if is_disabled() {
4256 return Err(Error::new(
4257 ErrorKind::Disabled,
4258 "the `cc` crate's functionality has been disabled by the `CC_FORCE_DISABLE` environment variable."
4259 ));
4260 }
4261 Ok(())
4262}
4263
4264#[cfg(test)]
4265mod tests {
4266 use super::*;
4267
4268 #[test]
4269 fn test_android_clang_compiler_uses_target_arg_internally() {
4270 for version in 16..21 {
4271 assert!(android_clang_compiler_uses_target_arg_internally(
4272 &PathBuf::from(format!("armv7a-linux-androideabi{}-clang", version))
4273 ));
4274 assert!(android_clang_compiler_uses_target_arg_internally(
4275 &PathBuf::from(format!("armv7a-linux-androideabi{}-clang++", version))
4276 ));
4277 }
4278 assert!(!android_clang_compiler_uses_target_arg_internally(
4279 &PathBuf::from("clang-i686-linux-android")
4280 ));
4281 assert!(!android_clang_compiler_uses_target_arg_internally(
4282 &PathBuf::from("clang")
4283 ));
4284 assert!(!android_clang_compiler_uses_target_arg_internally(
4285 &PathBuf::from("clang++")
4286 ));
4287 }
4288}