Debian Codegraph @

third_party/rust/cc/src/lib.rs

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