-
Notifications
You must be signed in to change notification settings - Fork 559
/
Copy pathrust.rs
3871 lines (3614 loc) · 129 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::cache::{FileObjectSource, Storage};
use crate::compiler::args::*;
use crate::compiler::{
c::ArtifactDescriptor, CCompileCommand, Cacheable, ColorMode, Compilation, CompileCommand,
Compiler, CompilerArguments, CompilerHasher, CompilerKind, CompilerProxy, HashResult, Language,
SingleCompileCommand,
};
#[cfg(feature = "dist-client")]
use crate::compiler::{DistPackagers, OutputsRewriter};
#[cfg(feature = "dist-client")]
use crate::dist::pkg;
#[cfg(feature = "dist-client")]
use crate::lru_disk_cache::{LruCache, Meter};
use crate::mock_command::{CommandCreatorSync, RunCommand};
use crate::util::{fmt_duration_as_secs, hash_all, hash_all_archives, run_input_output, Digest};
use crate::util::{HashToDigest, OsStrExt};
use crate::{counted_array, dist};
use async_trait::async_trait;
use filetime::FileTime;
use fs_err as fs;
use log::Level::Trace;
use once_cell::sync::Lazy;
#[cfg(feature = "dist-client")]
use semver::Version;
#[cfg(feature = "dist-client")]
use std::borrow::Borrow;
use std::borrow::Cow;
#[cfg(feature = "dist-client")]
use std::collections::hash_map::RandomState;
use std::collections::{HashMap, HashSet};
use std::env::consts::DLL_EXTENSION;
#[cfg(feature = "dist-client")]
use std::env::consts::{DLL_PREFIX, EXE_EXTENSION};
use std::ffi::OsString;
use std::fmt;
use std::future::Future;
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::pin::Pin;
use std::process;
use std::sync::Arc;
#[cfg(feature = "dist-client")]
use std::sync::Mutex;
use std::time;
use crate::errors::*;
#[cfg(feature = "dist-client")]
const RLIB_PREFIX: &str = "lib";
#[cfg(feature = "dist-client")]
const RLIB_EXTENSION: &str = "rlib";
#[cfg(feature = "dist-client")]
const RMETA_EXTENSION: &str = "rmeta";
/// 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 verbose version for this rustc.
///
/// Hash calculation will take this version into consideration to prevent
/// cached object broken after version bump.
///
/// Looks like the following:
///
/// ```shell
/// :) rustc -vV
/// rustc 1.66.1 (90743e729 2023-01-10)
/// binary: rustc
/// commit-hash: 90743e7298aca107ddaa0c202a4d3604e29bfeb6
/// commit-date: 2023-01-10
/// host: x86_64-unknown-linux-gnu
/// release: 1.66.1
/// LLVM version: 15.0.2
/// ```
version: String,
/// The path to the rustc sysroot.
sysroot: PathBuf,
/// The 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, not the rustup proxy.
executable: PathBuf,
/// The host triple for this rustc.
host: String,
/// The version for this rustc.
version: String,
/// The path to the rustc sysroot.
sysroot: PathBuf,
/// The 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,
}
/// a lookup proxy for determining the actual compiler used per file or directory
#[derive(Debug, Clone)]
pub struct RustupProxy {
proxy_executable: PathBuf,
}
#[derive(Debug, Clone, PartialEq)]
pub struct ParsedArguments {
/// The full commandline, with all parsed arguments
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>,
/// If profile info is being emitted, the path of the profile.
///
/// This could be filled while `-Cprofile-use` been enabled.
///
/// We need to add the profile into our outputs to enable distributed compilation.
/// We don't need to track `profile-generate` since it's users work to make sure
/// the `profdata` been generated from profraw files.
///
/// For more information, see https://doc.rust-lang.org/rustc/profile-guided-optimization.html
profile: Option<PathBuf>,
/// If `-Z profile` has been enabled, we will use a GCC-compatible, gcov-based
/// coverage implementation.
///
/// This is not supported in latest stable rust anymore, but we still keep it here
/// for the old nightly rustc.
///
/// We need to add the profile into our outputs to enable distributed compilation.
///
/// For more information, see https://doc.rust-lang.org/rustc/instrument-coverage.html
gcno: 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,
/// Whether `--json` was passed to this invocation.
has_json: bool,
/// A `--target` parameter that specifies a path to a JSON file.
target_json: Option<PathBuf>,
}
/// A struct on which to hang a `Compilation` impl.
#[derive(Debug, Clone)]
pub struct RustCompilation {
/// The path to the rustc executable, not the rustup proxy.
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, ArtifactDescriptor>,
/// 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, Eq)]
pub struct CrateTypes {
rlib: bool,
staticlib: bool,
}
/// Emit types that we will cache.
static ALLOWED_EMIT: Lazy<HashSet<&'static str>> =
Lazy::new(|| ["link", "metadata", "dep-info"].iter().copied().collect());
/// Version number for cache key.
const CACHE_VERSION: &[u8] = b"6";
/// Get absolute paths for all source files and env-deps listed in rustc's dep-info output.
async fn get_source_files_and_env_deps<T>(
creator: &T,
crate_name: &str,
executable: &Path,
arguments: &[OsString],
cwd: &Path,
env_vars: &[(OsString, OsString)],
pool: &tokio::runtime::Handle,
) -> Result<(Vec<PathBuf>, Vec<(OsString, OsString)>)>
where
T: CommandCreatorSync,
{
let start = time::Instant::now();
// Get the full list of source files from rustc's dep-info.
let temp_dir = tempfile::Builder::new()
.prefix("sccache")
.tempdir()
.context("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(env_vars.to_vec())
.current_dir(cwd);
trace!("[{}]: get dep-info: {:?}", crate_name, cmd);
// Output of command is in file under dep_file, so we ignore stdout&stderr
let _dep_info = run_input_output(cmd, None).await?;
// Parse the dep-info file, then hash the contents of those files.
let cwd = cwd.to_owned();
let name2 = crate_name.to_owned();
let parsed = pool
.spawn_blocking(move || {
parse_dep_file(&dep_file, &cwd)
.with_context(|| format!("Failed to parse dep info for {}", name2))
})
.await?;
parsed.map(move |(files, env_deps)| {
trace!(
"[{}]: got {} source files and {} env-deps from dep-info in {}",
crate_name,
files.len(),
env_deps.len(),
fmt_duration_as_secs(&start.elapsed())
);
// Just to make sure we capture temp_dir.
drop(temp_dir);
(files, env_deps)
})
}
/// 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>, Vec<(OsString, OsString)>)>
where
T: AsRef<Path>,
U: AsRef<Path>,
{
let mut f = fs::File::open(file.as_ref())?;
let mut deps = String::new();
f.read_to_string(&mut deps)?;
Ok((parse_dep_info(&deps, cwd), parse_env_dep_info(&deps)))
}
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
}
fn parse_env_dep_info(dep_info: &str) -> Vec<(OsString, OsString)> {
let mut env_deps = Vec::new();
for line in dep_info.lines() {
if let Some(env_dep) = line.strip_prefix("# env-dep:") {
let mut split = env_dep.splitn(2, '=');
match (split.next(), split.next()) {
(Some(var), Some(val)) => env_deps.push((var.into(), val.into())),
_ => env_deps.push((env_dep.into(), "".into())),
}
}
}
env_deps
}
/// Run `rustc --print file-names` to get the outputs of compilation.
async fn get_compiler_outputs<T>(
creator: &T,
executable: &Path,
arguments: Vec<OsString>,
cwd: &Path,
env_vars: &[(OsString, OsString)],
) -> Result<Vec<String>>
where
T: Clone + CommandCreatorSync,
{
let mut cmd = creator.clone().new_command_sync(executable);
cmd.args(&arguments)
.args(&["--print", "file-names"])
.env_clear()
.envs(env_vars.to_vec())
.current_dir(cwd);
if log_enabled!(Trace) {
trace!("get_compiler_outputs: {:?}", cmd);
}
let outputs = run_input_output(cmd, None).await?;
let outstr = String::from_utf8(outputs.stdout).context("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 async fn new<T>(
mut creator: T,
executable: PathBuf,
env_vars: &[(OsString, OsString)],
rustc_verbose_version: &str,
dist_archive: Option<PathBuf>,
pool: tokio::runtime::Handle,
) -> Result<Rust>
where
T: CommandCreatorSync,
{
// Taken from Cargo
let host = rustc_verbose_version
.lines()
.find(|l| l.starts_with("host: "))
.map(|l| &l[6..])
.context("rustc verbose version didn't have a line for `host:`")?
.to_string();
// it's fine to use the `executable` directly no matter if proxied or not
let mut cmd = creator.new_command_sync(&executable);
cmd.stdout(process::Stdio::piped())
.stderr(process::Stdio::null())
.arg("--print=sysroot")
.env_clear()
.envs(env_vars.to_vec());
let sysroot_and_libs = async move {
let output = run_input_output(cmd, None).await?;
//debug!("output.and_then: {}", output);
let outstr = String::from_utf8(output.stdout).context("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)
.with_context(|| 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() || t.is_symlink() && p.is_file())
&& p.extension().map(|e| e == DLL_EXTENSION).unwrap_or(false)
{
Some(p)
} else {
None
}
})
})
})
.collect::<Vec<_>>();
if let Some(path) = dist_archive {
trace!("Hashing {:?} along with rustc libs.", path);
libs.push(path);
};
libs.sort();
Result::Ok((sysroot, libs))
};
#[cfg(feature = "dist-client")]
{
use futures::TryFutureExt;
let rlib_dep_reader = {
let executable = executable.clone();
let env_vars = env_vars.to_owned();
pool.spawn_blocking(move || RlibDepReader::new_with_check(executable, &env_vars))
.map_err(anyhow::Error::from)
};
let ((sysroot, libs), rlib_dep_reader) =
futures::future::try_join(sysroot_and_libs, rlib_dep_reader).await?;
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).await.map(move |digests| Rust {
executable,
host,
version: rustc_verbose_version.to_string(),
sysroot,
compiler_shlibs_digests: digests,
rlib_dep_reader,
})
}
#[cfg(not(feature = "dist-client"))]
{
let (sysroot, libs) = sysroot_and_libs.await?;
hash_all(&libs, &pool).await.map(move |digests| Rust {
executable,
host,
version: rustc_verbose_version.to_string(),
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,
_env_vars: &[(OsString, OsString)],
) -> CompilerArguments<Box<dyn CompilerHasher<T> + 'static>> {
match parse_arguments(arguments, cwd) {
CompilerArguments::Ok(args) => CompilerArguments::Ok(Box::new(RustHasher {
executable: self.executable.clone(), // if rustup exists, this must already contain the true resolved compiler path
host: self.host.clone(),
version: self.version.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())
}
}
impl<T> CompilerProxy<T> for RustupProxy
where
T: CommandCreatorSync,
{
fn resolve_proxied_executable(
&self,
mut creator: T,
cwd: PathBuf,
env: &[(OsString, OsString)],
) -> Pin<Box<dyn Future<Output = Result<(PathBuf, FileTime)>> + Send>> {
let mut child = creator.new_command_sync(&self.proxy_executable);
child
.current_dir(&cwd)
.env_clear()
.envs(env.to_vec())
.args(&["which", "rustc"]);
Box::pin(async move {
let output = run_input_output(child, None)
.await
.context("Failed to execute rustup which rustc")?;
let stdout = String::from_utf8(output.stdout)
.context("Failed to parse output of rustup which rustc")?;
let proxied_compiler = PathBuf::from(stdout.trim());
trace!(
"proxy: rustup which rustc produced: {:?}",
&proxied_compiler
);
// TODO: Delegate FS access to a thread pool if possible
let attr = fs::metadata(proxied_compiler.as_path())
.context("Failed to obtain metadata of the resolved, true rustc")?;
if attr.is_file() {
Ok(FileTime::from_last_modification_time(&attr))
} else {
Err(anyhow!(
"proxy: rustup resolved compiler is not of type file"
))
}
.map(move |filetime| (proxied_compiler, filetime))
})
}
fn box_clone(&self) -> Box<dyn CompilerProxy<T>> {
Box::new((*self).clone())
}
}
impl RustupProxy {
pub fn new<P>(proxy_executable: P) -> Result<Self>
where
P: AsRef<Path>,
{
let proxy_executable = proxy_executable.as_ref().to_owned();
Ok(Self { proxy_executable })
}
pub async fn find_proxy_executable<T>(
compiler_executable: &Path,
proxy_name: &str,
mut creator: T,
env: &[(OsString, OsString)],
) -> Result<Result<Option<Self>>>
where
T: CommandCreatorSync,
{
enum ProxyPath {
Candidate(PathBuf),
ToBeDiscovered,
None,
}
// verification if rustc is a proxy or not
//
// the process is multistaged
//
// if it is determined that rustc is a proxy,
// then check if there is a rustup binary next to rustc
// if not then check if which() knows about a rustup and use that.
//
// The produced candidate is then tested if it is a rustup.
//
//
// The test for rustc being a proxy or not is done as follows
// and follow firefox rustc detection closely:
//
// https://searchfox.org/mozilla-central/rev/c79c0d65a183d9d38676855f455a5c6a7f7dadd3/build/moz.configure/rust.configure#23-80
//
// which boils down to
//
// `rustc +stable` returns retcode 0 if it is the rustup proxy
// `rustc +stable` returns retcode 1 (!=0) if it is installed via i.e. rpm packages
// verify rustc is proxy
let mut child = creator.new_command_sync(compiler_executable);
child.env_clear().envs(env.to_vec()).args(&["+stable"]);
let state = run_input_output(child, None).await.map(move |output| {
if output.status.success() {
trace!("proxy: Found a compiler proxy managed by rustup");
ProxyPath::ToBeDiscovered
} else {
trace!("proxy: Found a regular compiler");
ProxyPath::None
}
});
let state = match state {
Ok(ProxyPath::Candidate(_)) => unreachable!("Q.E.D."),
Ok(ProxyPath::ToBeDiscovered) => {
// simple check: is there a rustup in the same parent dir as rustc?
// that would be the preferred one
Ok(match compiler_executable.parent().map(Path::to_owned) {
Some(parent) => {
let proxy_candidate = parent.join(proxy_name);
if proxy_candidate.exists() {
trace!(
"proxy: Found a compiler proxy at {}",
proxy_candidate.display()
);
ProxyPath::Candidate(proxy_candidate)
} else {
ProxyPath::ToBeDiscovered
}
}
None => ProxyPath::ToBeDiscovered,
})
}
x => x,
};
let state = match state {
Ok(ProxyPath::ToBeDiscovered) => {
// still no rustup found, use which crate to find one
match which::which(proxy_name) {
Ok(proxy_candidate) => {
warn!(
"proxy: rustup found, but not where it was expected (next to rustc {})",
compiler_executable.display()
);
Ok(ProxyPath::Candidate(proxy_candidate))
}
Err(e) => {
trace!("proxy: rustup is not present: {}", e);
Ok(ProxyPath::ToBeDiscovered)
}
}
}
x => x,
};
match state {
Err(e) => Err(e),
Ok(ProxyPath::ToBeDiscovered) => Ok(Err(anyhow!(
"Failed to discover a rustup executable, but rustc behaves like a proxy"
))),
Ok(ProxyPath::None) => Ok(Ok(None)),
Ok(ProxyPath::Candidate(proxy_executable)) => {
// verify the candidate is a rustup
let mut child = creator.new_command_sync(&proxy_executable);
child.env_clear().envs(env.to_vec()).args(&["--version"]);
let rustup_candidate_check = run_input_output(child, None).await?;
let stdout = String::from_utf8(rustup_candidate_check.stdout)
.map_err(|_e| anyhow!("Response of `rustup --version` is not valid UTF-8"))?;
Ok(if stdout.trim().starts_with("rustup ") {
trace!("PROXY rustup --version produced: {}", &stdout);
Self::new(&proxy_executable).map(Some)
} else {
Err(anyhow!("Unexpected output or `rustup --version`"))
})
}
}
}
}
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_unstable();
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_unstable();
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 ArgUnstable {
opt: String,
value: Option<String>,
}
impl FromArg for ArgUnstable {
fn process(arg: OsString) -> ArgParseResult<Self> {
let (opt, value) = split_os_string_arg(arg, "=")?;
Ok(ArgUnstable { opt, value })
}
}
impl IntoArg for ArgUnstable {
fn into_arg_os_string(self) -> OsString {
let ArgUnstable { 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 ArgUnstable { 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,
}
}
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)?,
})
}
}