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