Debian Codegraph @

.cargo/vendor/cc/src/lib.rs

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