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.contains("uefi") {
1561 if target.contains("x86_64") {
1562 cmd.args.push("--target=x86_64-unknown-windows-gnu".into());
1563 } else if target.contains("i686") {
1564 cmd.args.push("--target=i686-unknown-windows-gnu".into())
1565 }
1566 } else {
1567 cmd.args.push(format!("--target={}", target).into());
1568 }
1569 }
1570 }
1571 ToolFamily::Msvc { clang_cl } => {
1572 // This is an undocumented flag from MSVC but helps with making
1573 // builds more reproducible by avoiding putting timestamps into
1574 // files.
1575 cmd.push_cc_arg("-Brepro".into());
1576
1577 if clang_cl {
1578 if target.contains("x86_64") {
1579 cmd.push_cc_arg("-m64".into());
1580 } else if target.contains("86") {
1581 cmd.push_cc_arg("-m32".into());
1582 cmd.push_cc_arg("-arch:IA32".into());
1583 } else {
1584 cmd.push_cc_arg(format!("--target={}", target).into());
1585 }
1586 } else {
1587 if target.contains("i586") {
1588 cmd.push_cc_arg("-arch:IA32".into());
1589 }
1590 }
1591
1592 // There is a check in corecrt.h that will generate a
1593 // compilation error if
1594 // _ARM_WINAPI_PARTITION_DESKTOP_SDK_AVAILABLE is
1595 // not defined to 1. The check was added in Windows
1596 // 8 days because only store apps were allowed on ARM.
1597 // This changed with the release of Windows 10 IoT Core.
1598 // The check will be going away in future versions of
1599 // the SDK, but for all released versions of the
1600 // Windows SDK it is required.
1601 if target.contains("arm") || target.contains("thumb") {
1602 cmd.args
1603 .push("-D_ARM_WINAPI_PARTITION_DESKTOP_SDK_AVAILABLE=1".into());
1604 }
1605 }
1606 ToolFamily::Gnu => {
1607 if target.contains("i686") || target.contains("i586") {
1608 cmd.args.push("-m32".into());
1609 } else if target == "x86_64-unknown-linux-gnux32" {
1610 cmd.args.push("-mx32".into());
1611 } else if target.contains("x86_64") || target.contains("powerpc64") {
1612 cmd.args.push("-m64".into());
1613 }
1614
1615 if target.contains("darwin") {
1616 if let Some(arch) = map_darwin_target_from_rust_to_compiler_architecture(target)
1617 {
1618 cmd.args.push("-arch".into());
1619 cmd.args.push(arch.into());
1620 }
1621 }
1622
1623 if target.contains("-kmc-solid_") {
1624 cmd.args.push("-finput-charset=utf-8".into());
1625 }
1626
1627 if self.static_flag.is_none() {
1628 let features = self
1629 .getenv("CARGO_CFG_TARGET_FEATURE")
1630 .unwrap_or(String::new());
1631 if features.contains("crt-static") {
1632 cmd.args.push("-static".into());
1633 }
1634 }
1635
1636 // armv7 targets get to use armv7 instructions
1637 if (target.starts_with("armv7") || target.starts_with("thumbv7"))
1638 && (target.contains("-linux-") || target.contains("-kmc-solid_"))
1639 {
1640 cmd.args.push("-march=armv7-a".into());
1641 }
1642
1643 // (x86 Android doesn't say "eabi")
1644 if target.contains("-androideabi") && target.contains("v7") {
1645 // -march=armv7-a handled above
1646 cmd.args.push("-mthumb".into());
1647 if !target.contains("neon") {
1648 // On android we can guarantee some extra float instructions
1649 // (specified in the android spec online)
1650 // NEON guarantees even more; see below.
1651 cmd.args.push("-mfpu=vfpv3-d16".into());
1652 }
1653 cmd.args.push("-mfloat-abi=softfp".into());
1654 }
1655
1656 if target.contains("neon") {
1657 cmd.args.push("-mfpu=neon-vfpv4".into());
1658 }
1659
1660 if target.starts_with("armv4t-unknown-linux-") {
1661 cmd.args.push("-march=armv4t".into());
1662 cmd.args.push("-marm".into());
1663 cmd.args.push("-mfloat-abi=soft".into());
1664 }
1665
1666 if target.starts_with("armv5te-unknown-linux-") {
1667 cmd.args.push("-march=armv5te".into());
1668 cmd.args.push("-marm".into());
1669 cmd.args.push("-mfloat-abi=soft".into());
1670 }
1671
1672 // For us arm == armv6 by default
1673 if target.starts_with("arm-unknown-linux-") {
1674 cmd.args.push("-march=armv6".into());
1675 cmd.args.push("-marm".into());
1676 if target.ends_with("hf") {
1677 cmd.args.push("-mfpu=vfp".into());
1678 } else {
1679 cmd.args.push("-mfloat-abi=soft".into());
1680 }
1681 }
1682
1683 // We can guarantee some settings for FRC
1684 if target.starts_with("arm-frc-") {
1685 cmd.args.push("-march=armv7-a".into());
1686 cmd.args.push("-mcpu=cortex-a9".into());
1687 cmd.args.push("-mfpu=vfpv3".into());
1688 cmd.args.push("-mfloat-abi=softfp".into());
1689 cmd.args.push("-marm".into());
1690 }
1691
1692 // Turn codegen down on i586 to avoid some instructions.
1693 if target.starts_with("i586-unknown-linux-") {
1694 cmd.args.push("-march=pentium".into());
1695 }
1696
1697 // Set codegen level for i686 correctly
1698 if target.starts_with("i686-unknown-linux-") {
1699 cmd.args.push("-march=i686".into());
1700 }
1701
1702 // Looks like `musl-gcc` makes it hard for `-m32` to make its way
1703 // all the way to the linker, so we need to actually instruct the
1704 // linker that we're generating 32-bit executables as well. This'll
1705 // typically only be used for build scripts which transitively use
1706 // these flags that try to compile executables.
1707 if target == "i686-unknown-linux-musl" || target == "i586-unknown-linux-musl" {
1708 cmd.args.push("-Wl,-melf_i386".into());
1709 }
1710
1711 if target.starts_with("thumb") {
1712 cmd.args.push("-mthumb".into());
1713
1714 if target.ends_with("eabihf") {
1715 cmd.args.push("-mfloat-abi=hard".into())
1716 }
1717 }
1718 if target.starts_with("thumbv6m") {
1719 cmd.args.push("-march=armv6s-m".into());
1720 }
1721 if target.starts_with("thumbv7em") {
1722 cmd.args.push("-march=armv7e-m".into());
1723
1724 if target.ends_with("eabihf") {
1725 cmd.args.push("-mfpu=fpv4-sp-d16".into())
1726 }
1727 }
1728 if target.starts_with("thumbv7m") {
1729 cmd.args.push("-march=armv7-m".into());
1730 }
1731 if target.starts_with("thumbv8m.base") {
1732 cmd.args.push("-march=armv8-m.base".into());
1733 }
1734 if target.starts_with("thumbv8m.main") {
1735 cmd.args.push("-march=armv8-m.main".into());
1736
1737 if target.ends_with("eabihf") {
1738 cmd.args.push("-mfpu=fpv5-sp-d16".into())
1739 }
1740 }
1741 if target.starts_with("armebv7r") | target.starts_with("armv7r") {
1742 if target.starts_with("armeb") {
1743 cmd.args.push("-mbig-endian".into());
1744 } else {
1745 cmd.args.push("-mlittle-endian".into());
1746 }
1747
1748 // ARM mode
1749 cmd.args.push("-marm".into());
1750
1751 // R Profile
1752 cmd.args.push("-march=armv7-r".into());
1753
1754 if target.ends_with("eabihf") {
1755 // Calling convention
1756 cmd.args.push("-mfloat-abi=hard".into());
1757
1758 // lowest common denominator FPU
1759 // (see Cortex-R4 technical reference manual)
1760 cmd.args.push("-mfpu=vfpv3-d16".into())
1761 } else {
1762 // Calling convention
1763 cmd.args.push("-mfloat-abi=soft".into());
1764 }
1765 }
1766 if target.starts_with("armv7a") {
1767 cmd.args.push("-march=armv7-a".into());
1768
1769 if target.ends_with("eabihf") {
1770 // lowest common denominator FPU
1771 cmd.args.push("-mfpu=vfpv3-d16".into());
1772 }
1773 }
1774 if target.starts_with("riscv32") || target.starts_with("riscv64") {
1775 // get the 32i/32imac/32imc/64gc/64imac/... part
1776 let mut parts = target.split('-');
1777 if let Some(arch) = parts.next() {
1778 let arch = &arch[5..];
1779 if target.contains("linux") && arch.starts_with("64") {
1780 cmd.args.push(("-march=rv64gc").into());
1781 cmd.args.push("-mabi=lp64d".into());
1782 } else if target.contains("linux") && arch.starts_with("32") {
1783 cmd.args.push(("-march=rv32gc").into());
1784 cmd.args.push("-mabi=ilp32d".into());
1785 } else if arch.starts_with("64") {
1786 cmd.args.push(("-march=rv".to_owned() + arch).into());
1787 cmd.args.push("-mabi=lp64".into());
1788 } else {
1789 cmd.args.push(("-march=rv".to_owned() + arch).into());
1790 cmd.args.push("-mabi=ilp32".into());
1791 }
1792 cmd.args.push("-mcmodel=medany".into());
1793 }
1794 }
1795 }
1796 }
1797
1798 if target.contains("apple-ios") {
1799 self.ios_flags(cmd)?;
1800 }
1801
1802 if self.static_flag.unwrap_or(false) {
1803 cmd.args.push("-static".into());
1804 }
1805 if self.shared_flag.unwrap_or(false) {
1806 cmd.args.push("-shared".into());
1807 }
1808
1809 if self.cpp {
1810 match (self.cpp_set_stdlib.as_ref(), cmd.family) {
1811 (None, _) => {}
1812 (Some(stdlib), ToolFamily::Gnu) | (Some(stdlib), ToolFamily::Clang) => {
1813 cmd.push_cc_arg(format!("-stdlib=lib{}", stdlib).into());
1814 }
1815 _ => {
1816 println!(
1817 "cargo:warning=cpp_set_stdlib is specified, but the {:?} compiler \
1818 does not support this option, ignored",
1819 cmd.family
1820 );
1821 }
1822 }
1823 }
1824
1825 Ok(())
1826 }
1827
has_flags(&self) -> bool1828 fn has_flags(&self) -> bool {
1829 let flags_env_var_name = if self.cpp { "CXXFLAGS" } else { "CFLAGS" };
1830 let flags_env_var_value = self.get_var(flags_env_var_name);
1831 if let Ok(_) = flags_env_var_value {
1832 true
1833 } else {
1834 false
1835 }
1836 }
1837
msvc_macro_assembler(&self) -> Result<(Command, String), Error>1838 fn msvc_macro_assembler(&self) -> Result<(Command, String), Error> {
1839 let target = self.get_target()?;
1840 let tool = if target.contains("x86_64") {
1841 "ml64.exe"
1842 } else if target.contains("arm") {
1843 "armasm.exe"
1844 } else if target.contains("aarch64") {
1845 "armasm64.exe"
1846 } else {
1847 "ml.exe"
1848 };
1849 let mut cmd = windows_registry::find(&target, tool).unwrap_or_else(|| self.cmd(tool));
1850 cmd.arg("-nologo"); // undocumented, yet working with armasm[64]
1851 for directory in self.include_directories.iter() {
1852 cmd.arg("-I").arg(directory);
1853 }
1854 if target.contains("aarch64") || target.contains("arm") {
1855 println!("cargo:warning=The MSVC ARM assemblers do not support -D flags");
1856 } else {
1857 for &(ref key, ref value) in self.definitions.iter() {
1858 if let Some(ref value) = *value {
1859 cmd.arg(&format!("-D{}={}", key, value));
1860 } else {
1861 cmd.arg(&format!("-D{}", key));
1862 }
1863 }
1864 }
1865
1866 if target.contains("i686") || target.contains("i586") {
1867 cmd.arg("-safeseh");
1868 }
1869 for flag in self.flags.iter() {
1870 cmd.arg(flag);
1871 }
1872
1873 Ok((cmd, tool.to_string()))
1874 }
1875
assemble(&self, lib_name: &str, dst: &Path, objs: &[Object]) -> Result<(), Error>1876 fn assemble(&self, lib_name: &str, dst: &Path, objs: &[Object]) -> Result<(), Error> {
1877 // Delete the destination if it exists as we want to
1878 // create on the first iteration instead of appending.
1879 let _ = fs::remove_file(&dst);
1880
1881 // Add objects to the archive in limited-length batches. This helps keep
1882 // the length of the command line within a reasonable length to avoid
1883 // blowing system limits on limiting platforms like Windows.
1884 let objs: Vec<_> = objs
1885 .iter()
1886 .map(|o| o.dst.clone())
1887 .chain(self.objects.clone())
1888 .collect();
1889 for chunk in objs.chunks(100) {
1890 self.assemble_progressive(dst, chunk)?;
1891 }
1892
1893 if self.cuda {
1894 // Link the device-side code and add it to the target library,
1895 // so that non-CUDA linker can link the final binary.
1896
1897 let out_dir = self.get_out_dir()?;
1898 let dlink = out_dir.join(lib_name.to_owned() + "_dlink.o");
1899 let mut nvcc = self.get_compiler().to_command();
1900 nvcc.arg("--device-link")
1901 .arg("-o")
1902 .arg(dlink.clone())
1903 .arg(dst);
1904 run(&mut nvcc, "nvcc")?;
1905 self.assemble_progressive(dst, &[dlink])?;
1906 }
1907
1908 let target = self.get_target()?;
1909 if target.contains("msvc") {
1910 // The Rust compiler will look for libfoo.a and foo.lib, but the
1911 // MSVC linker will also be passed foo.lib, so be sure that both
1912 // exist for now.
1913
1914 let lib_dst = dst.with_file_name(format!("{}.lib", lib_name));
1915 let _ = fs::remove_file(&lib_dst);
1916 match fs::hard_link(&dst, &lib_dst).or_else(|_| {
1917 // if hard-link fails, just copy (ignoring the number of bytes written)
1918 fs::copy(&dst, &lib_dst).map(|_| ())
1919 }) {
1920 Ok(_) => (),
1921 Err(_) => {
1922 return Err(Error::new(
1923 ErrorKind::IOError,
1924 "Could not copy or create a hard-link to the generated lib file.",
1925 ));
1926 }
1927 };
1928 } else {
1929 // Non-msvc targets (those using `ar`) need a separate step to add
1930 // the symbol table to archives since our construction command of
1931 // `cq` doesn't add it for us.
1932 let (mut ar, cmd) = self.get_ar()?;
1933 run(ar.arg("s").arg(dst), &cmd)?;
1934 }
1935
1936 Ok(())
1937 }
1938
assemble_progressive(&self, dst: &Path, objs: &[PathBuf]) -> Result<(), Error>1939 fn assemble_progressive(&self, dst: &Path, objs: &[PathBuf]) -> Result<(), Error> {
1940 let target = self.get_target()?;
1941
1942 if target.contains("msvc") {
1943 let (mut cmd, program) = self.get_ar()?;
1944 let mut out = OsString::from("-out:");
1945 out.push(dst);
1946 cmd.arg(out).arg("-nologo");
1947 for flag in self.ar_flags.iter() {
1948 cmd.arg(flag);
1949 }
1950 // If the library file already exists, add the library name
1951 // as an argument to let lib.exe know we are appending the objs.
1952 if dst.exists() {
1953 cmd.arg(dst);
1954 }
1955 cmd.args(objs);
1956 run(&mut cmd, &program)?;
1957 } else {
1958 let (mut ar, cmd) = self.get_ar()?;
1959
1960 // Set an environment variable to tell the OSX archiver to ensure
1961 // that all dates listed in the archive are zero, improving
1962 // determinism of builds. AFAIK there's not really official
1963 // documentation of this but there's a lot of references to it if
1964 // you search google.
1965 //
1966 // You can reproduce this locally on a mac with:
1967 //
1968 // $ touch foo.c
1969 // $ cc -c foo.c -o foo.o
1970 //
1971 // # Notice that these two checksums are different
1972 // $ ar crus libfoo1.a foo.o && sleep 2 && ar crus libfoo2.a foo.o
1973 // $ md5sum libfoo*.a
1974 //
1975 // # Notice that these two checksums are the same
1976 // $ export ZERO_AR_DATE=1
1977 // $ ar crus libfoo1.a foo.o && sleep 2 && touch foo.o && ar crus libfoo2.a foo.o
1978 // $ md5sum libfoo*.a
1979 //
1980 // In any case if this doesn't end up getting read, it shouldn't
1981 // cause that many issues!
1982 ar.env("ZERO_AR_DATE", "1");
1983 for flag in self.ar_flags.iter() {
1984 ar.arg(flag);
1985 }
1986 run(ar.arg("cq").arg(dst).args(objs), &cmd)?;
1987 }
1988
1989 Ok(())
1990 }
1991
ios_flags(&self, cmd: &mut Tool) -> Result<(), Error>1992 fn ios_flags(&self, cmd: &mut Tool) -> Result<(), Error> {
1993 enum ArchSpec {
1994 Device(&'static str),
1995 Simulator(&'static str),
1996 Catalyst(&'static str),
1997 }
1998
1999 let target = self.get_target()?;
2000 let arch = target.split('-').nth(0).ok_or_else(|| {
2001 Error::new(
2002 ErrorKind::ArchitectureInvalid,
2003 "Unknown architecture for iOS target.",
2004 )
2005 })?;
2006
2007 let is_catalyst = match target.split('-').nth(3) {
2008 Some(v) => v == "macabi",
2009 None => false,
2010 };
2011
2012 let is_sim = match target.split('-').nth(3) {
2013 Some(v) => v == "sim",
2014 None => false,
2015 };
2016
2017 let arch = if is_catalyst {
2018 match arch {
2019 "arm64e" => ArchSpec::Catalyst("arm64e"),
2020 "arm64" | "aarch64" => ArchSpec::Catalyst("arm64"),
2021 "x86_64" => ArchSpec::Catalyst("-m64"),
2022 _ => {
2023 return Err(Error::new(
2024 ErrorKind::ArchitectureInvalid,
2025 "Unknown architecture for iOS target.",
2026 ));
2027 }
2028 }
2029 } else if is_sim {
2030 match arch {
2031 "arm64" | "aarch64" => ArchSpec::Simulator("-arch arm64"),
2032 _ => {
2033 return Err(Error::new(
2034 ErrorKind::ArchitectureInvalid,
2035 "Unknown architecture for iOS simulator target.",
2036 ));
2037 }
2038 }
2039 } else {
2040 match arch {
2041 "arm" | "armv7" | "thumbv7" => ArchSpec::Device("armv7"),
2042 "armv7s" | "thumbv7s" => ArchSpec::Device("armv7s"),
2043 "arm64e" => ArchSpec::Device("arm64e"),
2044 "arm64" | "aarch64" => ArchSpec::Device("arm64"),
2045 "i386" | "i686" => ArchSpec::Simulator("-m32"),
2046 "x86_64" => ArchSpec::Simulator("-m64"),
2047 _ => {
2048 return Err(Error::new(
2049 ErrorKind::ArchitectureInvalid,
2050 "Unknown architecture for iOS target.",
2051 ));
2052 }
2053 }
2054 };
2055
2056 let min_version =
2057 std::env::var("IPHONEOS_DEPLOYMENT_TARGET").unwrap_or_else(|_| "7.0".into());
2058
2059 let sdk = match arch {
2060 ArchSpec::Device(arch) => {
2061 cmd.args.push("-arch".into());
2062 cmd.args.push(arch.into());
2063 cmd.args
2064 .push(format!("-miphoneos-version-min={}", min_version).into());
2065 "iphoneos"
2066 }
2067 ArchSpec::Simulator(arch) => {
2068 cmd.args.push(arch.into());
2069 cmd.args
2070 .push(format!("-mios-simulator-version-min={}", min_version).into());
2071 "iphonesimulator"
2072 }
2073 ArchSpec::Catalyst(_) => "macosx",
2074 };
2075
2076 self.print(&format!("Detecting iOS SDK path for {}", sdk));
2077 let sdk_path = self.apple_sdk_root(sdk)?;
2078 cmd.args.push("-isysroot".into());
2079 cmd.args.push(sdk_path);
2080 cmd.args.push("-fembed-bitcode".into());
2081 /*
2082 * TODO we probably ultimately want the -fembed-bitcode-marker flag
2083 * but can't have it now because of an issue in LLVM:
2084 * https://github.com/alexcrichton/cc-rs/issues/301
2085 * https://github.com/rust-lang/rust/pull/48896#comment-372192660
2086 */
2087 /*
2088 if self.get_opt_level()? == "0" {
2089 cmd.args.push("-fembed-bitcode-marker".into());
2090 }
2091 */
2092
2093 Ok(())
2094 }
2095
cmd<P: AsRef<OsStr>>(&self, prog: P) -> Command2096 fn cmd<P: AsRef<OsStr>>(&self, prog: P) -> Command {
2097 let mut cmd = Command::new(prog);
2098 for &(ref a, ref b) in self.env.iter() {
2099 cmd.env(a, b);
2100 }
2101 cmd
2102 }
2103
get_base_compiler(&self) -> Result<Tool, Error>2104 fn get_base_compiler(&self) -> Result<Tool, Error> {
2105 if let Some(ref c) = self.compiler {
2106 return Ok(Tool::new(c.clone()));
2107 }
2108 let host = self.get_host()?;
2109 let target = self.get_target()?;
2110 let (env, msvc, gnu, traditional, clang) = if self.cpp {
2111 ("CXX", "cl.exe", "g++", "c++", "clang++")
2112 } else {
2113 ("CC", "cl.exe", "gcc", "cc", "clang")
2114 };
2115
2116 // On historical Solaris systems, "cc" may have been Sun Studio, which
2117 // is not flag-compatible with "gcc". This history casts a long shadow,
2118 // and many modern illumos distributions today ship GCC as "gcc" without
2119 // also making it available as "cc".
2120 let default = if host.contains("solaris") || host.contains("illumos") {
2121 gnu
2122 } else {
2123 traditional
2124 };
2125
2126 let cl_exe = windows_registry::find_tool(&target, "cl.exe");
2127
2128 let tool_opt: Option<Tool> = self
2129 .env_tool(env)
2130 .map(|(tool, wrapper, args)| {
2131 // find the driver mode, if any
2132 const DRIVER_MODE: &str = "--driver-mode=";
2133 let driver_mode = args
2134 .iter()
2135 .find(|a| a.starts_with(DRIVER_MODE))
2136 .map(|a| &a[DRIVER_MODE.len()..]);
2137 // Chop off leading/trailing whitespace to work around
2138 // semi-buggy build scripts which are shared in
2139 // makefiles/configure scripts (where spaces are far more
2140 // lenient)
2141 let mut t = Tool::with_clang_driver(PathBuf::from(tool.trim()), driver_mode);
2142 if let Some(cc_wrapper) = wrapper {
2143 t.cc_wrapper_path = Some(PathBuf::from(cc_wrapper));
2144 }
2145 for arg in args {
2146 t.cc_wrapper_args.push(arg.into());
2147 }
2148 t
2149 })
2150 .or_else(|| {
2151 if target.contains("emscripten") {
2152 let tool = if self.cpp { "em++" } else { "emcc" };
2153 // Windows uses bat file so we have to be a bit more specific
2154 if cfg!(windows) {
2155 let mut t = Tool::new(PathBuf::from("cmd"));
2156 t.args.push("/c".into());
2157 t.args.push(format!("{}.bat", tool).into());
2158 Some(t)
2159 } else {
2160 Some(Tool::new(PathBuf::from(tool)))
2161 }
2162 } else {
2163 None
2164 }
2165 })
2166 .or_else(|| cl_exe.clone());
2167
2168 let tool = match tool_opt {
2169 Some(t) => t,
2170 None => {
2171 let compiler = if host.contains("windows") && target.contains("windows") {
2172 if target.contains("msvc") {
2173 msvc.to_string()
2174 } else {
2175 format!("{}.exe", gnu)
2176 }
2177 } else if target.contains("apple-ios") {
2178 clang.to_string()
2179 } else if target.contains("android") {
2180 autodetect_android_compiler(&target, &host, gnu, clang)
2181 } else if target.contains("cloudabi") {
2182 format!("{}-{}", target, traditional)
2183 } else if target == "wasm32-wasi"
2184 || target == "wasm32-unknown-wasi"
2185 || target == "wasm32-unknown-unknown"
2186 {
2187 "clang".to_string()
2188 } else if target.contains("vxworks") {
2189 if self.cpp {
2190 "wr-c++".to_string()
2191 } else {
2192 "wr-cc".to_string()
2193 }
2194 } else if target.starts_with("armv7a-kmc-solid_") {
2195 format!("arm-kmc-eabi-{}", gnu)
2196 } else if target.starts_with("aarch64-kmc-solid_") {
2197 format!("aarch64-kmc-elf-{}", gnu)
2198 } else if self.get_host()? != target {
2199 let prefix = self.prefix_for_target(&target);
2200 match prefix {
2201 Some(prefix) => format!("{}-{}", prefix, gnu),
2202 None => default.to_string(),
2203 }
2204 } else {
2205 default.to_string()
2206 };
2207
2208 let mut t = Tool::new(PathBuf::from(compiler));
2209 if let Some(cc_wrapper) = Self::rustc_wrapper_fallback() {
2210 t.cc_wrapper_path = Some(PathBuf::from(cc_wrapper));
2211 }
2212 t
2213 }
2214 };
2215
2216 let mut tool = if self.cuda {
2217 assert!(
2218 tool.args.is_empty(),
2219 "CUDA compilation currently assumes empty pre-existing args"
2220 );
2221 let nvcc = match self.get_var("NVCC") {
2222 Err(_) => "nvcc".into(),
2223 Ok(nvcc) => nvcc,
2224 };
2225 let mut nvcc_tool = Tool::with_features(PathBuf::from(nvcc), None, self.cuda);
2226 nvcc_tool
2227 .args
2228 .push(format!("-ccbin={}", tool.path.display()).into());
2229 nvcc_tool.family = tool.family;
2230 nvcc_tool
2231 } else {
2232 tool
2233 };
2234
2235 // New "standalone" C/C++ cross-compiler executables from recent Android NDK
2236 // are just shell scripts that call main clang binary (from Android NDK) with
2237 // proper `--target` argument.
2238 //
2239 // For example, armv7a-linux-androideabi16-clang passes
2240 // `--target=armv7a-linux-androideabi16` to clang.
2241 //
2242 // As the shell script calls the main clang binary, the command line limit length
2243 // on Windows is restricted to around 8k characters instead of around 32k characters.
2244 // To remove this limit, we call the main clang binary directly and construct the
2245 // `--target=` ourselves.
2246 if host.contains("windows") && android_clang_compiler_uses_target_arg_internally(&tool.path)
2247 {
2248 if let Some(path) = tool.path.file_name() {
2249 let file_name = path.to_str().unwrap().to_owned();
2250 let (target, clang) = file_name.split_at(file_name.rfind("-").unwrap());
2251
2252 tool.path.set_file_name(clang.trim_start_matches("-"));
2253 tool.path.set_extension("exe");
2254 tool.args.push(format!("--target={}", target).into());
2255
2256 // Additionally, shell scripts for target i686-linux-android versions 16 to 24
2257 // pass the `mstackrealign` option so we do that here as well.
2258 if target.contains("i686-linux-android") {
2259 let (_, version) = target.split_at(target.rfind("d").unwrap() + 1);
2260 if let Ok(version) = version.parse::<u32>() {
2261 if version > 15 && version < 25 {
2262 tool.args.push("-mstackrealign".into());
2263 }
2264 }
2265 }
2266 };
2267 }
2268
2269 // If we found `cl.exe` in our environment, the tool we're returning is
2270 // an MSVC-like tool, *and* no env vars were set then set env vars for
2271 // the tool that we're returning.
2272 //
2273 // Env vars are needed for things like `link.exe` being put into PATH as
2274 // well as header include paths sometimes. These paths are automatically
2275 // included by default but if the `CC` or `CXX` env vars are set these
2276 // won't be used. This'll ensure that when the env vars are used to
2277 // configure for invocations like `clang-cl` we still get a "works out
2278 // of the box" experience.
2279 if let Some(cl_exe) = cl_exe {
2280 if tool.family == (ToolFamily::Msvc { clang_cl: true })
2281 && tool.env.len() == 0
2282 && target.contains("msvc")
2283 {
2284 for &(ref k, ref v) in cl_exe.env.iter() {
2285 tool.env.push((k.to_owned(), v.to_owned()));
2286 }
2287 }
2288 }
2289
2290 Ok(tool)
2291 }
2292
get_var(&self, var_base: &str) -> Result<String, Error>2293 fn get_var(&self, var_base: &str) -> Result<String, Error> {
2294 let target = self.get_target()?;
2295 let host = self.get_host()?;
2296 let kind = if host == target { "HOST" } else { "TARGET" };
2297 let target_u = target.replace("-", "_");
2298 let res = self
2299 .getenv(&format!("{}_{}", var_base, target))
2300 .or_else(|| self.getenv(&format!("{}_{}", var_base, target_u)))
2301 .or_else(|| self.getenv(&format!("{}_{}", kind, var_base)))
2302 .or_else(|| self.getenv(var_base));
2303
2304 match res {
2305 Some(res) => Ok(res),
2306 None => Err(Error::new(
2307 ErrorKind::EnvVarNotFound,
2308 &format!("Could not find environment variable {}.", var_base),
2309 )),
2310 }
2311 }
2312
envflags(&self, name: &str) -> Vec<String>2313 fn envflags(&self, name: &str) -> Vec<String> {
2314 self.get_var(name)
2315 .unwrap_or(String::new())
2316 .split_ascii_whitespace()
2317 .map(|slice| slice.to_string())
2318 .collect()
2319 }
2320
2321 /// Returns a fallback `cc_compiler_wrapper` by introspecting `RUSTC_WRAPPER`
rustc_wrapper_fallback() -> Option<String>2322 fn rustc_wrapper_fallback() -> Option<String> {
2323 // No explicit CC wrapper was detected, but check if RUSTC_WRAPPER
2324 // is defined and is a build accelerator that is compatible with
2325 // C/C++ compilers (e.g. sccache)
2326 const VALID_WRAPPERS: &[&'static str] = &["sccache", "cachepot"];
2327
2328 let rustc_wrapper = std::env::var_os("RUSTC_WRAPPER")?;
2329 let wrapper_path = Path::new(&rustc_wrapper);
2330 let wrapper_stem = wrapper_path.file_stem()?;
2331
2332 if VALID_WRAPPERS.contains(&wrapper_stem.to_str()?) {
2333 Some(rustc_wrapper.to_str()?.to_owned())
2334 } else {
2335 None
2336 }
2337 }
2338
2339 /// Returns compiler path, optional modifier name from whitelist, and arguments vec
env_tool(&self, name: &str) -> Option<(String, Option<String>, Vec<String>)>2340 fn env_tool(&self, name: &str) -> Option<(String, Option<String>, Vec<String>)> {
2341 let tool = match self.get_var(name) {
2342 Ok(tool) => tool,
2343 Err(_) => return None,
2344 };
2345
2346 // If this is an exact path on the filesystem we don't want to do any
2347 // interpretation at all, just pass it on through. This'll hopefully get
2348 // us to support spaces-in-paths.
2349 if Path::new(&tool).exists() {
2350 return Some((tool, None, Vec::new()));
2351 }
2352
2353 // Ok now we want to handle a couple of scenarios. We'll assume from
2354 // here on out that spaces are splitting separate arguments. Two major
2355 // features we want to support are:
2356 //
2357 // CC='sccache cc'
2358 //
2359 // aka using `sccache` or any other wrapper/caching-like-thing for
2360 // compilations. We want to know what the actual compiler is still,
2361 // though, because our `Tool` API support introspection of it to see
2362 // what compiler is in use.
2363 //
2364 // additionally we want to support
2365 //
2366 // CC='cc -flag'
2367 //
2368 // where the CC env var is used to also pass default flags to the C
2369 // compiler.
2370 //
2371 // It's true that everything here is a bit of a pain, but apparently if
2372 // you're not literally make or bash then you get a lot of bug reports.
2373 let known_wrappers = ["ccache", "distcc", "sccache", "icecc", "cachepot"];
2374
2375 let mut parts = tool.split_whitespace();
2376 let maybe_wrapper = match parts.next() {
2377 Some(s) => s,
2378 None => return None,
2379 };
2380
2381 let file_stem = Path::new(maybe_wrapper)
2382 .file_stem()
2383 .unwrap()
2384 .to_str()
2385 .unwrap();
2386 if known_wrappers.contains(&file_stem) {
2387 if let Some(compiler) = parts.next() {
2388 return Some((
2389 compiler.to_string(),
2390 Some(maybe_wrapper.to_string()),
2391 parts.map(|s| s.to_string()).collect(),
2392 ));
2393 }
2394 }
2395
2396 Some((
2397 maybe_wrapper.to_string(),
2398 Self::rustc_wrapper_fallback(),
2399 parts.map(|s| s.to_string()).collect(),
2400 ))
2401 }
2402
2403 /// Returns the C++ standard library:
2404 /// 1. If [cpp_link_stdlib](cc::Build::cpp_link_stdlib) is set, uses its value.
2405 /// 2. Else if the `CXXSTDLIB` environment variable is set, uses its value.
2406 /// 3. Else the default is `libc++` for OS X and BSDs, `libc++_shared` for Android,
2407 /// `None` for MSVC and `libstdc++` for anything else.
get_cpp_link_stdlib(&self) -> Result<Option<String>, Error>2408 fn get_cpp_link_stdlib(&self) -> Result<Option<String>, Error> {
2409 match self.cpp_link_stdlib.clone() {
2410 Some(s) => Ok(s),
2411 None => {
2412 if let Ok(stdlib) = self.get_var("CXXSTDLIB") {
2413 if stdlib.is_empty() {
2414 Ok(None)
2415 } else {
2416 Ok(Some(stdlib))
2417 }
2418 } else {
2419 let target = self.get_target()?;
2420 if target.contains("msvc") {
2421 Ok(None)
2422 } else if target.contains("apple") {
2423 Ok(Some("c++".to_string()))
2424 } else if target.contains("freebsd") {
2425 Ok(Some("c++".to_string()))
2426 } else if target.contains("openbsd") {
2427 Ok(Some("c++".to_string()))
2428 } else if target.contains("android") {
2429 Ok(Some("c++_shared".to_string()))
2430 } else {
2431 Ok(Some("stdc++".to_string()))
2432 }
2433 }
2434 }
2435 }
2436 }
2437
get_ar(&self) -> Result<(Command, String), Error>2438 fn get_ar(&self) -> Result<(Command, String), Error> {
2439 if let Some(ref p) = self.archiver {
2440 let name = p.file_name().and_then(|s| s.to_str()).unwrap_or("ar");
2441 return Ok((self.cmd(p), name.to_string()));
2442 }
2443 if let Ok(p) = self.get_var("AR") {
2444 return Ok((self.cmd(&p), p));
2445 }
2446 let target = self.get_target()?;
2447 let default_ar = "ar".to_string();
2448 let program = if target.contains("android") {
2449 format!("{}-ar", target.replace("armv7", "arm"))
2450 } else if target.contains("emscripten") {
2451 // Windows use bat files so we have to be a bit more specific
2452 if cfg!(windows) {
2453 let mut cmd = self.cmd("cmd");
2454 cmd.arg("/c").arg("emar.bat");
2455 return Ok((cmd, "emar.bat".to_string()));
2456 }
2457
2458 "emar".to_string()
2459 } else if target.contains("msvc") {
2460 match windows_registry::find(&target, "lib.exe") {
2461 Some(t) => return Ok((t, "lib.exe".to_string())),
2462 None => "lib.exe".to_string(),
2463 }
2464 } else if target.contains("illumos") {
2465 // The default 'ar' on illumos uses a non-standard flags,
2466 // but the OS comes bundled with a GNU-compatible variant.
2467 //
2468 // Use the GNU-variant to match other Unix systems.
2469 "gar".to_string()
2470 } else if self.get_host()? != target {
2471 match self.prefix_for_target(&target) {
2472 Some(p) => {
2473 let target_ar = format!("{}-ar", p);
2474 if Command::new(&target_ar).output().is_ok() {
2475 target_ar
2476 } else {
2477 default_ar
2478 }
2479 }
2480 None => default_ar,
2481 }
2482 } else {
2483 default_ar
2484 };
2485 Ok((self.cmd(&program), program))
2486 }
2487
prefix_for_target(&self, target: &str) -> Option<String>2488 fn prefix_for_target(&self, target: &str) -> Option<String> {
2489 // CROSS_COMPILE is of the form: "arm-linux-gnueabi-"
2490 let cc_env = self.getenv("CROSS_COMPILE");
2491 let cross_compile = cc_env
2492 .as_ref()
2493 .map(|s| s.trim_right_matches('-').to_owned());
2494 cross_compile.or(match &target[..] {
2495 "aarch64-unknown-linux-gnu" => Some("aarch64-linux-gnu"),
2496 "aarch64-unknown-linux-musl" => Some("aarch64-linux-musl"),
2497 "aarch64-unknown-netbsd" => Some("aarch64--netbsd"),
2498 "arm-unknown-linux-gnueabi" => Some("arm-linux-gnueabi"),
2499 "armv4t-unknown-linux-gnueabi" => Some("arm-linux-gnueabi"),
2500 "armv5te-unknown-linux-gnueabi" => Some("arm-linux-gnueabi"),
2501 "armv5te-unknown-linux-musleabi" => Some("arm-linux-gnueabi"),
2502 "arm-frc-linux-gnueabi" => Some("arm-frc-linux-gnueabi"),
2503 "arm-unknown-linux-gnueabihf" => Some("arm-linux-gnueabihf"),
2504 "arm-unknown-linux-musleabi" => Some("arm-linux-musleabi"),
2505 "arm-unknown-linux-musleabihf" => Some("arm-linux-musleabihf"),
2506 "arm-unknown-netbsd-eabi" => Some("arm--netbsdelf-eabi"),
2507 "armv6-unknown-netbsd-eabihf" => Some("armv6--netbsdelf-eabihf"),
2508 "armv7-unknown-linux-gnueabi" => Some("arm-linux-gnueabi"),
2509 "armv7-unknown-linux-gnueabihf" => Some("arm-linux-gnueabihf"),
2510 "armv7-unknown-linux-musleabihf" => Some("arm-linux-musleabihf"),
2511 "armv7neon-unknown-linux-gnueabihf" => Some("arm-linux-gnueabihf"),
2512 "armv7neon-unknown-linux-musleabihf" => Some("arm-linux-musleabihf"),
2513 "thumbv7-unknown-linux-gnueabihf" => Some("arm-linux-gnueabihf"),
2514 "thumbv7-unknown-linux-musleabihf" => Some("arm-linux-musleabihf"),
2515 "thumbv7neon-unknown-linux-gnueabihf" => Some("arm-linux-gnueabihf"),
2516 "thumbv7neon-unknown-linux-musleabihf" => Some("arm-linux-musleabihf"),
2517 "armv7-unknown-netbsd-eabihf" => Some("armv7--netbsdelf-eabihf"),
2518 "hexagon-unknown-linux-musl" => Some("hexagon-linux-musl"),
2519 "i586-unknown-linux-musl" => Some("musl"),
2520 "i686-pc-windows-gnu" => Some("i686-w64-mingw32"),
2521 "i686-uwp-windows-gnu" => Some("i686-w64-mingw32"),
2522 "i686-unknown-linux-gnu" => self.find_working_gnu_prefix(&[
2523 "i686-linux-gnu",
2524 "x86_64-linux-gnu", // transparently support gcc-multilib
2525 ]), // explicit None if not found, so caller knows to fall back
2526 "i686-unknown-linux-musl" => Some("musl"),
2527 "i686-unknown-netbsd" => Some("i486--netbsdelf"),
2528 "mips-unknown-linux-gnu" => Some("mips-linux-gnu"),
2529 "mips-unknown-linux-musl" => Some("mips-linux-musl"),
2530 "mipsel-unknown-linux-gnu" => Some("mipsel-linux-gnu"),
2531 "mipsel-unknown-linux-musl" => Some("mipsel-linux-musl"),
2532 "mips64-unknown-linux-gnuabi64" => Some("mips64-linux-gnuabi64"),
2533 "mips64el-unknown-linux-gnuabi64" => Some("mips64el-linux-gnuabi64"),
2534 "mipsisa32r6-unknown-linux-gnu" => Some("mipsisa32r6-linux-gnu"),
2535 "mipsisa32r6el-unknown-linux-gnu" => Some("mipsisa32r6el-linux-gnu"),
2536 "mipsisa64r6-unknown-linux-gnuabi64" => Some("mipsisa64r6-linux-gnuabi64"),
2537 "mipsisa64r6el-unknown-linux-gnuabi64" => Some("mipsisa64r6el-linux-gnuabi64"),
2538 "powerpc-unknown-linux-gnu" => Some("powerpc-linux-gnu"),
2539 "powerpc-unknown-linux-gnuspe" => Some("powerpc-linux-gnuspe"),
2540 "powerpc-unknown-netbsd" => Some("powerpc--netbsd"),
2541 "powerpc64-unknown-linux-gnu" => Some("powerpc-linux-gnu"),
2542 "powerpc64le-unknown-linux-gnu" => Some("powerpc64le-linux-gnu"),
2543 "riscv32i-unknown-none-elf" => self.find_working_gnu_prefix(&[
2544 "riscv32-unknown-elf",
2545 "riscv64-unknown-elf",
2546 "riscv-none-embed",
2547 ]),
2548 "riscv32imac-unknown-none-elf" => self.find_working_gnu_prefix(&[
2549 "riscv32-unknown-elf",
2550 "riscv64-unknown-elf",
2551 "riscv-none-embed",
2552 ]),
2553 "riscv32imc-unknown-none-elf" => self.find_working_gnu_prefix(&[
2554 "riscv32-unknown-elf",
2555 "riscv64-unknown-elf",
2556 "riscv-none-embed",
2557 ]),
2558 "riscv64gc-unknown-none-elf" => self.find_working_gnu_prefix(&[
2559 "riscv64-unknown-elf",
2560 "riscv32-unknown-elf",
2561 "riscv-none-embed",
2562 ]),
2563 "riscv64imac-unknown-none-elf" => self.find_working_gnu_prefix(&[
2564 "riscv64-unknown-elf",
2565 "riscv32-unknown-elf",
2566 "riscv-none-embed",
2567 ]),
2568 "riscv64gc-unknown-linux-gnu" => Some("riscv64-linux-gnu"),
2569 "riscv32gc-unknown-linux-gnu" => Some("riscv32-linux-gnu"),
2570 "riscv64gc-unknown-linux-musl" => Some("riscv64-linux-musl"),
2571 "riscv32gc-unknown-linux-musl" => Some("riscv32-linux-musl"),
2572 "s390x-unknown-linux-gnu" => Some("s390x-linux-gnu"),
2573 "sparc-unknown-linux-gnu" => Some("sparc-linux-gnu"),
2574 "sparc64-unknown-linux-gnu" => Some("sparc64-linux-gnu"),
2575 "sparc64-unknown-netbsd" => Some("sparc64--netbsd"),
2576 "sparcv9-sun-solaris" => Some("sparcv9-sun-solaris"),
2577 "armv7a-none-eabi" => Some("arm-none-eabi"),
2578 "armv7a-none-eabihf" => Some("arm-none-eabi"),
2579 "armebv7r-none-eabi" => Some("arm-none-eabi"),
2580 "armebv7r-none-eabihf" => Some("arm-none-eabi"),
2581 "armv7r-none-eabi" => Some("arm-none-eabi"),
2582 "armv7r-none-eabihf" => Some("arm-none-eabi"),
2583 "thumbv6m-none-eabi" => Some("arm-none-eabi"),
2584 "thumbv7em-none-eabi" => Some("arm-none-eabi"),
2585 "thumbv7em-none-eabihf" => Some("arm-none-eabi"),
2586 "thumbv7m-none-eabi" => Some("arm-none-eabi"),
2587 "thumbv8m.base-none-eabi" => Some("arm-none-eabi"),
2588 "thumbv8m.main-none-eabi" => Some("arm-none-eabi"),
2589 "thumbv8m.main-none-eabihf" => Some("arm-none-eabi"),
2590 "x86_64-pc-windows-gnu" => Some("x86_64-w64-mingw32"),
2591 "x86_64-uwp-windows-gnu" => Some("x86_64-w64-mingw32"),
2592 "x86_64-rumprun-netbsd" => Some("x86_64-rumprun-netbsd"),
2593 "x86_64-unknown-linux-gnu" => self.find_working_gnu_prefix(&[
2594 "x86_64-linux-gnu", // rustfmt wrap
2595 ]), // explicit None if not found, so caller knows to fall back
2596 "x86_64-unknown-linux-musl" => Some("musl"),
2597 "x86_64-unknown-netbsd" => Some("x86_64--netbsd"),
2598 _ => None,
2599 }
2600 .map(|x| x.to_owned()))
2601 }
2602
2603 /// Some platforms have multiple, compatible, canonical prefixes. Look through
2604 /// each possible prefix for a compiler that exists and return it. The prefixes
2605 /// should be ordered from most-likely to least-likely.
find_working_gnu_prefix(&self, prefixes: &[&'static str]) -> Option<&'static str>2606 fn find_working_gnu_prefix(&self, prefixes: &[&'static str]) -> Option<&'static str> {
2607 let suffix = if self.cpp { "-g++" } else { "-gcc" };
2608 let extension = std::env::consts::EXE_SUFFIX;
2609
2610 // Loop through PATH entries searching for each toolchain. This ensures that we
2611 // are more likely to discover the toolchain early on, because chances are good
2612 // that the desired toolchain is in one of the higher-priority paths.
2613 env::var_os("PATH")
2614 .as_ref()
2615 .and_then(|path_entries| {
2616 env::split_paths(path_entries).find_map(|path_entry| {
2617 for prefix in prefixes {
2618 let target_compiler = format!("{}{}{}", prefix, suffix, extension);
2619 if path_entry.join(&target_compiler).exists() {
2620 return Some(prefix);
2621 }
2622 }
2623 None
2624 })
2625 })
2626 .map(|prefix| *prefix)
2627 .or_else(||
2628 // If no toolchain was found, provide the first toolchain that was passed in.
2629 // This toolchain has been shown not to exist, however it will appear in the
2630 // error that is shown to the user which should make it easier to search for
2631 // where it should be obtained.
2632 prefixes.first().map(|prefix| *prefix))
2633 }
2634
get_target(&self) -> Result<String, Error>2635 fn get_target(&self) -> Result<String, Error> {
2636 match self.target.clone() {
2637 Some(t) => Ok(t),
2638 None => Ok(self.getenv_unwrap("TARGET")?),
2639 }
2640 }
2641
get_host(&self) -> Result<String, Error>2642 fn get_host(&self) -> Result<String, Error> {
2643 match self.host.clone() {
2644 Some(h) => Ok(h),
2645 None => Ok(self.getenv_unwrap("HOST")?),
2646 }
2647 }
2648
get_opt_level(&self) -> Result<String, Error>2649 fn get_opt_level(&self) -> Result<String, Error> {
2650 match self.opt_level.as_ref().cloned() {
2651 Some(ol) => Ok(ol),
2652 None => Ok(self.getenv_unwrap("OPT_LEVEL")?),
2653 }
2654 }
2655
get_debug(&self) -> bool2656 fn get_debug(&self) -> bool {
2657 self.debug.unwrap_or_else(|| match self.getenv("DEBUG") {
2658 Some(s) => s != "false",
2659 None => false,
2660 })
2661 }
2662
get_force_frame_pointer(&self) -> bool2663 fn get_force_frame_pointer(&self) -> bool {
2664 self.force_frame_pointer.unwrap_or_else(|| self.get_debug())
2665 }
2666
get_out_dir(&self) -> Result<PathBuf, Error>2667 fn get_out_dir(&self) -> Result<PathBuf, Error> {
2668 match self.out_dir.clone() {
2669 Some(p) => Ok(p),
2670 None => Ok(env::var_os("OUT_DIR").map(PathBuf::from).ok_or_else(|| {
2671 Error::new(
2672 ErrorKind::EnvVarNotFound,
2673 "Environment variable OUT_DIR not defined.",
2674 )
2675 })?),
2676 }
2677 }
2678
getenv(&self, v: &str) -> Option<String>2679 fn getenv(&self, v: &str) -> Option<String> {
2680 let mut cache = self.env_cache.lock().unwrap();
2681 if let Some(val) = cache.get(v) {
2682 return val.clone();
2683 }
2684 let r = env::var(v).ok();
2685 self.print(&format!("{} = {:?}", v, r));
2686 cache.insert(v.to_string(), r.clone());
2687 r
2688 }
2689
getenv_unwrap(&self, v: &str) -> Result<String, Error>2690 fn getenv_unwrap(&self, v: &str) -> Result<String, Error> {
2691 match self.getenv(v) {
2692 Some(s) => Ok(s),
2693 None => Err(Error::new(
2694 ErrorKind::EnvVarNotFound,
2695 &format!("Environment variable {} not defined.", v.to_string()),
2696 )),
2697 }
2698 }
2699
print(&self, s: &str)2700 fn print(&self, s: &str) {
2701 if self.cargo_metadata {
2702 println!("{}", s);
2703 }
2704 }
2705
fix_env_for_apple_os(&self, cmd: &mut Command) -> Result<(), Error>2706 fn fix_env_for_apple_os(&self, cmd: &mut Command) -> Result<(), Error> {
2707 let target = self.get_target()?;
2708 let host = self.get_host()?;
2709 if host.contains("apple-darwin") && target.contains("apple-darwin") {
2710 // If, for example, `cargo` runs during the build of an XCode project, then `SDKROOT` environment variable
2711 // would represent the current target, and this is the problem for us, if we want to compile something
2712 // for the host, when host != target.
2713 // We can not just remove `SDKROOT`, because, again, for example, XCode add to PATH
2714 // /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin
2715 // and `cc` from this path can not find system include files, like `pthread.h`, if `SDKROOT`
2716 // is not set
2717 if let Ok(sdkroot) = env::var("SDKROOT") {
2718 if !sdkroot.contains("MacOSX") {
2719 let macos_sdk = self.apple_sdk_root("macosx")?;
2720 cmd.env("SDKROOT", macos_sdk);
2721 }
2722 }
2723 // Additionally, `IPHONEOS_DEPLOYMENT_TARGET` must not be set when using the Xcode linker at
2724 // "/Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/ld",
2725 // although this is apparently ignored when using the linker at "/usr/bin/ld".
2726 cmd.env_remove("IPHONEOS_DEPLOYMENT_TARGET");
2727 }
2728 Ok(())
2729 }
2730
apple_sdk_root(&self, sdk: &str) -> Result<OsString, Error>2731 fn apple_sdk_root(&self, sdk: &str) -> Result<OsString, Error> {
2732 let mut cache = self
2733 .apple_sdk_root_cache
2734 .lock()
2735 .expect("apple_sdk_root_cache lock failed");
2736 if let Some(ret) = cache.get(sdk) {
2737 return Ok(ret.clone());
2738 }
2739
2740 let sdk_path = run_output(
2741 self.cmd("xcrun")
2742 .arg("--show-sdk-path")
2743 .arg("--sdk")
2744 .arg(sdk),
2745 "xcrun",
2746 )?;
2747
2748 let sdk_path = match String::from_utf8(sdk_path) {
2749 Ok(p) => p,
2750 Err(_) => {
2751 return Err(Error::new(
2752 ErrorKind::IOError,
2753 "Unable to determine iOS SDK path.",
2754 ));
2755 }
2756 };
2757 let ret: OsString = sdk_path.trim().into();
2758 cache.insert(sdk.into(), ret.clone());
2759 Ok(ret)
2760 }
2761 }
2762
2763 impl Default for Build {
default() -> Build2764 fn default() -> Build {
2765 Build::new()
2766 }
2767 }
2768
2769 impl Tool {
new(path: PathBuf) -> Self2770 fn new(path: PathBuf) -> Self {
2771 Tool::with_features(path, None, false)
2772 }
2773
with_clang_driver(path: PathBuf, clang_driver: Option<&str>) -> Self2774 fn with_clang_driver(path: PathBuf, clang_driver: Option<&str>) -> Self {
2775 Self::with_features(path, clang_driver, false)
2776 }
2777
2778 #[cfg(windows)]
2779 /// Explicitly set the `ToolFamily`, skipping name-based detection.
with_family(path: PathBuf, family: ToolFamily) -> Self2780 fn with_family(path: PathBuf, family: ToolFamily) -> Self {
2781 Self {
2782 path: path,
2783 cc_wrapper_path: None,
2784 cc_wrapper_args: Vec::new(),
2785 args: Vec::new(),
2786 env: Vec::new(),
2787 family: family,
2788 cuda: false,
2789 removed_args: Vec::new(),
2790 }
2791 }
2792
with_features(path: PathBuf, clang_driver: Option<&str>, cuda: bool) -> Self2793 fn with_features(path: PathBuf, clang_driver: Option<&str>, cuda: bool) -> Self {
2794 // Try to detect family of the tool from its name, falling back to Gnu.
2795 let family = if let Some(fname) = path.file_name().and_then(|p| p.to_str()) {
2796 if fname.contains("clang-cl") {
2797 ToolFamily::Msvc { clang_cl: true }
2798 } else if fname.ends_with("cl") || fname == "cl.exe" {
2799 ToolFamily::Msvc { clang_cl: false }
2800 } else if fname.contains("clang") {
2801 match clang_driver {
2802 Some("cl") => ToolFamily::Msvc { clang_cl: true },
2803 _ => ToolFamily::Clang,
2804 }
2805 } else {
2806 ToolFamily::Gnu
2807 }
2808 } else {
2809 ToolFamily::Gnu
2810 };
2811
2812 Tool {
2813 path: path,
2814 cc_wrapper_path: None,
2815 cc_wrapper_args: Vec::new(),
2816 args: Vec::new(),
2817 env: Vec::new(),
2818 family: family,
2819 cuda: cuda,
2820 removed_args: Vec::new(),
2821 }
2822 }
2823
2824 /// Add an argument to be stripped from the final command arguments.
remove_arg(&mut self, flag: OsString)2825 fn remove_arg(&mut self, flag: OsString) {
2826 self.removed_args.push(flag);
2827 }
2828
2829 /// Add a flag, and optionally prepend the NVCC wrapper flag "-Xcompiler".
2830 ///
2831 /// Currently this is only used for compiling CUDA sources, since NVCC only
2832 /// accepts a limited set of GNU-like flags, and the rest must be prefixed
2833 /// with a "-Xcompiler" flag to get passed to the underlying C++ compiler.
push_cc_arg(&mut self, flag: OsString)2834 fn push_cc_arg(&mut self, flag: OsString) {
2835 if self.cuda {
2836 self.args.push("-Xcompiler".into());
2837 }
2838 self.args.push(flag);
2839 }
2840
is_duplicate_opt_arg(&self, flag: &OsString) -> bool2841 fn is_duplicate_opt_arg(&self, flag: &OsString) -> bool {
2842 let flag = flag.to_str().unwrap();
2843 let mut chars = flag.chars();
2844
2845 // Only duplicate check compiler flags
2846 if self.is_like_msvc() {
2847 if chars.next() != Some('/') {
2848 return false;
2849 }
2850 } else if self.is_like_gnu() || self.is_like_clang() {
2851 if chars.next() != Some('-') {
2852 return false;
2853 }
2854 }
2855
2856 // Check for existing optimization flags (-O, /O)
2857 if chars.next() == Some('O') {
2858 return self
2859 .args()
2860 .iter()
2861 .any(|ref a| a.to_str().unwrap_or("").chars().nth(1) == Some('O'));
2862 }
2863
2864 // TODO Check for existing -m..., -m...=..., /arch:... flags
2865 return false;
2866 }
2867
2868 /// Don't push optimization arg if it conflicts with existing args
push_opt_unless_duplicate(&mut self, flag: OsString)2869 fn push_opt_unless_duplicate(&mut self, flag: OsString) {
2870 if self.is_duplicate_opt_arg(&flag) {
2871 println!("Info: Ignoring duplicate arg {:?}", &flag);
2872 } else {
2873 self.push_cc_arg(flag);
2874 }
2875 }
2876
2877 /// Converts this compiler into a `Command` that's ready to be run.
2878 ///
2879 /// This is useful for when the compiler needs to be executed and the
2880 /// command returned will already have the initial arguments and environment
2881 /// variables configured.
to_command(&self) -> Command2882 pub fn to_command(&self) -> Command {
2883 let mut cmd = match self.cc_wrapper_path {
2884 Some(ref cc_wrapper_path) => {
2885 let mut cmd = Command::new(&cc_wrapper_path);
2886 cmd.arg(&self.path);
2887 cmd
2888 }
2889 None => Command::new(&self.path),
2890 };
2891 cmd.args(&self.cc_wrapper_args);
2892
2893 let value = self
2894 .args
2895 .iter()
2896 .filter(|a| !self.removed_args.contains(a))
2897 .collect::<Vec<_>>();
2898 cmd.args(&value);
2899
2900 for &(ref k, ref v) in self.env.iter() {
2901 cmd.env(k, v);
2902 }
2903 cmd
2904 }
2905
2906 /// Returns the path for this compiler.
2907 ///
2908 /// Note that this may not be a path to a file on the filesystem, e.g. "cc",
2909 /// but rather something which will be resolved when a process is spawned.
path(&self) -> &Path2910 pub fn path(&self) -> &Path {
2911 &self.path
2912 }
2913
2914 /// Returns the default set of arguments to the compiler needed to produce
2915 /// executables for the target this compiler generates.
args(&self) -> &[OsString]2916 pub fn args(&self) -> &[OsString] {
2917 &self.args
2918 }
2919
2920 /// Returns the set of environment variables needed for this compiler to
2921 /// operate.
2922 ///
2923 /// This is typically only used for MSVC compilers currently.
env(&self) -> &[(OsString, OsString)]2924 pub fn env(&self) -> &[(OsString, OsString)] {
2925 &self.env
2926 }
2927
2928 /// Returns the compiler command in format of CC environment variable.
2929 /// Or empty string if CC env was not present
2930 ///
2931 /// This is typically used by configure script
cc_env(&self) -> OsString2932 pub fn cc_env(&self) -> OsString {
2933 match self.cc_wrapper_path {
2934 Some(ref cc_wrapper_path) => {
2935 let mut cc_env = cc_wrapper_path.as_os_str().to_owned();
2936 cc_env.push(" ");
2937 cc_env.push(self.path.to_path_buf().into_os_string());
2938 for arg in self.cc_wrapper_args.iter() {
2939 cc_env.push(" ");
2940 cc_env.push(arg);
2941 }
2942 cc_env
2943 }
2944 None => OsString::from(""),
2945 }
2946 }
2947
2948 /// Returns the compiler flags in format of CFLAGS environment variable.
2949 /// Important here - this will not be CFLAGS from env, its internal gcc's flags to use as CFLAGS
2950 /// This is typically used by configure script
cflags_env(&self) -> OsString2951 pub fn cflags_env(&self) -> OsString {
2952 let mut flags = OsString::new();
2953 for (i, arg) in self.args.iter().enumerate() {
2954 if i > 0 {
2955 flags.push(" ");
2956 }
2957 flags.push(arg);
2958 }
2959 flags
2960 }
2961
2962 /// Whether the tool is GNU Compiler Collection-like.
is_like_gnu(&self) -> bool2963 pub fn is_like_gnu(&self) -> bool {
2964 self.family == ToolFamily::Gnu
2965 }
2966
2967 /// Whether the tool is Clang-like.
is_like_clang(&self) -> bool2968 pub fn is_like_clang(&self) -> bool {
2969 self.family == ToolFamily::Clang
2970 }
2971
2972 /// Whether the tool is MSVC-like.
is_like_msvc(&self) -> bool2973 pub fn is_like_msvc(&self) -> bool {
2974 match self.family {
2975 ToolFamily::Msvc { .. } => true,
2976 _ => false,
2977 }
2978 }
2979 }
2980
run(cmd: &mut Command, program: &str) -> Result<(), Error>2981 fn run(cmd: &mut Command, program: &str) -> Result<(), Error> {
2982 let (mut child, print) = spawn(cmd, program)?;
2983 let status = match child.wait() {
2984 Ok(s) => s,
2985 Err(_) => {
2986 return Err(Error::new(
2987 ErrorKind::ToolExecError,
2988 &format!(
2989 "Failed to wait on spawned child process, command {:?} with args {:?}.",
2990 cmd, program
2991 ),
2992 ));
2993 }
2994 };
2995 print.join().unwrap();
2996 println!("{}", status);
2997
2998 if status.success() {
2999 Ok(())
3000 } else {
3001 Err(Error::new(
3002 ErrorKind::ToolExecError,
3003 &format!(
3004 "Command {:?} with args {:?} did not execute successfully (status code {}).",
3005 cmd, program, status
3006 ),
3007 ))
3008 }
3009 }
3010
run_output(cmd: &mut Command, program: &str) -> Result<Vec<u8>, Error>3011 fn run_output(cmd: &mut Command, program: &str) -> Result<Vec<u8>, Error> {
3012 cmd.stdout(Stdio::piped());
3013 let (mut child, print) = spawn(cmd, program)?;
3014 let mut stdout = vec![];
3015 child
3016 .stdout
3017 .take()
3018 .unwrap()
3019 .read_to_end(&mut stdout)
3020 .unwrap();
3021 let status = match child.wait() {
3022 Ok(s) => s,
3023 Err(_) => {
3024 return Err(Error::new(
3025 ErrorKind::ToolExecError,
3026 &format!(
3027 "Failed to wait on spawned child process, command {:?} with args {:?}.",
3028 cmd, program
3029 ),
3030 ));
3031 }
3032 };
3033 print.join().unwrap();
3034 println!("{}", status);
3035
3036 if status.success() {
3037 Ok(stdout)
3038 } else {
3039 Err(Error::new(
3040 ErrorKind::ToolExecError,
3041 &format!(
3042 "Command {:?} with args {:?} did not execute successfully (status code {}).",
3043 cmd, program, status
3044 ),
3045 ))
3046 }
3047 }
3048
spawn(cmd: &mut Command, program: &str) -> Result<(Child, JoinHandle<()>), Error>3049 fn spawn(cmd: &mut Command, program: &str) -> Result<(Child, JoinHandle<()>), Error> {
3050 println!("running: {:?}", cmd);
3051
3052 // Capture the standard error coming from these programs, and write it out
3053 // with cargo:warning= prefixes. Note that this is a bit wonky to avoid
3054 // requiring the output to be UTF-8, we instead just ship bytes from one
3055 // location to another.
3056 match cmd.stderr(Stdio::piped()).spawn() {
3057 Ok(mut child) => {
3058 let stderr = BufReader::new(child.stderr.take().unwrap());
3059 let print = thread::spawn(move || {
3060 for line in stderr.split(b'\n').filter_map(|l| l.ok()) {
3061 print!("cargo:warning=");
3062 std::io::stdout().write_all(&line).unwrap();
3063 println!("");
3064 }
3065 });
3066 Ok((child, print))
3067 }
3068 Err(ref e) if e.kind() == io::ErrorKind::NotFound => {
3069 let extra = if cfg!(windows) {
3070 " (see https://github.com/alexcrichton/cc-rs#compile-time-requirements \
3071 for help)"
3072 } else {
3073 ""
3074 };
3075 Err(Error::new(
3076 ErrorKind::ToolNotFound,
3077 &format!("Failed to find tool. Is `{}` installed?{}", program, extra),
3078 ))
3079 }
3080 Err(ref e) => Err(Error::new(
3081 ErrorKind::ToolExecError,
3082 &format!(
3083 "Command {:?} with args {:?} failed to start: {:?}",
3084 cmd, program, e
3085 ),
3086 )),
3087 }
3088 }
3089
fail(s: &str) -> !3090 fn fail(s: &str) -> ! {
3091 eprintln!("\n\nerror occurred: {}\n\n", s);
3092 std::process::exit(1);
3093 }
3094
command_add_output_file( cmd: &mut Command, dst: &Path, cuda: bool, msvc: bool, clang: bool, is_asm: bool, is_arm: bool, )3095 fn command_add_output_file(
3096 cmd: &mut Command,
3097 dst: &Path,
3098 cuda: bool,
3099 msvc: bool,
3100 clang: bool,
3101 is_asm: bool,
3102 is_arm: bool,
3103 ) {
3104 if msvc && !clang && !cuda && !(is_asm && is_arm) {
3105 let mut s = OsString::from("-Fo");
3106 s.push(&dst);
3107 cmd.arg(s);
3108 } else {
3109 cmd.arg("-o").arg(&dst);
3110 }
3111 }
3112
3113 // Use by default minimum available API level
3114 // See note about naming here
3115 // https://android.googlesource.com/platform/ndk/+/refs/heads/ndk-release-r21/docs/BuildSystemMaintainers.md#Clang
3116 static NEW_STANDALONE_ANDROID_COMPILERS: [&str; 4] = [
3117 "aarch64-linux-android21-clang",
3118 "armv7a-linux-androideabi16-clang",
3119 "i686-linux-android16-clang",
3120 "x86_64-linux-android21-clang",
3121 ];
3122
3123 // New "standalone" C/C++ cross-compiler executables from recent Android NDK
3124 // are just shell scripts that call main clang binary (from Android NDK) with
3125 // proper `--target` argument.
3126 //
3127 // For example, armv7a-linux-androideabi16-clang passes
3128 // `--target=armv7a-linux-androideabi16` to clang.
3129 // So to construct proper command line check if
3130 // `--target` argument would be passed or not to clang
android_clang_compiler_uses_target_arg_internally(clang_path: &Path) -> bool3131 fn android_clang_compiler_uses_target_arg_internally(clang_path: &Path) -> bool {
3132 if let Some(filename) = clang_path.file_name() {
3133 if let Some(filename_str) = filename.to_str() {
3134 filename_str.contains("android")
3135 } else {
3136 false
3137 }
3138 } else {
3139 false
3140 }
3141 }
3142
3143 #[test]
test_android_clang_compiler_uses_target_arg_internally()3144 fn test_android_clang_compiler_uses_target_arg_internally() {
3145 for version in 16..21 {
3146 assert!(android_clang_compiler_uses_target_arg_internally(
3147 &PathBuf::from(format!("armv7a-linux-androideabi{}-clang", version))
3148 ));
3149 assert!(android_clang_compiler_uses_target_arg_internally(
3150 &PathBuf::from(format!("armv7a-linux-androideabi{}-clang++", version))
3151 ));
3152 }
3153 assert!(!android_clang_compiler_uses_target_arg_internally(
3154 &PathBuf::from("clang")
3155 ));
3156 assert!(!android_clang_compiler_uses_target_arg_internally(
3157 &PathBuf::from("clang++")
3158 ));
3159 }
3160
autodetect_android_compiler(target: &str, host: &str, gnu: &str, clang: &str) -> String3161 fn autodetect_android_compiler(target: &str, host: &str, gnu: &str, clang: &str) -> String {
3162 let new_clang_key = match target {
3163 "aarch64-linux-android" => Some("aarch64"),
3164 "armv7-linux-androideabi" => Some("armv7a"),
3165 "i686-linux-android" => Some("i686"),
3166 "x86_64-linux-android" => Some("x86_64"),
3167 _ => None,
3168 };
3169
3170 let new_clang = new_clang_key
3171 .map(|key| {
3172 NEW_STANDALONE_ANDROID_COMPILERS
3173 .iter()
3174 .find(|x| x.starts_with(key))
3175 })
3176 .unwrap_or(None);
3177
3178 if let Some(new_clang) = new_clang {
3179 if Command::new(new_clang).output().is_ok() {
3180 return (*new_clang).into();
3181 }
3182 }
3183
3184 let target = target
3185 .replace("armv7neon", "arm")
3186 .replace("armv7", "arm")
3187 .replace("thumbv7neon", "arm")
3188 .replace("thumbv7", "arm");
3189 let gnu_compiler = format!("{}-{}", target, gnu);
3190 let clang_compiler = format!("{}-{}", target, clang);
3191
3192 // On Windows, the Android clang compiler is provided as a `.cmd` file instead
3193 // of a `.exe` file. `std::process::Command` won't run `.cmd` files unless the
3194 // `.cmd` is explicitly appended to the command name, so we do that here.
3195 let clang_compiler_cmd = format!("{}-{}.cmd", target, clang);
3196
3197 // Check if gnu compiler is present
3198 // if not, use clang
3199 if Command::new(&gnu_compiler).output().is_ok() {
3200 gnu_compiler
3201 } else if host.contains("windows") && Command::new(&clang_compiler_cmd).output().is_ok() {
3202 clang_compiler_cmd
3203 } else {
3204 clang_compiler
3205 }
3206 }
3207
3208 // 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>3209 fn map_darwin_target_from_rust_to_compiler_architecture(target: &str) -> Option<&'static str> {
3210 if target.contains("x86_64") {
3211 Some("x86_64")
3212 } else if target.contains("arm64e") {
3213 Some("arm64e")
3214 } else if target.contains("aarch64") {
3215 Some("arm64")
3216 } else if target.contains("i686") {
3217 Some("i386")
3218 } else if target.contains("powerpc") {
3219 Some("ppc")
3220 } else if target.contains("powerpc64") {
3221 Some("ppc64")
3222 } else {
3223 None
3224 }
3225 }
3226
which(tool: &Path) -> Option<PathBuf>3227 fn which(tool: &Path) -> Option<PathBuf> {
3228 fn check_exe(exe: &mut PathBuf) -> bool {
3229 let exe_ext = std::env::consts::EXE_EXTENSION;
3230 exe.exists() || (!exe_ext.is_empty() && exe.set_extension(exe_ext) && exe.exists())
3231 }
3232
3233 // If |tool| is not just one "word," assume it's an actual path...
3234 if tool.components().count() > 1 {
3235 let mut exe = PathBuf::from(tool);
3236 return if check_exe(&mut exe) { Some(exe) } else { None };
3237 }
3238
3239 // Loop through PATH entries searching for the |tool|.
3240 let path_entries = env::var_os("PATH")?;
3241 env::split_paths(&path_entries).find_map(|path_entry| {
3242 let mut exe = path_entry.join(tool);
3243 return if check_exe(&mut exe) { Some(exe) } else { None };
3244 })
3245 }
3246