-
Notifications
You must be signed in to change notification settings - Fork 550
/
rust.rs
2222 lines (2040 loc) · 90.8 KB
/
rust.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
// Copyright 2016 Mozilla Foundation
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
use crate::compiler::{Cacheable, ColorMode, Compiler, CompilerArguments, CompileCommand, CompilerHasher, CompilerKind,
Compilation, HashResult};
#[cfg(feature = "dist-client")]
use crate::compiler::OutputsRewriter;
use crate::compiler::args::*;
use crate::dist;
#[cfg(feature = "dist-client")]
use crate::dist::pkg;
use futures::Future;
use futures_cpupool::CpuPool;
use log::Level::Trace;
#[cfg(feature = "dist-client")]
use lru_disk_cache::lru_cache;
use crate::mock_command::{CommandCreatorSync, RunCommand};
#[cfg(feature = "dist-client")]
#[cfg(feature = "dist-client")]
use std::borrow::Borrow;
use std::borrow::Cow;
use std::collections::{HashMap, HashSet};
#[cfg(feature = "dist-client")]
use std::collections::hash_map::RandomState;
#[cfg(feature = "dist-client")]
use std::env::consts::{DLL_PREFIX, EXE_EXTENSION};
use std::env::consts::DLL_EXTENSION;
use std::ffi::OsString;
use std::fmt;
use std::fs;
use std::hash::Hash;
#[cfg(feature = "dist-client")]
use std::io;
use std::io::Read;
use std::iter;
use std::path::{Path, PathBuf};
use std::process;
#[cfg(feature = "dist-client")]
use std::sync::{Arc, Mutex};
use std::time;
use tempdir::TempDir;
use crate::util::{fmt_duration_as_secs, run_input_output, Digest, hash_all};
use crate::util::{HashToDigest, OsStrExt, ref_env};
use crate::errors::*;
/// Can dylibs (like proc macros) be distributed on this platform?
#[cfg(all(feature = "dist-client", target_os = "linux", target_arch = "x86_64"))]
const CAN_DIST_DYLIBS: bool = true;
#[cfg(all(feature = "dist-client", not(all(target_os = "linux", target_arch = "x86_64"))))]
const CAN_DIST_DYLIBS: bool = false;
#[cfg(feature = "dist-client")]
const RLIB_PREFIX: &str = "lib";
#[cfg(feature = "dist-client")]
const RLIB_EXTENSION: &str = "rlib";
/// Directory in the sysroot containing binary to which rustc is linked.
#[cfg(feature = "dist-client")]
const BINS_DIR: &str = "bin";
/// Directory in the sysroot containing shared libraries to which rustc is linked.
#[cfg(not(windows))]
const LIBS_DIR: &str = "lib";
/// Directory in the sysroot containing shared libraries to which rustc is linked.
#[cfg(windows)]
const LIBS_DIR: &str = "bin";
/// A struct on which to hang a `Compiler` impl.
#[derive(Debug, Clone)]
pub struct Rust {
/// The path to the rustc executable.
executable: PathBuf,
/// The host triple for this rustc.
host: String,
/// The path to the rustc sysroot.
sysroot: PathBuf,
/// The SHA-1 digests of all the shared libraries in rustc's $sysroot/lib (or /bin on Windows).
compiler_shlibs_digests: Vec<String>,
/// A shared, caching reader for rlib dependencies
#[cfg(feature = "dist-client")]
rlib_dep_reader: Option<Arc<RlibDepReader>>,
}
/// A struct on which to hang a `CompilerHasher` impl.
#[derive(Debug, Clone)]
pub struct RustHasher {
/// The path to the rustc executable.
executable: PathBuf,
/// The host triple for this rustc.
host: String,
/// The path to the rustc sysroot.
sysroot: PathBuf,
/// The SHA-1 digests of all the shared libraries in rustc's $sysroot/lib (or /bin on Windows).
compiler_shlibs_digests: Vec<String>,
/// A shared, caching reader for rlib dependencies
#[cfg(feature = "dist-client")]
rlib_dep_reader: Option<Arc<RlibDepReader>>,
/// Parsed arguments from the rustc invocation
parsed_args: ParsedArguments,
}
#[derive(Debug, Clone, PartialEq)]
pub struct ParsedArguments {
/// The full commandline, with all parsed aguments
arguments: Vec<Argument<ArgData>>,
/// The location of compiler outputs.
output_dir: PathBuf,
/// Paths to extern crates used in the compile.
externs: Vec<PathBuf>,
/// The directories searched for rlibs
crate_link_paths: Vec<PathBuf>,
/// Static libraries linked to in the compile.
staticlibs: Vec<PathBuf>,
/// The crate name passed to --crate-name.
crate_name: String,
/// The crate types that will be generated
crate_types: CrateTypes,
/// If dependency info is being emitted, the name of the dep info file.
dep_info: Option<PathBuf>,
/// rustc says that emits .rlib for --emit=metadata
/// https://github.com/rust-lang/rust/issues/54852
emit: HashSet<String>,
/// The value of any `--color` option passed on the commandline.
color_mode: ColorMode,
}
/// A struct on which to hang a `Compilation` impl.
#[derive(Debug, Clone)]
pub struct RustCompilation {
/// The path to the rustc executable.
executable: PathBuf,
/// The host triple for this rustc.
host: String,
/// The sysroot for this rustc
sysroot: PathBuf,
/// A shared, caching reader for rlib dependencies
#[cfg(feature = "dist-client")]
rlib_dep_reader: Option<Arc<RlibDepReader>>,
/// All arguments passed to rustc
arguments: Vec<Argument<ArgData>>,
/// The compiler inputs.
inputs: Vec<PathBuf>,
/// The compiler outputs.
outputs: HashMap<String, PathBuf>,
/// The directories searched for rlibs
crate_link_paths: Vec<PathBuf>,
/// The crate name being compiled.
crate_name: String,
/// The crate types that will be generated
crate_types: CrateTypes,
/// If dependency info is being emitted, the name of the dep info file.
dep_info: Option<PathBuf>,
/// The current working directory
cwd: PathBuf,
/// The environment variables
env_vars: Vec<(OsString, OsString)>,
}
// The selection of crate types for this compilation
#[derive(Debug, Clone, PartialEq)]
pub struct CrateTypes {
rlib: bool,
staticlib: bool,
}
lazy_static! {
/// Emit types that we will cache.
static ref ALLOWED_EMIT: HashSet<&'static str> = [
"link",
"metadata",
"dep-info",
].iter().map(|s| *s).collect();
}
/// Version number for cache key.
const CACHE_VERSION: &[u8] = b"3";
/// Get absolute paths for all source files listed in rustc's dep-info output.
fn get_source_files<T>(creator: &T,
crate_name: &str,
executable: &Path,
arguments: &[OsString],
cwd: &Path,
env_vars: &[(OsString, OsString)],
pool: &CpuPool)
-> SFuture<Vec<PathBuf>>
where T: CommandCreatorSync,
{
let start = time::Instant::now();
// Get the full list of source files from rustc's dep-info.
let temp_dir = ftry!(TempDir::new("sccache").chain_err(|| "Failed to create temp dir"));
let dep_file = temp_dir.path().join("deps.d");
let mut cmd = creator.clone().new_command_sync(executable);
cmd.args(&arguments)
.args(&["--emit", "dep-info"])
.arg("-o")
.arg(&dep_file)
.env_clear()
.envs(ref_env(env_vars))
.current_dir(cwd);
trace!("[{}]: get dep-info: {:?}", crate_name, cmd);
let dep_info = run_input_output(cmd, None);
// Parse the dep-info file, then hash the contents of those files.
let pool = pool.clone();
let cwd = cwd.to_owned();
let crate_name = crate_name.to_owned();
Box::new(dep_info.and_then(move |_| -> SFuture<_> {
let name2 = crate_name.clone();
let parsed = pool.spawn_fn(move || {
parse_dep_file(&dep_file, &cwd).chain_err(|| {
format!("Failed to parse dep info for {}", name2)
})
});
Box::new(parsed.map(move |files| {
trace!("[{}]: got {} source files from dep-info in {}", crate_name,
files.len(), fmt_duration_as_secs(&start.elapsed()));
// Just to make sure we capture temp_dir.
drop(temp_dir);
files
}))
}))
}
/// Parse dependency info from `file` and return a Vec of files mentioned.
/// Treat paths as relative to `cwd`.
fn parse_dep_file<T, U>(file: T, cwd: U) -> Result<Vec<PathBuf>>
where T: AsRef<Path>,
U: AsRef<Path>,
{
let mut f = fs::File::open(file)?;
let mut deps = String::new();
f.read_to_string(&mut deps)?;
Ok(parse_dep_info(&deps, cwd))
}
fn parse_dep_info<T>(dep_info: &str, cwd: T) -> Vec<PathBuf>
where T: AsRef<Path>
{
let cwd = cwd.as_ref();
// Just parse the first line, which should have the dep-info file and all
// source files.
let line = match dep_info.lines().next() {
None => return vec![],
Some(l) => l,
};
let pos = match line.find(": ") {
None => return vec![],
Some(p) => p,
};
let mut deps = Vec::new();
let mut current_dep = String::new();
let mut iter = line[pos + 2..].chars().peekable();
loop {
match iter.next() {
Some('\\') => {
if iter.peek() == Some(&' ') {
current_dep.push(' ');
iter.next();
} else {
current_dep.push('\\');
}
},
Some(' ') => {
deps.push(current_dep);
current_dep = String::new();
},
Some(c) => current_dep.push(c),
None => {
if !current_dep.is_empty() {
deps.push(current_dep);
}
break
},
}
}
let mut deps = deps.iter().map(|s| cwd.join(s)).collect::<Vec<_>>();
deps.sort();
deps
}
/// Run `rustc --print file-names` to get the outputs of compilation.
fn get_compiler_outputs<T>(creator: &T,
executable: &Path,
arguments: &[OsString],
cwd: &Path,
env_vars: &[(OsString, OsString)]) -> SFuture<Vec<String>>
where T: CommandCreatorSync,
{
let mut cmd = creator.clone().new_command_sync(executable);
cmd.args(&arguments)
.args(&["--print", "file-names"])
.env_clear()
.envs(ref_env(env_vars))
.current_dir(cwd);
if log_enabled!(Trace) {
trace!("get_compiler_outputs: {:?}", cmd);
}
let outputs = run_input_output(cmd, None);
Box::new(outputs.and_then(move |output| -> Result<_> {
let outstr = String::from_utf8(output.stdout).chain_err(|| "Error parsing rustc output")?;
if log_enabled!(Trace) {
trace!("get_compiler_outputs: {:?}", outstr);
}
Ok(outstr.lines().map(|l| l.to_owned()).collect())
}))
}
impl Rust {
/// Create a new Rust compiler instance, calculating the hashes of
/// all the shared libraries in its sysroot.
pub fn new<T>(mut creator: T,
executable: PathBuf,
env_vars: &[(OsString, OsString)],
rustc_verbose_version: &str,
pool: CpuPool) -> SFuture<Rust>
where T: CommandCreatorSync,
{
// Taken from Cargo
let host = ftry!(rustc_verbose_version
.lines()
.find(|l| l.starts_with("host: "))
.map(|l| &l[6..])
.ok_or_else(|| Error::from("rustc verbose version didn't have a line for `host:`")))
.to_string();
let mut cmd = creator.new_command_sync(&executable);
cmd.stdout(process::Stdio::piped())
.stderr(process::Stdio::null())
.arg("--print=sysroot")
.env_clear()
.envs(ref_env(env_vars));
let output = run_input_output(cmd, None);
let sysroot_and_libs = output.and_then(move |output| -> Result<_> {
//debug!("output.and_then: {}", output);
let outstr = String::from_utf8(output.stdout).chain_err(|| "Error parsing sysroot")?;
let sysroot = PathBuf::from(outstr.trim_end());
let libs_path = sysroot.join(LIBS_DIR);
let mut libs = fs::read_dir(&libs_path).chain_err(|| format!("Failed to list rustc sysroot: `{:?}`", libs_path))?.filter_map(|e| {
e.ok().and_then(|e| {
e.file_type().ok().and_then(|t| {
let p = e.path();
if t.is_file() && p.extension().map(|e| e == DLL_EXTENSION).unwrap_or(false) {
Some(p)
} else {
None
}
})
})
}).collect::<Vec<_>>();
libs.sort();
Ok((sysroot, libs))
});
#[cfg(feature = "dist-client")]
let rlib_dep_reader = {
let executable = executable.clone();
let env_vars = env_vars.to_owned();
pool.spawn_fn(move || Ok(RlibDepReader::new_with_check(executable, &env_vars)))
};
#[cfg(feature = "dist-client")]
return Box::new(sysroot_and_libs.join(rlib_dep_reader).and_then(move |((sysroot, libs), rlib_dep_reader)| {
let rlib_dep_reader = match rlib_dep_reader {
Ok(r) => Some(Arc::new(r)),
Err(e) => {
warn!("Failed to initialise RlibDepDecoder, distributed compiles will be inefficient: {}", e);
None
},
};
hash_all(&libs, &pool).map(move |digests| {
Rust {
executable: executable,
host,
sysroot,
compiler_shlibs_digests: digests,
rlib_dep_reader,
}
})
}));
#[cfg(not(feature = "dist-client"))]
return Box::new(sysroot_and_libs.and_then(move |(sysroot, libs)| {
hash_all(&libs, &pool).map(move |digests| {
Rust {
executable: executable,
host,
sysroot,
compiler_shlibs_digests: digests,
}
})
}));
}
}
impl<T> Compiler<T> for Rust
where T: CommandCreatorSync,
{
fn kind(&self) -> CompilerKind { CompilerKind::Rust }
#[cfg(feature = "dist-client")]
fn get_toolchain_packager(&self) -> Box<dyn pkg::ToolchainPackager> {
Box::new(RustToolchainPackager { sysroot: self.sysroot.clone() })
}
/// Parse `arguments` as rustc command-line arguments, determine if
/// we can cache the result of compilation. This is only intended to
/// cover a subset of rustc invocations, primarily focused on those
/// that will occur when cargo invokes rustc.
///
/// Caveats:
/// * We don't support compilation from stdin.
/// * We require --emit.
/// * We only support `link` and `dep-info` in --emit (and don't support *just* 'dep-info')
/// * We require `--out-dir`.
/// * We don't support `-o file`.
fn parse_arguments(&self,
arguments: &[OsString],
cwd: &Path) -> CompilerArguments<Box<dyn CompilerHasher<T> + 'static>>
{
match parse_arguments(arguments, cwd) {
CompilerArguments::Ok(args) => {
CompilerArguments::Ok(Box::new(RustHasher {
executable: self.executable.clone(),
host: self.host.clone(),
sysroot: self.sysroot.clone(),
compiler_shlibs_digests: self.compiler_shlibs_digests.clone(),
#[cfg(feature = "dist-client")]
rlib_dep_reader: self.rlib_dep_reader.clone(),
parsed_args: args,
}))
}
CompilerArguments::NotCompilation => CompilerArguments::NotCompilation,
CompilerArguments::CannotCache(why, extra_info) => CompilerArguments::CannotCache(why, extra_info),
}
}
fn box_clone(&self) -> Box<dyn Compiler<T>> {
Box::new((*self).clone())
}
}
macro_rules! make_os_string {
($( $v:expr ),*) => {{
let mut s = OsString::new();
$(
s.push($v);
)*
s
}};
}
#[derive(Clone, Debug, PartialEq)]
struct ArgCrateTypes {
rlib: bool,
staticlib: bool,
others: HashSet<String>,
}
impl FromArg for ArgCrateTypes {
fn process(arg: OsString) -> ArgParseResult<Self> {
let arg = String::process(arg)?;
let mut crate_types = ArgCrateTypes {
rlib: false,
staticlib: false,
others: HashSet::new(),
};
for ty in arg.split(",") {
match ty {
// It is assumed that "lib" always refers to "rlib", which
// is true right now but may not be in the future
"lib" |
"rlib" => crate_types.rlib = true,
"staticlib" => crate_types.staticlib = true,
other => { crate_types.others.insert(other.to_owned()); },
}
}
Ok(crate_types)
}
}
impl IntoArg for ArgCrateTypes {
fn into_arg_os_string(self) -> OsString {
let ArgCrateTypes { rlib, staticlib, others } = self;
let mut types: Vec<_> = others.iter().map(String::as_str)
.chain(if rlib { Some("rlib") } else { None })
.chain(if staticlib { Some("staticlib") } else { None }).collect();
types.sort();
let types_string = types.join(",");
types_string.into()
}
fn into_arg_string(self, _transformer: PathTransformerFn<'_>) -> ArgToStringResult {
let ArgCrateTypes { rlib, staticlib, others } = self;
let mut types: Vec<_> = others.iter().map(String::as_str)
.chain(if rlib { Some("rlib") } else { None })
.chain(if staticlib { Some("staticlib") } else { None }).collect();
types.sort();
let types_string = types.join(",");
Ok(types_string)
}
}
#[derive(Clone, Debug, PartialEq)]
struct ArgLinkLibrary {
kind: String,
name: String,
}
impl FromArg for ArgLinkLibrary {
fn process(arg: OsString) -> ArgParseResult<Self> {
let (kind, name) = match split_os_string_arg(arg, "=")? {
(kind, Some(name)) => (kind, name),
// If no kind is specified, the default is dylib.
(name, None) => ("dylib".to_owned(), name),
};
Ok(ArgLinkLibrary { kind, name })
}
}
impl IntoArg for ArgLinkLibrary {
fn into_arg_os_string(self) -> OsString {
let ArgLinkLibrary { kind, name } = self;
make_os_string!(kind, "=", name)
}
fn into_arg_string(self, _transformer: PathTransformerFn<'_>) -> ArgToStringResult {
let ArgLinkLibrary { kind, name } = self;
Ok(format!("{}={}", kind, name))
}
}
#[derive(Clone, Debug, PartialEq)]
struct ArgLinkPath {
kind: String,
path: PathBuf,
}
impl FromArg for ArgLinkPath {
fn process(arg: OsString) -> ArgParseResult<Self> {
let (kind, path) = match split_os_string_arg(arg, "=")? {
(kind, Some(path)) => (kind, path),
// If no kind is specified, the path is used to search for all kinds
(path, None) => ("all".to_owned(), path),
};
Ok(ArgLinkPath { kind, path: path.into() })
}
}
impl IntoArg for ArgLinkPath {
fn into_arg_os_string(self) -> OsString {
let ArgLinkPath { kind, path } = self;
make_os_string!(kind, "=", path)
}
fn into_arg_string(self, transformer: PathTransformerFn<'_>) -> ArgToStringResult {
let ArgLinkPath { kind, path } = self;
Ok(format!("{}={}", kind, path.into_arg_string(transformer)?))
}
}
#[derive(Clone, Debug, PartialEq)]
struct ArgCodegen {
opt: String,
value: Option<String>,
}
impl FromArg for ArgCodegen {
fn process(arg: OsString) -> ArgParseResult<Self> {
let (opt, value) = split_os_string_arg(arg, "=")?;
Ok(ArgCodegen { opt, value })
}
}
impl IntoArg for ArgCodegen {
fn into_arg_os_string(self) -> OsString {
let ArgCodegen { opt, value } = self;
if let Some(value) = value {
make_os_string!(opt, "=", value)
} else {
make_os_string!(opt)
}
}
fn into_arg_string(self, transformer: PathTransformerFn<'_>) -> ArgToStringResult {
let ArgCodegen { opt, value } = self;
Ok(if let Some(value) = value {
format!("{}={}", opt, value.into_arg_string(transformer)?)
} else {
opt
})
}
}
#[derive(Clone, Debug, PartialEq)]
struct ArgExtern {
name: String,
path: PathBuf,
}
impl FromArg for ArgExtern {
fn process(arg: OsString) -> ArgParseResult<Self> {
if let (name, Some(path)) = split_os_string_arg(arg, "=")? {
Ok(ArgExtern { name, path: path.into() })
} else {
Err(ArgParseError::Other("no path for extern"))
}
}
}
impl IntoArg for ArgExtern {
fn into_arg_os_string(self) -> OsString {
let ArgExtern { name, path } = self;
make_os_string!(name, "=", path)
}
fn into_arg_string(self, transformer: PathTransformerFn<'_>) -> ArgToStringResult {
let ArgExtern { name, path } = self;
Ok(format!("{}={}", name, path.into_arg_string(transformer)?))
}
}
#[derive(Clone, Debug, PartialEq)]
enum ArgTarget {
Name(String),
Path(PathBuf),
Unsure(OsString),
}
impl FromArg for ArgTarget {
fn process(arg: OsString) -> ArgParseResult<Self> {
// Is it obviously a json file path?
if Path::new(&arg).extension().map(|ext| ext == "json").unwrap_or(false) {
return Ok(ArgTarget::Path(arg.into()))
}
// Time for clever detection - if we append .json (even if it's clearly
// a directory, i.e. resulting in /my/dir/.json), does the path exist?
let mut path = arg.clone();
path.push(".json");
if Path::new(&path).is_file() {
// Unfortunately, we're now not sure what will happen without having
// a list of all the built-in targets handy, as they don't get .json
// auto-added for target json discovery
return Ok(ArgTarget::Unsure(arg))
}
// The file doesn't exist so it can't be a path, safe to assume it's a name
Ok(ArgTarget::Name(arg.into_string().map_err(ArgParseError::InvalidUnicode)?))
}
}
impl IntoArg for ArgTarget {
fn into_arg_os_string(self) -> OsString {
match self {
ArgTarget::Name(s) => s.into(),
ArgTarget::Path(p) => p.into(),
ArgTarget::Unsure(s) => s.into(),
}
}
fn into_arg_string(self, transformer: PathTransformerFn<'_>) -> ArgToStringResult {
Ok(match self {
ArgTarget::Name(s) => s,
ArgTarget::Path(p) => p.into_arg_string(transformer)?,
ArgTarget::Unsure(s) => s.into_arg_string(transformer)?,
})
}
}
ArgData!{
TooHardFlag,
TooHard(OsString),
TooHardPath(PathBuf),
NotCompilationFlag,
NotCompilation(OsString),
LinkLibrary(ArgLinkLibrary),
LinkPath(ArgLinkPath),
Emit(String),
Extern(ArgExtern),
Color(String),
CrateName(String),
CrateType(ArgCrateTypes),
OutDir(PathBuf),
CodeGen(ArgCodegen),
PassThrough(OsString),
Target(ArgTarget),
}
use self::ArgData::*;
// These are taken from https://github.com/rust-lang/rust/blob/b671c32ddc8c36d50866428d83b7716233356721/src/librustc/session/config.rs#L1186
counted_array!(static ARGS: [ArgInfo<ArgData>; _] = [
flag!("-", TooHardFlag),
take_arg!("--allow", OsString, CanBeSeparated('='), PassThrough),
take_arg!("--cap-lints", OsString, CanBeSeparated('='), PassThrough),
take_arg!("--cfg", OsString, CanBeSeparated('='), PassThrough),
take_arg!("--codegen", ArgCodegen, CanBeSeparated('='), CodeGen),
take_arg!("--color", String, CanBeSeparated('='), Color),
take_arg!("--crate-name", String, CanBeSeparated('='), CrateName),
take_arg!("--crate-type", ArgCrateTypes, CanBeSeparated('='), CrateType),
take_arg!("--deny", OsString, CanBeSeparated('='), PassThrough),
take_arg!("--emit", String, CanBeSeparated('='), Emit),
take_arg!("--error-format", OsString, CanBeSeparated('='), PassThrough),
take_arg!("--explain", OsString, CanBeSeparated('='), NotCompilation),
take_arg!("--extern", ArgExtern, CanBeSeparated('='), Extern),
take_arg!("--forbid", OsString, CanBeSeparated('='), PassThrough),
flag!("--help", NotCompilationFlag),
take_arg!("--out-dir", PathBuf, CanBeSeparated('='), OutDir),
take_arg!("--pretty", OsString, CanBeSeparated('='), NotCompilation),
take_arg!("--print", OsString, CanBeSeparated('='), NotCompilation),
take_arg!("--remap-path-prefix", OsString, CanBeSeparated('='), TooHard),
take_arg!("--sysroot", PathBuf, CanBeSeparated('='), TooHardPath),
take_arg!("--target", ArgTarget, CanBeSeparated('='), Target),
take_arg!("--unpretty", OsString, CanBeSeparated('='), NotCompilation),
flag!("--version", NotCompilationFlag),
take_arg!("--warn", OsString, CanBeSeparated('='), PassThrough),
take_arg!("-A", OsString, CanBeSeparated, PassThrough),
take_arg!("-C", ArgCodegen, CanBeSeparated, CodeGen),
take_arg!("-D", OsString, CanBeSeparated, PassThrough),
take_arg!("-F", OsString, CanBeSeparated, PassThrough),
take_arg!("-L", ArgLinkPath, CanBeSeparated, LinkPath),
flag!("-V", NotCompilationFlag),
take_arg!("-W", OsString, CanBeSeparated, PassThrough),
take_arg!("-Z", OsString, CanBeSeparated, PassThrough),
take_arg!("-l", ArgLinkLibrary, CanBeSeparated, LinkLibrary),
take_arg!("-o", PathBuf, CanBeSeparated, TooHardPath),
]);
fn parse_arguments(arguments: &[OsString], cwd: &Path) -> CompilerArguments<ParsedArguments>
{
let mut args = vec![];
let mut emit: Option<HashSet<String>> = None;
let mut input = None;
let mut output_dir = None;
let mut crate_name = None;
let mut crate_types = CrateTypes { rlib: false, staticlib: false };
let mut extra_filename = None;
let mut externs = vec![];
let mut crate_link_paths = vec![];
let mut static_lib_names = vec![];
let mut static_link_paths: Vec<PathBuf> = vec![];
let mut color_mode = ColorMode::Auto;
for arg in ArgsIter::new(arguments.iter().map(|s| s.clone()), &ARGS[..]) {
let arg = try_or_cannot_cache!(arg, "argument parse");
match arg.get_data() {
Some(TooHardFlag) |
Some(TooHard(_)) |
Some(TooHardPath(_)) => {
cannot_cache!(arg.flag_str().expect(
"Can't be Argument::Raw/UnknownFlag",
))
}
Some(NotCompilationFlag) |
Some(NotCompilation(_)) => return CompilerArguments::NotCompilation,
Some(LinkLibrary(ArgLinkLibrary { kind, name })) => {
if kind == "static" {
static_lib_names.push(name.to_owned())
}
},
Some(LinkPath(ArgLinkPath { kind, path })) => {
// "crate" is not typically necessary as cargo will normally
// emit explicit --extern arguments
if kind == "crate" || kind == "dependency" || kind == "all" {
crate_link_paths.push(cwd.join(path))
}
if kind == "native" || kind == "all" {
static_link_paths.push(cwd.join(path))
}
},
Some(Emit(value)) => {
if emit.is_some() {
// We don't support passing --emit more than once.
cannot_cache!("more than one --emit");
}
emit = Some(value.split(",").map(str::to_owned).collect())
}
Some(CrateType(ArgCrateTypes { rlib, staticlib, others })) => {
// We can't cache non-rlib/staticlib crates, because rustc invokes the
// system linker to link them, and we don't know about all the linker inputs.
if !others.is_empty() {
let others: Vec<&str> = others.iter().map(String::as_str).collect();
let others_string = others.join(",");
cannot_cache!("crate-type", others_string)
}
crate_types.rlib |= rlib;
crate_types.staticlib |= staticlib;
}
Some(CrateName(value)) => crate_name = Some(value.clone()),
Some(OutDir(value)) => output_dir = Some(value.clone()),
Some(Extern(ArgExtern { name: _, path })) => externs.push(path.clone()),
Some(CodeGen(ArgCodegen { opt, value })) => {
match (opt.as_ref(), value) {
("extra-filename", Some(value)) => extra_filename = Some(value.to_owned()),
("extra-filename", None) => cannot_cache!("extra-filename"),
// Incremental compilation makes a mess of sccache's entire world
// view. It produces additional compiler outputs that we don't cache,
// and just letting rustc do its work in incremental mode is likely
// to be faster than trying to fetch a result from cache anyway, so
// don't bother caching compiles where it's enabled currently.
// Longer-term we would like to figure out better integration between
// sccache and rustc in the incremental scenario:
// https://github.com/mozilla/sccache/issues/236
("incremental", _) => cannot_cache!("incremental"),
(_, _) => (),
}
}
Some(Color(value)) => {
// We'll just assume the last specified value wins.
color_mode = match value.as_ref() {
"always" => ColorMode::On,
"never" => ColorMode::Off,
_ => ColorMode::Auto,
};
}
Some(PassThrough(_)) => (),
Some(Target(target)) => {
match target {
ArgTarget::Path(_) |
ArgTarget::Unsure(_) => cannot_cache!("target"),
ArgTarget::Name(_) => (),
}
}
None => {
match arg {
Argument::Raw(ref val) => {
if input.is_some() {
// Can't cache compilations with multiple inputs.
cannot_cache!("multiple input files");
}
input = Some(val.clone());
}
Argument::UnknownFlag(_) => {}
_ => unreachable!(),
}
}
}
// We'll drop --color arguments, we're going to pass --color=always and the client will
// strip colors if necessary.
match arg.get_data() {
Some(Color(_)) => {}
_ => args.push(arg.normalize(NormalizedDisposition::Separated)),
}
}
// Unwrap required values.
macro_rules! req {
($x:ident) => {
let $x = if let Some($x) = $x {
$x
} else {
debug!("Can't cache compilation, missing `{}`", stringify!($x));
cannot_cache!(concat!("missing ", stringify!($x)));
};
}
};
// We don't actually save the input value, but there needs to be one.
req!(input);
drop(input);
req!(output_dir);
req!(emit);
req!(crate_name);
// We won't cache invocations that are not producing
// binary output.
if !emit.is_empty() && !emit.contains("link") && !emit.contains("metadata") {
return CompilerArguments::NotCompilation;
}
// If it's not an rlib and not a staticlib then crate-type wasn't passed,
// so it will usually be inferred as a binary, though the `#![crate_type`
// annotation may dictate otherwise - either way, we don't know what to do.
if let CrateTypes { rlib: false, staticlib: false } = crate_types {
cannot_cache!("crate-type", "No crate-type passed".to_owned())
}
// We won't cache invocations that are outputting anything but
// linker output and dep-info.
if emit.iter().any(|e| !ALLOWED_EMIT.contains(e.as_str())) {
cannot_cache!("unsupported --emit");
}
// Figure out the dep-info filename, if emitting dep-info.
let dep_info = if emit.contains("dep-info") {
let mut dep_info = crate_name.clone();
if let Some(extra_filename) = extra_filename {
dep_info.push_str(&extra_filename[..]);
}
dep_info.push_str(".d");
Some(dep_info)
} else {
None
};
// Locate all static libs specified on the commandline.
let staticlibs = static_lib_names.into_iter().filter_map(|name| {
for path in static_link_paths.iter() {
for f in &[format_args!("lib{}.a", name), format_args!("{}.lib", name),
format_args!("{}.a", name)] {
let lib_path = path.join(fmt::format(*f));
if lib_path.exists() {
return Some(lib_path);
}
}
}
// rustc will just error if there's a missing static library, so don't worry about
// it too much.
None
}).collect();
// We'll figure out the source files and outputs later in
// `generate_hash_key` where we can run rustc.
// Cargo doesn't deterministically order --externs, and we need the hash inputs in a
// deterministic order.
externs.sort();
CompilerArguments::Ok(ParsedArguments {
arguments: args,
output_dir: output_dir.into(),
crate_types,
externs: externs,
crate_link_paths,
staticlibs: staticlibs,
crate_name: crate_name.to_string(),
dep_info: dep_info.map(|s| s.into()),
emit,
color_mode,
})
}
impl<T> CompilerHasher<T> for RustHasher
where T: CommandCreatorSync,
{
fn generate_hash_key(self: Box<Self>,
creator: &T,
cwd: PathBuf,
env_vars: Vec<(OsString, OsString)>,
_may_dist: bool,
pool: &CpuPool)
-> SFuture<HashResult>
{
let me = *self;
let RustHasher {
executable,
host,
sysroot,
compiler_shlibs_digests, #[cfg(feature = "dist-client")]
rlib_dep_reader,
parsed_args:
ParsedArguments {
arguments,
output_dir,
externs,
crate_link_paths,
staticlibs,
crate_name,
crate_types,
dep_info,
emit,
color_mode: _,
},
} = me;
trace!("[{}]: generate_hash_key", crate_name);
// TODO: this doesn't produce correct arguments if they should be concatenated - should use iter_os_strings
let os_string_arguments: Vec<(OsString, Option<OsString>)> = arguments.iter()
.map(|arg| (arg.to_os_string(), arg.get_data().cloned().map(IntoArg::into_arg_os_string))).collect();
// `filtered_arguments` omits --emit and --out-dir arguments.
// It's used for invoking rustc with `--emit=dep-info` to get the list of
// source files for this crate.
let filtered_arguments = os_string_arguments.iter()
.filter_map(|&(ref arg, ref val)| {
if arg == "--emit" || arg == "--out-dir" {
None
} else {
Some((arg, val))
}
})
.flat_map(|(arg, val)| Some(arg).into_iter().chain(val))
.map(|a| a.clone())
.collect::<Vec<_>>();
// Find all the source files and hash them
let source_hashes_pool = pool.clone();
let source_files = get_source_files(creator, &crate_name, &executable, &filtered_arguments, &cwd, &env_vars, pool);
let source_files_and_hashes = source_files
.and_then(move |source_files| {
hash_all(&source_files, &source_hashes_pool).map(|source_hashes| (source_files, source_hashes))
});
// Hash the contents of the externs listed on the commandline.
trace!("[{}]: hashing {} externs", crate_name, externs.len());
let abs_externs = externs.iter().map(|e| cwd.join(e)).collect::<Vec<_>>();
let extern_hashes = hash_all(&abs_externs, pool);
// Hash the contents of the staticlibs listed on the commandline.
trace!("[{}]: hashing {} staticlibs", crate_name, staticlibs.len());
let abs_staticlibs = staticlibs.iter().map(|s| cwd.join(s)).collect::<Vec<_>>();
let staticlib_hashes = hash_all(&abs_staticlibs, pool);
let creator = creator.clone();
let hashes = source_files_and_hashes.join3(extern_hashes, staticlib_hashes);
Box::new(hashes.and_then(move |((source_files, source_hashes), extern_hashes, staticlib_hashes)|
-> SFuture<_> {
// If you change any of the inputs to the hash, you should change `CACHE_VERSION`.
let mut m = Digest::new();
// Hash inputs:
// 1. A version
m.update(CACHE_VERSION);
// 2. compiler_shlibs_digests
for d in compiler_shlibs_digests {
m.update(d.as_bytes());
}