-
Notifications
You must be signed in to change notification settings - Fork 448
/
lib.rs
2016 lines (1837 loc) · 67.5 KB
/
lib.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//! A library for build scripts to compile custom C code
//!
//! This library is intended to be used as a `build-dependencies` entry in
//! `Cargo.toml`:
//!
//! ```toml
//! [build-dependencies]
//! cc = "1.0"
//! ```
//!
//! The purpose of this crate is to provide the utility functions necessary to
//! compile C code into a static archive which is then linked into a Rust crate.
//! Configuration is available through the `Build` struct.
//!
//! This crate will automatically detect situations such as cross compilation or
//! other environment variables set by Cargo and will build code appropriately.
//!
//! The crate is not limited to C code, it can accept any source code that can
//! be passed to a C or C++ compiler. As such, assembly files with extensions
//! `.s` (gcc/clang) and `.asm` (MSVC) can also be compiled.
//!
//! [`Build`]: struct.Build.html
//!
//! # Parallelism
//!
//! To parallelize computation, enable the `parallel` feature for the crate.
//!
//! ```toml
//! [build-dependencies]
//! cc = { version = "1.0", features = ["parallel"] }
//! ```
//! To specify the max number of concurrent compilation jobs, set the `NUM_JOBS`
//! environment variable to the desired amount.
//!
//! Cargo will also set this environment variable when executed with the `-jN` flag.
//!
//! If `NUM_JOBS` is not set, the `RAYON_NUM_THREADS` environment variable can
//! also specify the build paralellism.
//!
//! # Examples
//!
//! Use the `Build` struct to compile `src/foo.c`:
//!
//! ```no_run
//! extern crate cc;
//!
//! fn main() {
//! cc::Build::new()
//! .file("src/foo.c")
//! .define("FOO", Some("bar"))
//! .include("src")
//! .compile("foo");
//! }
//! ```
#![doc(html_root_url = "https://docs.rs/cc/1.0")]
#![cfg_attr(test, deny(warnings))]
#![deny(missing_docs)]
#[cfg(feature = "parallel")]
extern crate rayon;
use std::env;
use std::ffi::{OsString, OsStr};
use std::fs;
use std::path::{PathBuf, Path};
use std::process::{Command, Stdio, Child};
use std::io::{self, BufReader, BufRead, Read, Write};
use std::thread::{self, JoinHandle};
use std::collections::HashMap;
use std::sync::{Arc, Mutex};
// These modules are all glue to support reading the MSVC version from
// the registry and from COM interfaces
#[cfg(windows)]
mod registry;
#[cfg(windows)]
#[macro_use]
mod winapi;
#[cfg(windows)]
mod com;
#[cfg(windows)]
mod setup_config;
pub mod windows_registry;
/// A builder for compilation of a native static library.
///
/// A `Build` is the main type of the `cc` crate and is used to control all the
/// various configuration options and such of a compile. You'll find more
/// documentation on each method itself.
#[derive(Clone, Debug)]
pub struct Build {
include_directories: Vec<PathBuf>,
definitions: Vec<(String, Option<String>)>,
objects: Vec<PathBuf>,
flags: Vec<String>,
flags_supported: Vec<String>,
known_flag_support_status: Arc<Mutex<HashMap<String, bool>>>,
files: Vec<PathBuf>,
cpp: bool,
cpp_link_stdlib: Option<Option<String>>,
cpp_set_stdlib: Option<String>,
cuda: bool,
target: Option<String>,
host: Option<String>,
out_dir: Option<PathBuf>,
opt_level: Option<String>,
debug: Option<bool>,
env: Vec<(OsString, OsString)>,
compiler: Option<PathBuf>,
archiver: Option<PathBuf>,
cargo_metadata: bool,
pic: Option<bool>,
static_crt: Option<bool>,
shared_flag: Option<bool>,
static_flag: Option<bool>,
warnings_into_errors: bool,
warnings: bool,
}
/// Represents the types of errors that may occur while using cc-rs.
#[derive(Clone, Debug)]
enum ErrorKind {
/// Error occurred while performing I/O.
IOError,
/// Invalid architecture supplied.
ArchitectureInvalid,
/// Environment variable not found, with the var in question as extra info.
EnvVarNotFound,
/// Error occurred while using external tools (ie: invocation of compiler).
ToolExecError,
/// Error occurred due to missing external tools.
ToolNotFound,
}
/// Represents an internal error that occurred, with an explanation.
#[derive(Clone, Debug)]
pub struct Error {
/// Describes the kind of error that occurred.
kind: ErrorKind,
/// More explanation of error that occurred.
message: String,
}
impl Error {
fn new(kind: ErrorKind, message: &str) -> Error {
Error {
kind: kind,
message: message.to_owned(),
}
}
}
impl From<io::Error> for Error {
fn from(e: io::Error) -> Error {
Error::new(ErrorKind::IOError, &format!("{}", e))
}
}
/// Configuration used to represent an invocation of a C compiler.
///
/// This can be used to figure out what compiler is in use, what the arguments
/// to it are, and what the environment variables look like for the compiler.
/// This can be used to further configure other build systems (e.g. forward
/// along CC and/or CFLAGS) or the `to_command` method can be used to run the
/// compiler itself.
#[derive(Clone, Debug)]
pub struct Tool {
path: PathBuf,
cc_wrapper_path: Option<PathBuf>,
cc_wrapper_args: Vec<OsString>,
args: Vec<OsString>,
env: Vec<(OsString, OsString)>,
family: ToolFamily,
cuda: bool,
}
/// Represents the family of tools this tool belongs to.
///
/// Each family of tools differs in how and what arguments they accept.
///
/// Detection of a family is done on best-effort basis and may not accurately reflect the tool.
#[derive(Copy, Clone, Debug, PartialEq)]
enum ToolFamily {
/// Tool is GNU Compiler Collection-like.
Gnu,
/// Tool is Clang-like. It differs from the GCC in a sense that it accepts superset of flags
/// and its cross-compilation approach is different.
Clang,
/// Tool is the MSVC cl.exe.
Msvc,
}
impl ToolFamily {
/// What the flag to request debug info for this family of tools look like
fn debug_flag(&self) -> &'static str {
match *self {
ToolFamily::Msvc => "/Z7",
ToolFamily::Gnu | ToolFamily::Clang => "-g",
}
}
/// What the flag to include directories into header search path looks like
fn include_flag(&self) -> &'static str {
match *self {
ToolFamily::Msvc => "/I",
ToolFamily::Gnu | ToolFamily::Clang => "-I",
}
}
/// What the flag to request macro-expanded source output looks like
fn expand_flag(&self) -> &'static str {
match *self {
ToolFamily::Msvc => "/E",
ToolFamily::Gnu | ToolFamily::Clang => "-E",
}
}
/// What the flags to enable all warnings
fn warnings_flags(&self) -> &'static [&'static str] {
static MSVC_FLAGS: &'static [&'static str] = &["/W4"];
static GNU_CLANG_FLAGS: &'static [&'static str] = &["-Wall", "-Wextra"];
match *self {
ToolFamily::Msvc => &MSVC_FLAGS,
ToolFamily::Gnu | ToolFamily::Clang => &GNU_CLANG_FLAGS,
}
}
/// What the flag to turn warning into errors
fn warnings_to_errors_flag(&self) -> &'static str {
match *self {
ToolFamily::Msvc => "/WX",
ToolFamily::Gnu | ToolFamily::Clang => "-Werror",
}
}
/// NVCC-specific. Device code debug info flag. This is separate from the
/// debug info flag passed to the C++ compiler.
fn nvcc_debug_flag(&self) -> &'static str {
match *self {
ToolFamily::Msvc => unimplemented!(),
ToolFamily::Gnu |
ToolFamily::Clang => "-G",
}
}
/// NVCC-specific. Redirect the following flag to the underlying C++
/// compiler.
fn nvcc_redirect_flag(&self) -> &'static str {
match *self {
ToolFamily::Msvc => unimplemented!(),
ToolFamily::Gnu |
ToolFamily::Clang => "-Xcompiler",
}
}
}
/// Represents an object.
///
/// This is a source file -> object file pair.
#[derive(Clone, Debug)]
struct Object {
src: PathBuf,
dst: PathBuf,
}
impl Object {
/// Create a new source file -> object file pair.
fn new(src: PathBuf, dst: PathBuf) -> Object {
Object {
src: src,
dst: dst,
}
}
}
impl Build {
/// Construct a new instance of a blank set of configuration.
///
/// This builder is finished with the [`compile`] function.
///
/// [`compile`]: struct.Build.html#method.compile
pub fn new() -> Build {
Build {
include_directories: Vec::new(),
definitions: Vec::new(),
objects: Vec::new(),
flags: Vec::new(),
flags_supported: Vec::new(),
known_flag_support_status: Arc::new(Mutex::new(HashMap::new())),
files: Vec::new(),
shared_flag: None,
static_flag: None,
cpp: false,
cpp_link_stdlib: None,
cpp_set_stdlib: None,
cuda: false,
target: None,
host: None,
out_dir: None,
opt_level: None,
debug: None,
env: Vec::new(),
compiler: None,
archiver: None,
cargo_metadata: true,
pic: None,
static_crt: None,
warnings: true,
warnings_into_errors: false,
}
}
/// Add a directory to the `-I` or include path for headers
///
/// # Example
///
/// ```no_run
/// use std::path::Path;
///
/// let library_path = Path::new("/path/to/library");
///
/// cc::Build::new()
/// .file("src/foo.c")
/// .include(library_path)
/// .include("src")
/// .compile("foo");
/// ```
pub fn include<P: AsRef<Path>>(&mut self, dir: P) -> &mut Build {
self.include_directories.push(dir.as_ref().to_path_buf());
self
}
/// Specify a `-D` variable with an optional value.
///
/// # Example
///
/// ```no_run
/// cc::Build::new()
/// .file("src/foo.c")
/// .define("FOO", "BAR")
/// .define("BAZ", None)
/// .compile("foo");
/// ```
pub fn define<'a, V: Into<Option<&'a str>>>(&mut self, var: &str, val: V) -> &mut Build {
self.definitions.push((
var.to_string(),
val.into().map(|s| s.to_string()),
));
self
}
/// Add an arbitrary object file to link in
pub fn object<P: AsRef<Path>>(&mut self, obj: P) -> &mut Build {
self.objects.push(obj.as_ref().to_path_buf());
self
}
/// Add an arbitrary flag to the invocation of the compiler
///
/// # Example
///
/// ```no_run
/// cc::Build::new()
/// .file("src/foo.c")
/// .flag("-ffunction-sections")
/// .compile("foo");
/// ```
pub fn flag(&mut self, flag: &str) -> &mut Build {
self.flags.push(flag.to_string());
self
}
fn ensure_check_file(&self) -> Result<PathBuf, Error> {
let out_dir = self.get_out_dir()?;
let src = if self.cuda {
assert!(self.cpp);
out_dir.join("flag_check.cu")
} else if self.cpp {
out_dir.join("flag_check.cpp")
} else {
out_dir.join("flag_check.c")
};
if !src.exists() {
let mut f = fs::File::create(&src)?;
write!(f, "int main(void) {{ return 0; }}")?;
}
Ok(src)
}
/// Run the compiler to test if it accepts the given flag.
///
/// For a convenience method for setting flags conditionally,
/// see `flag_if_supported()`.
///
/// It may return error if it's unable to run the compilier with a test file
/// (e.g. the compiler is missing or a write to the `out_dir` failed).
///
/// Note: Once computed, the result of this call is stored in the
/// `known_flag_support` field. If `is_flag_supported(flag)`
/// is called again, the result will be read from the hash table.
pub fn is_flag_supported(&self, flag: &str) -> Result<bool, Error> {
let known_status = self.known_flag_support_status.lock().ok()
.and_then(|flag_status| flag_status.get(flag).cloned());
if let Some(is_supported) = known_status {
return Ok(is_supported)
}
let out_dir = self.get_out_dir()?;
let src = self.ensure_check_file()?;
let obj = out_dir.join("flag_check");
let target = self.get_target()?;
let mut cfg = Build::new();
cfg.flag(flag)
.target(&target)
.opt_level(0)
.host(&target)
.debug(false)
.cpp(self.cpp)
.cuda(self.cuda);
let compiler = cfg.try_get_compiler()?;
let mut cmd = compiler.to_command();
command_add_output_file(&mut cmd, &obj, target.contains("msvc"), false);
// We need to explicitly tell msvc not to link and create an exe
// in the root directory of the crate
if target.contains("msvc") {
cmd.arg("/c");
}
cmd.arg(&src);
let output = cmd.output()?;
let is_supported = output.stderr.is_empty();
if let Ok(mut flag_status) = self.known_flag_support_status.lock() {
flag_status.insert(flag.to_owned(), is_supported);
}
Ok(is_supported)
}
/// Add an arbitrary flag to the invocation of the compiler if it supports it
///
/// # Example
///
/// ```no_run
/// cc::Build::new()
/// .file("src/foo.c")
/// .flag_if_supported("-Wlogical-op") // only supported by GCC
/// .flag_if_supported("-Wunreachable-code") // only supported by clang
/// .compile("foo");
/// ```
pub fn flag_if_supported(&mut self, flag: &str) -> &mut Build {
self.flags_supported.push(flag.to_string());
self
}
/// Set the `-shared` flag.
///
/// When enabled, the compiler will produce a shared object which can
/// then be linked with other objects to form an executable.
///
/// # Example
///
/// ```no_run
/// cc::Build::new()
/// .file("src/foo.c")
/// .shared_flag(true)
/// .compile("libfoo.so");
/// ```
pub fn shared_flag(&mut self, shared_flag: bool) -> &mut Build {
self.shared_flag = Some(shared_flag);
self
}
/// Set the `-static` flag.
///
/// When enabled on systems that support dynamic linking, this prevents
/// linking with the shared libraries.
///
/// # Example
///
/// ```no_run
/// cc::Build::new()
/// .file("src/foo.c")
/// .shared_flag(true)
/// .static_flag(true)
/// .compile("foo");
/// ```
pub fn static_flag(&mut self, static_flag: bool) -> &mut Build {
self.static_flag = Some(static_flag);
self
}
/// Add a file which will be compiled
pub fn file<P: AsRef<Path>>(&mut self, p: P) -> &mut Build {
self.files.push(p.as_ref().to_path_buf());
self
}
/// Add files which will be compiled
pub fn files<P>(&mut self, p: P) -> &mut Build
where
P: IntoIterator,
P::Item: AsRef<Path>,
{
for file in p.into_iter() {
self.file(file);
}
self
}
/// Set C++ support.
///
/// The other `cpp_*` options will only become active if this is set to
/// `true`.
pub fn cpp(&mut self, cpp: bool) -> &mut Build {
self.cpp = cpp;
self
}
/// Set CUDA C++ support.
///
/// Enabling CUDA will pass the detected C/C++ toolchain as an argument to
/// the CUDA compiler, NVCC. NVCC itself accepts some limited GNU-like args;
/// any other arguments for the C/C++ toolchain will be redirected using
/// "-Xcompiler" flags.
///
/// If enabled, this also implicitly enables C++ support.
pub fn cuda(&mut self, cuda: bool) -> &mut Build {
self.cuda = cuda;
if cuda {
self.cpp = true;
}
self
}
/// Set warnings into errors flag.
///
/// Disabled by default.
///
/// Warning: turning warnings into errors only make sense
/// if you are a developer of the crate using cc-rs.
/// Some warnings only appear on some architecture or
/// specific version of the compiler. Any user of this crate,
/// or any other crate depending on it, could fail during
/// compile time.
///
/// # Example
///
/// ```no_run
/// cc::Build::new()
/// .file("src/foo.c")
/// .warnings_into_errors(true)
/// .compile("libfoo.a");
/// ```
pub fn warnings_into_errors(&mut self, warnings_into_errors: bool) -> &mut Build {
self.warnings_into_errors = warnings_into_errors;
self
}
/// Set warnings flags.
///
/// Adds some flags:
/// - "/Wall" for MSVC.
/// - "-Wall", "-Wextra" for GNU and Clang.
///
/// Enabled by default.
///
/// # Example
///
/// ```no_run
/// cc::Build::new()
/// .file("src/foo.c")
/// .warnings(false)
/// .compile("libfoo.a");
/// ```
pub fn warnings(&mut self, warnings: bool) -> &mut Build {
self.warnings = warnings;
self
}
/// Set the standard library to link against when compiling with C++
/// support.
///
/// The default value of this property depends on the current target: On
/// OS X `Some("c++")` is used, when compiling for a Visual Studio based
/// target `None` is used and for other targets `Some("stdc++")` is used.
///
/// A value of `None` indicates that no automatic linking should happen,
/// otherwise cargo will link against the specified library.
///
/// The given library name must not contain the `lib` prefix.
///
/// Common values:
/// - `stdc++` for GNU
/// - `c++` for Clang
///
/// # Example
///
/// ```no_run
/// cc::Build::new()
/// .file("src/foo.c")
/// .shared_flag(true)
/// .cpp_link_stdlib("stdc++")
/// .compile("libfoo.so");
/// ```
pub fn cpp_link_stdlib<'a, V: Into<Option<&'a str>>>(
&mut self,
cpp_link_stdlib: V,
) -> &mut Build {
self.cpp_link_stdlib = Some(cpp_link_stdlib.into().map(|s| s.into()));
self
}
/// Force the C++ compiler to use the specified standard library.
///
/// Setting this option will automatically set `cpp_link_stdlib` to the same
/// value.
///
/// The default value of this option is always `None`.
///
/// This option has no effect when compiling for a Visual Studio based
/// target.
///
/// This option sets the `-stdlib` flag, which is only supported by some
/// compilers (clang, icc) but not by others (gcc). The library will not
/// detect which compiler is used, as such it is the responsibility of the
/// caller to ensure that this option is only used in conjuction with a
/// compiler which supports the `-stdlib` flag.
///
/// A value of `None` indicates that no specific C++ standard library should
/// be used, otherwise `-stdlib` is added to the compile invocation.
///
/// The given library name must not contain the `lib` prefix.
///
/// Common values:
/// - `stdc++` for GNU
/// - `c++` for Clang
///
/// # Example
///
/// ```no_run
/// cc::Build::new()
/// .file("src/foo.c")
/// .cpp_set_stdlib("c++")
/// .compile("libfoo.a");
/// ```
pub fn cpp_set_stdlib<'a, V: Into<Option<&'a str>>>(
&mut self,
cpp_set_stdlib: V,
) -> &mut Build {
let cpp_set_stdlib = cpp_set_stdlib.into();
self.cpp_set_stdlib = cpp_set_stdlib.map(|s| s.into());
self.cpp_link_stdlib(cpp_set_stdlib);
self
}
/// Configures the target this configuration will be compiling for.
///
/// This option is automatically scraped from the `TARGET` environment
/// variable by build scripts, so it's not required to call this function.
///
/// # Example
///
/// ```no_run
/// cc::Build::new()
/// .file("src/foo.c")
/// .target("aarch64-linux-android")
/// .compile("foo");
/// ```
pub fn target(&mut self, target: &str) -> &mut Build {
self.target = Some(target.to_string());
self
}
/// Configures the host assumed by this configuration.
///
/// This option is automatically scraped from the `HOST` environment
/// variable by build scripts, so it's not required to call this function.
///
/// # Example
///
/// ```no_run
/// cc::Build::new()
/// .file("src/foo.c")
/// .host("arm-linux-gnueabihf")
/// .compile("foo");
/// ```
pub fn host(&mut self, host: &str) -> &mut Build {
self.host = Some(host.to_string());
self
}
/// Configures the optimization level of the generated object files.
///
/// This option is automatically scraped from the `OPT_LEVEL` environment
/// variable by build scripts, so it's not required to call this function.
pub fn opt_level(&mut self, opt_level: u32) -> &mut Build {
self.opt_level = Some(opt_level.to_string());
self
}
/// Configures the optimization level of the generated object files.
///
/// This option is automatically scraped from the `OPT_LEVEL` environment
/// variable by build scripts, so it's not required to call this function.
pub fn opt_level_str(&mut self, opt_level: &str) -> &mut Build {
self.opt_level = Some(opt_level.to_string());
self
}
/// Configures whether the compiler will emit debug information when
/// generating object files.
///
/// This option is automatically scraped from the `PROFILE` environment
/// variable by build scripts (only enabled when the profile is "debug"), so
/// it's not required to call this function.
pub fn debug(&mut self, debug: bool) -> &mut Build {
self.debug = Some(debug);
self
}
/// Configures the output directory where all object files and static
/// libraries will be located.
///
/// This option is automatically scraped from the `OUT_DIR` environment
/// variable by build scripts, so it's not required to call this function.
pub fn out_dir<P: AsRef<Path>>(&mut self, out_dir: P) -> &mut Build {
self.out_dir = Some(out_dir.as_ref().to_owned());
self
}
/// Configures the compiler to be used to produce output.
///
/// This option is automatically determined from the target platform or a
/// number of environment variables, so it's not required to call this
/// function.
pub fn compiler<P: AsRef<Path>>(&mut self, compiler: P) -> &mut Build {
self.compiler = Some(compiler.as_ref().to_owned());
self
}
/// Configures the tool used to assemble archives.
///
/// This option is automatically determined from the target platform or a
/// number of environment variables, so it's not required to call this
/// function.
pub fn archiver<P: AsRef<Path>>(&mut self, archiver: P) -> &mut Build {
self.archiver = Some(archiver.as_ref().to_owned());
self
}
/// Define whether metadata should be emitted for cargo allowing it to
/// automatically link the binary. Defaults to `true`.
///
/// The emitted metadata is:
///
/// - `rustc-link-lib=static=`*compiled lib*
/// - `rustc-link-search=native=`*target folder*
/// - When target is MSVC, the ATL-MFC libs are added via `rustc-link-search=native=`
/// - When C++ is enabled, the C++ stdlib is added via `rustc-link-lib`
///
pub fn cargo_metadata(&mut self, cargo_metadata: bool) -> &mut Build {
self.cargo_metadata = cargo_metadata;
self
}
/// Configures whether the compiler will emit position independent code.
///
/// This option defaults to `false` for `windows-gnu` targets and
/// to `true` for all other targets.
pub fn pic(&mut self, pic: bool) -> &mut Build {
self.pic = Some(pic);
self
}
/// Configures whether the /MT flag or the /MD flag will be passed to msvc build tools.
///
/// This option defaults to `false`, and affect only msvc targets.
pub fn static_crt(&mut self, static_crt: bool) -> &mut Build {
self.static_crt = Some(static_crt);
self
}
#[doc(hidden)]
pub fn __set_env<A, B>(&mut self, a: A, b: B) -> &mut Build
where
A: AsRef<OsStr>,
B: AsRef<OsStr>,
{
self.env.push(
(a.as_ref().to_owned(), b.as_ref().to_owned()),
);
self
}
/// Run the compiler, generating the file `output`
///
/// This will return a result instead of panicing; see compile() for the complete description.
pub fn try_compile(&self, output: &str) -> Result<(), Error> {
let (lib_name, gnu_lib_name) = if output.starts_with("lib") && output.ends_with(".a") {
(&output[3..output.len() - 2], output.to_owned())
} else {
let mut gnu = String::with_capacity(5 + output.len());
gnu.push_str("lib");
gnu.push_str(&output);
gnu.push_str(".a");
(output, gnu)
};
let dst = self.get_out_dir()?;
let mut objects = Vec::new();
for file in self.files.iter() {
let obj = dst.join(file).with_extension("o");
let obj = if !obj.starts_with(&dst) {
dst.join(obj.file_name().ok_or_else(|| {
Error::new(ErrorKind::IOError, "Getting object file details failed.")
})?)
} else {
obj
};
match obj.parent() {
Some(s) => fs::create_dir_all(s)?,
None => {
return Err(Error::new(
ErrorKind::IOError,
"Getting object file details failed.",
))
}
};
objects.push(Object::new(file.to_path_buf(), obj));
}
self.compile_objects(&objects)?;
self.assemble(lib_name, &dst.join(gnu_lib_name), &objects)?;
if self.get_target()?.contains("msvc") {
let compiler = self.get_base_compiler()?;
let atlmfc_lib = compiler
.env()
.iter()
.find(|&&(ref var, _)| var.as_os_str() == OsStr::new("LIB"))
.and_then(|&(_, ref lib_paths)| {
env::split_paths(lib_paths).find(|path| {
let sub = Path::new("atlmfc/lib");
path.ends_with(sub) || path.parent().map_or(false, |p| p.ends_with(sub))
})
});
if let Some(atlmfc_lib) = atlmfc_lib {
self.print(&format!(
"cargo:rustc-link-search=native={}",
atlmfc_lib.display()
));
}
}
self.print(&format!("cargo:rustc-link-lib=static={}", lib_name));
self.print(&format!("cargo:rustc-link-search=native={}", dst.display()));
// Add specific C++ libraries, if enabled.
if self.cpp {
if let Some(stdlib) = self.get_cpp_link_stdlib()? {
self.print(&format!("cargo:rustc-link-lib={}", stdlib));
}
}
Ok(())
}
/// Run the compiler, generating the file `output`
///
/// The name `output` should be the name of the library. For backwards compatibility,
/// the `output` may start with `lib` and end with `.a`. The Rust compilier will create
/// the assembly with the lib prefix and .a extension. MSVC will create a file without prefix,
/// ending with `.lib`.
///
/// # Panics
///
/// Panics if `output` is not formatted correctly or if one of the underlying
/// compiler commands fails. It can also panic if it fails reading file names
/// or creating directories.
pub fn compile(&self, output: &str) {
if let Err(e) = self.try_compile(output) {
fail(&e.message);
}
}
#[cfg(feature = "parallel")]
fn compile_objects(&self, objs: &[Object]) -> Result<(), Error> {
use self::rayon::prelude::*;
let mut cfg = rayon::Configuration::new();
if let Ok(amt) = env::var("NUM_JOBS") {
if let Ok(amt) = amt.parse() {
cfg = cfg.num_threads(amt);
}
}
drop(rayon::initialize(cfg));
let results: Mutex<Vec<Result<(), Error>>> = Mutex::new(Vec::new());
objs.par_iter().with_max_len(1).for_each(
|obj| {
let res = self.compile_object(obj);
results.lock().unwrap().push(res)
},
);
// Check for any errors and return the first one found.
for result in results.into_inner().unwrap().iter() {
if result.is_err() {
return result.clone();
}
}
Ok(())
}
#[cfg(not(feature = "parallel"))]
fn compile_objects(&self, objs: &[Object]) -> Result<(), Error> {
for obj in objs {
self.compile_object(obj)?;
}
Ok(())
}
fn compile_object(&self, obj: &Object) -> Result<(), Error> {
let is_asm = obj.src.extension().and_then(|s| s.to_str()) == Some("asm");
let msvc = self.get_target()?.contains("msvc");
let (mut cmd, name) = if msvc && is_asm {
self.msvc_macro_assembler()?
} else {
let compiler = self.try_get_compiler()?;
let mut cmd = compiler.to_command();
for &(ref a, ref b) in self.env.iter() {
cmd.env(a, b);
}
(
cmd,
compiler
.path
.file_name()
.ok_or_else(|| {
Error::new(ErrorKind::IOError, "Failed to get compiler path.")
})?
.to_string_lossy()
.into_owned(),
)
};
command_add_output_file(&mut cmd, &obj.dst, msvc, is_asm);
cmd.arg(if msvc { "/c" } else { "-c" });
cmd.arg(&obj.src);
run(&mut cmd, &name)?;
Ok(())
}
/// This will return a result instead of panicing; see expand() for the complete description.
pub fn try_expand(&self) -> Result<Vec<u8>, Error> {
let compiler = self.try_get_compiler()?;
let mut cmd = compiler.to_command();
for &(ref a, ref b) in self.env.iter() {
cmd.env(a, b);
}
cmd.arg(compiler.family.expand_flag());
assert!(
self.files.len() <= 1,
"Expand may only be called for a single file"
);
for file in self.files.iter() {
cmd.arg(file);
}
let name = compiler
.path
.file_name()
.ok_or_else(|| {
Error::new(ErrorKind::IOError, "Failed to get compiler path.")
})?
.to_string_lossy()
.into_owned();
Ok(run_output(&mut cmd, &name)?)
}
/// Run the compiler, returning the macro-expanded version of the input files.
///
/// This is only relevant for C and C++ files.
///
/// # Panics