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