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