1 //! A library for build scripts to compile custom C code
2 //!
3 //! This library is intended to be used as a `build-dependencies` entry in
4 //! `Cargo.toml`:
5 //!
6 //! ```toml
7 //! [build-dependencies]
8 //! cc = "1.0"
9 //! ```
10 //!
11 //! The purpose of this crate is to provide the utility functions necessary to
12 //! compile C code into a static archive which is then linked into a Rust crate.
13 //! Configuration is available through the `Build` struct.
14 //!
15 //! This crate will automatically detect situations such as cross compilation or
16 //! other environment variables set by Cargo and will build code appropriately.
17 //!
18 //! The crate is not limited to C code, it can accept any source code that can
19 //! be passed to a C or C++ compiler. As such, assembly files with extensions
20 //! `.s` (gcc/clang) and `.asm` (MSVC) can also be compiled.
21 //!
22 //! [`Build`]: struct.Build.html
23 //!
24 //! # Parallelism
25 //!
26 //! To parallelize computation, enable the `parallel` feature for the crate.
27 //!
28 //! ```toml
29 //! [build-dependencies]
30 //! cc = { version = "1.0", features = ["parallel"] }
31 //! ```
32 //! To specify the max number of concurrent compilation jobs, set the `NUM_JOBS`
33 //! environment variable to the desired amount.
34 //!
35 //! Cargo will also set this environment variable when executed with the `-jN` flag.
36 //!
37 //! If `NUM_JOBS` is not set, the `RAYON_NUM_THREADS` environment variable can
38 //! also specify the build parallelism.
39 //!
40 //! # Examples
41 //!
42 //! Use the `Build` struct to compile `src/foo.c`:
43 //!
44 //! ```no_run
45 //! fn main() {
46 //! cc::Build::new()
47 //! .file("src/foo.c")
48 //! .define("FOO", Some("bar"))
49 //! .include("src")
50 //! .compile("foo");
51 //! }
52 //! ```
53
54 #![doc(html_root_url = "https://docs.rs/cc/1.0")]
55 #![cfg_attr(test, deny(warnings))]
56 #![allow(deprecated)]
57 #![deny(missing_docs)]
58
59 use std::collections::HashMap;
60 use std::env;
61 use std::ffi::{OsStr, OsString};
62 use std::fmt::{self, Display};
63 use std::fs;
64 use std::io::{self, BufRead, BufReader, Read, Write};
65 use std::path::{Path, PathBuf};
66 use std::process::{Child, Command, Stdio};
67 use std::sync::{Arc, Mutex};
68 use std::thread::{self, JoinHandle};
69
70 // These modules are all glue to support reading the MSVC version from
71 // the registry and from COM interfaces
72 #[cfg(windows)]
73 mod registry;
74 #[cfg(windows)]
75 #[macro_use]
76 mod winapi;
77 #[cfg(windows)]
78 mod com;
79 #[cfg(windows)]
80 mod setup_config;
81 #[cfg(windows)]
82 mod vs_instances;
83
84 pub mod windows_registry;
85
86 /// A builder for compilation of a native library.
87 ///
88 /// A `Build` is the main type of the `cc` crate and is used to control all the
89 /// various configuration options and such of a compile. You'll find more
90 /// documentation on each method itself.
91 #[derive(Clone, Debug)]
92 pub struct Build {
93 include_directories: Vec<PathBuf>,
94 definitions: Vec<(String, Option<String>)>,
95 objects: Vec<PathBuf>,
96 flags: Vec<String>,
97 flags_supported: Vec<String>,
98 known_flag_support_status: Arc<Mutex<HashMap<String, bool>>>,
99 ar_flags: Vec<String>,
100 no_default_flags: bool,
101 files: Vec<PathBuf>,
102 cpp: bool,
103 cpp_link_stdlib: Option<Option<String>>,
104 cpp_set_stdlib: Option<String>,
105 cuda: bool,
106 cudart: Option<String>,
107 target: Option<String>,
108 host: Option<String>,
109 out_dir: Option<PathBuf>,
110 opt_level: Option<String>,
111 debug: Option<bool>,
112 force_frame_pointer: Option<bool>,
113 env: Vec<(OsString, OsString)>,
114 compiler: Option<PathBuf>,
115 archiver: Option<PathBuf>,
116 cargo_metadata: bool,
117 pic: Option<bool>,
118 use_plt: Option<bool>,
119 static_crt: Option<bool>,
120 shared_flag: Option<bool>,
121 static_flag: Option<bool>,
122 warnings_into_errors: bool,
123 warnings: Option<bool>,
124 extra_warnings: Option<bool>,
125 env_cache: Arc<Mutex<HashMap<String, Option<String>>>>,
126 apple_sdk_root_cache: Arc<Mutex<HashMap<String, OsString>>>,
127 }
128
129 /// Represents the types of errors that may occur while using cc-rs.
130 #[derive(Clone, Debug)]
131 enum ErrorKind {
132 /// Error occurred while performing I/O.
133 IOError,
134 /// Invalid architecture supplied.
135 ArchitectureInvalid,
136 /// Environment variable not found, with the var in question as extra info.
137 EnvVarNotFound,
138 /// Error occurred while using external tools (ie: invocation of compiler).
139 ToolExecError,
140 /// Error occurred due to missing external tools.
141 ToolNotFound,
142 }
143
144 /// Represents an internal error that occurred, with an explanation.
145 #[derive(Clone, Debug)]
146 pub struct Error {
147 /// Describes the kind of error that occurred.
148 kind: ErrorKind,
149 /// More explanation of error that occurred.
150 message: String,
151 }
152
153 impl Error {
new(kind: ErrorKind, message: &str) -> Error154 fn new(kind: ErrorKind, message: &str) -> Error {
155 Error {
156 kind: kind,
157 message: message.to_owned(),
158 }
159 }
160 }
161
162 impl From<io::Error> for Error {
from(e: io::Error) -> Error163 fn from(e: io::Error) -> Error {
164 Error::new(ErrorKind::IOError, &format!("{}", e))
165 }
166 }
167
168 impl Display for Error {
fmt(&self, f: &mut fmt::Formatter) -> fmt::Result169 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
170 write!(f, "{:?}: {}", self.kind, self.message)
171 }
172 }
173
174 impl std::error::Error for Error {}
175
176 /// Configuration used to represent an invocation of a C compiler.
177 ///
178 /// This can be used to figure out what compiler is in use, what the arguments
179 /// to it are, and what the environment variables look like for the compiler.
180 /// This can be used to further configure other build systems (e.g. forward
181 /// along CC and/or CFLAGS) or the `to_command` method can be used to run the
182 /// compiler itself.
183 #[derive(Clone, Debug)]
184 pub struct Tool {
185 path: PathBuf,
186 cc_wrapper_path: Option<PathBuf>,
187 cc_wrapper_args: Vec<OsString>,
188 args: Vec<OsString>,
189 env: Vec<(OsString, OsString)>,
190 family: ToolFamily,
191 cuda: bool,
192 removed_args: Vec<OsString>,
193 }
194
195 /// Represents the family of tools this tool belongs to.
196 ///
197 /// Each family of tools differs in how and what arguments they accept.
198 ///
199 /// Detection of a family is done on best-effort basis and may not accurately reflect the tool.
200 #[derive(Copy, Clone, Debug, PartialEq)]
201 enum ToolFamily {
202 /// Tool is GNU Compiler Collection-like.
203 Gnu,
204 /// Tool is Clang-like. It differs from the GCC in a sense that it accepts superset of flags
205 /// and its cross-compilation approach is different.
206 Clang,
207 /// Tool is the MSVC cl.exe.
208 Msvc { clang_cl: bool },
209 }
210
211 impl ToolFamily {
212 /// What the flag to request debug info for this family of tools look like
add_debug_flags(&self, cmd: &mut Tool)213 fn add_debug_flags(&self, cmd: &mut Tool) {
214 match *self {
215 ToolFamily::Msvc { .. } => {
216 cmd.push_cc_arg("-Z7".into());
217 }
218 ToolFamily::Gnu | ToolFamily::Clang => {
219 cmd.push_cc_arg("-g".into());
220 }
221 }
222 }
223
224 /// What the flag to force frame pointers.
add_force_frame_pointer(&self, cmd: &mut Tool)225 fn add_force_frame_pointer(&self, cmd: &mut Tool) {
226 match *self {
227 ToolFamily::Gnu | ToolFamily::Clang => {
228 cmd.push_cc_arg("-fno-omit-frame-pointer".into());
229 }
230 _ => (),
231 }
232 }
233
234 /// What the flags to enable all warnings
warnings_flags(&self) -> &'static str235 fn warnings_flags(&self) -> &'static str {
236 match *self {
237 ToolFamily::Msvc { .. } => "-W4",
238 ToolFamily::Gnu | ToolFamily::Clang => "-Wall",
239 }
240 }
241
242 /// What the flags to enable extra warnings
extra_warnings_flags(&self) -> Option<&'static str>243 fn extra_warnings_flags(&self) -> Option<&'static str> {
244 match *self {
245 ToolFamily::Msvc { .. } => None,
246 ToolFamily::Gnu | ToolFamily::Clang => Some("-Wextra"),
247 }
248 }
249
250 /// What the flag to turn warning into errors
warnings_to_errors_flag(&self) -> &'static str251 fn warnings_to_errors_flag(&self) -> &'static str {
252 match *self {
253 ToolFamily::Msvc { .. } => "-WX",
254 ToolFamily::Gnu | ToolFamily::Clang => "-Werror",
255 }
256 }
257
verbose_stderr(&self) -> bool258 fn verbose_stderr(&self) -> bool {
259 *self == ToolFamily::Clang
260 }
261 }
262
263 /// Represents an object.
264 ///
265 /// This is a source file -> object file pair.
266 #[derive(Clone, Debug)]
267 struct Object {
268 src: PathBuf,
269 dst: PathBuf,
270 }
271
272 impl Object {
273 /// Create a new source file -> object file pair.
new(src: PathBuf, dst: PathBuf) -> Object274 fn new(src: PathBuf, dst: PathBuf) -> Object {
275 Object { src: src, dst: dst }
276 }
277 }
278
279 impl Build {
280 /// Construct a new instance of a blank set of configuration.
281 ///
282 /// This builder is finished with the [`compile`] function.
283 ///
284 /// [`compile`]: struct.Build.html#method.compile
new() -> Build285 pub fn new() -> Build {
286 Build {
287 include_directories: Vec::new(),
288 definitions: Vec::new(),
289 objects: Vec::new(),
290 flags: Vec::new(),
291 flags_supported: Vec::new(),
292 known_flag_support_status: Arc::new(Mutex::new(HashMap::new())),
293 ar_flags: Vec::new(),
294 no_default_flags: false,
295 files: Vec::new(),
296 shared_flag: None,
297 static_flag: None,
298 cpp: false,
299 cpp_link_stdlib: None,
300 cpp_set_stdlib: None,
301 cuda: false,
302 cudart: None,
303 target: None,
304 host: None,
305 out_dir: None,
306 opt_level: None,
307 debug: None,
308 force_frame_pointer: None,
309 env: Vec::new(),
310 compiler: None,
311 archiver: None,
312 cargo_metadata: true,
313 pic: None,
314 use_plt: None,
315 static_crt: None,
316 warnings: None,
317 extra_warnings: None,
318 warnings_into_errors: false,
319 env_cache: Arc::new(Mutex::new(HashMap::new())),
320 apple_sdk_root_cache: Arc::new(Mutex::new(HashMap::new())),
321 }
322 }
323
324 /// Add a directory to the `-I` or include path for headers
325 ///
326 /// # Example
327 ///
328 /// ```no_run
329 /// use std::path::Path;
330 ///
331 /// let library_path = Path::new("/path/to/library");
332 ///
333 /// cc::Build::new()
334 /// .file("src/foo.c")
335 /// .include(library_path)
336 /// .include("src")
337 /// .compile("foo");
338 /// ```
include<P: AsRef<Path>>(&mut self, dir: P) -> &mut Build339 pub fn include<P: AsRef<Path>>(&mut self, dir: P) -> &mut Build {
340 self.include_directories.push(dir.as_ref().to_path_buf());
341 self
342 }
343
344 /// Add multiple directories to the `-I` include path.
345 ///
346 /// # Example
347 ///
348 /// ```no_run
349 /// # use std::path::Path;
350 /// # let condition = true;
351 /// #
352 /// let mut extra_dir = None;
353 /// if condition {
354 /// extra_dir = Some(Path::new("/path/to"));
355 /// }
356 ///
357 /// cc::Build::new()
358 /// .file("src/foo.c")
359 /// .includes(extra_dir)
360 /// .compile("foo");
361 /// ```
includes<P>(&mut self, dirs: P) -> &mut Build where P: IntoIterator, P::Item: AsRef<Path>,362 pub fn includes<P>(&mut self, dirs: P) -> &mut Build
363 where
364 P: IntoIterator,
365 P::Item: AsRef<Path>,
366 {
367 for dir in dirs {
368 self.include(dir);
369 }
370 self
371 }
372
373 /// Specify a `-D` variable with an optional value.
374 ///
375 /// # Example
376 ///
377 /// ```no_run
378 /// cc::Build::new()
379 /// .file("src/foo.c")
380 /// .define("FOO", "BAR")
381 /// .define("BAZ", None)
382 /// .compile("foo");
383 /// ```
define<'a, V: Into<Option<&'a str>>>(&mut self, var: &str, val: V) -> &mut Build384 pub fn define<'a, V: Into<Option<&'a str>>>(&mut self, var: &str, val: V) -> &mut Build {
385 self.definitions
386 .push((var.to_string(), val.into().map(|s| s.to_string())));
387 self
388 }
389
390 /// Add an arbitrary object file to link in
object<P: AsRef<Path>>(&mut self, obj: P) -> &mut Build391 pub fn object<P: AsRef<Path>>(&mut self, obj: P) -> &mut Build {
392 self.objects.push(obj.as_ref().to_path_buf());
393 self
394 }
395
396 /// Add an arbitrary flag to the invocation of the compiler
397 ///
398 /// # Example
399 ///
400 /// ```no_run
401 /// cc::Build::new()
402 /// .file("src/foo.c")
403 /// .flag("-ffunction-sections")
404 /// .compile("foo");
405 /// ```
flag(&mut self, flag: &str) -> &mut Build406 pub fn flag(&mut self, flag: &str) -> &mut Build {
407 self.flags.push(flag.to_string());
408 self
409 }
410
411 /// Add an arbitrary flag to the invocation of the compiler
412 ///
413 /// # Example
414 ///
415 /// ```no_run
416 /// cc::Build::new()
417 /// .file("src/foo.c")
418 /// .file("src/bar.c")
419 /// .ar_flag("/NODEFAULTLIB:libc.dll")
420 /// .compile("foo");
421 /// ```
422
ar_flag(&mut self, flag: &str) -> &mut Build423 pub fn ar_flag(&mut self, flag: &str) -> &mut Build {
424 self.ar_flags.push(flag.to_string());
425 self
426 }
427
ensure_check_file(&self) -> Result<PathBuf, Error>428 fn ensure_check_file(&self) -> Result<PathBuf, Error> {
429 let out_dir = self.get_out_dir()?;
430 let src = if self.cuda {
431 assert!(self.cpp);
432 out_dir.join("flag_check.cu")
433 } else if self.cpp {
434 out_dir.join("flag_check.cpp")
435 } else {
436 out_dir.join("flag_check.c")
437 };
438
439 if !src.exists() {
440 let mut f = fs::File::create(&src)?;
441 write!(f, "int main(void) {{ return 0; }}")?;
442 }
443
444 Ok(src)
445 }
446
447 /// Run the compiler to test if it accepts the given flag.
448 ///
449 /// For a convenience method for setting flags conditionally,
450 /// see `flag_if_supported()`.
451 ///
452 /// It may return error if it's unable to run the compiler with a test file
453 /// (e.g. the compiler is missing or a write to the `out_dir` failed).
454 ///
455 /// Note: Once computed, the result of this call is stored in the
456 /// `known_flag_support` field. If `is_flag_supported(flag)`
457 /// is called again, the result will be read from the hash table.
is_flag_supported(&self, flag: &str) -> Result<bool, Error>458 pub fn is_flag_supported(&self, flag: &str) -> Result<bool, Error> {
459 let mut known_status = self.known_flag_support_status.lock().unwrap();
460 if let Some(is_supported) = known_status.get(flag).cloned() {
461 return Ok(is_supported);
462 }
463
464 let out_dir = self.get_out_dir()?;
465 let src = self.ensure_check_file()?;
466 let obj = out_dir.join("flag_check");
467 let target = self.get_target()?;
468 let host = self.get_host()?;
469 let mut cfg = Build::new();
470 cfg.flag(flag)
471 .target(&target)
472 .opt_level(0)
473 .host(&host)
474 .debug(false)
475 .cpp(self.cpp)
476 .cuda(self.cuda);
477 let mut compiler = cfg.try_get_compiler()?;
478
479 // Clang uses stderr for verbose output, which yields a false positive
480 // result if the CFLAGS/CXXFLAGS include -v to aid in debugging.
481 if compiler.family.verbose_stderr() {
482 compiler.remove_arg("-v".into());
483 }
484
485 let mut cmd = compiler.to_command();
486 let is_arm = target.contains("aarch64") || target.contains("arm");
487 let clang = compiler.family == ToolFamily::Clang;
488 command_add_output_file(
489 &mut cmd,
490 &obj,
491 self.cuda,
492 target.contains("msvc"),
493 clang,
494 false,
495 is_arm,
496 );
497
498 // We need to explicitly tell msvc not to link and create an exe
499 // in the root directory of the crate
500 if target.contains("msvc") && !self.cuda {
501 cmd.arg("-c");
502 }
503
504 cmd.arg(&src);
505
506 let output = cmd.output()?;
507 let is_supported = output.stderr.is_empty();
508
509 known_status.insert(flag.to_owned(), is_supported);
510 Ok(is_supported)
511 }
512
513 /// Add an arbitrary flag to the invocation of the compiler if it supports it
514 ///
515 /// # Example
516 ///
517 /// ```no_run
518 /// cc::Build::new()
519 /// .file("src/foo.c")
520 /// .flag_if_supported("-Wlogical-op") // only supported by GCC
521 /// .flag_if_supported("-Wunreachable-code") // only supported by clang
522 /// .compile("foo");
523 /// ```
flag_if_supported(&mut self, flag: &str) -> &mut Build524 pub fn flag_if_supported(&mut self, flag: &str) -> &mut Build {
525 self.flags_supported.push(flag.to_string());
526 self
527 }
528
529 /// Set the `-shared` flag.
530 ///
531 /// When enabled, the compiler will produce a shared object which can
532 /// then be linked with other objects to form an executable.
533 ///
534 /// # Example
535 ///
536 /// ```no_run
537 /// cc::Build::new()
538 /// .file("src/foo.c")
539 /// .shared_flag(true)
540 /// .compile("libfoo.so");
541 /// ```
shared_flag(&mut self, shared_flag: bool) -> &mut Build542 pub fn shared_flag(&mut self, shared_flag: bool) -> &mut Build {
543 self.shared_flag = Some(shared_flag);
544 self
545 }
546
547 /// Set the `-static` flag.
548 ///
549 /// When enabled on systems that support dynamic linking, this prevents
550 /// linking with the shared libraries.
551 ///
552 /// # Example
553 ///
554 /// ```no_run
555 /// cc::Build::new()
556 /// .file("src/foo.c")
557 /// .shared_flag(true)
558 /// .static_flag(true)
559 /// .compile("foo");
560 /// ```
static_flag(&mut self, static_flag: bool) -> &mut Build561 pub fn static_flag(&mut self, static_flag: bool) -> &mut Build {
562 self.static_flag = Some(static_flag);
563 self
564 }
565
566 /// Disables the generation of default compiler flags. The default compiler
567 /// flags may cause conflicts in some cross compiling scenarios.
568 ///
569 /// Setting the `CRATE_CC_NO_DEFAULTS` environment variable has the same
570 /// effect as setting this to `true`. The presence of the environment
571 /// variable and the value of `no_default_flags` will be OR'd together.
no_default_flags(&mut self, no_default_flags: bool) -> &mut Build572 pub fn no_default_flags(&mut self, no_default_flags: bool) -> &mut Build {
573 self.no_default_flags = no_default_flags;
574 self
575 }
576
577 /// Add a file which will be compiled
file<P: AsRef<Path>>(&mut self, p: P) -> &mut Build578 pub fn file<P: AsRef<Path>>(&mut self, p: P) -> &mut Build {
579 self.files.push(p.as_ref().to_path_buf());
580 self
581 }
582
583 /// Add files which will be compiled
files<P>(&mut self, p: P) -> &mut Build where P: IntoIterator, P::Item: AsRef<Path>,584 pub fn files<P>(&mut self, p: P) -> &mut Build
585 where
586 P: IntoIterator,
587 P::Item: AsRef<Path>,
588 {
589 for file in p.into_iter() {
590 self.file(file);
591 }
592 self
593 }
594
595 /// Set C++ support.
596 ///
597 /// The other `cpp_*` options will only become active if this is set to
598 /// `true`.
cpp(&mut self, cpp: bool) -> &mut Build599 pub fn cpp(&mut self, cpp: bool) -> &mut Build {
600 self.cpp = cpp;
601 self
602 }
603
604 /// Set CUDA C++ support.
605 ///
606 /// Enabling CUDA will pass the detected C/C++ toolchain as an argument to
607 /// the CUDA compiler, NVCC. NVCC itself accepts some limited GNU-like args;
608 /// any other arguments for the C/C++ toolchain will be redirected using
609 /// "-Xcompiler" flags.
610 ///
611 /// If enabled, this also implicitly enables C++ support.
cuda(&mut self, cuda: bool) -> &mut Build612 pub fn cuda(&mut self, cuda: bool) -> &mut Build {
613 self.cuda = cuda;
614 if cuda {
615 self.cpp = true;
616 self.cudart = Some("static".to_string());
617 }
618 self
619 }
620
621 /// Link CUDA run-time.
622 ///
623 /// This option mimics the `--cudart` NVCC command-line option. Just like
624 /// the original it accepts `{none|shared|static}`, with default being
625 /// `static`. The method has to be invoked after `.cuda(true)`, or not
626 /// at all, if the default is right for the project.
cudart(&mut self, cudart: &str) -> &mut Build627 pub fn cudart(&mut self, cudart: &str) -> &mut Build {
628 if self.cuda {
629 self.cudart = Some(cudart.to_string());
630 }
631 self
632 }
633
634 /// Set warnings into errors flag.
635 ///
636 /// Disabled by default.
637 ///
638 /// Warning: turning warnings into errors only make sense
639 /// if you are a developer of the crate using cc-rs.
640 /// Some warnings only appear on some architecture or
641 /// specific version of the compiler. Any user of this crate,
642 /// or any other crate depending on it, could fail during
643 /// compile time.
644 ///
645 /// # Example
646 ///
647 /// ```no_run
648 /// cc::Build::new()
649 /// .file("src/foo.c")
650 /// .warnings_into_errors(true)
651 /// .compile("libfoo.a");
652 /// ```
warnings_into_errors(&mut self, warnings_into_errors: bool) -> &mut Build653 pub fn warnings_into_errors(&mut self, warnings_into_errors: bool) -> &mut Build {
654 self.warnings_into_errors = warnings_into_errors;
655 self
656 }
657
658 /// Set warnings flags.
659 ///
660 /// Adds some flags:
661 /// - "-Wall" for MSVC.
662 /// - "-Wall", "-Wextra" for GNU and Clang.
663 ///
664 /// Enabled by default.
665 ///
666 /// # Example
667 ///
668 /// ```no_run
669 /// cc::Build::new()
670 /// .file("src/foo.c")
671 /// .warnings(false)
672 /// .compile("libfoo.a");
673 /// ```
warnings(&mut self, warnings: bool) -> &mut Build674 pub fn warnings(&mut self, warnings: bool) -> &mut Build {
675 self.warnings = Some(warnings);
676 self.extra_warnings = Some(warnings);
677 self
678 }
679
680 /// Set extra warnings flags.
681 ///
682 /// Adds some flags:
683 /// - nothing for MSVC.
684 /// - "-Wextra" for GNU and Clang.
685 ///
686 /// Enabled by default.
687 ///
688 /// # Example
689 ///
690 /// ```no_run
691 /// // Disables -Wextra, -Wall remains enabled:
692 /// cc::Build::new()
693 /// .file("src/foo.c")
694 /// .extra_warnings(false)
695 /// .compile("libfoo.a");
696 /// ```
extra_warnings(&mut self, warnings: bool) -> &mut Build697 pub fn extra_warnings(&mut self, warnings: bool) -> &mut Build {
698 self.extra_warnings = Some(warnings);
699 self
700 }
701
702 /// Set the standard library to link against when compiling with C++
703 /// support.
704 ///
705 /// See [`get_cpp_link_stdlib`](cc::Build::get_cpp_link_stdlib) documentation
706 /// for the default value.
707 /// If the `CXXSTDLIB` environment variable is set, its value will
708 /// override the default value, but not the value explicitly set by calling
709 /// this function.
710 ///
711 /// A value of `None` indicates that no automatic linking should happen,
712 /// otherwise cargo will link against the specified library.
713 ///
714 /// The given library name must not contain the `lib` prefix.
715 ///
716 /// Common values:
717 /// - `stdc++` for GNU
718 /// - `c++` for Clang
719 /// - `c++_shared` or `c++_static` for Android
720 ///
721 /// # Example
722 ///
723 /// ```no_run
724 /// cc::Build::new()
725 /// .file("src/foo.c")
726 /// .shared_flag(true)
727 /// .cpp_link_stdlib("stdc++")
728 /// .compile("libfoo.so");
729 /// ```
cpp_link_stdlib<'a, V: Into<Option<&'a str>>>( &mut self, cpp_link_stdlib: V, ) -> &mut Build730 pub fn cpp_link_stdlib<'a, V: Into<Option<&'a str>>>(
731 &mut self,
732 cpp_link_stdlib: V,
733 ) -> &mut Build {
734 self.cpp_link_stdlib = Some(cpp_link_stdlib.into().map(|s| s.into()));
735 self
736 }
737
738 /// Force the C++ compiler to use the specified standard library.
739 ///
740 /// Setting this option will automatically set `cpp_link_stdlib` to the same
741 /// value.
742 ///
743 /// The default value of this option is always `None`.
744 ///
745 /// This option has no effect when compiling for a Visual Studio based
746 /// target.
747 ///
748 /// This option sets the `-stdlib` flag, which is only supported by some
749 /// compilers (clang, icc) but not by others (gcc). The library will not
750 /// detect which compiler is used, as such it is the responsibility of the
751 /// caller to ensure that this option is only used in conjunction with a
752 /// compiler which supports the `-stdlib` flag.
753 ///
754 /// A value of `None` indicates that no specific C++ standard library should
755 /// be used, otherwise `-stdlib` is added to the compile invocation.
756 ///
757 /// The given library name must not contain the `lib` prefix.
758 ///
759 /// Common values:
760 /// - `stdc++` for GNU
761 /// - `c++` for Clang
762 ///
763 /// # Example
764 ///
765 /// ```no_run
766 /// cc::Build::new()
767 /// .file("src/foo.c")
768 /// .cpp_set_stdlib("c++")
769 /// .compile("libfoo.a");
770 /// ```
cpp_set_stdlib<'a, V: Into<Option<&'a str>>>( &mut self, cpp_set_stdlib: V, ) -> &mut Build771 pub fn cpp_set_stdlib<'a, V: Into<Option<&'a str>>>(
772 &mut self,
773 cpp_set_stdlib: V,
774 ) -> &mut Build {
775 let cpp_set_stdlib = cpp_set_stdlib.into();
776 self.cpp_set_stdlib = cpp_set_stdlib.map(|s| s.into());
777 self.cpp_link_stdlib(cpp_set_stdlib);
778 self
779 }
780
781 /// Configures the target this configuration will be compiling for.
782 ///
783 /// This option is automatically scraped from the `TARGET` environment
784 /// variable by build scripts, so it's not required to call this function.
785 ///
786 /// # Example
787 ///
788 /// ```no_run
789 /// cc::Build::new()
790 /// .file("src/foo.c")
791 /// .target("aarch64-linux-android")
792 /// .compile("foo");
793 /// ```
target(&mut self, target: &str) -> &mut Build794 pub fn target(&mut self, target: &str) -> &mut Build {
795 self.target = Some(target.to_string());
796 self
797 }
798
799 /// Configures the host assumed by this configuration.
800 ///
801 /// This option is automatically scraped from the `HOST` environment
802 /// variable by build scripts, so it's not required to call this function.
803 ///
804 /// # Example
805 ///
806 /// ```no_run
807 /// cc::Build::new()
808 /// .file("src/foo.c")
809 /// .host("arm-linux-gnueabihf")
810 /// .compile("foo");
811 /// ```
host(&mut self, host: &str) -> &mut Build812 pub fn host(&mut self, host: &str) -> &mut Build {
813 self.host = Some(host.to_string());
814 self
815 }
816
817 /// Configures the optimization level of the generated object files.
818 ///
819 /// This option is automatically scraped from the `OPT_LEVEL` environment
820 /// variable by build scripts, so it's not required to call this function.
opt_level(&mut self, opt_level: u32) -> &mut Build821 pub fn opt_level(&mut self, opt_level: u32) -> &mut Build {
822 self.opt_level = Some(opt_level.to_string());
823 self
824 }
825
826 /// Configures the optimization level of the generated object files.
827 ///
828 /// This option is automatically scraped from the `OPT_LEVEL` environment
829 /// variable by build scripts, so it's not required to call this function.
opt_level_str(&mut self, opt_level: &str) -> &mut Build830 pub fn opt_level_str(&mut self, opt_level: &str) -> &mut Build {
831 self.opt_level = Some(opt_level.to_string());
832 self
833 }
834
835 /// Configures whether the compiler will emit debug information when
836 /// generating object files.
837 ///
838 /// This option is automatically scraped from the `DEBUG` environment
839 /// variable by build scripts, so it's not required to call this function.
debug(&mut self, debug: bool) -> &mut Build840 pub fn debug(&mut self, debug: bool) -> &mut Build {
841 self.debug = Some(debug);
842 self
843 }
844
845 /// Configures whether the compiler will emit instructions to store
846 /// frame pointers during codegen.
847 ///
848 /// This option is automatically enabled when debug information is emitted.
849 /// Otherwise the target platform compiler's default will be used.
850 /// You can use this option to force a specific setting.
force_frame_pointer(&mut self, force: bool) -> &mut Build851 pub fn force_frame_pointer(&mut self, force: bool) -> &mut Build {
852 self.force_frame_pointer = Some(force);
853 self
854 }
855
856 /// Configures the output directory where all object files and static
857 /// libraries will be located.
858 ///
859 /// This option is automatically scraped from the `OUT_DIR` environment
860 /// variable by build scripts, so it's not required to call this function.
out_dir<P: AsRef<Path>>(&mut self, out_dir: P) -> &mut Build861 pub fn out_dir<P: AsRef<Path>>(&mut self, out_dir: P) -> &mut Build {
862 self.out_dir = Some(out_dir.as_ref().to_owned());
863 self
864 }
865
866 /// Configures the compiler to be used to produce output.
867 ///
868 /// This option is automatically determined from the target platform or a
869 /// number of environment variables, so it's not required to call this
870 /// function.
compiler<P: AsRef<Path>>(&mut self, compiler: P) -> &mut Build871 pub fn compiler<P: AsRef<Path>>(&mut self, compiler: P) -> &mut Build {
872 self.compiler = Some(compiler.as_ref().to_owned());
873 self
874 }
875
876 /// Configures the tool used to assemble archives.
877 ///
878 /// This option is automatically determined from the target platform or a
879 /// number of environment variables, so it's not required to call this
880 /// function.
archiver<P: AsRef<Path>>(&mut self, archiver: P) -> &mut Build881 pub fn archiver<P: AsRef<Path>>(&mut self, archiver: P) -> &mut Build {
882 self.archiver = Some(archiver.as_ref().to_owned());
883 self
884 }
885 /// Define whether metadata should be emitted for cargo allowing it to
886 /// automatically link the binary. Defaults to `true`.
887 ///
888 /// The emitted metadata is:
889 ///
890 /// - `rustc-link-lib=static=`*compiled lib*
891 /// - `rustc-link-search=native=`*target folder*
892 /// - When target is MSVC, the ATL-MFC libs are added via `rustc-link-search=native=`
893 /// - When C++ is enabled, the C++ stdlib is added via `rustc-link-lib`
894 ///
cargo_metadata(&mut self, cargo_metadata: bool) -> &mut Build895 pub fn cargo_metadata(&mut self, cargo_metadata: bool) -> &mut Build {
896 self.cargo_metadata = cargo_metadata;
897 self
898 }
899
900 /// Configures whether the compiler will emit position independent code.
901 ///
902 /// This option defaults to `false` for `windows-gnu` and bare metal targets and
903 /// to `true` for all other targets.
pic(&mut self, pic: bool) -> &mut Build904 pub fn pic(&mut self, pic: bool) -> &mut Build {
905 self.pic = Some(pic);
906 self
907 }
908
909 /// Configures whether the Procedure Linkage Table is used for indirect
910 /// calls into shared libraries.
911 ///
912 /// The PLT is used to provide features like lazy binding, but introduces
913 /// a small performance loss due to extra pointer indirection. Setting
914 /// `use_plt` to `false` can provide a small performance increase.
915 ///
916 /// Note that skipping the PLT requires a recent version of GCC/Clang.
917 ///
918 /// This only applies to ELF targets. It has no effect on other platforms.
use_plt(&mut self, use_plt: bool) -> &mut Build919 pub fn use_plt(&mut self, use_plt: bool) -> &mut Build {
920 self.use_plt = Some(use_plt);
921 self
922 }
923
924 /// Configures whether the /MT flag or the /MD flag will be passed to msvc build tools.
925 ///
926 /// This option defaults to `false`, and affect only msvc targets.
static_crt(&mut self, static_crt: bool) -> &mut Build927 pub fn static_crt(&mut self, static_crt: bool) -> &mut Build {
928 self.static_crt = Some(static_crt);
929 self
930 }
931
932 #[doc(hidden)]
__set_env<A, B>(&mut self, a: A, b: B) -> &mut Build where A: AsRef<OsStr>, B: AsRef<OsStr>,933 pub fn __set_env<A, B>(&mut self, a: A, b: B) -> &mut Build
934 where
935 A: AsRef<OsStr>,
936 B: AsRef<OsStr>,
937 {
938 self.env
939 .push((a.as_ref().to_owned(), b.as_ref().to_owned()));
940 self
941 }
942
943 /// Run the compiler, generating the file `output`
944 ///
945 /// This will return a result instead of panicing; see compile() for the complete description.
try_compile(&self, output: &str) -> Result<(), Error>946 pub fn try_compile(&self, output: &str) -> Result<(), Error> {
947 let (lib_name, gnu_lib_name) = if output.starts_with("lib") && output.ends_with(".a") {
948 (&output[3..output.len() - 2], output.to_owned())
949 } else {
950 let mut gnu = String::with_capacity(5 + output.len());
951 gnu.push_str("lib");
952 gnu.push_str(&output);
953 gnu.push_str(".a");
954 (output, gnu)
955 };
956 let dst = self.get_out_dir()?;
957
958 let mut objects = Vec::new();
959 for file in self.files.iter() {
960 let obj = dst.join(file).with_extension("o");
961 let obj = if !obj.starts_with(&dst) {
962 dst.join(obj.file_name().ok_or_else(|| {
963 Error::new(ErrorKind::IOError, "Getting object file details failed.")
964 })?)
965 } else {
966 obj
967 };
968
969 match obj.parent() {
970 Some(s) => fs::create_dir_all(s)?,
971 None => {
972 return Err(Error::new(
973 ErrorKind::IOError,
974 "Getting object file details failed.",
975 ));
976 }
977 };
978
979 objects.push(Object::new(file.to_path_buf(), obj));
980 }
981 self.compile_objects(&objects)?;
982 self.assemble(lib_name, &dst.join(gnu_lib_name), &objects)?;
983
984 if self.get_target()?.contains("msvc") {
985 let compiler = self.get_base_compiler()?;
986 let atlmfc_lib = compiler
987 .env()
988 .iter()
989 .find(|&&(ref var, _)| var.as_os_str() == OsStr::new("LIB"))
990 .and_then(|&(_, ref lib_paths)| {
991 env::split_paths(lib_paths).find(|path| {
992 let sub = Path::new("atlmfc/lib");
993 path.ends_with(sub) || path.parent().map_or(false, |p| p.ends_with(sub))
994 })
995 });
996
997 if let Some(atlmfc_lib) = atlmfc_lib {
998 self.print(&format!(
999 "cargo:rustc-link-search=native={}",
1000 atlmfc_lib.display()
1001 ));
1002 }
1003 }
1004
1005 self.print(&format!("cargo:rustc-link-lib=static={}", lib_name));
1006 self.print(&format!("cargo:rustc-link-search=native={}", dst.display()));
1007
1008 // Add specific C++ libraries, if enabled.
1009 if self.cpp {
1010 if let Some(stdlib) = self.get_cpp_link_stdlib()? {
1011 self.print(&format!("cargo:rustc-link-lib={}", stdlib));
1012 }
1013 }
1014
1015 let cudart = match &self.cudart {
1016 Some(opt) => opt.as_str(), // {none|shared|static}
1017 None => "none",
1018 };
1019 if cudart != "none" {
1020 if let Some(nvcc) = which(&self.get_compiler().path) {
1021 // Try to figure out the -L search path. If it fails,
1022 // it's on user to specify one by passing it through
1023 // RUSTFLAGS environment variable.
1024 let mut libtst = false;
1025 let mut libdir = nvcc;
1026 libdir.pop(); // remove 'nvcc'
1027 libdir.push("..");
1028 let target_arch = env::var("CARGO_CFG_TARGET_ARCH").unwrap();
1029 if cfg!(target_os = "linux") {
1030 libdir.push("targets");
1031 libdir.push(target_arch.to_owned() + "-linux");
1032 libdir.push("lib");
1033 libtst = true;
1034 } else if cfg!(target_env = "msvc") {
1035 libdir.push("lib");
1036 match target_arch.as_str() {
1037 "x86_64" => {
1038 libdir.push("x64");
1039 libtst = true;
1040 }
1041 "x86" => {
1042 libdir.push("Win32");
1043 libtst = true;
1044 }
1045 _ => libtst = false,
1046 }
1047 }
1048 if libtst && libdir.is_dir() {
1049 println!(
1050 "cargo:rustc-link-search=native={}",
1051 libdir.to_str().unwrap()
1052 );
1053 }
1054
1055 // And now the -l flag.
1056 let lib = match cudart {
1057 "shared" => "cudart",
1058 "static" => "cudart_static",
1059 bad => panic!("unsupported cudart option: {}", bad),
1060 };
1061 println!("cargo:rustc-link-lib={}", lib);
1062 }
1063 }
1064
1065 Ok(())
1066 }
1067
1068 /// Run the compiler, generating the file `output`
1069 ///
1070 /// The name `output` should be the name of the library. For backwards compatibility,
1071 /// the `output` may start with `lib` and end with `.a`. The Rust compiler will create
1072 /// the assembly with the lib prefix and .a extension. MSVC will create a file without prefix,
1073 /// ending with `.lib`.
1074 ///
1075 /// # Panics
1076 ///
1077 /// Panics if `output` is not formatted correctly or if one of the underlying
1078 /// compiler commands fails. It can also panic if it fails reading file names
1079 /// or creating directories.
compile(&self, output: &str)1080 pub fn compile(&self, output: &str) {
1081 if let Err(e) = self.try_compile(output) {
1082 fail(&e.message);
1083 }
1084 }
1085
1086 #[cfg(feature = "parallel")]
compile_objects<'me>(&'me self, objs: &[Object]) -> Result<(), Error>1087 fn compile_objects<'me>(&'me self, objs: &[Object]) -> Result<(), Error> {
1088 use std::sync::atomic::{AtomicBool, Ordering::SeqCst};
1089 use std::sync::Once;
1090
1091 // Limit our parallelism globally with a jobserver. Start off by
1092 // releasing our own token for this process so we can have a bit of an
1093 // easier to write loop below. If this fails, though, then we're likely
1094 // on Windows with the main implicit token, so we just have a bit extra
1095 // parallelism for a bit and don't reacquire later.
1096 let server = jobserver();
1097 let reacquire = server.release_raw().is_ok();
1098
1099 // When compiling objects in parallel we do a few dirty tricks to speed
1100 // things up:
1101 //
1102 // * First is that we use the `jobserver` crate to limit the parallelism
1103 // of this build script. The `jobserver` crate will use a jobserver
1104 // configured by Cargo for build scripts to ensure that parallelism is
1105 // coordinated across C compilations and Rust compilations. Before we
1106 // compile anything we make sure to wait until we acquire a token.
1107 //
1108 // Note that this jobserver is cached globally so we only used one per
1109 // process and only worry about creating it once.
1110 //
1111 // * Next we use a raw `thread::spawn` per thread to actually compile
1112 // objects in parallel. We only actually spawn a thread after we've
1113 // acquired a token to perform some work
1114 //
1115 // * Finally though we want to keep the dependencies of this crate
1116 // pretty light, so we avoid using a safe abstraction like `rayon` and
1117 // instead rely on some bits of `unsafe` code. We know that this stack
1118 // frame persists while everything is compiling so we use all the
1119 // stack-allocated objects without cloning/reallocating. We use a
1120 // transmute to `State` with a `'static` lifetime to persist
1121 // everything we need across the boundary, and the join-on-drop
1122 // semantics of `JoinOnDrop` should ensure that our stack frame is
1123 // alive while threads are alive.
1124 //
1125 // With all that in mind we compile all objects in a loop here, after we
1126 // acquire the appropriate tokens, Once all objects have been compiled
1127 // we join on all the threads and propagate the results of compilation.
1128 //
1129 // Note that as a slight optimization we try to break out as soon as
1130 // possible as soon as any compilation fails to ensure that errors get
1131 // out to the user as fast as possible.
1132 let error = AtomicBool::new(false);
1133 let mut threads = Vec::new();
1134 for obj in objs {
1135 if error.load(SeqCst) {
1136 break;
1137 }
1138 let token = server.acquire()?;
1139 let state = State {
1140 build: self,
1141 obj,
1142 error: &error,
1143 };
1144 let state = unsafe { std::mem::transmute::<State, State<'static>>(state) };
1145 let thread = thread::spawn(|| {
1146 let state: State<'me> = state; // erase the `'static` lifetime
1147 let result = state.build.compile_object(state.obj);
1148 if result.is_err() {
1149 state.error.store(true, SeqCst);
1150 }
1151 drop(token); // make sure our jobserver token is released after the compile
1152 return result;
1153 });
1154 threads.push(JoinOnDrop(Some(thread)));
1155 }
1156
1157 for mut thread in threads {
1158 if let Some(thread) = thread.0.take() {
1159 thread.join().expect("thread should not panic")?;
1160 }
1161 }
1162
1163 // Reacquire our process's token before we proceed, which we released
1164 // before entering the loop above.
1165 if reacquire {
1166 server.acquire_raw()?;
1167 }
1168
1169 return Ok(());
1170
1171 /// Shared state from the parent thread to the child thread. This
1172 /// package of pointers is temporarily transmuted to a `'static`
1173 /// lifetime to cross the thread boundary and then once the thread is
1174 /// running we erase the `'static` to go back to an anonymous lifetime.
1175 struct State<'a> {
1176 build: &'a Build,
1177 obj: &'a Object,
1178 error: &'a AtomicBool,
1179 }
1180
1181 /// Returns a suitable `jobserver::Client` used to coordinate
1182 /// parallelism between build scripts.
1183 fn jobserver() -> &'static jobserver::Client {
1184 static INIT: Once = Once::new();
1185 static mut JOBSERVER: Option<jobserver::Client> = None;
1186
1187 fn _assert_sync<T: Sync>() {}
1188 _assert_sync::<jobserver::Client>();
1189
1190 unsafe {
1191 INIT.call_once(|| {
1192 let server = default_jobserver();
1193 JOBSERVER = Some(server);
1194 });
1195 JOBSERVER.as_ref().unwrap()
1196 }
1197 }
1198
1199 unsafe fn default_jobserver() -> jobserver::Client {
1200 // Try to use the environmental jobserver which Cargo typically
1201 // initializes for us...
1202 if let Some(client) = jobserver::Client::from_env() {
1203 return client;
1204 }
1205
1206 // ... but if that fails for whatever reason select something
1207 // reasonable and crate a new jobserver. Use `NUM_JOBS` if set (it's
1208 // configured by Cargo) and otherwise just fall back to a
1209 // semi-reasonable number. Note that we could use `num_cpus` here
1210 // but it's an extra dependency that will almost never be used, so
1211 // it's generally not too worth it.
1212 let mut parallelism = 4;
1213 if let Ok(amt) = env::var("NUM_JOBS") {
1214 if let Ok(amt) = amt.parse() {
1215 parallelism = amt;
1216 }
1217 }
1218
1219 // If we create our own jobserver then be sure to reserve one token
1220 // for ourselves.
1221 let client = jobserver::Client::new(parallelism).expect("failed to create jobserver");
1222 client.acquire_raw().expect("failed to acquire initial");
1223 return client;
1224 }
1225
1226 struct JoinOnDrop(Option<thread::JoinHandle<Result<(), Error>>>);
1227
1228 impl Drop for JoinOnDrop {
1229 fn drop(&mut self) {
1230 if let Some(thread) = self.0.take() {
1231 drop(thread.join());
1232 }
1233 }
1234 }
1235 }
1236
1237 #[cfg(not(feature = "parallel"))]
compile_objects(&self, objs: &[Object]) -> Result<(), Error>1238 fn compile_objects(&self, objs: &[Object]) -> Result<(), Error> {
1239 for obj in objs {
1240 self.compile_object(obj)?;
1241 }
1242 Ok(())
1243 }
1244
compile_object(&self, obj: &Object) -> Result<(), Error>1245 fn compile_object(&self, obj: &Object) -> Result<(), Error> {
1246 let is_asm = obj.src.extension().and_then(|s| s.to_str()) == Some("asm");
1247 let target = self.get_target()?;
1248 let msvc = target.contains("msvc");
1249 let compiler = self.try_get_compiler()?;
1250 let clang = compiler.family == ToolFamily::Clang;
1251 let (mut cmd, name) = if msvc && is_asm {
1252 self.msvc_macro_assembler()?
1253 } else {
1254 let mut cmd = compiler.to_command();
1255 for &(ref a, ref b) in self.env.iter() {
1256 cmd.env(a, b);
1257 }
1258 (
1259 cmd,
1260 compiler
1261 .path
1262 .file_name()
1263 .ok_or_else(|| Error::new(ErrorKind::IOError, "Failed to get compiler path."))?
1264 .to_string_lossy()
1265 .into_owned(),
1266 )
1267 };
1268 let is_arm = target.contains("aarch64") || target.contains("arm");
1269 command_add_output_file(&mut cmd, &obj.dst, self.cuda, msvc, clang, is_asm, is_arm);
1270 // armasm and armasm64 don't requrie -c option
1271 if !msvc || !is_asm || !is_arm {
1272 cmd.arg("-c");
1273 }
1274 if self.cuda && self.files.len() > 1 {
1275 cmd.arg("--device-c");
1276 }
1277 cmd.arg(&obj.src);
1278 if cfg!(target_os = "macos") {
1279 self.fix_env_for_apple_os(&mut cmd)?;
1280 }
1281
1282 run(&mut cmd, &name)?;
1283 Ok(())
1284 }
1285
1286 /// This will return a result instead of panicing; see expand() for the complete description.
try_expand(&self) -> Result<Vec<u8>, Error>1287 pub fn try_expand(&self) -> Result<Vec<u8>, Error> {
1288 let compiler = self.try_get_compiler()?;
1289 let mut cmd = compiler.to_command();
1290 for &(ref a, ref b) in self.env.iter() {
1291 cmd.env(a, b);
1292 }
1293 cmd.arg("-E");
1294
1295 assert!(
1296 self.files.len() <= 1,
1297 "Expand may only be called for a single file"
1298 );
1299
1300 for file in self.files.iter() {
1301 cmd.arg(file);
1302 }
1303
1304 let name = compiler
1305 .path
1306 .file_name()
1307 .ok_or_else(|| Error::new(ErrorKind::IOError, "Failed to get compiler path."))?
1308 .to_string_lossy()
1309 .into_owned();
1310
1311 Ok(run_output(&mut cmd, &name)?)
1312 }
1313
1314 /// Run the compiler, returning the macro-expanded version of the input files.
1315 ///
1316 /// This is only relevant for C and C++ files.
1317 ///
1318 /// # Panics
1319 /// Panics if more than one file is present in the config, or if compiler
1320 /// path has an invalid file name.
1321 ///
1322 /// # Example
1323 /// ```no_run
1324 /// let out = cc::Build::new().file("src/foo.c").expand();
1325 /// ```
expand(&self) -> Vec<u8>1326 pub fn expand(&self) -> Vec<u8> {
1327 match self.try_expand() {
1328 Err(e) => fail(&e.message),
1329 Ok(v) => v,
1330 }
1331 }
1332
1333 /// Get the compiler that's in use for this configuration.
1334 ///
1335 /// This function will return a `Tool` which represents the culmination
1336 /// of this configuration at a snapshot in time. The returned compiler can
1337 /// be inspected (e.g. the path, arguments, environment) to forward along to
1338 /// other tools, or the `to_command` method can be used to invoke the
1339 /// compiler itself.
1340 ///
1341 /// This method will take into account all configuration such as debug
1342 /// information, optimization level, include directories, defines, etc.
1343 /// Additionally, the compiler binary in use follows the standard
1344 /// conventions for this path, e.g. looking at the explicitly set compiler,
1345 /// environment variables (a number of which are inspected here), and then
1346 /// falling back to the default configuration.
1347 ///
1348 /// # Panics
1349 ///
1350 /// Panics if an error occurred while determining the architecture.
get_compiler(&self) -> Tool1351 pub fn get_compiler(&self) -> Tool {
1352 match self.try_get_compiler() {
1353 Ok(tool) => tool,
1354 Err(e) => fail(&e.message),
1355 }
1356 }
1357
1358 /// Get the compiler that's in use for this configuration.
1359 ///
1360 /// This will return a result instead of panicing; see get_compiler() for the complete description.
try_get_compiler(&self) -> Result<Tool, Error>1361 pub fn try_get_compiler(&self) -> Result<Tool, Error> {
1362 let opt_level = self.get_opt_level()?;
1363 let target = self.get_target()?;
1364
1365 let mut cmd = self.get_base_compiler()?;
1366 let envflags = self.envflags(if self.cpp { "CXXFLAGS" } else { "CFLAGS" });
1367
1368 // Disable default flag generation via `no_default_flags` or environment variable
1369 let no_defaults = self.no_default_flags || self.getenv("CRATE_CC_NO_DEFAULTS").is_some();
1370
1371 if !no_defaults {
1372 self.add_default_flags(&mut cmd, &target, &opt_level)?;
1373 } else {
1374 println!("Info: default compiler flags are disabled");
1375 }
1376
1377 for arg in envflags {
1378 cmd.push_cc_arg(arg.into());
1379 }
1380
1381 for directory in self.include_directories.iter() {
1382 cmd.args.push("-I".into());
1383 cmd.args.push(directory.into());
1384 }
1385
1386 // If warnings and/or extra_warnings haven't been explicitly set,
1387 // then we set them only if the environment doesn't already have
1388 // CFLAGS/CXXFLAGS, since those variables presumably already contain
1389 // the desired set of warnings flags.
1390
1391 if self
1392 .warnings
1393 .unwrap_or(if self.has_flags() { false } else { true })
1394 {
1395 let wflags = cmd.family.warnings_flags().into();
1396 cmd.push_cc_arg(wflags);
1397 }
1398
1399 if self
1400 .extra_warnings
1401 .unwrap_or(if self.has_flags() { false } else { true })
1402 {
1403 if let Some(wflags) = cmd.family.extra_warnings_flags() {
1404 cmd.push_cc_arg(wflags.into());
1405 }
1406 }
1407
1408 for flag in self.flags.iter() {
1409 cmd.args.push(flag.into());
1410 }
1411
1412 for flag in self.flags_supported.iter() {
1413 if self.is_flag_supported(flag).unwrap_or(false) {
1414 cmd.push_cc_arg(flag.into());
1415 }
1416 }
1417
1418 for &(ref key, ref value) in self.definitions.iter() {
1419 if let Some(ref value) = *value {
1420 cmd.args.push(format!("-D{}={}", key, value).into());
1421 } else {
1422 cmd.args.push(format!("-D{}", key).into());
1423 }
1424 }
1425
1426 if self.warnings_into_errors {
1427 let warnings_to_errors_flag = cmd.family.warnings_to_errors_flag().into();
1428 cmd.push_cc_arg(warnings_to_errors_flag);
1429 }
1430
1431 Ok(cmd)
1432 }
1433
add_default_flags( &self, cmd: &mut Tool, target: &str, opt_level: &str, ) -> Result<(), Error>1434 fn add_default_flags(
1435 &self,
1436 cmd: &mut Tool,
1437 target: &str,
1438 opt_level: &str,
1439 ) -> Result<(), Error> {
1440 // Non-target flags
1441 // If the flag is not conditioned on target variable, it belongs here :)
1442 match cmd.family {
1443 ToolFamily::Msvc { .. } => {
1444 cmd.push_cc_arg("-nologo".into());
1445
1446 let crt_flag = match self.static_crt {
1447 Some(true) => "-MT",
1448 Some(false) => "-MD",
1449 None => {
1450 let features = self
1451 .getenv("CARGO_CFG_TARGET_FEATURE")
1452 .unwrap_or(String::new());
1453 if features.contains("crt-static") {
1454 "-MT"
1455 } else {
1456 "-MD"
1457 }
1458 }
1459 };
1460 cmd.push_cc_arg(crt_flag.into());
1461
1462 match &opt_level[..] {
1463 // Msvc uses /O1 to enable all optimizations that minimize code size.
1464 "z" | "s" | "1" => cmd.push_opt_unless_duplicate("-O1".into()),
1465 // -O3 is a valid value for gcc and clang compilers, but not msvc. Cap to /O2.
1466 "2" | "3" => cmd.push_opt_unless_duplicate("-O2".into()),
1467 _ => {}
1468 }
1469 }
1470 ToolFamily::Gnu | ToolFamily::Clang => {
1471 // arm-linux-androideabi-gcc 4.8 shipped with Android NDK does
1472 // not support '-Oz'
1473 if opt_level == "z" && cmd.family != ToolFamily::Clang {
1474 cmd.push_opt_unless_duplicate("-Os".into());
1475 } else {
1476 cmd.push_opt_unless_duplicate(format!("-O{}", opt_level).into());
1477 }
1478
1479 if cmd.family == ToolFamily::Clang && target.contains("android") {
1480 // For compatibility with code that doesn't use pre-defined `__ANDROID__` macro.
1481 // If compiler used via ndk-build or cmake (officially supported build methods)
1482 // this macros is defined.
1483 // See https://android.googlesource.com/platform/ndk/+/refs/heads/ndk-release-r21/build/cmake/android.toolchain.cmake#456
1484 // https://android.googlesource.com/platform/ndk/+/refs/heads/ndk-release-r21/build/core/build-binary.mk#141
1485 cmd.push_opt_unless_duplicate("-DANDROID".into());
1486 }
1487
1488 if !target.contains("apple-ios") {
1489 cmd.push_cc_arg("-ffunction-sections".into());
1490 cmd.push_cc_arg("-fdata-sections".into());
1491 }
1492 // Disable generation of PIC on bare-metal for now: rust-lld doesn't support this yet
1493 if self.pic.unwrap_or(
1494 !target.contains("windows")
1495 && !target.contains("-none-")
1496 && !target.contains("uefi"),
1497 ) {
1498 cmd.push_cc_arg("-fPIC".into());
1499 // PLT only applies if code is compiled with PIC support,
1500 // and only for ELF targets.
1501 if target.contains("linux") && !self.use_plt.unwrap_or(true) {
1502 cmd.push_cc_arg("-fno-plt".into());
1503 }
1504 }
1505 }
1506 }
1507
1508 if self.get_debug() {
1509 if self.cuda {
1510 // NVCC debug flag
1511 cmd.args.push("-G".into());
1512 }
1513 let family = cmd.family;
1514 family.add_debug_flags(cmd);
1515 }
1516
1517 if self.get_force_frame_pointer() {
1518 let family = cmd.family;
1519 family.add_force_frame_pointer(cmd);
1520 }
1521
1522 // Target flags
1523 match cmd.family {
1524 ToolFamily::Clang => {
1525 if !(target.contains("android")
1526 && android_clang_compiler_uses_target_arg_internally(&cmd.path))
1527 {
1528 if target.contains("darwin") {
1529 if let Some(arch) =
1530 map_darwin_target_from_rust_to_compiler_architecture(target)
1531 {
1532 cmd.args
1533 .push(format!("--target={}-apple-darwin", arch).into());
1534 }
1535 } else if target.contains("macabi") {
1536 if let Some(arch) =
1537 map_darwin_target_from_rust_to_compiler_architecture(target)
1538 {
1539 cmd.args
1540 .push(format!("--target={}-apple-ios13.0-macabi", arch).into());
1541 }
1542 } else if target.contains("ios-sim") {
1543 if let Some(arch) =
1544 map_darwin_target_from_rust_to_compiler_architecture(target)
1545 {
1546 let deployment_target = env::var("IPHONEOS_DEPLOYMENT_TARGET")
1547 .unwrap_or_else(|_| "7.0".into());
1548 cmd.args.push(
1549 format!(
1550 "--target={}-apple-ios{}-simulator",
1551 arch, deployment_target
1552 )
1553 .into(),
1554 );
1555 }
1556 } else if target.starts_with("riscv64gc-") {
1557 cmd.args.push(
1558 format!("--target={}", target.replace("riscv64gc", "riscv64")).into(),
1559 );
1560 } else if target.starts_with("riscv32gc-") {
1561 cmd.args.push(
1562 format!("--target={}", target.replace("riscv32gc", "riscv32")).into(),
1563 );
1564 } else if target.contains("uefi") {
1565 if target.contains("x86_64") {
1566 cmd.args.push("--target=x86_64-unknown-windows-gnu".into());
1567 } else if target.contains("i686") {
1568 cmd.args.push("--target=i686-unknown-windows-gnu".into())
1569 }
1570 } else {
1571 cmd.args.push(format!("--target={}", target).into());
1572 }
1573 }
1574 }
1575 ToolFamily::Msvc { clang_cl } => {
1576 // This is an undocumented flag from MSVC but helps with making
1577 // builds more reproducible by avoiding putting timestamps into
1578 // files.
1579 cmd.push_cc_arg("-Brepro".into());
1580
1581 if clang_cl {
1582 if target.contains("x86_64") {
1583 cmd.push_cc_arg("-m64".into());
1584 } else if target.contains("86") {
1585 cmd.push_cc_arg("-m32".into());
1586 cmd.push_cc_arg("-arch:IA32".into());
1587 } else {
1588 cmd.push_cc_arg(format!("--target={}", target).into());
1589 }
1590 } else {
1591 if target.contains("i586") {
1592 cmd.push_cc_arg("-arch:IA32".into());
1593 }
1594 }
1595
1596 // There is a check in corecrt.h that will generate a
1597 // compilation error if
1598 // _ARM_WINAPI_PARTITION_DESKTOP_SDK_AVAILABLE is
1599 // not defined to 1. The check was added in Windows
1600 // 8 days because only store apps were allowed on ARM.
1601 // This changed with the release of Windows 10 IoT Core.
1602 // The check will be going away in future versions of
1603 // the SDK, but for all released versions of the
1604 // Windows SDK it is required.
1605 if target.contains("arm") || target.contains("thumb") {
1606 cmd.args
1607 .push("-D_ARM_WINAPI_PARTITION_DESKTOP_SDK_AVAILABLE=1".into());
1608 }
1609 }
1610 ToolFamily::Gnu => {
1611 if target.contains("i686") || target.contains("i586") {
1612 cmd.args.push("-m32".into());
1613 } else if target == "x86_64-unknown-linux-gnux32" {
1614 cmd.args.push("-mx32".into());
1615 } else if target.contains("x86_64") || target.contains("powerpc64") {
1616 cmd.args.push("-m64".into());
1617 }
1618
1619 if target.contains("darwin") {
1620 if let Some(arch) = map_darwin_target_from_rust_to_compiler_architecture(target)
1621 {
1622 cmd.args.push("-arch".into());
1623 cmd.args.push(arch.into());
1624 }
1625 }
1626
1627 if target.contains("-kmc-solid_") {
1628 cmd.args.push("-finput-charset=utf-8".into());
1629 }
1630
1631 if self.static_flag.is_none() {
1632 let features = self
1633 .getenv("CARGO_CFG_TARGET_FEATURE")
1634 .unwrap_or(String::new());
1635 if features.contains("crt-static") {
1636 cmd.args.push("-static".into());
1637 }
1638 }
1639
1640 // armv7 targets get to use armv7 instructions
1641 if (target.starts_with("armv7") || target.starts_with("thumbv7"))
1642 && (target.contains("-linux-") || target.contains("-kmc-solid_"))
1643 {
1644 cmd.args.push("-march=armv7-a".into());
1645
1646 if target.ends_with("eabihf") {
1647 // lowest common denominator FPU
1648 cmd.args.push("-mfpu=vfpv3-d16".into());
1649 }
1650 }
1651
1652 // (x86 Android doesn't say "eabi")
1653 if target.contains("-androideabi") && target.contains("v7") {
1654 // -march=armv7-a handled above
1655 cmd.args.push("-mthumb".into());
1656 if !target.contains("neon") {
1657 // On android we can guarantee some extra float instructions
1658 // (specified in the android spec online)
1659 // NEON guarantees even more; see below.
1660 cmd.args.push("-mfpu=vfpv3-d16".into());
1661 }
1662 cmd.args.push("-mfloat-abi=softfp".into());
1663 }
1664
1665 if target.contains("neon") {
1666 cmd.args.push("-mfpu=neon-vfpv4".into());
1667 }
1668
1669 if target.starts_with("armv4t-unknown-linux-") {
1670 cmd.args.push("-march=armv4t".into());
1671 cmd.args.push("-marm".into());
1672 cmd.args.push("-mfloat-abi=soft".into());
1673 }
1674
1675 if target.starts_with("armv5te-unknown-linux-") {
1676 cmd.args.push("-march=armv5te".into());
1677 cmd.args.push("-marm".into());
1678 cmd.args.push("-mfloat-abi=soft".into());
1679 }
1680
1681 // For us arm == armv6 by default
1682 if target.starts_with("arm-unknown-linux-") {
1683 cmd.args.push("-march=armv6".into());
1684 cmd.args.push("-marm".into());
1685 if target.ends_with("hf") {
1686 cmd.args.push("-mfpu=vfp".into());
1687 } else {
1688 cmd.args.push("-mfloat-abi=soft".into());
1689 }
1690 }
1691
1692 // We can guarantee some settings for FRC
1693 if target.starts_with("arm-frc-") {
1694 cmd.args.push("-march=armv7-a".into());
1695 cmd.args.push("-mcpu=cortex-a9".into());
1696 cmd.args.push("-mfpu=vfpv3".into());
1697 cmd.args.push("-mfloat-abi=softfp".into());
1698 cmd.args.push("-marm".into());
1699 }
1700
1701 // Turn codegen down on i586 to avoid some instructions.
1702 if target.starts_with("i586-unknown-linux-") {
1703 cmd.args.push("-march=pentium".into());
1704 }
1705
1706 // Set codegen level for i686 correctly
1707 if target.starts_with("i686-unknown-linux-") {
1708 cmd.args.push("-march=i686".into());
1709 }
1710
1711 // Looks like `musl-gcc` makes it hard for `-m32` to make its way
1712 // all the way to the linker, so we need to actually instruct the
1713 // linker that we're generating 32-bit executables as well. This'll
1714 // typically only be used for build scripts which transitively use
1715 // these flags that try to compile executables.
1716 if target == "i686-unknown-linux-musl" || target == "i586-unknown-linux-musl" {
1717 cmd.args.push("-Wl,-melf_i386".into());
1718 }
1719
1720 if target.starts_with("thumb") {
1721 cmd.args.push("-mthumb".into());
1722
1723 if target.ends_with("eabihf") {
1724 cmd.args.push("-mfloat-abi=hard".into())
1725 }
1726 }
1727 if target.starts_with("thumbv6m") {
1728 cmd.args.push("-march=armv6s-m".into());
1729 }
1730 if target.starts_with("thumbv7em") {
1731 cmd.args.push("-march=armv7e-m".into());
1732
1733 if target.ends_with("eabihf") {
1734 cmd.args.push("-mfpu=fpv4-sp-d16".into())
1735 }
1736 }
1737 if target.starts_with("thumbv7m") {
1738 cmd.args.push("-march=armv7-m".into());
1739 }
1740 if target.starts_with("thumbv8m.base") {
1741 cmd.args.push("-march=armv8-m.base".into());
1742 }
1743 if target.starts_with("thumbv8m.main") {
1744 cmd.args.push("-march=armv8-m.main".into());
1745
1746 if target.ends_with("eabihf") {
1747 cmd.args.push("-mfpu=fpv5-sp-d16".into())
1748 }
1749 }
1750 if target.starts_with("armebv7r") | target.starts_with("armv7r") {
1751 if target.starts_with("armeb") {
1752 cmd.args.push("-mbig-endian".into());
1753 } else {
1754 cmd.args.push("-mlittle-endian".into());
1755 }
1756
1757 // ARM mode
1758 cmd.args.push("-marm".into());
1759
1760 // R Profile
1761 cmd.args.push("-march=armv7-r".into());
1762
1763 if target.ends_with("eabihf") {
1764 // Calling convention
1765 cmd.args.push("-mfloat-abi=hard".into());
1766
1767 // lowest common denominator FPU
1768 // (see Cortex-R4 technical reference manual)
1769 cmd.args.push("-mfpu=vfpv3-d16".into())
1770 } else {
1771 // Calling convention
1772 cmd.args.push("-mfloat-abi=soft".into());
1773 }
1774 }
1775 if target.starts_with("armv7a") {
1776 cmd.args.push("-march=armv7-a".into());
1777
1778 if target.ends_with("eabihf") {
1779 // lowest common denominator FPU
1780 cmd.args.push("-mfpu=vfpv3-d16".into());
1781 }
1782 }
1783 if target.starts_with("riscv32") || target.starts_with("riscv64") {
1784 // get the 32i/32imac/32imc/64gc/64imac/... part
1785 let mut parts = target.split('-');
1786 if let Some(arch) = parts.next() {
1787 let arch = &arch[5..];
1788 if target.contains("linux") && arch.starts_with("64") {
1789 cmd.args.push(("-march=rv64gc").into());
1790 cmd.args.push("-mabi=lp64d".into());
1791 } else if target.contains("linux") && arch.starts_with("32") {
1792 cmd.args.push(("-march=rv32gc").into());
1793 cmd.args.push("-mabi=ilp32d".into());
1794 } else if arch.starts_with("64") {
1795 cmd.args.push(("-march=rv".to_owned() + arch).into());
1796 cmd.args.push("-mabi=lp64".into());
1797 } else {
1798 cmd.args.push(("-march=rv".to_owned() + arch).into());
1799 cmd.args.push("-mabi=ilp32".into());
1800 }
1801 cmd.args.push("-mcmodel=medany".into());
1802 }
1803 }
1804 }
1805 }
1806
1807 if target.contains("apple-ios") {
1808 self.ios_flags(cmd)?;
1809 }
1810
1811 if self.static_flag.unwrap_or(false) {
1812 cmd.args.push("-static".into());
1813 }
1814 if self.shared_flag.unwrap_or(false) {
1815 cmd.args.push("-shared".into());
1816 }
1817
1818 if self.cpp {
1819 match (self.cpp_set_stdlib.as_ref(), cmd.family) {
1820 (None, _) => {}
1821 (Some(stdlib), ToolFamily::Gnu) | (Some(stdlib), ToolFamily::Clang) => {
1822 cmd.push_cc_arg(format!("-stdlib=lib{}", stdlib).into());
1823 }
1824 _ => {
1825 println!(
1826 "cargo:warning=cpp_set_stdlib is specified, but the {:?} compiler \
1827 does not support this option, ignored",
1828 cmd.family
1829 );
1830 }
1831 }
1832 }
1833
1834 Ok(())
1835 }
1836
has_flags(&self) -> bool1837 fn has_flags(&self) -> bool {
1838 let flags_env_var_name = if self.cpp { "CXXFLAGS" } else { "CFLAGS" };
1839 let flags_env_var_value = self.get_var(flags_env_var_name);
1840 if let Ok(_) = flags_env_var_value {
1841 true
1842 } else {
1843 false
1844 }
1845 }
1846
msvc_macro_assembler(&self) -> Result<(Command, String), Error>1847 fn msvc_macro_assembler(&self) -> Result<(Command, String), Error> {
1848 let target = self.get_target()?;
1849 let tool = if target.contains("x86_64") {
1850 "ml64.exe"
1851 } else if target.contains("arm") {
1852 "armasm.exe"
1853 } else if target.contains("aarch64") {
1854 "armasm64.exe"
1855 } else {
1856 "ml.exe"
1857 };
1858 let mut cmd = windows_registry::find(&target, tool).unwrap_or_else(|| self.cmd(tool));
1859 cmd.arg("-nologo"); // undocumented, yet working with armasm[64]
1860 for directory in self.include_directories.iter() {
1861 cmd.arg("-I").arg(directory);
1862 }
1863 if target.contains("aarch64") || target.contains("arm") {
1864 println!("cargo:warning=The MSVC ARM assemblers do not support -D flags");
1865 } else {
1866 for &(ref key, ref value) in self.definitions.iter() {
1867 if let Some(ref value) = *value {
1868 cmd.arg(&format!("-D{}={}", key, value));
1869 } else {
1870 cmd.arg(&format!("-D{}", key));
1871 }
1872 }
1873 }
1874
1875 if target.contains("i686") || target.contains("i586") {
1876 cmd.arg("-safeseh");
1877 }
1878 for flag in self.flags.iter() {
1879 cmd.arg(flag);
1880 }
1881
1882 Ok((cmd, tool.to_string()))
1883 }
1884
assemble(&self, lib_name: &str, dst: &Path, objs: &[Object]) -> Result<(), Error>1885 fn assemble(&self, lib_name: &str, dst: &Path, objs: &[Object]) -> Result<(), Error> {
1886 // Delete the destination if it exists as we want to
1887 // create on the first iteration instead of appending.
1888 let _ = fs::remove_file(&dst);
1889
1890 // Add objects to the archive in limited-length batches. This helps keep
1891 // the length of the command line within a reasonable length to avoid
1892 // blowing system limits on limiting platforms like Windows.
1893 let objs: Vec<_> = objs
1894 .iter()
1895 .map(|o| o.dst.clone())
1896 .chain(self.objects.clone())
1897 .collect();
1898 for chunk in objs.chunks(100) {
1899 self.assemble_progressive(dst, chunk)?;
1900 }
1901
1902 if self.cuda {
1903 // Link the device-side code and add it to the target library,
1904 // so that non-CUDA linker can link the final binary.
1905
1906 let out_dir = self.get_out_dir()?;
1907 let dlink = out_dir.join(lib_name.to_owned() + "_dlink.o");
1908 let mut nvcc = self.get_compiler().to_command();
1909 nvcc.arg("--device-link")
1910 .arg("-o")
1911 .arg(dlink.clone())
1912 .arg(dst);
1913 run(&mut nvcc, "nvcc")?;
1914 self.assemble_progressive(dst, &[dlink])?;
1915 }
1916
1917 let target = self.get_target()?;
1918 if target.contains("msvc") {
1919 // The Rust compiler will look for libfoo.a and foo.lib, but the
1920 // MSVC linker will also be passed foo.lib, so be sure that both
1921 // exist for now.
1922
1923 let lib_dst = dst.with_file_name(format!("{}.lib", lib_name));
1924 let _ = fs::remove_file(&lib_dst);
1925 match fs::hard_link(&dst, &lib_dst).or_else(|_| {
1926 // if hard-link fails, just copy (ignoring the number of bytes written)
1927 fs::copy(&dst, &lib_dst).map(|_| ())
1928 }) {
1929 Ok(_) => (),
1930 Err(_) => {
1931 return Err(Error::new(
1932 ErrorKind::IOError,
1933 "Could not copy or create a hard-link to the generated lib file.",
1934 ));
1935 }
1936 };
1937 } else {
1938 // Non-msvc targets (those using `ar`) need a separate step to add
1939 // the symbol table to archives since our construction command of
1940 // `cq` doesn't add it for us.
1941 let (mut ar, cmd) = self.get_ar()?;
1942 run(ar.arg("s").arg(dst), &cmd)?;
1943 }
1944
1945 Ok(())
1946 }
1947
assemble_progressive(&self, dst: &Path, objs: &[PathBuf]) -> Result<(), Error>1948 fn assemble_progressive(&self, dst: &Path, objs: &[PathBuf]) -> Result<(), Error> {
1949 let target = self.get_target()?;
1950
1951 if target.contains("msvc") {
1952 let (mut cmd, program) = self.get_ar()?;
1953 let mut out = OsString::from("-out:");
1954 out.push(dst);
1955 cmd.arg(out).arg("-nologo");
1956 for flag in self.ar_flags.iter() {
1957 cmd.arg(flag);
1958 }
1959 // If the library file already exists, add the library name
1960 // as an argument to let lib.exe know we are appending the objs.
1961 if dst.exists() {
1962 cmd.arg(dst);
1963 }
1964 cmd.args(objs);
1965 run(&mut cmd, &program)?;
1966 } else {
1967 let (mut ar, cmd) = self.get_ar()?;
1968
1969 // Set an environment variable to tell the OSX archiver to ensure
1970 // that all dates listed in the archive are zero, improving
1971 // determinism of builds. AFAIK there's not really official
1972 // documentation of this but there's a lot of references to it if
1973 // you search google.
1974 //
1975 // You can reproduce this locally on a mac with:
1976 //
1977 // $ touch foo.c
1978 // $ cc -c foo.c -o foo.o
1979 //
1980 // # Notice that these two checksums are different
1981 // $ ar crus libfoo1.a foo.o && sleep 2 && ar crus libfoo2.a foo.o
1982 // $ md5sum libfoo*.a
1983 //
1984 // # Notice that these two checksums are the same
1985 // $ export ZERO_AR_DATE=1
1986 // $ ar crus libfoo1.a foo.o && sleep 2 && touch foo.o && ar crus libfoo2.a foo.o
1987 // $ md5sum libfoo*.a
1988 //
1989 // In any case if this doesn't end up getting read, it shouldn't
1990 // cause that many issues!
1991 ar.env("ZERO_AR_DATE", "1");
1992 for flag in self.ar_flags.iter() {
1993 ar.arg(flag);
1994 }
1995 run(ar.arg("cq").arg(dst).args(objs), &cmd)?;
1996 }
1997
1998 Ok(())
1999 }
2000
ios_flags(&self, cmd: &mut Tool) -> Result<(), Error>2001 fn ios_flags(&self, cmd: &mut Tool) -> Result<(), Error> {
2002 enum ArchSpec {
2003 Device(&'static str),
2004 Simulator(&'static str),
2005 Catalyst(&'static str),
2006 }
2007
2008 let target = self.get_target()?;
2009 let arch = target.split('-').nth(0).ok_or_else(|| {
2010 Error::new(
2011 ErrorKind::ArchitectureInvalid,
2012 "Unknown architecture for iOS target.",
2013 )
2014 })?;
2015
2016 let is_catalyst = match target.split('-').nth(3) {
2017 Some(v) => v == "macabi",
2018 None => false,
2019 };
2020
2021 let is_sim = match target.split('-').nth(3) {
2022 Some(v) => v == "sim",
2023 None => false,
2024 };
2025
2026 let arch = if is_catalyst {
2027 match arch {
2028 "arm64e" => ArchSpec::Catalyst("arm64e"),
2029 "arm64" | "aarch64" => ArchSpec::Catalyst("arm64"),
2030 "x86_64" => ArchSpec::Catalyst("-m64"),
2031 _ => {
2032 return Err(Error::new(
2033 ErrorKind::ArchitectureInvalid,
2034 "Unknown architecture for iOS target.",
2035 ));
2036 }
2037 }
2038 } else if is_sim {
2039 match arch {
2040 "arm64" | "aarch64" => ArchSpec::Simulator("-arch arm64"),
2041 _ => {
2042 return Err(Error::new(
2043 ErrorKind::ArchitectureInvalid,
2044 "Unknown architecture for iOS simulator target.",
2045 ));
2046 }
2047 }
2048 } else {
2049 match arch {
2050 "arm" | "armv7" | "thumbv7" => ArchSpec::Device("armv7"),
2051 "armv7s" | "thumbv7s" => ArchSpec::Device("armv7s"),
2052 "arm64e" => ArchSpec::Device("arm64e"),
2053 "arm64" | "aarch64" => ArchSpec::Device("arm64"),
2054 "i386" | "i686" => ArchSpec::Simulator("-m32"),
2055 "x86_64" => ArchSpec::Simulator("-m64"),
2056 _ => {
2057 return Err(Error::new(
2058 ErrorKind::ArchitectureInvalid,
2059 "Unknown architecture for iOS target.",
2060 ));
2061 }
2062 }
2063 };
2064
2065 let min_version =
2066 std::env::var("IPHONEOS_DEPLOYMENT_TARGET").unwrap_or_else(|_| "7.0".into());
2067
2068 let sdk = match arch {
2069 ArchSpec::Device(arch) => {
2070 cmd.args.push("-arch".into());
2071 cmd.args.push(arch.into());
2072 cmd.args
2073 .push(format!("-miphoneos-version-min={}", min_version).into());
2074 "iphoneos"
2075 }
2076 ArchSpec::Simulator(arch) => {
2077 cmd.args.push(arch.into());
2078 cmd.args
2079 .push(format!("-mios-simulator-version-min={}", min_version).into());
2080 "iphonesimulator"
2081 }
2082 ArchSpec::Catalyst(_) => "macosx",
2083 };
2084
2085 self.print(&format!("Detecting iOS SDK path for {}", sdk));
2086 let sdk_path = self.apple_sdk_root(sdk)?;
2087 cmd.args.push("-isysroot".into());
2088 cmd.args.push(sdk_path);
2089 cmd.args.push("-fembed-bitcode".into());
2090 /*
2091 * TODO we probably ultimately want the -fembed-bitcode-marker flag
2092 * but can't have it now because of an issue in LLVM:
2093 * https://github.com/alexcrichton/cc-rs/issues/301
2094 * https://github.com/rust-lang/rust/pull/48896#comment-372192660
2095 */
2096 /*
2097 if self.get_opt_level()? == "0" {
2098 cmd.args.push("-fembed-bitcode-marker".into());
2099 }
2100 */
2101
2102 Ok(())
2103 }
2104
cmd<P: AsRef<OsStr>>(&self, prog: P) -> Command2105 fn cmd<P: AsRef<OsStr>>(&self, prog: P) -> Command {
2106 let mut cmd = Command::new(prog);
2107 for &(ref a, ref b) in self.env.iter() {
2108 cmd.env(a, b);
2109 }
2110 cmd
2111 }
2112
get_base_compiler(&self) -> Result<Tool, Error>2113 fn get_base_compiler(&self) -> Result<Tool, Error> {
2114 if let Some(ref c) = self.compiler {
2115 return Ok(Tool::new(c.clone()));
2116 }
2117 let host = self.get_host()?;
2118 let target = self.get_target()?;
2119 let (env, msvc, gnu, traditional, clang) = if self.cpp {
2120 ("CXX", "cl.exe", "g++", "c++", "clang++")
2121 } else {
2122 ("CC", "cl.exe", "gcc", "cc", "clang")
2123 };
2124
2125 // On historical Solaris systems, "cc" may have been Sun Studio, which
2126 // is not flag-compatible with "gcc". This history casts a long shadow,
2127 // and many modern illumos distributions today ship GCC as "gcc" without
2128 // also making it available as "cc".
2129 let default = if host.contains("solaris") || host.contains("illumos") {
2130 gnu
2131 } else {
2132 traditional
2133 };
2134
2135 let cl_exe = windows_registry::find_tool(&target, "cl.exe");
2136
2137 let tool_opt: Option<Tool> = self
2138 .env_tool(env)
2139 .map(|(tool, wrapper, args)| {
2140 // find the driver mode, if any
2141 const DRIVER_MODE: &str = "--driver-mode=";
2142 let driver_mode = args
2143 .iter()
2144 .find(|a| a.starts_with(DRIVER_MODE))
2145 .map(|a| &a[DRIVER_MODE.len()..]);
2146 // Chop off leading/trailing whitespace to work around
2147 // semi-buggy build scripts which are shared in
2148 // makefiles/configure scripts (where spaces are far more
2149 // lenient)
2150 let mut t = Tool::with_clang_driver(PathBuf::from(tool.trim()), driver_mode);
2151 if let Some(cc_wrapper) = wrapper {
2152 t.cc_wrapper_path = Some(PathBuf::from(cc_wrapper));
2153 }
2154 for arg in args {
2155 t.cc_wrapper_args.push(arg.into());
2156 }
2157 t
2158 })
2159 .or_else(|| {
2160 if target.contains("emscripten") {
2161 let tool = if self.cpp { "em++" } else { "emcc" };
2162 // Windows uses bat file so we have to be a bit more specific
2163 if cfg!(windows) {
2164 let mut t = Tool::new(PathBuf::from("cmd"));
2165 t.args.push("/c".into());
2166 t.args.push(format!("{}.bat", tool).into());
2167 Some(t)
2168 } else {
2169 Some(Tool::new(PathBuf::from(tool)))
2170 }
2171 } else {
2172 None
2173 }
2174 })
2175 .or_else(|| cl_exe.clone());
2176
2177 let tool = match tool_opt {
2178 Some(t) => t,
2179 None => {
2180 let compiler = if host.contains("windows") && target.contains("windows") {
2181 if target.contains("msvc") {
2182 msvc.to_string()
2183 } else {
2184 format!("{}.exe", gnu)
2185 }
2186 } else if target.contains("apple-ios") {
2187 clang.to_string()
2188 } else if target.contains("android") {
2189 autodetect_android_compiler(&target, &host, gnu, clang)
2190 } else if target.contains("cloudabi") {
2191 format!("{}-{}", target, traditional)
2192 } else if target == "wasm32-wasi"
2193 || target == "wasm32-unknown-wasi"
2194 || target == "wasm32-unknown-unknown"
2195 {
2196 "clang".to_string()
2197 } else if target.contains("vxworks") {
2198 if self.cpp {
2199 "wr-c++".to_string()
2200 } else {
2201 "wr-cc".to_string()
2202 }
2203 } else if target.starts_with("armv7a-kmc-solid_") {
2204 format!("arm-kmc-eabi-{}", gnu)
2205 } else if target.starts_with("aarch64-kmc-solid_") {
2206 format!("aarch64-kmc-elf-{}", gnu)
2207 } else if self.get_host()? != target {
2208 let prefix = self.prefix_for_target(&target);
2209 match prefix {
2210 Some(prefix) => format!("{}-{}", prefix, gnu),
2211 None => default.to_string(),
2212 }
2213 } else {
2214 default.to_string()
2215 };
2216
2217 let mut t = Tool::new(PathBuf::from(compiler));
2218 if let Some(cc_wrapper) = Self::rustc_wrapper_fallback() {
2219 t.cc_wrapper_path = Some(PathBuf::from(cc_wrapper));
2220 }
2221 t
2222 }
2223 };
2224
2225 let mut tool = if self.cuda {
2226 assert!(
2227 tool.args.is_empty(),
2228 "CUDA compilation currently assumes empty pre-existing args"
2229 );
2230 let nvcc = match self.get_var("NVCC") {
2231 Err(_) => "nvcc".into(),
2232 Ok(nvcc) => nvcc,
2233 };
2234 let mut nvcc_tool = Tool::with_features(PathBuf::from(nvcc), None, self.cuda);
2235 nvcc_tool
2236 .args
2237 .push(format!("-ccbin={}", tool.path.display()).into());
2238 nvcc_tool.family = tool.family;
2239 nvcc_tool
2240 } else {
2241 tool
2242 };
2243
2244 // New "standalone" C/C++ cross-compiler executables from recent Android NDK
2245 // are just shell scripts that call main clang binary (from Android NDK) with
2246 // proper `--target` argument.
2247 //
2248 // For example, armv7a-linux-androideabi16-clang passes
2249 // `--target=armv7a-linux-androideabi16` to clang.
2250 //
2251 // As the shell script calls the main clang binary, the command line limit length
2252 // on Windows is restricted to around 8k characters instead of around 32k characters.
2253 // To remove this limit, we call the main clang binary directly and construct the
2254 // `--target=` ourselves.
2255 if host.contains("windows") && android_clang_compiler_uses_target_arg_internally(&tool.path)
2256 {
2257 if let Some(path) = tool.path.file_name() {
2258 let file_name = path.to_str().unwrap().to_owned();
2259 let (target, clang) = file_name.split_at(file_name.rfind("-").unwrap());
2260
2261 tool.path.set_file_name(clang.trim_start_matches("-"));
2262 tool.path.set_extension("exe");
2263 tool.args.push(format!("--target={}", target).into());
2264
2265 // Additionally, shell scripts for target i686-linux-android versions 16 to 24
2266 // pass the `mstackrealign` option so we do that here as well.
2267 if target.contains("i686-linux-android") {
2268 let (_, version) = target.split_at(target.rfind("d").unwrap() + 1);
2269 if let Ok(version) = version.parse::<u32>() {
2270 if version > 15 && version < 25 {
2271 tool.args.push("-mstackrealign".into());
2272 }
2273 }
2274 }
2275 };
2276 }
2277
2278 // If we found `cl.exe` in our environment, the tool we're returning is
2279 // an MSVC-like tool, *and* no env vars were set then set env vars for
2280 // the tool that we're returning.
2281 //
2282 // Env vars are needed for things like `link.exe` being put into PATH as
2283 // well as header include paths sometimes. These paths are automatically
2284 // included by default but if the `CC` or `CXX` env vars are set these
2285 // won't be used. This'll ensure that when the env vars are used to
2286 // configure for invocations like `clang-cl` we still get a "works out
2287 // of the box" experience.
2288 if let Some(cl_exe) = cl_exe {
2289 if tool.family == (ToolFamily::Msvc { clang_cl: true })
2290 && tool.env.len() == 0
2291 && target.contains("msvc")
2292 {
2293 for &(ref k, ref v) in cl_exe.env.iter() {
2294 tool.env.push((k.to_owned(), v.to_owned()));
2295 }
2296 }
2297 }
2298
2299 Ok(tool)
2300 }
2301
get_var(&self, var_base: &str) -> Result<String, Error>2302 fn get_var(&self, var_base: &str) -> Result<String, Error> {
2303 let target = self.get_target()?;
2304 let host = self.get_host()?;
2305 let kind = if host == target { "HOST" } else { "TARGET" };
2306 let target_u = target.replace("-", "_");
2307 let res = self
2308 .getenv(&format!("{}_{}", var_base, target))
2309 .or_else(|| self.getenv(&format!("{}_{}", var_base, target_u)))
2310 .or_else(|| self.getenv(&format!("{}_{}", kind, var_base)))
2311 .or_else(|| self.getenv(var_base));
2312
2313 match res {
2314 Some(res) => Ok(res),
2315 None => Err(Error::new(
2316 ErrorKind::EnvVarNotFound,
2317 &format!("Could not find environment variable {}.", var_base),
2318 )),
2319 }
2320 }
2321
envflags(&self, name: &str) -> Vec<String>2322 fn envflags(&self, name: &str) -> Vec<String> {
2323 self.get_var(name)
2324 .unwrap_or(String::new())
2325 .split_ascii_whitespace()
2326 .map(|slice| slice.to_string())
2327 .collect()
2328 }
2329
2330 /// Returns a fallback `cc_compiler_wrapper` by introspecting `RUSTC_WRAPPER`
rustc_wrapper_fallback() -> Option<String>2331 fn rustc_wrapper_fallback() -> Option<String> {
2332 // No explicit CC wrapper was detected, but check if RUSTC_WRAPPER
2333 // is defined and is a build accelerator that is compatible with
2334 // C/C++ compilers (e.g. sccache)
2335 const VALID_WRAPPERS: &[&'static str] = &["sccache", "cachepot"];
2336
2337 let rustc_wrapper = std::env::var_os("RUSTC_WRAPPER")?;
2338 let wrapper_path = Path::new(&rustc_wrapper);
2339 let wrapper_stem = wrapper_path.file_stem()?;
2340
2341 if VALID_WRAPPERS.contains(&wrapper_stem.to_str()?) {
2342 Some(rustc_wrapper.to_str()?.to_owned())
2343 } else {
2344 None
2345 }
2346 }
2347
2348 /// Returns compiler path, optional modifier name from whitelist, and arguments vec
env_tool(&self, name: &str) -> Option<(String, Option<String>, Vec<String>)>2349 fn env_tool(&self, name: &str) -> Option<(String, Option<String>, Vec<String>)> {
2350 let tool = match self.get_var(name) {
2351 Ok(tool) => tool,
2352 Err(_) => return None,
2353 };
2354
2355 // If this is an exact path on the filesystem we don't want to do any
2356 // interpretation at all, just pass it on through. This'll hopefully get
2357 // us to support spaces-in-paths.
2358 if Path::new(&tool).exists() {
2359 return Some((tool, None, Vec::new()));
2360 }
2361
2362 // Ok now we want to handle a couple of scenarios. We'll assume from
2363 // here on out that spaces are splitting separate arguments. Two major
2364 // features we want to support are:
2365 //
2366 // CC='sccache cc'
2367 //
2368 // aka using `sccache` or any other wrapper/caching-like-thing for
2369 // compilations. We want to know what the actual compiler is still,
2370 // though, because our `Tool` API support introspection of it to see
2371 // what compiler is in use.
2372 //
2373 // additionally we want to support
2374 //
2375 // CC='cc -flag'
2376 //
2377 // where the CC env var is used to also pass default flags to the C
2378 // compiler.
2379 //
2380 // It's true that everything here is a bit of a pain, but apparently if
2381 // you're not literally make or bash then you get a lot of bug reports.
2382 let known_wrappers = ["ccache", "distcc", "sccache", "icecc", "cachepot"];
2383
2384 let mut parts = tool.split_whitespace();
2385 let maybe_wrapper = match parts.next() {
2386 Some(s) => s,
2387 None => return None,
2388 };
2389
2390 let file_stem = Path::new(maybe_wrapper)
2391 .file_stem()
2392 .unwrap()
2393 .to_str()
2394 .unwrap();
2395 if known_wrappers.contains(&file_stem) {
2396 if let Some(compiler) = parts.next() {
2397 return Some((
2398 compiler.to_string(),
2399 Some(maybe_wrapper.to_string()),
2400 parts.map(|s| s.to_string()).collect(),
2401 ));
2402 }
2403 }
2404
2405 Some((
2406 maybe_wrapper.to_string(),
2407 Self::rustc_wrapper_fallback(),
2408 parts.map(|s| s.to_string()).collect(),
2409 ))
2410 }
2411
2412 /// Returns the C++ standard library:
2413 /// 1. If [cpp_link_stdlib](cc::Build::cpp_link_stdlib) is set, uses its value.
2414 /// 2. Else if the `CXXSTDLIB` environment variable is set, uses its value.
2415 /// 3. Else the default is `libc++` for OS X and BSDs, `libc++_shared` for Android,
2416 /// `None` for MSVC and `libstdc++` for anything else.
get_cpp_link_stdlib(&self) -> Result<Option<String>, Error>2417 fn get_cpp_link_stdlib(&self) -> Result<Option<String>, Error> {
2418 match self.cpp_link_stdlib.clone() {
2419 Some(s) => Ok(s),
2420 None => {
2421 if let Ok(stdlib) = self.get_var("CXXSTDLIB") {
2422 if stdlib.is_empty() {
2423 Ok(None)
2424 } else {
2425 Ok(Some(stdlib))
2426 }
2427 } else {
2428 let target = self.get_target()?;
2429 if target.contains("msvc") {
2430 Ok(None)
2431 } else if target.contains("apple") {
2432 Ok(Some("c++".to_string()))
2433 } else if target.contains("freebsd") {
2434 Ok(Some("c++".to_string()))
2435 } else if target.contains("openbsd") {
2436 Ok(Some("c++".to_string()))
2437 } else if target.contains("android") {
2438 Ok(Some("c++_shared".to_string()))
2439 } else {
2440 Ok(Some("stdc++".to_string()))
2441 }
2442 }
2443 }
2444 }
2445 }
2446
get_ar(&self) -> Result<(Command, String), Error>2447 fn get_ar(&self) -> Result<(Command, String), Error> {
2448 if let Some(ref p) = self.archiver {
2449 let name = p.file_name().and_then(|s| s.to_str()).unwrap_or("ar");
2450 return Ok((self.cmd(p), name.to_string()));
2451 }
2452 if let Ok(p) = self.get_var("AR") {
2453 return Ok((self.cmd(&p), p));
2454 }
2455 let target = self.get_target()?;
2456 let default_ar = "ar".to_string();
2457 let program = if target.contains("android") {
2458 format!("{}-ar", target.replace("armv7", "arm"))
2459 } else if target.contains("emscripten") {
2460 // Windows use bat files so we have to be a bit more specific
2461 if cfg!(windows) {
2462 let mut cmd = self.cmd("cmd");
2463 cmd.arg("/c").arg("emar.bat");
2464 return Ok((cmd, "emar.bat".to_string()));
2465 }
2466
2467 "emar".to_string()
2468 } else if target.contains("msvc") {
2469 match windows_registry::find(&target, "lib.exe") {
2470 Some(t) => return Ok((t, "lib.exe".to_string())),
2471 None => "lib.exe".to_string(),
2472 }
2473 } else if target.contains("illumos") {
2474 // The default 'ar' on illumos uses a non-standard flags,
2475 // but the OS comes bundled with a GNU-compatible variant.
2476 //
2477 // Use the GNU-variant to match other Unix systems.
2478 "gar".to_string()
2479 } else if self.get_host()? != target {
2480 match self.prefix_for_target(&target) {
2481 Some(p) => {
2482 let target_ar = format!("{}-ar", p);
2483 if Command::new(&target_ar).output().is_ok() {
2484 target_ar
2485 } else {
2486 default_ar
2487 }
2488 }
2489 None => default_ar,
2490 }
2491 } else {
2492 default_ar
2493 };
2494 Ok((self.cmd(&program), program))
2495 }
2496
prefix_for_target(&self, target: &str) -> Option<String>2497 fn prefix_for_target(&self, target: &str) -> Option<String> {
2498 // CROSS_COMPILE is of the form: "arm-linux-gnueabi-"
2499 let cc_env = self.getenv("CROSS_COMPILE");
2500 let cross_compile = cc_env
2501 .as_ref()
2502 .map(|s| s.trim_right_matches('-').to_owned());
2503 cross_compile.or(match &target[..] {
2504 "aarch64-unknown-linux-gnu" => Some("aarch64-linux-gnu"),
2505 "aarch64-unknown-linux-musl" => Some("aarch64-linux-musl"),
2506 "aarch64-unknown-netbsd" => Some("aarch64--netbsd"),
2507 "arm-unknown-linux-gnueabi" => Some("arm-linux-gnueabi"),
2508 "armv4t-unknown-linux-gnueabi" => Some("arm-linux-gnueabi"),
2509 "armv5te-unknown-linux-gnueabi" => Some("arm-linux-gnueabi"),
2510 "armv5te-unknown-linux-musleabi" => Some("arm-linux-gnueabi"),
2511 "arm-frc-linux-gnueabi" => Some("arm-frc-linux-gnueabi"),
2512 "arm-unknown-linux-gnueabihf" => Some("arm-linux-gnueabihf"),
2513 "arm-unknown-linux-musleabi" => Some("arm-linux-musleabi"),
2514 "arm-unknown-linux-musleabihf" => Some("arm-linux-musleabihf"),
2515 "arm-unknown-netbsd-eabi" => Some("arm--netbsdelf-eabi"),
2516 "armv6-unknown-netbsd-eabihf" => Some("armv6--netbsdelf-eabihf"),
2517 "armv7-unknown-linux-gnueabi" => Some("arm-linux-gnueabi"),
2518 "armv7-unknown-linux-gnueabihf" => Some("arm-linux-gnueabihf"),
2519 "armv7-unknown-linux-musleabihf" => Some("arm-linux-musleabihf"),
2520 "armv7neon-unknown-linux-gnueabihf" => Some("arm-linux-gnueabihf"),
2521 "armv7neon-unknown-linux-musleabihf" => Some("arm-linux-musleabihf"),
2522 "thumbv7-unknown-linux-gnueabihf" => Some("arm-linux-gnueabihf"),
2523 "thumbv7-unknown-linux-musleabihf" => Some("arm-linux-musleabihf"),
2524 "thumbv7neon-unknown-linux-gnueabihf" => Some("arm-linux-gnueabihf"),
2525 "thumbv7neon-unknown-linux-musleabihf" => Some("arm-linux-musleabihf"),
2526 "armv7-unknown-netbsd-eabihf" => Some("armv7--netbsdelf-eabihf"),
2527 "hexagon-unknown-linux-musl" => Some("hexagon-linux-musl"),
2528 "i586-unknown-linux-musl" => Some("musl"),
2529 "i686-pc-windows-gnu" => Some("i686-w64-mingw32"),
2530 "i686-uwp-windows-gnu" => Some("i686-w64-mingw32"),
2531 "i686-unknown-linux-gnu" => self.find_working_gnu_prefix(&[
2532 "i686-linux-gnu",
2533 "x86_64-linux-gnu", // transparently support gcc-multilib
2534 ]), // explicit None if not found, so caller knows to fall back
2535 "i686-unknown-linux-musl" => Some("musl"),
2536 "i686-unknown-netbsd" => Some("i486--netbsdelf"),
2537 "mips-unknown-linux-gnu" => Some("mips-linux-gnu"),
2538 "mips-unknown-linux-musl" => Some("mips-linux-musl"),
2539 "mipsel-unknown-linux-gnu" => Some("mipsel-linux-gnu"),
2540 "mipsel-unknown-linux-musl" => Some("mipsel-linux-musl"),
2541 "mips64-unknown-linux-gnuabi64" => Some("mips64-linux-gnuabi64"),
2542 "mips64el-unknown-linux-gnuabi64" => Some("mips64el-linux-gnuabi64"),
2543 "mipsisa32r6-unknown-linux-gnu" => Some("mipsisa32r6-linux-gnu"),
2544 "mipsisa32r6el-unknown-linux-gnu" => Some("mipsisa32r6el-linux-gnu"),
2545 "mipsisa64r6-unknown-linux-gnuabi64" => Some("mipsisa64r6-linux-gnuabi64"),
2546 "mipsisa64r6el-unknown-linux-gnuabi64" => Some("mipsisa64r6el-linux-gnuabi64"),
2547 "powerpc-unknown-linux-gnu" => Some("powerpc-linux-gnu"),
2548 "powerpc-unknown-linux-gnuspe" => Some("powerpc-linux-gnuspe"),
2549 "powerpc-unknown-netbsd" => Some("powerpc--netbsd"),
2550 "powerpc64-unknown-linux-gnu" => Some("powerpc-linux-gnu"),
2551 "powerpc64le-unknown-linux-gnu" => Some("powerpc64le-linux-gnu"),
2552 "riscv32i-unknown-none-elf" => self.find_working_gnu_prefix(&[
2553 "riscv32-unknown-elf",
2554 "riscv64-unknown-elf",
2555 "riscv-none-embed",
2556 ]),
2557 "riscv32imac-unknown-none-elf" => self.find_working_gnu_prefix(&[
2558 "riscv32-unknown-elf",
2559 "riscv64-unknown-elf",
2560 "riscv-none-embed",
2561 ]),
2562 "riscv32imc-unknown-none-elf" => self.find_working_gnu_prefix(&[
2563 "riscv32-unknown-elf",
2564 "riscv64-unknown-elf",
2565 "riscv-none-embed",
2566 ]),
2567 "riscv64gc-unknown-none-elf" => self.find_working_gnu_prefix(&[
2568 "riscv64-unknown-elf",
2569 "riscv32-unknown-elf",
2570 "riscv-none-embed",
2571 ]),
2572 "riscv64imac-unknown-none-elf" => self.find_working_gnu_prefix(&[
2573 "riscv64-unknown-elf",
2574 "riscv32-unknown-elf",
2575 "riscv-none-embed",
2576 ]),
2577 "riscv64gc-unknown-linux-gnu" => Some("riscv64-linux-gnu"),
2578 "riscv32gc-unknown-linux-gnu" => Some("riscv32-linux-gnu"),
2579 "riscv64gc-unknown-linux-musl" => Some("riscv64-linux-musl"),
2580 "riscv32gc-unknown-linux-musl" => Some("riscv32-linux-musl"),
2581 "s390x-unknown-linux-gnu" => Some("s390x-linux-gnu"),
2582 "sparc-unknown-linux-gnu" => Some("sparc-linux-gnu"),
2583 "sparc64-unknown-linux-gnu" => Some("sparc64-linux-gnu"),
2584 "sparc64-unknown-netbsd" => Some("sparc64--netbsd"),
2585 "sparcv9-sun-solaris" => Some("sparcv9-sun-solaris"),
2586 "armv7a-none-eabi" => Some("arm-none-eabi"),
2587 "armv7a-none-eabihf" => Some("arm-none-eabi"),
2588 "armebv7r-none-eabi" => Some("arm-none-eabi"),
2589 "armebv7r-none-eabihf" => Some("arm-none-eabi"),
2590 "armv7r-none-eabi" => Some("arm-none-eabi"),
2591 "armv7r-none-eabihf" => Some("arm-none-eabi"),
2592 "thumbv6m-none-eabi" => Some("arm-none-eabi"),
2593 "thumbv7em-none-eabi" => Some("arm-none-eabi"),
2594 "thumbv7em-none-eabihf" => Some("arm-none-eabi"),
2595 "thumbv7m-none-eabi" => Some("arm-none-eabi"),
2596 "thumbv8m.base-none-eabi" => Some("arm-none-eabi"),
2597 "thumbv8m.main-none-eabi" => Some("arm-none-eabi"),
2598 "thumbv8m.main-none-eabihf" => Some("arm-none-eabi"),
2599 "x86_64-pc-windows-gnu" => Some("x86_64-w64-mingw32"),
2600 "x86_64-uwp-windows-gnu" => Some("x86_64-w64-mingw32"),
2601 "x86_64-rumprun-netbsd" => Some("x86_64-rumprun-netbsd"),
2602 "x86_64-unknown-linux-gnu" => self.find_working_gnu_prefix(&[
2603 "x86_64-linux-gnu", // rustfmt wrap
2604 ]), // explicit None if not found, so caller knows to fall back
2605 "x86_64-unknown-linux-musl" => Some("musl"),
2606 "x86_64-unknown-netbsd" => Some("x86_64--netbsd"),
2607 _ => None,
2608 }
2609 .map(|x| x.to_owned()))
2610 }
2611
2612 /// Some platforms have multiple, compatible, canonical prefixes. Look through
2613 /// each possible prefix for a compiler that exists and return it. The prefixes
2614 /// should be ordered from most-likely to least-likely.
find_working_gnu_prefix(&self, prefixes: &[&'static str]) -> Option<&'static str>2615 fn find_working_gnu_prefix(&self, prefixes: &[&'static str]) -> Option<&'static str> {
2616 let suffix = if self.cpp { "-g++" } else { "-gcc" };
2617 let extension = std::env::consts::EXE_SUFFIX;
2618
2619 // Loop through PATH entries searching for each toolchain. This ensures that we
2620 // are more likely to discover the toolchain early on, because chances are good
2621 // that the desired toolchain is in one of the higher-priority paths.
2622 env::var_os("PATH")
2623 .as_ref()
2624 .and_then(|path_entries| {
2625 env::split_paths(path_entries).find_map(|path_entry| {
2626 for prefix in prefixes {
2627 let target_compiler = format!("{}{}{}", prefix, suffix, extension);
2628 if path_entry.join(&target_compiler).exists() {
2629 return Some(prefix);
2630 }
2631 }
2632 None
2633 })
2634 })
2635 .map(|prefix| *prefix)
2636 .or_else(||
2637 // If no toolchain was found, provide the first toolchain that was passed in.
2638 // This toolchain has been shown not to exist, however it will appear in the
2639 // error that is shown to the user which should make it easier to search for
2640 // where it should be obtained.
2641 prefixes.first().map(|prefix| *prefix))
2642 }
2643
get_target(&self) -> Result<String, Error>2644 fn get_target(&self) -> Result<String, Error> {
2645 match self.target.clone() {
2646 Some(t) => Ok(t),
2647 None => Ok(self.getenv_unwrap("TARGET")?),
2648 }
2649 }
2650
get_host(&self) -> Result<String, Error>2651 fn get_host(&self) -> Result<String, Error> {
2652 match self.host.clone() {
2653 Some(h) => Ok(h),
2654 None => Ok(self.getenv_unwrap("HOST")?),
2655 }
2656 }
2657
get_opt_level(&self) -> Result<String, Error>2658 fn get_opt_level(&self) -> Result<String, Error> {
2659 match self.opt_level.as_ref().cloned() {
2660 Some(ol) => Ok(ol),
2661 None => Ok(self.getenv_unwrap("OPT_LEVEL")?),
2662 }
2663 }
2664
get_debug(&self) -> bool2665 fn get_debug(&self) -> bool {
2666 self.debug.unwrap_or_else(|| match self.getenv("DEBUG") {
2667 Some(s) => s != "false",
2668 None => false,
2669 })
2670 }
2671
get_force_frame_pointer(&self) -> bool2672 fn get_force_frame_pointer(&self) -> bool {
2673 self.force_frame_pointer.unwrap_or_else(|| self.get_debug())
2674 }
2675
get_out_dir(&self) -> Result<PathBuf, Error>2676 fn get_out_dir(&self) -> Result<PathBuf, Error> {
2677 match self.out_dir.clone() {
2678 Some(p) => Ok(p),
2679 None => Ok(env::var_os("OUT_DIR").map(PathBuf::from).ok_or_else(|| {
2680 Error::new(
2681 ErrorKind::EnvVarNotFound,
2682 "Environment variable OUT_DIR not defined.",
2683 )
2684 })?),
2685 }
2686 }
2687
getenv(&self, v: &str) -> Option<String>2688 fn getenv(&self, v: &str) -> Option<String> {
2689 let mut cache = self.env_cache.lock().unwrap();
2690 if let Some(val) = cache.get(v) {
2691 return val.clone();
2692 }
2693 let r = env::var(v).ok();
2694 self.print(&format!("{} = {:?}", v, r));
2695 cache.insert(v.to_string(), r.clone());
2696 r
2697 }
2698
getenv_unwrap(&self, v: &str) -> Result<String, Error>2699 fn getenv_unwrap(&self, v: &str) -> Result<String, Error> {
2700 match self.getenv(v) {
2701 Some(s) => Ok(s),
2702 None => Err(Error::new(
2703 ErrorKind::EnvVarNotFound,
2704 &format!("Environment variable {} not defined.", v.to_string()),
2705 )),
2706 }
2707 }
2708
print(&self, s: &str)2709 fn print(&self, s: &str) {
2710 if self.cargo_metadata {
2711 println!("{}", s);
2712 }
2713 }
2714
fix_env_for_apple_os(&self, cmd: &mut Command) -> Result<(), Error>2715 fn fix_env_for_apple_os(&self, cmd: &mut Command) -> Result<(), Error> {
2716 let target = self.get_target()?;
2717 let host = self.get_host()?;
2718 if host.contains("apple-darwin") && target.contains("apple-darwin") {
2719 // If, for example, `cargo` runs during the build of an XCode project, then `SDKROOT` environment variable
2720 // would represent the current target, and this is the problem for us, if we want to compile something
2721 // for the host, when host != target.
2722 // We can not just remove `SDKROOT`, because, again, for example, XCode add to PATH
2723 // /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin
2724 // and `cc` from this path can not find system include files, like `pthread.h`, if `SDKROOT`
2725 // is not set
2726 if let Ok(sdkroot) = env::var("SDKROOT") {
2727 if !sdkroot.contains("MacOSX") {
2728 let macos_sdk = self.apple_sdk_root("macosx")?;
2729 cmd.env("SDKROOT", macos_sdk);
2730 }
2731 }
2732 // Additionally, `IPHONEOS_DEPLOYMENT_TARGET` must not be set when using the Xcode linker at
2733 // "/Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/ld",
2734 // although this is apparently ignored when using the linker at "/usr/bin/ld".
2735 cmd.env_remove("IPHONEOS_DEPLOYMENT_TARGET");
2736 }
2737 Ok(())
2738 }
2739
apple_sdk_root(&self, sdk: &str) -> Result<OsString, Error>2740 fn apple_sdk_root(&self, sdk: &str) -> Result<OsString, Error> {
2741 let mut cache = self
2742 .apple_sdk_root_cache
2743 .lock()
2744 .expect("apple_sdk_root_cache lock failed");
2745 if let Some(ret) = cache.get(sdk) {
2746 return Ok(ret.clone());
2747 }
2748
2749 let sdk_path = run_output(
2750 self.cmd("xcrun")
2751 .arg("--show-sdk-path")
2752 .arg("--sdk")
2753 .arg(sdk),
2754 "xcrun",
2755 )?;
2756
2757 let sdk_path = match String::from_utf8(sdk_path) {
2758 Ok(p) => p,
2759 Err(_) => {
2760 return Err(Error::new(
2761 ErrorKind::IOError,
2762 "Unable to determine iOS SDK path.",
2763 ));
2764 }
2765 };
2766 let ret: OsString = sdk_path.trim().into();
2767 cache.insert(sdk.into(), ret.clone());
2768 Ok(ret)
2769 }
2770 }
2771
2772 impl Default for Build {
default() -> Build2773 fn default() -> Build {
2774 Build::new()
2775 }
2776 }
2777
2778 impl Tool {
new(path: PathBuf) -> Self2779 fn new(path: PathBuf) -> Self {
2780 Tool::with_features(path, None, false)
2781 }
2782
with_clang_driver(path: PathBuf, clang_driver: Option<&str>) -> Self2783 fn with_clang_driver(path: PathBuf, clang_driver: Option<&str>) -> Self {
2784 Self::with_features(path, clang_driver, false)
2785 }
2786
2787 #[cfg(windows)]
2788 /// Explicitly set the `ToolFamily`, skipping name-based detection.
with_family(path: PathBuf, family: ToolFamily) -> Self2789 fn with_family(path: PathBuf, family: ToolFamily) -> Self {
2790 Self {
2791 path: path,
2792 cc_wrapper_path: None,
2793 cc_wrapper_args: Vec::new(),
2794 args: Vec::new(),
2795 env: Vec::new(),
2796 family: family,
2797 cuda: false,
2798 removed_args: Vec::new(),
2799 }
2800 }
2801
with_features(path: PathBuf, clang_driver: Option<&str>, cuda: bool) -> Self2802 fn with_features(path: PathBuf, clang_driver: Option<&str>, cuda: bool) -> Self {
2803 // Try to detect family of the tool from its name, falling back to Gnu.
2804 let family = if let Some(fname) = path.file_name().and_then(|p| p.to_str()) {
2805 if fname.contains("clang-cl") {
2806 ToolFamily::Msvc { clang_cl: true }
2807 } else if fname.ends_with("cl") || fname == "cl.exe" {
2808 ToolFamily::Msvc { clang_cl: false }
2809 } else if fname.contains("clang") {
2810 match clang_driver {
2811 Some("cl") => ToolFamily::Msvc { clang_cl: true },
2812 _ => ToolFamily::Clang,
2813 }
2814 } else {
2815 ToolFamily::Gnu
2816 }
2817 } else {
2818 ToolFamily::Gnu
2819 };
2820
2821 Tool {
2822 path: path,
2823 cc_wrapper_path: None,
2824 cc_wrapper_args: Vec::new(),
2825 args: Vec::new(),
2826 env: Vec::new(),
2827 family: family,
2828 cuda: cuda,
2829 removed_args: Vec::new(),
2830 }
2831 }
2832
2833 /// Add an argument to be stripped from the final command arguments.
remove_arg(&mut self, flag: OsString)2834 fn remove_arg(&mut self, flag: OsString) {
2835 self.removed_args.push(flag);
2836 }
2837
2838 /// Add a flag, and optionally prepend the NVCC wrapper flag "-Xcompiler".
2839 ///
2840 /// Currently this is only used for compiling CUDA sources, since NVCC only
2841 /// accepts a limited set of GNU-like flags, and the rest must be prefixed
2842 /// with a "-Xcompiler" flag to get passed to the underlying C++ compiler.
push_cc_arg(&mut self, flag: OsString)2843 fn push_cc_arg(&mut self, flag: OsString) {
2844 if self.cuda {
2845 self.args.push("-Xcompiler".into());
2846 }
2847 self.args.push(flag);
2848 }
2849
is_duplicate_opt_arg(&self, flag: &OsString) -> bool2850 fn is_duplicate_opt_arg(&self, flag: &OsString) -> bool {
2851 let flag = flag.to_str().unwrap();
2852 let mut chars = flag.chars();
2853
2854 // Only duplicate check compiler flags
2855 if self.is_like_msvc() {
2856 if chars.next() != Some('/') {
2857 return false;
2858 }
2859 } else if self.is_like_gnu() || self.is_like_clang() {
2860 if chars.next() != Some('-') {
2861 return false;
2862 }
2863 }
2864
2865 // Check for existing optimization flags (-O, /O)
2866 if chars.next() == Some('O') {
2867 return self
2868 .args()
2869 .iter()
2870 .any(|ref a| a.to_str().unwrap_or("").chars().nth(1) == Some('O'));
2871 }
2872
2873 // TODO Check for existing -m..., -m...=..., /arch:... flags
2874 return false;
2875 }
2876
2877 /// Don't push optimization arg if it conflicts with existing args
push_opt_unless_duplicate(&mut self, flag: OsString)2878 fn push_opt_unless_duplicate(&mut self, flag: OsString) {
2879 if self.is_duplicate_opt_arg(&flag) {
2880 println!("Info: Ignoring duplicate arg {:?}", &flag);
2881 } else {
2882 self.push_cc_arg(flag);
2883 }
2884 }
2885
2886 /// Converts this compiler into a `Command` that's ready to be run.
2887 ///
2888 /// This is useful for when the compiler needs to be executed and the
2889 /// command returned will already have the initial arguments and environment
2890 /// variables configured.
to_command(&self) -> Command2891 pub fn to_command(&self) -> Command {
2892 let mut cmd = match self.cc_wrapper_path {
2893 Some(ref cc_wrapper_path) => {
2894 let mut cmd = Command::new(&cc_wrapper_path);
2895 cmd.arg(&self.path);
2896 cmd
2897 }
2898 None => Command::new(&self.path),
2899 };
2900 cmd.args(&self.cc_wrapper_args);
2901
2902 let value = self
2903 .args
2904 .iter()
2905 .filter(|a| !self.removed_args.contains(a))
2906 .collect::<Vec<_>>();
2907 cmd.args(&value);
2908
2909 for &(ref k, ref v) in self.env.iter() {
2910 cmd.env(k, v);
2911 }
2912 cmd
2913 }
2914
2915 /// Returns the path for this compiler.
2916 ///
2917 /// Note that this may not be a path to a file on the filesystem, e.g. "cc",
2918 /// but rather something which will be resolved when a process is spawned.
path(&self) -> &Path2919 pub fn path(&self) -> &Path {
2920 &self.path
2921 }
2922
2923 /// Returns the default set of arguments to the compiler needed to produce
2924 /// executables for the target this compiler generates.
args(&self) -> &[OsString]2925 pub fn args(&self) -> &[OsString] {
2926 &self.args
2927 }
2928
2929 /// Returns the set of environment variables needed for this compiler to
2930 /// operate.
2931 ///
2932 /// This is typically only used for MSVC compilers currently.
env(&self) -> &[(OsString, OsString)]2933 pub fn env(&self) -> &[(OsString, OsString)] {
2934 &self.env
2935 }
2936
2937 /// Returns the compiler command in format of CC environment variable.
2938 /// Or empty string if CC env was not present
2939 ///
2940 /// This is typically used by configure script
cc_env(&self) -> OsString2941 pub fn cc_env(&self) -> OsString {
2942 match self.cc_wrapper_path {
2943 Some(ref cc_wrapper_path) => {
2944 let mut cc_env = cc_wrapper_path.as_os_str().to_owned();
2945 cc_env.push(" ");
2946 cc_env.push(self.path.to_path_buf().into_os_string());
2947 for arg in self.cc_wrapper_args.iter() {
2948 cc_env.push(" ");
2949 cc_env.push(arg);
2950 }
2951 cc_env
2952 }
2953 None => OsString::from(""),
2954 }
2955 }
2956
2957 /// Returns the compiler flags in format of CFLAGS environment variable.
2958 /// Important here - this will not be CFLAGS from env, its internal gcc's flags to use as CFLAGS
2959 /// This is typically used by configure script
cflags_env(&self) -> OsString2960 pub fn cflags_env(&self) -> OsString {
2961 let mut flags = OsString::new();
2962 for (i, arg) in self.args.iter().enumerate() {
2963 if i > 0 {
2964 flags.push(" ");
2965 }
2966 flags.push(arg);
2967 }
2968 flags
2969 }
2970
2971 /// Whether the tool is GNU Compiler Collection-like.
is_like_gnu(&self) -> bool2972 pub fn is_like_gnu(&self) -> bool {
2973 self.family == ToolFamily::Gnu
2974 }
2975
2976 /// Whether the tool is Clang-like.
is_like_clang(&self) -> bool2977 pub fn is_like_clang(&self) -> bool {
2978 self.family == ToolFamily::Clang
2979 }
2980
2981 /// Whether the tool is MSVC-like.
is_like_msvc(&self) -> bool2982 pub fn is_like_msvc(&self) -> bool {
2983 match self.family {
2984 ToolFamily::Msvc { .. } => true,
2985 _ => false,
2986 }
2987 }
2988 }
2989
run(cmd: &mut Command, program: &str) -> Result<(), Error>2990 fn run(cmd: &mut Command, program: &str) -> Result<(), Error> {
2991 let (mut child, print) = spawn(cmd, program)?;
2992 let status = match child.wait() {
2993 Ok(s) => s,
2994 Err(_) => {
2995 return Err(Error::new(
2996 ErrorKind::ToolExecError,
2997 &format!(
2998 "Failed to wait on spawned child process, command {:?} with args {:?}.",
2999 cmd, program
3000 ),
3001 ));
3002 }
3003 };
3004 print.join().unwrap();
3005 println!("{}", status);
3006
3007 if status.success() {
3008 Ok(())
3009 } else {
3010 Err(Error::new(
3011 ErrorKind::ToolExecError,
3012 &format!(
3013 "Command {:?} with args {:?} did not execute successfully (status code {}).",
3014 cmd, program, status
3015 ),
3016 ))
3017 }
3018 }
3019
run_output(cmd: &mut Command, program: &str) -> Result<Vec<u8>, Error>3020 fn run_output(cmd: &mut Command, program: &str) -> Result<Vec<u8>, Error> {
3021 cmd.stdout(Stdio::piped());
3022 let (mut child, print) = spawn(cmd, program)?;
3023 let mut stdout = vec![];
3024 child
3025 .stdout
3026 .take()
3027 .unwrap()
3028 .read_to_end(&mut stdout)
3029 .unwrap();
3030 let status = match child.wait() {
3031 Ok(s) => s,
3032 Err(_) => {
3033 return Err(Error::new(
3034 ErrorKind::ToolExecError,
3035 &format!(
3036 "Failed to wait on spawned child process, command {:?} with args {:?}.",
3037 cmd, program
3038 ),
3039 ));
3040 }
3041 };
3042 print.join().unwrap();
3043 println!("{}", status);
3044
3045 if status.success() {
3046 Ok(stdout)
3047 } else {
3048 Err(Error::new(
3049 ErrorKind::ToolExecError,
3050 &format!(
3051 "Command {:?} with args {:?} did not execute successfully (status code {}).",
3052 cmd, program, status
3053 ),
3054 ))
3055 }
3056 }
3057
spawn(cmd: &mut Command, program: &str) -> Result<(Child, JoinHandle<()>), Error>3058 fn spawn(cmd: &mut Command, program: &str) -> Result<(Child, JoinHandle<()>), Error> {
3059 println!("running: {:?}", cmd);
3060
3061 // Capture the standard error coming from these programs, and write it out
3062 // with cargo:warning= prefixes. Note that this is a bit wonky to avoid
3063 // requiring the output to be UTF-8, we instead just ship bytes from one
3064 // location to another.
3065 match cmd.stderr(Stdio::piped()).spawn() {
3066 Ok(mut child) => {
3067 let stderr = BufReader::new(child.stderr.take().unwrap());
3068 let print = thread::spawn(move || {
3069 for line in stderr.split(b'\n').filter_map(|l| l.ok()) {
3070 print!("cargo:warning=");
3071 std::io::stdout().write_all(&line).unwrap();
3072 println!("");
3073 }
3074 });
3075 Ok((child, print))
3076 }
3077 Err(ref e) if e.kind() == io::ErrorKind::NotFound => {
3078 let extra = if cfg!(windows) {
3079 " (see https://github.com/alexcrichton/cc-rs#compile-time-requirements \
3080 for help)"
3081 } else {
3082 ""
3083 };
3084 Err(Error::new(
3085 ErrorKind::ToolNotFound,
3086 &format!("Failed to find tool. Is `{}` installed?{}", program, extra),
3087 ))
3088 }
3089 Err(ref e) => Err(Error::new(
3090 ErrorKind::ToolExecError,
3091 &format!(
3092 "Command {:?} with args {:?} failed to start: {:?}",
3093 cmd, program, e
3094 ),
3095 )),
3096 }
3097 }
3098
fail(s: &str) -> !3099 fn fail(s: &str) -> ! {
3100 eprintln!("\n\nerror occurred: {}\n\n", s);
3101 std::process::exit(1);
3102 }
3103
command_add_output_file( cmd: &mut Command, dst: &Path, cuda: bool, msvc: bool, clang: bool, is_asm: bool, is_arm: bool, )3104 fn command_add_output_file(
3105 cmd: &mut Command,
3106 dst: &Path,
3107 cuda: bool,
3108 msvc: bool,
3109 clang: bool,
3110 is_asm: bool,
3111 is_arm: bool,
3112 ) {
3113 if msvc && !clang && !cuda && !(is_asm && is_arm) {
3114 let mut s = OsString::from("-Fo");
3115 s.push(&dst);
3116 cmd.arg(s);
3117 } else {
3118 cmd.arg("-o").arg(&dst);
3119 }
3120 }
3121
3122 // Use by default minimum available API level
3123 // See note about naming here
3124 // https://android.googlesource.com/platform/ndk/+/refs/heads/ndk-release-r21/docs/BuildSystemMaintainers.md#Clang
3125 static NEW_STANDALONE_ANDROID_COMPILERS: [&str; 4] = [
3126 "aarch64-linux-android21-clang",
3127 "armv7a-linux-androideabi16-clang",
3128 "i686-linux-android16-clang",
3129 "x86_64-linux-android21-clang",
3130 ];
3131
3132 // New "standalone" C/C++ cross-compiler executables from recent Android NDK
3133 // are just shell scripts that call main clang binary (from Android NDK) with
3134 // proper `--target` argument.
3135 //
3136 // For example, armv7a-linux-androideabi16-clang passes
3137 // `--target=armv7a-linux-androideabi16` to clang.
3138 // So to construct proper command line check if
3139 // `--target` argument would be passed or not to clang
android_clang_compiler_uses_target_arg_internally(clang_path: &Path) -> bool3140 fn android_clang_compiler_uses_target_arg_internally(clang_path: &Path) -> bool {
3141 if let Some(filename) = clang_path.file_name() {
3142 if let Some(filename_str) = filename.to_str() {
3143 filename_str.contains("android")
3144 } else {
3145 false
3146 }
3147 } else {
3148 false
3149 }
3150 }
3151
3152 #[test]
test_android_clang_compiler_uses_target_arg_internally()3153 fn test_android_clang_compiler_uses_target_arg_internally() {
3154 for version in 16..21 {
3155 assert!(android_clang_compiler_uses_target_arg_internally(
3156 &PathBuf::from(format!("armv7a-linux-androideabi{}-clang", version))
3157 ));
3158 assert!(android_clang_compiler_uses_target_arg_internally(
3159 &PathBuf::from(format!("armv7a-linux-androideabi{}-clang++", version))
3160 ));
3161 }
3162 assert!(!android_clang_compiler_uses_target_arg_internally(
3163 &PathBuf::from("clang")
3164 ));
3165 assert!(!android_clang_compiler_uses_target_arg_internally(
3166 &PathBuf::from("clang++")
3167 ));
3168 }
3169
autodetect_android_compiler(target: &str, host: &str, gnu: &str, clang: &str) -> String3170 fn autodetect_android_compiler(target: &str, host: &str, gnu: &str, clang: &str) -> String {
3171 let new_clang_key = match target {
3172 "aarch64-linux-android" => Some("aarch64"),
3173 "armv7-linux-androideabi" => Some("armv7a"),
3174 "i686-linux-android" => Some("i686"),
3175 "x86_64-linux-android" => Some("x86_64"),
3176 _ => None,
3177 };
3178
3179 let new_clang = new_clang_key
3180 .map(|key| {
3181 NEW_STANDALONE_ANDROID_COMPILERS
3182 .iter()
3183 .find(|x| x.starts_with(key))
3184 })
3185 .unwrap_or(None);
3186
3187 if let Some(new_clang) = new_clang {
3188 if Command::new(new_clang).output().is_ok() {
3189 return (*new_clang).into();
3190 }
3191 }
3192
3193 let target = target
3194 .replace("armv7neon", "arm")
3195 .replace("armv7", "arm")
3196 .replace("thumbv7neon", "arm")
3197 .replace("thumbv7", "arm");
3198 let gnu_compiler = format!("{}-{}", target, gnu);
3199 let clang_compiler = format!("{}-{}", target, clang);
3200
3201 // On Windows, the Android clang compiler is provided as a `.cmd` file instead
3202 // of a `.exe` file. `std::process::Command` won't run `.cmd` files unless the
3203 // `.cmd` is explicitly appended to the command name, so we do that here.
3204 let clang_compiler_cmd = format!("{}-{}.cmd", target, clang);
3205
3206 // Check if gnu compiler is present
3207 // if not, use clang
3208 if Command::new(&gnu_compiler).output().is_ok() {
3209 gnu_compiler
3210 } else if host.contains("windows") && Command::new(&clang_compiler_cmd).output().is_ok() {
3211 clang_compiler_cmd
3212 } else {
3213 clang_compiler
3214 }
3215 }
3216
3217 // Rust and clang/cc don't agree on how to name the target.
map_darwin_target_from_rust_to_compiler_architecture(target: &str) -> Option<&'static str>3218 fn map_darwin_target_from_rust_to_compiler_architecture(target: &str) -> Option<&'static str> {
3219 if target.contains("x86_64") {
3220 Some("x86_64")
3221 } else if target.contains("arm64e") {
3222 Some("arm64e")
3223 } else if target.contains("aarch64") {
3224 Some("arm64")
3225 } else if target.contains("i686") {
3226 Some("i386")
3227 } else if target.contains("powerpc") {
3228 Some("ppc")
3229 } else if target.contains("powerpc64") {
3230 Some("ppc64")
3231 } else {
3232 None
3233 }
3234 }
3235
which(tool: &Path) -> Option<PathBuf>3236 fn which(tool: &Path) -> Option<PathBuf> {
3237 fn check_exe(exe: &mut PathBuf) -> bool {
3238 let exe_ext = std::env::consts::EXE_EXTENSION;
3239 exe.exists() || (!exe_ext.is_empty() && exe.set_extension(exe_ext) && exe.exists())
3240 }
3241
3242 // If |tool| is not just one "word," assume it's an actual path...
3243 if tool.components().count() > 1 {
3244 let mut exe = PathBuf::from(tool);
3245 return if check_exe(&mut exe) { Some(exe) } else { None };
3246 }
3247
3248 // Loop through PATH entries searching for the |tool|.
3249 let path_entries = env::var_os("PATH")?;
3250 env::split_paths(&path_entries).find_map(|path_entry| {
3251 let mut exe = path_entry.join(tool);
3252 return if check_exe(&mut exe) { Some(exe) } else { None };
3253 })
3254 }
3255