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