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.args.push("-Brepro".into());
1429 
1430                 if clang_cl {
1431                     if target.contains("x86_64") {
1432                         cmd.args.push("-m64".into());
1433                     } else if target.contains("86") {
1434                         cmd.args.push("-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 self.static_flag.is_none() {
1469                     let features = self
1470                         .getenv("CARGO_CFG_TARGET_FEATURE")
1471                         .unwrap_or(String::new());
1472                     if features.contains("crt-static") {
1473                         cmd.args.push("-static".into());
1474                     }
1475                 }
1476 
1477                 // armv7 targets get to use armv7 instructions
1478                 if (target.starts_with("armv7") || target.starts_with("thumbv7"))
1479                     && target.contains("-linux-")
1480                 {
1481                     cmd.args.push("-march=armv7-a".into());
1482                 }
1483 
1484                 // (x86 Android doesn't say "eabi")
1485                 if target.contains("-androideabi") && target.contains("v7") {
1486                     // -march=armv7-a handled above
1487                     cmd.args.push("-mthumb".into());
1488                     if !target.contains("neon") {
1489                         // On android we can guarantee some extra float instructions
1490                         // (specified in the android spec online)
1491                         // NEON guarantees even more; see below.
1492                         cmd.args.push("-mfpu=vfpv3-d16".into());
1493                     }
1494                     cmd.args.push("-mfloat-abi=softfp".into());
1495                 }
1496 
1497                 if target.contains("neon") {
1498                     cmd.args.push("-mfpu=neon-vfpv4".into());
1499                 }
1500 
1501                 if target.starts_with("armv4t-unknown-linux-") {
1502                     cmd.args.push("-march=armv4t".into());
1503                     cmd.args.push("-marm".into());
1504                     cmd.args.push("-mfloat-abi=soft".into());
1505                 }
1506 
1507                 if target.starts_with("armv5te-unknown-linux-") {
1508                     cmd.args.push("-march=armv5te".into());
1509                     cmd.args.push("-marm".into());
1510                     cmd.args.push("-mfloat-abi=soft".into());
1511                 }
1512 
1513                 // For us arm == armv6 by default
1514                 if target.starts_with("arm-unknown-linux-") {
1515                     cmd.args.push("-march=armv6".into());
1516                     cmd.args.push("-marm".into());
1517                     if target.ends_with("hf") {
1518                         cmd.args.push("-mfpu=vfp".into());
1519                     } else {
1520                         cmd.args.push("-mfloat-abi=soft".into());
1521                     }
1522                 }
1523 
1524                 // We can guarantee some settings for FRC
1525                 if target.starts_with("arm-frc-") {
1526                     cmd.args.push("-march=armv7-a".into());
1527                     cmd.args.push("-mcpu=cortex-a9".into());
1528                     cmd.args.push("-mfpu=vfpv3".into());
1529                     cmd.args.push("-mfloat-abi=softfp".into());
1530                     cmd.args.push("-marm".into());
1531                 }
1532 
1533                 // Turn codegen down on i586 to avoid some instructions.
1534                 if target.starts_with("i586-unknown-linux-") {
1535                     cmd.args.push("-march=pentium".into());
1536                 }
1537 
1538                 // Set codegen level for i686 correctly
1539                 if target.starts_with("i686-unknown-linux-") {
1540                     cmd.args.push("-march=i686".into());
1541                 }
1542 
1543                 // Looks like `musl-gcc` makes is hard for `-m32` to make its way
1544                 // all the way to the linker, so we need to actually instruct the
1545                 // linker that we're generating 32-bit executables as well. This'll
1546                 // typically only be used for build scripts which transitively use
1547                 // these flags that try to compile executables.
1548                 if target == "i686-unknown-linux-musl" || target == "i586-unknown-linux-musl" {
1549                     cmd.args.push("-Wl,-melf_i386".into());
1550                 }
1551 
1552                 if target.starts_with("thumb") {
1553                     cmd.args.push("-mthumb".into());
1554 
1555                     if target.ends_with("eabihf") {
1556                         cmd.args.push("-mfloat-abi=hard".into())
1557                     }
1558                 }
1559                 if target.starts_with("thumbv6m") {
1560                     cmd.args.push("-march=armv6s-m".into());
1561                 }
1562                 if target.starts_with("thumbv7em") {
1563                     cmd.args.push("-march=armv7e-m".into());
1564 
1565                     if target.ends_with("eabihf") {
1566                         cmd.args.push("-mfpu=fpv4-sp-d16".into())
1567                     }
1568                 }
1569                 if target.starts_with("thumbv7m") {
1570                     cmd.args.push("-march=armv7-m".into());
1571                 }
1572                 if target.starts_with("thumbv8m.base") {
1573                     cmd.args.push("-march=armv8-m.base".into());
1574                 }
1575                 if target.starts_with("thumbv8m.main") {
1576                     cmd.args.push("-march=armv8-m.main".into());
1577 
1578                     if target.ends_with("eabihf") {
1579                         cmd.args.push("-mfpu=fpv5-sp-d16".into())
1580                     }
1581                 }
1582                 if target.starts_with("armebv7r") | target.starts_with("armv7r") {
1583                     if target.starts_with("armeb") {
1584                         cmd.args.push("-mbig-endian".into());
1585                     } else {
1586                         cmd.args.push("-mlittle-endian".into());
1587                     }
1588 
1589                     // ARM mode
1590                     cmd.args.push("-marm".into());
1591 
1592                     // R Profile
1593                     cmd.args.push("-march=armv7-r".into());
1594 
1595                     if target.ends_with("eabihf") {
1596                         // Calling convention
1597                         cmd.args.push("-mfloat-abi=hard".into());
1598 
1599                         // lowest common denominator FPU
1600                         // (see Cortex-R4 technical reference manual)
1601                         cmd.args.push("-mfpu=vfpv3-d16".into())
1602                     } else {
1603                         // Calling convention
1604                         cmd.args.push("-mfloat-abi=soft".into());
1605                     }
1606                 }
1607                 if target.starts_with("armv7a") {
1608                     cmd.args.push("-march=armv7-a".into());
1609 
1610                     if target.ends_with("eabihf") {
1611                         // lowest common denominator FPU
1612                         cmd.args.push("-mfpu=vfpv3-d16".into());
1613                     }
1614                 }
1615                 if target.starts_with("riscv32") || target.starts_with("riscv64") {
1616                     // get the 32i/32imac/32imc/64gc/64imac/... part
1617                     let mut parts = target.split('-');
1618                     if let Some(arch) = parts.next() {
1619                         let arch = &arch[5..];
1620                         cmd.args.push(("-march=rv".to_owned() + arch).into());
1621                         if target.contains("linux") && arch.starts_with("64") {
1622                             cmd.args.push("-mabi=lp64d".into());
1623                         } else if target.contains("linux") && arch.starts_with("32") {
1624                             cmd.args.push("-mabi=ilp32d".into());
1625                         } else if arch.starts_with("64") {
1626                             cmd.args.push("-mabi=lp64".into());
1627                         } else {
1628                             cmd.args.push("-mabi=ilp32".into());
1629                         }
1630                         cmd.args.push("-mcmodel=medany".into());
1631                     }
1632                 }
1633             }
1634         }
1635 
1636         if target.contains("-ios") {
1637             // FIXME: potential bug. iOS is always compiled with Clang, but Gcc compiler may be
1638             // detected instead.
1639             self.ios_flags(cmd)?;
1640         }
1641 
1642         if self.static_flag.unwrap_or(false) {
1643             cmd.args.push("-static".into());
1644         }
1645         if self.shared_flag.unwrap_or(false) {
1646             cmd.args.push("-shared".into());
1647         }
1648 
1649         if self.cpp {
1650             match (self.cpp_set_stdlib.as_ref(), cmd.family) {
1651                 (None, _) => {}
1652                 (Some(stdlib), ToolFamily::Gnu) | (Some(stdlib), ToolFamily::Clang) => {
1653                     cmd.push_cc_arg(format!("-stdlib=lib{}", stdlib).into());
1654                 }
1655                 _ => {
1656                     println!(
1657                         "cargo:warning=cpp_set_stdlib is specified, but the {:?} compiler \
1658                          does not support this option, ignored",
1659                         cmd.family
1660                     );
1661                 }
1662             }
1663         }
1664 
1665         Ok(())
1666     }
1667 
has_flags(&self) -> bool1668     fn has_flags(&self) -> bool {
1669         let flags_env_var_name = if self.cpp { "CXXFLAGS" } else { "CFLAGS" };
1670         let flags_env_var_value = self.get_var(flags_env_var_name);
1671         if let Ok(_) = flags_env_var_value {
1672             true
1673         } else {
1674             false
1675         }
1676     }
1677 
msvc_macro_assembler(&self) -> Result<(Command, String), Error>1678     fn msvc_macro_assembler(&self) -> Result<(Command, String), Error> {
1679         let target = self.get_target()?;
1680         let tool = if target.contains("x86_64") {
1681             "ml64.exe"
1682         } else if target.contains("arm") {
1683             "armasm.exe"
1684         } else if target.contains("aarch64") {
1685             "armasm64.exe"
1686         } else {
1687             "ml.exe"
1688         };
1689         let mut cmd = windows_registry::find(&target, tool).unwrap_or_else(|| self.cmd(tool));
1690         for directory in self.include_directories.iter() {
1691             cmd.arg("-I").arg(directory);
1692         }
1693         for &(ref key, ref value) in self.definitions.iter() {
1694             if let Some(ref value) = *value {
1695                 cmd.arg(&format!("-D{}={}", key, value));
1696             } else {
1697                 cmd.arg(&format!("-D{}", key));
1698             }
1699         }
1700 
1701         if target.contains("i686") || target.contains("i586") {
1702             cmd.arg("-safeseh");
1703         }
1704         for flag in self.flags.iter() {
1705             cmd.arg(flag);
1706         }
1707 
1708         Ok((cmd, tool.to_string()))
1709     }
1710 
assemble(&self, lib_name: &str, dst: &Path, objs: &[Object]) -> Result<(), Error>1711     fn assemble(&self, lib_name: &str, dst: &Path, objs: &[Object]) -> Result<(), Error> {
1712         // Delete the destination if it exists as the `ar` tool at least on Unix
1713         // appends to it, which we don't want.
1714         let _ = fs::remove_file(&dst);
1715 
1716         let objects: Vec<_> = objs.iter().map(|obj| obj.dst.clone()).collect();
1717         let target = self.get_target()?;
1718         if target.contains("msvc") {
1719             let (mut cmd, program) = self.get_ar()?;
1720             let mut out = OsString::from("-out:");
1721             out.push(dst);
1722             cmd.arg(out).arg("-nologo");
1723             for flag in self.ar_flags.iter() {
1724                 cmd.arg(flag);
1725             }
1726 
1727             // Similar to https://github.com/rust-lang/rust/pull/47507
1728             // and https://github.com/rust-lang/rust/pull/48548
1729             let estimated_command_line_len = objects
1730                 .iter()
1731                 .chain(&self.objects)
1732                 .map(|a| a.as_os_str().len())
1733                 .sum::<usize>();
1734             if estimated_command_line_len > 1024 * 6 {
1735                 let mut args = String::from("\u{FEFF}"); // BOM
1736                 for arg in objects.iter().chain(&self.objects) {
1737                     args.push('"');
1738                     for c in arg.to_str().unwrap().chars() {
1739                         if c == '"' {
1740                             args.push('\\')
1741                         }
1742                         args.push(c)
1743                     }
1744                     args.push('"');
1745                     args.push('\n');
1746                 }
1747 
1748                 let mut utf16le = Vec::new();
1749                 for code_unit in args.encode_utf16() {
1750                     utf16le.push(code_unit as u8);
1751                     utf16le.push((code_unit >> 8) as u8);
1752                 }
1753 
1754                 let mut args_file = OsString::from(dst);
1755                 args_file.push(".args");
1756                 fs::File::create(&args_file)
1757                     .unwrap()
1758                     .write_all(&utf16le)
1759                     .unwrap();
1760 
1761                 let mut args_file_arg = OsString::from("@");
1762                 args_file_arg.push(args_file);
1763                 cmd.arg(args_file_arg);
1764             } else {
1765                 cmd.args(&objects).args(&self.objects);
1766             }
1767             run(&mut cmd, &program)?;
1768 
1769             // The Rust compiler will look for libfoo.a and foo.lib, but the
1770             // MSVC linker will also be passed foo.lib, so be sure that both
1771             // exist for now.
1772             let lib_dst = dst.with_file_name(format!("{}.lib", lib_name));
1773             let _ = fs::remove_file(&lib_dst);
1774             match fs::hard_link(&dst, &lib_dst).or_else(|_| {
1775                 // if hard-link fails, just copy (ignoring the number of bytes written)
1776                 fs::copy(&dst, &lib_dst).map(|_| ())
1777             }) {
1778                 Ok(_) => (),
1779                 Err(_) => {
1780                     return Err(Error::new(
1781                         ErrorKind::IOError,
1782                         "Could not copy or create a hard-link to the generated lib file.",
1783                     ));
1784                 }
1785             };
1786         } else {
1787             let (mut ar, cmd) = self.get_ar()?;
1788 
1789             // Set an environment variable to tell the OSX archiver to ensure
1790             // that all dates listed in the archive are zero, improving
1791             // determinism of builds. AFAIK there's not really official
1792             // documentation of this but there's a lot of references to it if
1793             // you search google.
1794             //
1795             // You can reproduce this locally on a mac with:
1796             //
1797             //      $ touch foo.c
1798             //      $ cc -c foo.c -o foo.o
1799             //
1800             //      # Notice that these two checksums are different
1801             //      $ ar crus libfoo1.a foo.o && sleep 2 && ar crus libfoo2.a foo.o
1802             //      $ md5sum libfoo*.a
1803             //
1804             //      # Notice that these two checksums are the same
1805             //      $ export ZERO_AR_DATE=1
1806             //      $ ar crus libfoo1.a foo.o && sleep 2 && touch foo.o && ar crus libfoo2.a foo.o
1807             //      $ md5sum libfoo*.a
1808             //
1809             // In any case if this doesn't end up getting read, it shouldn't
1810             // cause that many issues!
1811             ar.env("ZERO_AR_DATE", "1");
1812             for flag in self.ar_flags.iter() {
1813                 ar.arg(flag);
1814             }
1815             run(
1816                 ar.arg("crs").arg(dst).args(&objects).args(&self.objects),
1817                 &cmd,
1818             )?;
1819         }
1820 
1821         Ok(())
1822     }
1823 
ios_flags(&self, cmd: &mut Tool) -> Result<(), Error>1824     fn ios_flags(&self, cmd: &mut Tool) -> Result<(), Error> {
1825         enum ArchSpec {
1826             Device(&'static str),
1827             Simulator(&'static str),
1828         }
1829 
1830         let target = self.get_target()?;
1831         let arch = target.split('-').nth(0).ok_or_else(|| {
1832             Error::new(
1833                 ErrorKind::ArchitectureInvalid,
1834                 "Unknown architecture for iOS target.",
1835             )
1836         })?;
1837         let arch = match arch {
1838             "arm" | "armv7" | "thumbv7" => ArchSpec::Device("armv7"),
1839             "armv7s" | "thumbv7s" => ArchSpec::Device("armv7s"),
1840             "arm64" | "aarch64" => ArchSpec::Device("arm64"),
1841             "i386" | "i686" => ArchSpec::Simulator("-m32"),
1842             "x86_64" => ArchSpec::Simulator("-m64"),
1843             _ => {
1844                 return Err(Error::new(
1845                     ErrorKind::ArchitectureInvalid,
1846                     "Unknown architecture for iOS target.",
1847                 ));
1848             }
1849         };
1850 
1851         let min_version =
1852             std::env::var("IPHONEOS_DEPLOYMENT_TARGET").unwrap_or_else(|_| "7.0".into());
1853 
1854         let sdk = match arch {
1855             ArchSpec::Device(arch) => {
1856                 cmd.args.push("-arch".into());
1857                 cmd.args.push(arch.into());
1858                 cmd.args
1859                     .push(format!("-miphoneos-version-min={}", min_version).into());
1860                 "iphoneos"
1861             }
1862             ArchSpec::Simulator(arch) => {
1863                 cmd.args.push(arch.into());
1864                 cmd.args
1865                     .push(format!("-mios-simulator-version-min={}", min_version).into());
1866                 "iphonesimulator"
1867             }
1868         };
1869 
1870         self.print(&format!("Detecting iOS SDK path for {}", sdk));
1871         let sdk_path = self
1872             .cmd("xcrun")
1873             .arg("--show-sdk-path")
1874             .arg("--sdk")
1875             .arg(sdk)
1876             .stderr(Stdio::inherit())
1877             .output()?
1878             .stdout;
1879 
1880         let sdk_path = match String::from_utf8(sdk_path) {
1881             Ok(p) => p,
1882             Err(_) => {
1883                 return Err(Error::new(
1884                     ErrorKind::IOError,
1885                     "Unable to determine iOS SDK path.",
1886                 ));
1887             }
1888         };
1889 
1890         cmd.args.push("-isysroot".into());
1891         cmd.args.push(sdk_path.trim().into());
1892         cmd.args.push("-fembed-bitcode".into());
1893         /*
1894          * TODO we probably ultimately want the -fembed-bitcode-marker flag
1895          * but can't have it now because of an issue in LLVM:
1896          * https://github.com/alexcrichton/cc-rs/issues/301
1897          * https://github.com/rust-lang/rust/pull/48896#comment-372192660
1898          */
1899         /*
1900         if self.get_opt_level()? == "0" {
1901             cmd.args.push("-fembed-bitcode-marker".into());
1902         }
1903         */
1904 
1905         Ok(())
1906     }
1907 
cmd<P: AsRef<OsStr>>(&self, prog: P) -> Command1908     fn cmd<P: AsRef<OsStr>>(&self, prog: P) -> Command {
1909         let mut cmd = Command::new(prog);
1910         for &(ref a, ref b) in self.env.iter() {
1911             cmd.env(a, b);
1912         }
1913         cmd
1914     }
1915 
get_base_compiler(&self) -> Result<Tool, Error>1916     fn get_base_compiler(&self) -> Result<Tool, Error> {
1917         if let Some(ref c) = self.compiler {
1918             return Ok(Tool::new(c.clone()));
1919         }
1920         let host = self.get_host()?;
1921         let target = self.get_target()?;
1922         let (env, msvc, gnu, traditional, clang) = if self.cpp {
1923             ("CXX", "cl.exe", "g++", "c++", "clang++")
1924         } else {
1925             ("CC", "cl.exe", "gcc", "cc", "clang")
1926         };
1927 
1928         // On historical Solaris systems, "cc" may have been Sun Studio, which
1929         // is not flag-compatible with "gcc".  This history casts a long shadow,
1930         // and many modern illumos distributions today ship GCC as "gcc" without
1931         // also making it available as "cc".
1932         let default = if host.contains("solaris") || host.contains("illumos") {
1933             gnu
1934         } else {
1935             traditional
1936         };
1937 
1938         let cl_exe = windows_registry::find_tool(&target, "cl.exe");
1939 
1940         let tool_opt: Option<Tool> = self
1941             .env_tool(env)
1942             .map(|(tool, wrapper, args)| {
1943                 // find the driver mode, if any
1944                 const DRIVER_MODE: &str = "--driver-mode=";
1945                 let driver_mode = args
1946                     .iter()
1947                     .find(|a| a.starts_with(DRIVER_MODE))
1948                     .map(|a| &a[DRIVER_MODE.len()..]);
1949                 // Chop off leading/trailing whitespace to work around
1950                 // semi-buggy build scripts which are shared in
1951                 // makefiles/configure scripts (where spaces are far more
1952                 // lenient)
1953                 let mut t = Tool::with_clang_driver(PathBuf::from(tool.trim()), driver_mode);
1954                 if let Some(cc_wrapper) = wrapper {
1955                     t.cc_wrapper_path = Some(PathBuf::from(cc_wrapper));
1956                 }
1957                 for arg in args {
1958                     t.cc_wrapper_args.push(arg.into());
1959                 }
1960                 t
1961             })
1962             .or_else(|| {
1963                 if target.contains("emscripten") {
1964                     let tool = if self.cpp { "em++" } else { "emcc" };
1965                     // Windows uses bat file so we have to be a bit more specific
1966                     if cfg!(windows) {
1967                         let mut t = Tool::new(PathBuf::from("cmd"));
1968                         t.args.push("/c".into());
1969                         t.args.push(format!("{}.bat", tool).into());
1970                         Some(t)
1971                     } else {
1972                         Some(Tool::new(PathBuf::from(tool)))
1973                     }
1974                 } else {
1975                     None
1976                 }
1977             })
1978             .or_else(|| cl_exe.clone());
1979 
1980         let tool = match tool_opt {
1981             Some(t) => t,
1982             None => {
1983                 let compiler = if host.contains("windows") && target.contains("windows") {
1984                     if target.contains("msvc") {
1985                         msvc.to_string()
1986                     } else {
1987                         format!("{}.exe", gnu)
1988                     }
1989                 } else if target.contains("android") {
1990                     autodetect_android_compiler(&target, &host, gnu, clang)
1991                 } else if target.contains("cloudabi") {
1992                     format!("{}-{}", target, traditional)
1993                 } else if target == "wasm32-wasi"
1994                     || target == "wasm32-unknown-wasi"
1995                     || target == "wasm32-unknown-unknown"
1996                 {
1997                     "clang".to_string()
1998                 } else if target.contains("vxworks") {
1999                     "wr-c++".to_string()
2000                 } else if self.get_host()? != target {
2001                     let prefix = self.prefix_for_target(&target);
2002                     match prefix {
2003                         Some(prefix) => format!("{}-{}", prefix, gnu),
2004                         None => default.to_string(),
2005                     }
2006                 } else {
2007                     default.to_string()
2008                 };
2009 
2010                 let mut t = Tool::new(PathBuf::from(compiler));
2011                 if let Some(cc_wrapper) = Self::rustc_wrapper_fallback() {
2012                     t.cc_wrapper_path = Some(PathBuf::from(cc_wrapper));
2013                 }
2014                 t
2015             }
2016         };
2017 
2018         let mut tool = if self.cuda {
2019             assert!(
2020                 tool.args.is_empty(),
2021                 "CUDA compilation currently assumes empty pre-existing args"
2022             );
2023             let nvcc = match self.get_var("NVCC") {
2024                 Err(_) => "nvcc".into(),
2025                 Ok(nvcc) => nvcc,
2026             };
2027             let mut nvcc_tool = Tool::with_features(PathBuf::from(nvcc), None, self.cuda);
2028             nvcc_tool
2029                 .args
2030                 .push(format!("-ccbin={}", tool.path.display()).into());
2031             nvcc_tool.family = tool.family;
2032             nvcc_tool
2033         } else {
2034             tool
2035         };
2036 
2037         // If we found `cl.exe` in our environment, the tool we're returning is
2038         // an MSVC-like tool, *and* no env vars were set then set env vars for
2039         // the tool that we're returning.
2040         //
2041         // Env vars are needed for things like `link.exe` being put into PATH as
2042         // well as header include paths sometimes. These paths are automatically
2043         // included by default but if the `CC` or `CXX` env vars are set these
2044         // won't be used. This'll ensure that when the env vars are used to
2045         // configure for invocations like `clang-cl` we still get a "works out
2046         // of the box" experience.
2047         if let Some(cl_exe) = cl_exe {
2048             if tool.family == (ToolFamily::Msvc { clang_cl: true })
2049                 && tool.env.len() == 0
2050                 && target.contains("msvc")
2051             {
2052                 for &(ref k, ref v) in cl_exe.env.iter() {
2053                     tool.env.push((k.to_owned(), v.to_owned()));
2054                 }
2055             }
2056         }
2057 
2058         Ok(tool)
2059     }
2060 
get_var(&self, var_base: &str) -> Result<String, Error>2061     fn get_var(&self, var_base: &str) -> Result<String, Error> {
2062         let target = self.get_target()?;
2063         let host = self.get_host()?;
2064         let kind = if host == target { "HOST" } else { "TARGET" };
2065         let target_u = target.replace("-", "_");
2066         let res = self
2067             .getenv(&format!("{}_{}", var_base, target))
2068             .or_else(|| self.getenv(&format!("{}_{}", var_base, target_u)))
2069             .or_else(|| self.getenv(&format!("{}_{}", kind, var_base)))
2070             .or_else(|| self.getenv(var_base));
2071 
2072         match res {
2073             Some(res) => Ok(res),
2074             None => Err(Error::new(
2075                 ErrorKind::EnvVarNotFound,
2076                 &format!("Could not find environment variable {}.", var_base),
2077             )),
2078         }
2079     }
2080 
envflags(&self, name: &str) -> Vec<String>2081     fn envflags(&self, name: &str) -> Vec<String> {
2082         self.get_var(name)
2083             .unwrap_or(String::new())
2084             .split(|c: char| c.is_whitespace())
2085             .filter(|s| !s.is_empty())
2086             .map(|s| s.to_string())
2087             .collect()
2088     }
2089 
2090     /// Returns a fallback `cc_compiler_wrapper` by introspecting `RUSTC_WRAPPER`
rustc_wrapper_fallback() -> Option<String>2091     fn rustc_wrapper_fallback() -> Option<String> {
2092         // No explicit CC wrapper was detected, but check if RUSTC_WRAPPER
2093         // is defined and is a build accelerator that is compatible with
2094         // C/C++ compilers (e.g. sccache)
2095         let valid_wrappers = ["sccache"];
2096 
2097         let rustc_wrapper = std::env::var_os("RUSTC_WRAPPER")?;
2098         let wrapper_path = Path::new(&rustc_wrapper);
2099         let wrapper_stem = wrapper_path.file_stem()?;
2100 
2101         if valid_wrappers.contains(&wrapper_stem.to_str()?) {
2102             Some(rustc_wrapper.to_str()?.to_owned())
2103         } else {
2104             None
2105         }
2106     }
2107 
2108     /// Returns compiler path, optional modifier name from whitelist, and arguments vec
env_tool(&self, name: &str) -> Option<(String, Option<String>, Vec<String>)>2109     fn env_tool(&self, name: &str) -> Option<(String, Option<String>, Vec<String>)> {
2110         let tool = match self.get_var(name) {
2111             Ok(tool) => tool,
2112             Err(_) => return None,
2113         };
2114 
2115         // If this is an exact path on the filesystem we don't want to do any
2116         // interpretation at all, just pass it on through. This'll hopefully get
2117         // us to support spaces-in-paths.
2118         if Path::new(&tool).exists() {
2119             return Some((tool, None, Vec::new()));
2120         }
2121 
2122         // Ok now we want to handle a couple of scenarios. We'll assume from
2123         // here on out that spaces are splitting separate arguments. Two major
2124         // features we want to support are:
2125         //
2126         //      CC='sccache cc'
2127         //
2128         // aka using `sccache` or any other wrapper/caching-like-thing for
2129         // compilations. We want to know what the actual compiler is still,
2130         // though, because our `Tool` API support introspection of it to see
2131         // what compiler is in use.
2132         //
2133         // additionally we want to support
2134         //
2135         //      CC='cc -flag'
2136         //
2137         // where the CC env var is used to also pass default flags to the C
2138         // compiler.
2139         //
2140         // It's true that everything here is a bit of a pain, but apparently if
2141         // you're not literally make or bash then you get a lot of bug reports.
2142         let known_wrappers = ["ccache", "distcc", "sccache", "icecc"];
2143 
2144         let mut parts = tool.split_whitespace();
2145         let maybe_wrapper = match parts.next() {
2146             Some(s) => s,
2147             None => return None,
2148         };
2149 
2150         let file_stem = Path::new(maybe_wrapper)
2151             .file_stem()
2152             .unwrap()
2153             .to_str()
2154             .unwrap();
2155         if known_wrappers.contains(&file_stem) {
2156             if let Some(compiler) = parts.next() {
2157                 return Some((
2158                     compiler.to_string(),
2159                     Some(maybe_wrapper.to_string()),
2160                     parts.map(|s| s.to_string()).collect(),
2161                 ));
2162             }
2163         }
2164 
2165         Some((
2166             maybe_wrapper.to_string(),
2167             Self::rustc_wrapper_fallback(),
2168             parts.map(|s| s.to_string()).collect(),
2169         ))
2170     }
2171 
2172     /// Returns the default C++ standard library for the current target: `libc++`
2173     /// for OS X and `libstdc++` for anything else.
get_cpp_link_stdlib(&self) -> Result<Option<String>, Error>2174     fn get_cpp_link_stdlib(&self) -> Result<Option<String>, Error> {
2175         match self.cpp_link_stdlib.clone() {
2176             Some(s) => Ok(s),
2177             None => {
2178                 if let Ok(stdlib) = self.get_var("CXXSTDLIB") {
2179                     if stdlib.is_empty() {
2180                         Ok(None)
2181                     } else {
2182                         Ok(Some(stdlib))
2183                     }
2184                 } else {
2185                     let target = self.get_target()?;
2186                     if target.contains("msvc") {
2187                         Ok(None)
2188                     } else if target.contains("apple") {
2189                         Ok(Some("c++".to_string()))
2190                     } else if target.contains("freebsd") {
2191                         Ok(Some("c++".to_string()))
2192                     } else if target.contains("openbsd") {
2193                         Ok(Some("c++".to_string()))
2194                     } else {
2195                         Ok(Some("stdc++".to_string()))
2196                     }
2197                 }
2198             }
2199         }
2200     }
2201 
get_ar(&self) -> Result<(Command, String), Error>2202     fn get_ar(&self) -> Result<(Command, String), Error> {
2203         if let Some(ref p) = self.archiver {
2204             let name = p.file_name().and_then(|s| s.to_str()).unwrap_or("ar");
2205             return Ok((self.cmd(p), name.to_string()));
2206         }
2207         if let Ok(p) = self.get_var("AR") {
2208             return Ok((self.cmd(&p), p));
2209         }
2210         let target = self.get_target()?;
2211         let default_ar = "ar".to_string();
2212         let program = if target.contains("android") {
2213             format!("{}-ar", target.replace("armv7", "arm"))
2214         } else if target.contains("emscripten") {
2215             // Windows use bat files so we have to be a bit more specific
2216             if cfg!(windows) {
2217                 let mut cmd = self.cmd("cmd");
2218                 cmd.arg("/c").arg("emar.bat");
2219                 return Ok((cmd, "emar.bat".to_string()));
2220             }
2221 
2222             "emar".to_string()
2223         } else if target.contains("msvc") {
2224             match windows_registry::find(&target, "lib.exe") {
2225                 Some(t) => return Ok((t, "lib.exe".to_string())),
2226                 None => "lib.exe".to_string(),
2227             }
2228         } else if self.get_host()? != target {
2229             match self.prefix_for_target(&target) {
2230                 Some(p) => {
2231                     let target_ar = format!("{}-ar", p);
2232                     if Command::new(&target_ar).output().is_ok() {
2233                         target_ar
2234                     } else {
2235                         default_ar
2236                     }
2237                 }
2238                 None => default_ar,
2239             }
2240         } else {
2241             default_ar
2242         };
2243         Ok((self.cmd(&program), program))
2244     }
2245 
prefix_for_target(&self, target: &str) -> Option<String>2246     fn prefix_for_target(&self, target: &str) -> Option<String> {
2247         // CROSS_COMPILE is of the form: "arm-linux-gnueabi-"
2248         let cc_env = self.getenv("CROSS_COMPILE");
2249         let cross_compile = cc_env
2250             .as_ref()
2251             .map(|s| s.trim_right_matches('-').to_owned());
2252         cross_compile.or(match &target[..] {
2253             "aarch64-unknown-linux-gnu" => Some("aarch64-linux-gnu"),
2254             "aarch64-unknown-linux-musl" => Some("aarch64-linux-musl"),
2255             "aarch64-unknown-netbsd" => Some("aarch64--netbsd"),
2256             "arm-unknown-linux-gnueabi" => Some("arm-linux-gnueabi"),
2257             "armv4t-unknown-linux-gnueabi" => Some("arm-linux-gnueabi"),
2258             "armv5te-unknown-linux-gnueabi" => Some("arm-linux-gnueabi"),
2259             "armv5te-unknown-linux-musleabi" => Some("arm-linux-gnueabi"),
2260             "arm-frc-linux-gnueabi" => Some("arm-frc-linux-gnueabi"),
2261             "arm-unknown-linux-gnueabihf" => Some("arm-linux-gnueabihf"),
2262             "arm-unknown-linux-musleabi" => Some("arm-linux-musleabi"),
2263             "arm-unknown-linux-musleabihf" => Some("arm-linux-musleabihf"),
2264             "arm-unknown-netbsd-eabi" => Some("arm--netbsdelf-eabi"),
2265             "armv6-unknown-netbsd-eabihf" => Some("armv6--netbsdelf-eabihf"),
2266             "armv7-unknown-linux-gnueabihf" => Some("arm-linux-gnueabihf"),
2267             "armv7-unknown-linux-musleabihf" => Some("arm-linux-musleabihf"),
2268             "armv7neon-unknown-linux-gnueabihf" => Some("arm-linux-gnueabihf"),
2269             "armv7neon-unknown-linux-musleabihf" => Some("arm-linux-musleabihf"),
2270             "thumbv7-unknown-linux-gnueabihf" => Some("arm-linux-gnueabihf"),
2271             "thumbv7-unknown-linux-musleabihf" => Some("arm-linux-musleabihf"),
2272             "thumbv7neon-unknown-linux-gnueabihf" => Some("arm-linux-gnueabihf"),
2273             "thumbv7neon-unknown-linux-musleabihf" => Some("arm-linux-musleabihf"),
2274             "armv7-unknown-netbsd-eabihf" => Some("armv7--netbsdelf-eabihf"),
2275             "i586-unknown-linux-musl" => Some("musl"),
2276             "i686-pc-windows-gnu" => Some("i686-w64-mingw32"),
2277             "i686-uwp-windows-gnu" => Some("i686-w64-mingw32"),
2278             "i686-unknown-linux-musl" => Some("musl"),
2279             "i686-unknown-netbsd" => Some("i486--netbsdelf"),
2280             "mips-unknown-linux-gnu" => Some("mips-linux-gnu"),
2281             "mipsel-unknown-linux-gnu" => Some("mipsel-linux-gnu"),
2282             "mips64-unknown-linux-gnuabi64" => Some("mips64-linux-gnuabi64"),
2283             "mips64el-unknown-linux-gnuabi64" => Some("mips64el-linux-gnuabi64"),
2284             "mipsisa32r6-unknown-linux-gnu" => Some("mipsisa32r6-linux-gnu"),
2285             "mipsisa32r6el-unknown-linux-gnu" => Some("mipsisa32r6el-linux-gnu"),
2286             "mipsisa64r6-unknown-linux-gnuabi64" => Some("mipsisa64r6-linux-gnuabi64"),
2287             "mipsisa64r6el-unknown-linux-gnuabi64" => Some("mipsisa64r6el-linux-gnuabi64"),
2288             "powerpc-unknown-linux-gnu" => Some("powerpc-linux-gnu"),
2289             "powerpc-unknown-linux-gnuspe" => Some("powerpc-linux-gnuspe"),
2290             "powerpc-unknown-netbsd" => Some("powerpc--netbsd"),
2291             "powerpc64-unknown-linux-gnu" => Some("powerpc-linux-gnu"),
2292             "powerpc64le-unknown-linux-gnu" => Some("powerpc64le-linux-gnu"),
2293             "riscv32i-unknown-none-elf" => Some("riscv32-unknown-elf"),
2294             "riscv32imac-unknown-none-elf" => Some("riscv32-unknown-elf"),
2295             "riscv32imc-unknown-none-elf" => Some("riscv32-unknown-elf"),
2296             "riscv64gc-unknown-none-elf" => Some("riscv64-unknown-elf"),
2297             "riscv64imac-unknown-none-elf" => Some("riscv64-unknown-elf"),
2298             "riscv64gc-unknown-linux-gnu" => Some("riscv64-linux-gnu"),
2299             "s390x-unknown-linux-gnu" => Some("s390x-linux-gnu"),
2300             "sparc-unknown-linux-gnu" => Some("sparc-linux-gnu"),
2301             "sparc64-unknown-linux-gnu" => Some("sparc64-linux-gnu"),
2302             "sparc64-unknown-netbsd" => Some("sparc64--netbsd"),
2303             "sparcv9-sun-solaris" => Some("sparcv9-sun-solaris"),
2304             "armv7a-none-eabi" => Some("arm-none-eabi"),
2305             "armv7a-none-eabihf" => Some("arm-none-eabi"),
2306             "armebv7r-none-eabi" => Some("arm-none-eabi"),
2307             "armebv7r-none-eabihf" => Some("arm-none-eabi"),
2308             "armv7r-none-eabi" => Some("arm-none-eabi"),
2309             "armv7r-none-eabihf" => Some("arm-none-eabi"),
2310             "thumbv6m-none-eabi" => Some("arm-none-eabi"),
2311             "thumbv7em-none-eabi" => Some("arm-none-eabi"),
2312             "thumbv7em-none-eabihf" => Some("arm-none-eabi"),
2313             "thumbv7m-none-eabi" => Some("arm-none-eabi"),
2314             "thumbv8m.base-none-eabi" => Some("arm-none-eabi"),
2315             "thumbv8m.main-none-eabi" => Some("arm-none-eabi"),
2316             "thumbv8m.main-none-eabihf" => Some("arm-none-eabi"),
2317             "x86_64-pc-windows-gnu" => Some("x86_64-w64-mingw32"),
2318             "x86_64-uwp-windows-gnu" => Some("x86_64-w64-mingw32"),
2319             "x86_64-rumprun-netbsd" => Some("x86_64-rumprun-netbsd"),
2320             "x86_64-unknown-linux-musl" => Some("musl"),
2321             "x86_64-unknown-netbsd" => Some("x86_64--netbsd"),
2322             _ => None,
2323         }
2324         .map(|x| x.to_owned()))
2325     }
2326 
get_target(&self) -> Result<String, Error>2327     fn get_target(&self) -> Result<String, Error> {
2328         match self.target.clone() {
2329             Some(t) => Ok(t),
2330             None => Ok(self.getenv_unwrap("TARGET")?),
2331         }
2332     }
2333 
get_host(&self) -> Result<String, Error>2334     fn get_host(&self) -> Result<String, Error> {
2335         match self.host.clone() {
2336             Some(h) => Ok(h),
2337             None => Ok(self.getenv_unwrap("HOST")?),
2338         }
2339     }
2340 
get_opt_level(&self) -> Result<String, Error>2341     fn get_opt_level(&self) -> Result<String, Error> {
2342         match self.opt_level.as_ref().cloned() {
2343             Some(ol) => Ok(ol),
2344             None => Ok(self.getenv_unwrap("OPT_LEVEL")?),
2345         }
2346     }
2347 
get_debug(&self) -> bool2348     fn get_debug(&self) -> bool {
2349         self.debug.unwrap_or_else(|| match self.getenv("DEBUG") {
2350             Some(s) => s != "false",
2351             None => false,
2352         })
2353     }
2354 
get_force_frame_pointer(&self) -> bool2355     fn get_force_frame_pointer(&self) -> bool {
2356         self.force_frame_pointer.unwrap_or_else(|| self.get_debug())
2357     }
2358 
get_out_dir(&self) -> Result<PathBuf, Error>2359     fn get_out_dir(&self) -> Result<PathBuf, Error> {
2360         match self.out_dir.clone() {
2361             Some(p) => Ok(p),
2362             None => Ok(env::var_os("OUT_DIR").map(PathBuf::from).ok_or_else(|| {
2363                 Error::new(
2364                     ErrorKind::EnvVarNotFound,
2365                     "Environment variable OUT_DIR not defined.",
2366                 )
2367             })?),
2368         }
2369     }
2370 
getenv(&self, v: &str) -> Option<String>2371     fn getenv(&self, v: &str) -> Option<String> {
2372         let mut cache = self.env_cache.lock().unwrap();
2373         if let Some(val) = cache.get(v) {
2374             return val.clone();
2375         }
2376         let r = env::var(v).ok();
2377         self.print(&format!("{} = {:?}", v, r));
2378         cache.insert(v.to_string(), r.clone());
2379         r
2380     }
2381 
getenv_unwrap(&self, v: &str) -> Result<String, Error>2382     fn getenv_unwrap(&self, v: &str) -> Result<String, Error> {
2383         match self.getenv(v) {
2384             Some(s) => Ok(s),
2385             None => Err(Error::new(
2386                 ErrorKind::EnvVarNotFound,
2387                 &format!("Environment variable {} not defined.", v.to_string()),
2388             )),
2389         }
2390     }
2391 
print(&self, s: &str)2392     fn print(&self, s: &str) {
2393         if self.cargo_metadata {
2394             println!("{}", s);
2395         }
2396     }
2397 }
2398 
2399 impl Default for Build {
default() -> Build2400     fn default() -> Build {
2401         Build::new()
2402     }
2403 }
2404 
2405 impl Tool {
new(path: PathBuf) -> Self2406     fn new(path: PathBuf) -> Self {
2407         Tool::with_features(path, None, false)
2408     }
2409 
with_clang_driver(path: PathBuf, clang_driver: Option<&str>) -> Self2410     fn with_clang_driver(path: PathBuf, clang_driver: Option<&str>) -> Self {
2411         Self::with_features(path, clang_driver, false)
2412     }
2413 
2414     #[cfg(windows)]
2415     /// Explictly set the `ToolFamily`, skipping name-based detection.
with_family(path: PathBuf, family: ToolFamily) -> Self2416     fn with_family(path: PathBuf, family: ToolFamily) -> Self {
2417         Self {
2418             path: path,
2419             cc_wrapper_path: None,
2420             cc_wrapper_args: Vec::new(),
2421             args: Vec::new(),
2422             env: Vec::new(),
2423             family: family,
2424             cuda: false,
2425             removed_args: Vec::new(),
2426         }
2427     }
2428 
with_features(path: PathBuf, clang_driver: Option<&str>, cuda: bool) -> Self2429     fn with_features(path: PathBuf, clang_driver: Option<&str>, cuda: bool) -> Self {
2430         // Try to detect family of the tool from its name, falling back to Gnu.
2431         let family = if let Some(fname) = path.file_name().and_then(|p| p.to_str()) {
2432             if fname.contains("clang-cl") {
2433                 ToolFamily::Msvc { clang_cl: true }
2434             } else if fname.contains("cl")
2435                 && !fname.contains("cloudabi")
2436                 && !fname.contains("uclibc")
2437                 && !fname.contains("clang")
2438             {
2439                 ToolFamily::Msvc { clang_cl: false }
2440             } else if fname.contains("clang") {
2441                 match clang_driver {
2442                     Some("cl") => ToolFamily::Msvc { clang_cl: true },
2443                     _ => ToolFamily::Clang,
2444                 }
2445             } else {
2446                 ToolFamily::Gnu
2447             }
2448         } else {
2449             ToolFamily::Gnu
2450         };
2451 
2452         Tool {
2453             path: path,
2454             cc_wrapper_path: None,
2455             cc_wrapper_args: Vec::new(),
2456             args: Vec::new(),
2457             env: Vec::new(),
2458             family: family,
2459             cuda: cuda,
2460             removed_args: Vec::new(),
2461         }
2462     }
2463 
2464     /// Add an argument to be stripped from the final command arguments.
remove_arg(&mut self, flag: OsString)2465     fn remove_arg(&mut self, flag: OsString) {
2466         self.removed_args.push(flag);
2467     }
2468 
2469     /// Add a flag, and optionally prepend the NVCC wrapper flag "-Xcompiler".
2470     ///
2471     /// Currently this is only used for compiling CUDA sources, since NVCC only
2472     /// accepts a limited set of GNU-like flags, and the rest must be prefixed
2473     /// with a "-Xcompiler" flag to get passed to the underlying C++ compiler.
push_cc_arg(&mut self, flag: OsString)2474     fn push_cc_arg(&mut self, flag: OsString) {
2475         if self.cuda {
2476             self.args.push("-Xcompiler".into());
2477         }
2478         self.args.push(flag);
2479     }
2480 
is_duplicate_opt_arg(&self, flag: &OsString) -> bool2481     fn is_duplicate_opt_arg(&self, flag: &OsString) -> bool {
2482         let flag = flag.to_str().unwrap();
2483         let mut chars = flag.chars();
2484 
2485         // Only duplicate check compiler flags
2486         if self.is_like_msvc() {
2487             if chars.next() != Some('/') {
2488                 return false;
2489             }
2490         } else if self.is_like_gnu() || self.is_like_clang() {
2491             if chars.next() != Some('-') {
2492                 return false;
2493             }
2494         }
2495 
2496         // Check for existing optimization flags (-O, /O)
2497         if chars.next() == Some('O') {
2498             return self
2499                 .args()
2500                 .iter()
2501                 .any(|ref a| a.to_str().unwrap_or("").chars().nth(1) == Some('O'));
2502         }
2503 
2504         // TODO Check for existing -m..., -m...=..., /arch:... flags
2505         return false;
2506     }
2507 
2508     /// Don't push optimization arg if it conflicts with existing args
push_opt_unless_duplicate(&mut self, flag: OsString)2509     fn push_opt_unless_duplicate(&mut self, flag: OsString) {
2510         if self.is_duplicate_opt_arg(&flag) {
2511             println!("Info: Ignoring duplicate arg {:?}", &flag);
2512         } else {
2513             self.push_cc_arg(flag);
2514         }
2515     }
2516 
2517     /// Converts this compiler into a `Command` that's ready to be run.
2518     ///
2519     /// This is useful for when the compiler needs to be executed and the
2520     /// command returned will already have the initial arguments and environment
2521     /// variables configured.
to_command(&self) -> Command2522     pub fn to_command(&self) -> Command {
2523         let mut cmd = match self.cc_wrapper_path {
2524             Some(ref cc_wrapper_path) => {
2525                 let mut cmd = Command::new(&cc_wrapper_path);
2526                 cmd.arg(&self.path);
2527                 cmd
2528             }
2529             None => Command::new(&self.path),
2530         };
2531         cmd.args(&self.cc_wrapper_args);
2532 
2533         let value = self
2534             .args
2535             .iter()
2536             .filter(|a| !self.removed_args.contains(a))
2537             .collect::<Vec<_>>();
2538         cmd.args(&value);
2539 
2540         for &(ref k, ref v) in self.env.iter() {
2541             cmd.env(k, v);
2542         }
2543         cmd
2544     }
2545 
2546     /// Returns the path for this compiler.
2547     ///
2548     /// Note that this may not be a path to a file on the filesystem, e.g. "cc",
2549     /// but rather something which will be resolved when a process is spawned.
path(&self) -> &Path2550     pub fn path(&self) -> &Path {
2551         &self.path
2552     }
2553 
2554     /// Returns the default set of arguments to the compiler needed to produce
2555     /// executables for the target this compiler generates.
args(&self) -> &[OsString]2556     pub fn args(&self) -> &[OsString] {
2557         &self.args
2558     }
2559 
2560     /// Returns the set of environment variables needed for this compiler to
2561     /// operate.
2562     ///
2563     /// This is typically only used for MSVC compilers currently.
env(&self) -> &[(OsString, OsString)]2564     pub fn env(&self) -> &[(OsString, OsString)] {
2565         &self.env
2566     }
2567 
2568     /// Returns the compiler command in format of CC environment variable.
2569     /// Or empty string if CC env was not present
2570     ///
2571     /// This is typically used by configure script
cc_env(&self) -> OsString2572     pub fn cc_env(&self) -> OsString {
2573         match self.cc_wrapper_path {
2574             Some(ref cc_wrapper_path) => {
2575                 let mut cc_env = cc_wrapper_path.as_os_str().to_owned();
2576                 cc_env.push(" ");
2577                 cc_env.push(self.path.to_path_buf().into_os_string());
2578                 for arg in self.cc_wrapper_args.iter() {
2579                     cc_env.push(" ");
2580                     cc_env.push(arg);
2581                 }
2582                 cc_env
2583             }
2584             None => OsString::from(""),
2585         }
2586     }
2587 
2588     /// Returns the compiler flags in format of CFLAGS environment variable.
2589     /// Important here - this will not be CFLAGS from env, its internal gcc's flags to use as CFLAGS
2590     /// This is typically used by configure script
cflags_env(&self) -> OsString2591     pub fn cflags_env(&self) -> OsString {
2592         let mut flags = OsString::new();
2593         for (i, arg) in self.args.iter().enumerate() {
2594             if i > 0 {
2595                 flags.push(" ");
2596             }
2597             flags.push(arg);
2598         }
2599         flags
2600     }
2601 
2602     /// Whether the tool is GNU Compiler Collection-like.
is_like_gnu(&self) -> bool2603     pub fn is_like_gnu(&self) -> bool {
2604         self.family == ToolFamily::Gnu
2605     }
2606 
2607     /// Whether the tool is Clang-like.
is_like_clang(&self) -> bool2608     pub fn is_like_clang(&self) -> bool {
2609         self.family == ToolFamily::Clang
2610     }
2611 
2612     /// Whether the tool is MSVC-like.
is_like_msvc(&self) -> bool2613     pub fn is_like_msvc(&self) -> bool {
2614         match self.family {
2615             ToolFamily::Msvc { .. } => true,
2616             _ => false,
2617         }
2618     }
2619 }
2620 
run(cmd: &mut Command, program: &str) -> Result<(), Error>2621 fn run(cmd: &mut Command, program: &str) -> Result<(), Error> {
2622     let (mut child, print) = spawn(cmd, program)?;
2623     let status = match child.wait() {
2624         Ok(s) => s,
2625         Err(_) => {
2626             return Err(Error::new(
2627                 ErrorKind::ToolExecError,
2628                 &format!(
2629                     "Failed to wait on spawned child process, command {:?} with args {:?}.",
2630                     cmd, program
2631                 ),
2632             ));
2633         }
2634     };
2635     print.join().unwrap();
2636     println!("{}", status);
2637 
2638     if status.success() {
2639         Ok(())
2640     } else {
2641         Err(Error::new(
2642             ErrorKind::ToolExecError,
2643             &format!(
2644                 "Command {:?} with args {:?} did not execute successfully (status code {}).",
2645                 cmd, program, status
2646             ),
2647         ))
2648     }
2649 }
2650 
run_output(cmd: &mut Command, program: &str) -> Result<Vec<u8>, Error>2651 fn run_output(cmd: &mut Command, program: &str) -> Result<Vec<u8>, Error> {
2652     cmd.stdout(Stdio::piped());
2653     let (mut child, print) = spawn(cmd, program)?;
2654     let mut stdout = vec![];
2655     child
2656         .stdout
2657         .take()
2658         .unwrap()
2659         .read_to_end(&mut stdout)
2660         .unwrap();
2661     let status = match child.wait() {
2662         Ok(s) => s,
2663         Err(_) => {
2664             return Err(Error::new(
2665                 ErrorKind::ToolExecError,
2666                 &format!(
2667                     "Failed to wait on spawned child process, command {:?} with args {:?}.",
2668                     cmd, program
2669                 ),
2670             ));
2671         }
2672     };
2673     print.join().unwrap();
2674     println!("{}", status);
2675 
2676     if status.success() {
2677         Ok(stdout)
2678     } else {
2679         Err(Error::new(
2680             ErrorKind::ToolExecError,
2681             &format!(
2682                 "Command {:?} with args {:?} did not execute successfully (status code {}).",
2683                 cmd, program, status
2684             ),
2685         ))
2686     }
2687 }
2688 
spawn(cmd: &mut Command, program: &str) -> Result<(Child, JoinHandle<()>), Error>2689 fn spawn(cmd: &mut Command, program: &str) -> Result<(Child, JoinHandle<()>), Error> {
2690     println!("running: {:?}", cmd);
2691 
2692     // Capture the standard error coming from these programs, and write it out
2693     // with cargo:warning= prefixes. Note that this is a bit wonky to avoid
2694     // requiring the output to be UTF-8, we instead just ship bytes from one
2695     // location to another.
2696     match cmd.stderr(Stdio::piped()).spawn() {
2697         Ok(mut child) => {
2698             let stderr = BufReader::new(child.stderr.take().unwrap());
2699             let print = thread::spawn(move || {
2700                 for line in stderr.split(b'\n').filter_map(|l| l.ok()) {
2701                     print!("cargo:warning=");
2702                     std::io::stdout().write_all(&line).unwrap();
2703                     println!("");
2704                 }
2705             });
2706             Ok((child, print))
2707         }
2708         Err(ref e) if e.kind() == io::ErrorKind::NotFound => {
2709             let extra = if cfg!(windows) {
2710                 " (see https://github.com/alexcrichton/cc-rs#compile-time-requirements \
2711                  for help)"
2712             } else {
2713                 ""
2714             };
2715             Err(Error::new(
2716                 ErrorKind::ToolNotFound,
2717                 &format!("Failed to find tool. Is `{}` installed?{}", program, extra),
2718             ))
2719         }
2720         Err(_) => Err(Error::new(
2721             ErrorKind::ToolExecError,
2722             &format!("Command {:?} with args {:?} failed to start.", cmd, program),
2723         )),
2724     }
2725 }
2726 
fail(s: &str) -> !2727 fn fail(s: &str) -> ! {
2728     let _ = writeln!(io::stderr(), "\n\nerror occurred: {}\n\n", s);
2729     std::process::exit(1);
2730 }
2731 
command_add_output_file( cmd: &mut Command, dst: &Path, cuda: bool, msvc: bool, clang: bool, is_asm: bool, is_arm: bool, )2732 fn command_add_output_file(
2733     cmd: &mut Command,
2734     dst: &Path,
2735     cuda: bool,
2736     msvc: bool,
2737     clang: bool,
2738     is_asm: bool,
2739     is_arm: bool,
2740 ) {
2741     if msvc && !clang && !cuda && !(is_asm && is_arm) {
2742         let mut s = OsString::from("-Fo");
2743         s.push(&dst);
2744         cmd.arg(s);
2745     } else {
2746         cmd.arg("-o").arg(&dst);
2747     }
2748 }
2749 
2750 // Use by default minimum available API level
2751 // See note about naming here
2752 // https://android.googlesource.com/platform/ndk/+/refs/heads/ndk-release-r21/docs/BuildSystemMaintainers.md#Clang
2753 static NEW_STANDALONE_ANDROID_COMPILERS: [&str; 4] = [
2754     "aarch64-linux-android21-clang",
2755     "armv7a-linux-androideabi16-clang",
2756     "i686-linux-android16-clang",
2757     "x86_64-linux-android21-clang",
2758 ];
2759 
2760 // New "standalone" C/C++ cross-compiler executables from recent Android NDK
2761 // are just shell scripts that call main clang binary (from Android NDK) with
2762 // proper `--target` argument.
2763 //
2764 // For example, armv7a-linux-androideabi16-clang passes
2765 // `--target=armv7a-linux-androideabi16` to clang.
2766 // So to construct proper command line check if
2767 // `--target` argument would be passed or not to clang
android_clang_compiler_uses_target_arg_internally(clang_path: &Path) -> bool2768 fn android_clang_compiler_uses_target_arg_internally(clang_path: &Path) -> bool {
2769     NEW_STANDALONE_ANDROID_COMPILERS.iter().any(|x| {
2770         let x: &OsStr = x.as_ref();
2771         x == clang_path.as_os_str()
2772     })
2773 }
2774 
autodetect_android_compiler(target: &str, host: &str, gnu: &str, clang: &str) -> String2775 fn autodetect_android_compiler(target: &str, host: &str, gnu: &str, clang: &str) -> String {
2776     let new_clang_key = match target {
2777         "aarch64-linux-android" => Some("aarch64"),
2778         "armv7-linux-androideabi" => Some("armv7a"),
2779         "i686-linux-android" => Some("i686"),
2780         "x86_64-linux-android" => Some("x86_64"),
2781         _ => None,
2782     };
2783 
2784     let new_clang = new_clang_key
2785         .map(|key| {
2786             NEW_STANDALONE_ANDROID_COMPILERS
2787                 .iter()
2788                 .find(|x| x.starts_with(key))
2789         })
2790         .unwrap_or(None);
2791 
2792     if let Some(new_clang) = new_clang {
2793         if Command::new(new_clang).output().is_ok() {
2794             return (*new_clang).into();
2795         }
2796     }
2797 
2798     let target = target
2799         .replace("armv7neon", "arm")
2800         .replace("armv7", "arm")
2801         .replace("thumbv7neon", "arm")
2802         .replace("thumbv7", "arm");
2803     let gnu_compiler = format!("{}-{}", target, gnu);
2804     let clang_compiler = format!("{}-{}", target, clang);
2805 
2806     // On Windows, the Android clang compiler is provided as a `.cmd` file instead
2807     // of a `.exe` file. `std::process::Command` won't run `.cmd` files unless the
2808     // `.cmd` is explicitly appended to the command name, so we do that here.
2809     let clang_compiler_cmd = format!("{}-{}.cmd", target, clang);
2810 
2811     // Check if gnu compiler is present
2812     // if not, use clang
2813     if Command::new(&gnu_compiler).output().is_ok() {
2814         gnu_compiler
2815     } else if host.contains("windows") && Command::new(&clang_compiler_cmd).output().is_ok() {
2816         clang_compiler_cmd
2817     } else {
2818         clang_compiler
2819     }
2820 }
2821