-
Notifications
You must be signed in to change notification settings - Fork 556
/
Copy pathc.rs
2045 lines (1879 loc) · 69.4 KB
/
c.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, PreprocessorCacheModeConfig, Storage};
use crate::compiler::preprocessor_cache::preprocessor_cache_entry_hash_key;
use crate::compiler::{
Cacheable, ColorMode, Compilation, CompileCommand, Compiler, CompilerArguments, CompilerHasher,
CompilerKind, HashResult, Language,
};
#[cfg(feature = "dist-client")]
use crate::compiler::{DistPackagers, NoopOutputsRewriter};
use crate::dist;
#[cfg(feature = "dist-client")]
use crate::dist::pkg;
use crate::mock_command::CommandCreatorSync;
use crate::util::{
decode_path, encode_path, hash_all, Digest, HashToDigest, MetadataCtimeExt, TimeMacroFinder,
Timestamp,
};
use async_trait::async_trait;
use fs_err as fs;
use once_cell::sync::Lazy;
use std::borrow::Cow;
use std::collections::{HashMap, HashSet};
use std::ffi::{OsStr, OsString};
use std::fmt;
use std::hash::Hash;
use std::io;
use std::ops::ControlFlow;
use std::path::{Path, PathBuf};
use std::process;
use std::sync::Arc;
use crate::errors::*;
use super::preprocessor_cache::PreprocessorCacheEntry;
use super::CacheControl;
/// A generic implementation of the `Compiler` trait for C/C++ compilers.
#[derive(Clone)]
pub struct CCompiler<I>
where
I: CCompilerImpl,
{
executable: PathBuf,
executable_digest: String,
compiler: I,
}
/// A generic implementation of the `CompilerHasher` trait for C/C++ compilers.
#[derive(Debug, Clone)]
pub struct CCompilerHasher<I>
where
I: CCompilerImpl,
{
parsed_args: ParsedArguments,
executable: PathBuf,
executable_digest: String,
compiler: I,
}
/// Artifact produced by a C/C++ compiler.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct ArtifactDescriptor {
/// Path to the artifact.
pub path: PathBuf,
/// Whether the artifact is an optional object file.
pub optional: bool,
}
/// The results of parsing a compiler commandline.
#[allow(dead_code)]
#[derive(Debug, PartialEq, Eq, Clone)]
pub struct ParsedArguments {
/// The input source file.
pub input: PathBuf,
/// Whether to prepend the input with `--`
pub double_dash_input: bool,
/// The type of language used in the input source file.
pub language: Language,
/// The flag required to compile for the given language
pub compilation_flag: OsString,
/// The file in which to generate dependencies.
pub depfile: Option<PathBuf>,
/// Output files and whether it's optional, keyed by a simple name, like "obj".
pub outputs: HashMap<&'static str, ArtifactDescriptor>,
/// Commandline arguments for dependency generation.
pub dependency_args: Vec<OsString>,
/// Commandline arguments for the preprocessor (not including common_args).
pub preprocessor_args: Vec<OsString>,
/// Commandline arguments for the preprocessor or the compiler.
pub common_args: Vec<OsString>,
/// Commandline arguments for the compiler that specify the architecture given
pub arch_args: Vec<OsString>,
/// Commandline arguments for the preprocessor or the compiler that don't affect the computed hash.
pub unhashed_args: Vec<OsString>,
/// Extra unhashed files that need to be sent along with dist compiles.
pub extra_dist_files: Vec<PathBuf>,
/// Extra files that need to have their contents hashed.
pub extra_hash_files: Vec<PathBuf>,
/// Whether or not the `-showIncludes` argument is passed on MSVC
pub msvc_show_includes: bool,
/// Whether the compilation is generating profiling or coverage data.
pub profile_generate: bool,
/// The color mode.
pub color_mode: ColorMode,
/// arguments are incompatible with rewrite_includes_only
pub suppress_rewrite_includes_only: bool,
/// Arguments are incompatible with preprocessor cache mode
pub too_hard_for_preprocessor_cache_mode: Option<OsString>,
}
impl ParsedArguments {
pub fn output_pretty(&self) -> Cow<'_, str> {
self.outputs
.get("obj")
.and_then(|o| o.path.file_name())
.map(|s| s.to_string_lossy())
.unwrap_or(Cow::Borrowed("Unknown filename"))
}
}
/// A generic implementation of the `Compilation` trait for C/C++ compilers.
struct CCompilation<I: CCompilerImpl> {
parsed_args: ParsedArguments,
#[cfg(feature = "dist-client")]
preprocessed_input: Vec<u8>,
executable: PathBuf,
compiler: I,
cwd: PathBuf,
env_vars: Vec<(OsString, OsString)>,
}
/// Supported C compilers.
#[derive(Debug, PartialEq, Eq, Clone)]
pub enum CCompilerKind {
/// GCC
Gcc,
/// clang
Clang,
/// Diab
Diab,
/// Microsoft Visual C++
Msvc,
/// NVIDIA CUDA compiler
Nvcc,
/// NVIDIA CUDA optimizer and PTX generator
Cicc,
/// NVIDIA CUDA PTX assembler
Ptxas,
/// NVIDIA hpc c, c++ compiler
Nvhpc,
/// Tasking VX
TaskingVX,
}
/// An interface to a specific C compiler.
#[async_trait]
pub trait CCompilerImpl: Clone + fmt::Debug + Send + Sync + 'static {
/// Return the kind of compiler.
fn kind(&self) -> CCompilerKind;
/// Return true iff this is g++ or clang++.
fn plusplus(&self) -> bool;
/// Return the compiler version reported by the compiler executable.
fn version(&self) -> Option<String>;
/// Determine whether `arguments` are supported by this compiler.
fn parse_arguments(
&self,
arguments: &[OsString],
cwd: &Path,
env_vars: &[(OsString, OsString)],
) -> CompilerArguments<ParsedArguments>;
/// Run the C preprocessor with the specified set of arguments.
#[allow(clippy::too_many_arguments)]
async fn preprocess<T>(
&self,
creator: &T,
executable: &Path,
parsed_args: &ParsedArguments,
cwd: &Path,
env_vars: &[(OsString, OsString)],
may_dist: bool,
rewrite_includes_only: bool,
preprocessor_cache_mode: bool,
) -> Result<process::Output>
where
T: CommandCreatorSync;
/// Generate a command that can be used to invoke the C compiler to perform
/// the compilation.
fn generate_compile_commands<T>(
&self,
path_transformer: &mut dist::PathTransformer,
executable: &Path,
parsed_args: &ParsedArguments,
cwd: &Path,
env_vars: &[(OsString, OsString)],
rewrite_includes_only: bool,
) -> Result<(
Box<dyn CompileCommand<T>>,
Option<dist::CompileCommand>,
Cacheable,
)>
where
T: CommandCreatorSync;
}
impl<I> CCompiler<I>
where
I: CCompilerImpl,
{
pub async fn new(
compiler: I,
executable: PathBuf,
pool: &tokio::runtime::Handle,
) -> Result<CCompiler<I>> {
let digest = Digest::file(executable.clone(), pool).await?;
Ok(CCompiler {
executable,
executable_digest: {
if let Some(version) = compiler.version() {
let mut m = Digest::new();
m.update(digest.as_bytes());
m.update(version.as_bytes());
m.finish()
} else {
digest
}
},
compiler,
})
}
fn extract_rocm_arg(args: &ParsedArguments, flag: &str) -> Option<PathBuf> {
args.common_args.iter().find_map(|arg| match arg.to_str() {
Some(sarg) if sarg.starts_with(flag) => {
Some(PathBuf::from(sarg[arg.len()..].to_string()))
}
_ => None,
})
}
fn extract_rocm_env(env_vars: &[(OsString, OsString)], name: &str) -> Option<PathBuf> {
env_vars.iter().find_map(|(k, v)| match v.to_str() {
Some(path) if k == name => Some(PathBuf::from(path.to_string())),
_ => None,
})
}
// See https://clang.llvm.org/docs/HIPSupport.html for details regarding the
// order in which the environment variables and command-line arguments control the
// directory to search for bitcode libraries.
fn search_hip_device_libs(
args: &ParsedArguments,
env_vars: &[(OsString, OsString)],
) -> Vec<PathBuf> {
let rocm_path_arg: Option<PathBuf> = Self::extract_rocm_arg(args, "--rocm-path=");
let hip_device_lib_path_arg: Option<PathBuf> =
Self::extract_rocm_arg(args, "--hip-device-lib-path=");
let rocm_path_env: Option<PathBuf> = Self::extract_rocm_env(env_vars, "ROCM_PATH");
let hip_device_lib_path_env: Option<PathBuf> =
Self::extract_rocm_env(env_vars, "HIP_DEVICE_LIB_PATH");
let hip_device_lib_path: PathBuf = hip_device_lib_path_arg
.or(hip_device_lib_path_env)
.or(rocm_path_arg.map(|path| path.join("amdgcn").join("bitcode")))
.or(rocm_path_env.map(|path| path.join("amdgcn").join("bitcode")))
// This is the default location in official AMD packages and containers.
.unwrap_or(PathBuf::from("/opt/rocm/amdgcn/bitcode"));
hip_device_lib_path
.read_dir()
.ok()
.map(|f| {
f.flatten()
.filter(|f| f.path().extension().map_or(false, |ext| ext == "bc"))
.map(|f| f.path())
.collect()
})
.unwrap_or_default()
}
}
impl<T: CommandCreatorSync, I: CCompilerImpl> Compiler<T> for CCompiler<I> {
fn kind(&self) -> CompilerKind {
CompilerKind::C(self.compiler.kind())
}
#[cfg(feature = "dist-client")]
fn get_toolchain_packager(&self) -> Box<dyn pkg::ToolchainPackager> {
Box::new(CToolchainPackager {
executable: self.executable.clone(),
kind: self.compiler.kind(),
})
}
fn parse_arguments(
&self,
arguments: &[OsString],
cwd: &Path,
env_vars: &[(OsString, OsString)],
) -> CompilerArguments<Box<dyn CompilerHasher<T> + 'static>> {
match self.compiler.parse_arguments(arguments, cwd, env_vars) {
CompilerArguments::Ok(mut args) => {
// Handle SCCACHE_EXTRAFILES
for (k, v) in env_vars.iter() {
if k.as_os_str() == OsStr::new("SCCACHE_EXTRAFILES") {
args.extra_hash_files.extend(std::env::split_paths(&v))
}
}
// Handle cache invalidation for the ROCm device bitcode libraries. Every HIP
// object links in some LLVM bitcode libraries (.bc files), so in some sense
// every HIP object compilation has an direct dependency on those bitcode
// libraries.
//
// The bitcode libraries are unlikely to change **except** when a ROCm version
// changes, so for correctness we should take these bitcode libraries into
// account by adding them to `extra_hash_files`.
//
// In reality, not every available bitcode library is needed, but that is
// too much to handle on our side so we just hash every bitcode library we find.
if args.language == Language::Hip {
args.extra_hash_files
.extend(Self::search_hip_device_libs(&args, env_vars))
}
CompilerArguments::Ok(Box::new(CCompilerHasher {
parsed_args: args,
executable: self.executable.clone(),
executable_digest: self.executable_digest.clone(),
compiler: self.compiler.clone(),
}))
}
CompilerArguments::CannotCache(why, extra_info) => {
CompilerArguments::CannotCache(why, extra_info)
}
CompilerArguments::NotCompilation => CompilerArguments::NotCompilation,
}
}
fn box_clone(&self) -> Box<dyn Compiler<T>> {
Box::new((*self).clone())
}
}
#[async_trait]
impl<T, I> CompilerHasher<T> for CCompilerHasher<I>
where
T: CommandCreatorSync,
I: CCompilerImpl,
{
async fn generate_hash_key(
self: Box<Self>,
creator: &T,
cwd: PathBuf,
env_vars: Vec<(OsString, OsString)>,
may_dist: bool,
pool: &tokio::runtime::Handle,
rewrite_includes_only: bool,
storage: Arc<dyn Storage>,
cache_control: CacheControl,
) -> Result<HashResult<T>> {
let start_of_compilation = std::time::SystemTime::now();
let CCompilerHasher {
parsed_args,
executable,
executable_digest,
compiler,
} = *self;
let extra_hashes = hash_all(&parsed_args.extra_hash_files, &pool.clone()).await?;
// Create an argument vector containing both preprocessor and arch args, to
// use in creating a hash key
let mut preprocessor_and_arch_args = parsed_args.preprocessor_args.clone();
preprocessor_and_arch_args.extend(parsed_args.arch_args.to_vec());
// common_args is used in preprocessing too
preprocessor_and_arch_args.extend(parsed_args.common_args.to_vec());
let absolute_input_path: Cow<'_, _> = if parsed_args.input.is_absolute() {
Cow::Borrowed(&parsed_args.input)
} else {
Cow::Owned(cwd.join(&parsed_args.input))
};
// Try to look for a cached preprocessing step for this compilation
// request.
let preprocessor_cache_mode_config = storage.preprocessor_cache_mode_config();
let too_hard_for_preprocessor_cache_mode =
parsed_args.too_hard_for_preprocessor_cache_mode.is_some();
if let Some(arg) = &parsed_args.too_hard_for_preprocessor_cache_mode {
debug!(
"parse_arguments: Cannot use preprocessor cache because of {:?}",
arg
);
}
let use_preprocessor_cache_mode = {
let can_use_preprocessor_cache_mode = !may_dist
&& preprocessor_cache_mode_config.use_preprocessor_cache_mode
&& !too_hard_for_preprocessor_cache_mode;
let mut use_preprocessor_cache_mode = can_use_preprocessor_cache_mode;
// Allow overrides from the env
for (key, val) in env_vars.iter() {
if key == "SCCACHE_DIRECT" {
if let Some(val) = val.to_str() {
use_preprocessor_cache_mode = match val.to_lowercase().as_str() {
"false" | "off" | "0" => false,
_ => can_use_preprocessor_cache_mode,
};
}
break;
}
}
if can_use_preprocessor_cache_mode && !use_preprocessor_cache_mode {
debug!(
"parse_arguments: Disabling preprocessor cache because SCCACHE_DIRECT=false"
);
}
use_preprocessor_cache_mode
};
// Disable preprocessor cache when doing distributed compilation
let mut preprocessor_key = if use_preprocessor_cache_mode {
preprocessor_cache_entry_hash_key(
&executable_digest,
parsed_args.language,
&preprocessor_and_arch_args,
&extra_hashes,
&env_vars,
&absolute_input_path,
compiler.plusplus(),
preprocessor_cache_mode_config,
)?
} else {
None
};
if let Some(preprocessor_key) = &preprocessor_key {
if cache_control == CacheControl::Default {
if let Some(mut seekable) = storage
.get_preprocessor_cache_entry(preprocessor_key)
.await?
{
let mut buf = vec![];
seekable.read_to_end(&mut buf)?;
let mut preprocessor_cache_entry = PreprocessorCacheEntry::read(&buf)?;
let mut updated = false;
let hit = preprocessor_cache_entry
.lookup_result_digest(preprocessor_cache_mode_config, &mut updated);
let mut update_failed = false;
if updated {
// Time macros have been found, we need to update
// the preprocessor cache entry. See [`PreprocessorCacheEntry::result_matches`].
debug!(
"Preprocessor cache updated because of time macros: {preprocessor_key}"
);
if let Err(e) = storage
.put_preprocessor_cache_entry(
preprocessor_key,
preprocessor_cache_entry,
)
.await
{
debug!("Failed to update preprocessor cache: {}", e);
update_failed = true;
}
}
if !update_failed {
if let Some(key) = hit {
debug!("Preprocessor cache hit: {preprocessor_key}");
// A compiler binary may be a symlink to another and
// so has the same digest, but that means
// the toolchain will not contain the correct path
// to invoke the compiler! Add the compiler
// executable path to try and prevent this
let weak_toolchain_key =
format!("{}-{}", executable.to_string_lossy(), executable_digest);
return Ok(HashResult {
key,
compilation: Box::new(CCompilation {
parsed_args: parsed_args.to_owned(),
#[cfg(feature = "dist-client")]
// TODO or is it never relevant since dist?
preprocessed_input: vec![],
executable: executable.to_owned(),
compiler: compiler.to_owned(),
cwd: cwd.to_owned(),
env_vars: env_vars.to_owned(),
}),
weak_toolchain_key,
});
} else {
debug!("Preprocessor cache miss: {preprocessor_key}");
}
}
}
}
}
let result = compiler
.preprocess(
creator,
&executable,
&parsed_args,
&cwd,
&env_vars,
may_dist,
rewrite_includes_only,
use_preprocessor_cache_mode,
)
.await;
let out_pretty = parsed_args.output_pretty().into_owned();
let result = result.map_err(|e| {
debug!("[{}]: preprocessor failed: {:?}", out_pretty, e);
e
});
let outputs = parsed_args.outputs.clone();
let args_cwd = cwd.clone();
let mut preprocessor_result = result.or_else(move |err| {
// Errors remove all traces of potential output.
debug!("removing files {:?}", &outputs);
let v: std::result::Result<(), std::io::Error> =
outputs.values().try_for_each(|output| {
let mut path = args_cwd.clone();
path.push(&output.path);
match fs::metadata(&path) {
// File exists, remove it.
Ok(_) => fs::remove_file(&path),
_ => Ok(()),
}
});
if v.is_err() {
warn!("Could not remove files after preprocessing failed!");
}
match err.downcast::<ProcessError>() {
Ok(ProcessError(output)) => {
debug!(
"[{}]: preprocessor returned error status {:?}",
out_pretty,
output.status.code()
);
// Drop the stdout since it's the preprocessor output,
// just hand back stderr and the exit status.
bail!(ProcessError(process::Output {
stdout: vec!(),
..output
}))
}
Err(err) => Err(err),
}
})?;
// Remember include files needed in this preprocessing step
let mut include_files = HashMap::new();
if preprocessor_key.is_some() {
// TODO how to propagate stats and which stats?
if !process_preprocessed_file(
&absolute_input_path,
&cwd,
&mut preprocessor_result.stdout,
&mut include_files,
preprocessor_cache_mode_config,
start_of_compilation,
StandardFsAbstraction,
)? {
debug!("Disabling preprocessor cache mode");
preprocessor_key = None;
}
}
trace!(
"[{}]: Preprocessor output is {} bytes",
parsed_args.output_pretty(),
preprocessor_result.stdout.len()
);
// Create an argument vector containing both common and arch args, to
// use in creating a hash key
let mut common_and_arch_args = parsed_args.common_args.clone();
common_and_arch_args.extend(parsed_args.arch_args.to_vec());
let key = {
hash_key(
&executable_digest,
parsed_args.language,
&common_and_arch_args,
&extra_hashes,
&env_vars,
&preprocessor_result.stdout,
compiler.plusplus(),
)
};
// Cache the preprocessing step
if let Some(preprocessor_key) = preprocessor_key {
if !include_files.is_empty() {
let mut preprocessor_cache_entry = PreprocessorCacheEntry::new();
let mut files: Vec<_> = include_files
.into_iter()
.map(|(path, digest)| (digest, path))
.collect();
files.sort_unstable_by(|a, b| a.1.cmp(&b.1));
preprocessor_cache_entry.add_result(start_of_compilation, &key, files);
if let Err(e) = storage
.put_preprocessor_cache_entry(&preprocessor_key, preprocessor_cache_entry)
.await
{
debug!("Failed to update preprocessor cache: {}", e);
}
}
}
// A compiler binary may be a symlink to another and so has the same digest, but that means
// the toolchain will not contain the correct path to invoke the compiler! Add the compiler
// executable path to try and prevent this
let weak_toolchain_key = format!("{}-{}", executable.to_string_lossy(), executable_digest);
Ok(HashResult {
key,
compilation: Box::new(CCompilation {
parsed_args,
#[cfg(feature = "dist-client")]
preprocessed_input: preprocessor_result.stdout,
executable,
compiler,
cwd,
env_vars,
}),
weak_toolchain_key,
})
}
fn color_mode(&self) -> ColorMode {
self.parsed_args.color_mode
}
fn output_pretty(&self) -> Cow<'_, str> {
self.parsed_args.output_pretty()
}
fn box_clone(&self) -> Box<dyn CompilerHasher<T>> {
Box::new((*self).clone())
}
fn language(&self) -> Language {
self.parsed_args.language
}
}
const PRAGMA_GCC_PCH_PREPROCESS: &[u8] = b"pragma GCC pch_preprocess";
const HASH_31_COMMAND_LINE_NEWLINE: &[u8] = b"# 31 \"<command-line>\"\n";
const HASH_32_COMMAND_LINE_2_NEWLINE: &[u8] = b"# 32 \"<command-line>\" 2\n";
const INCBIN_DIRECTIVE: &[u8] = b".incbin";
/// Remember the include files in the preprocessor output if it can be cached.
/// Returns `false` if preprocessor cache mode should be disabled.
fn process_preprocessed_file(
input_file: &Path,
cwd: &Path,
bytes: &mut [u8],
included_files: &mut HashMap<PathBuf, String>,
config: PreprocessorCacheModeConfig,
time_of_compilation: std::time::SystemTime,
fs_impl: impl PreprocessorFSAbstraction,
) -> Result<bool> {
let mut start = 0;
let mut hash_start = 0;
let total_len = bytes.len();
let mut digest = Digest::new();
let mut normalized_include_paths: HashMap<Vec<u8>, Option<Vec<u8>>> = HashMap::new();
// There must be at least 7 characters (# 1 "x") left to potentially find an
// include file path.
while start < total_len.saturating_sub(7) {
let mut slice = &bytes[start..];
// Check if we look at a line containing the file name of an included file.
// At least the following formats exist (where N is a positive integer):
//
// GCC:
//
// # N "file"
// # N "file" N
// #pragma GCC pch_preprocess "file"
//
// HP's compiler:
//
// #line N "file"
//
// AIX's compiler:
//
// #line N "file"
// #line N
//
// Note that there may be other lines starting with '#' left after
// preprocessing as well, for instance "# pragma".
if slice[0] == b'#'
// GCC:
&& ((slice[1] == b' ' && slice[2] >= b'0' && slice[2] <= b'9')
// GCC precompiled header:
|| slice[1..].starts_with(PRAGMA_GCC_PCH_PREPROCESS)
// HP/AIX:
|| (&slice[1..5] == b"line "))
&& (start == 0 || bytes[start - 1] == b'\n')
{
match process_preprocessor_line(
input_file,
cwd,
included_files,
config,
time_of_compilation,
bytes,
start,
hash_start,
&mut digest,
total_len,
&mut normalized_include_paths,
&fs_impl,
)? {
ControlFlow::Continue((s, h)) => {
start = s;
hash_start = h;
}
ControlFlow::Break((s, h, continue_preprocessor_cache_mode)) => {
if !continue_preprocessor_cache_mode {
return Ok(false);
}
start = s;
hash_start = h;
continue;
}
};
} else if slice
.strip_prefix(INCBIN_DIRECTIVE)
.filter(|slice| {
slice.starts_with(b"\"") || slice.starts_with(b" \"") || slice.starts_with(b" \\\"")
})
.is_some()
{
// An assembler .inc bin (without the space) statement, which could be
// part of inline assembly, refers to an external file. If the file
// changes, the hash should change as well, but finding out what file to
// hash is too hard for sccache, so just bail out.
debug!("Found potential unsupported .inc bin directive in source code");
return Ok(false);
} else if slice.starts_with(b"___________") && (start == 0 || bytes[start - 1] == b'\n') {
// Unfortunately the distcc-pump wrapper outputs standard output lines:
// __________Using distcc-pump from /usr/bin
// __________Using # distcc servers in pump mode
// __________Shutting down distcc-pump include server
digest.update(&bytes[hash_start..start]);
while start < total_len && slice[0] != b'\n' {
start += 1;
if start < total_len {
slice = &bytes[start..];
}
}
slice = &bytes[start..];
if slice[0] == b'\n' {
start += 1;
}
hash_start = start;
continue;
} else {
start += 1;
}
}
digest.update(&bytes[hash_start..]);
Ok(true)
}
/// What to do after handling a preprocessor number line.
/// The `Break` variant is `(start, hash_start, continue_preprocessor_cache_mode)`.
/// The `Continue` variant is `(start, hash_start)`.
type PreprocessedLineAction = ControlFlow<(usize, usize, bool), (usize, usize)>;
#[allow(clippy::too_many_arguments)]
fn process_preprocessor_line(
input_file: &Path,
cwd: &Path,
included_files: &mut HashMap<PathBuf, String>,
config: PreprocessorCacheModeConfig,
time_of_compilation: std::time::SystemTime,
bytes: &mut [u8],
mut start: usize,
mut hash_start: usize,
digest: &mut Digest,
total_len: usize,
normalized_include_paths: &mut HashMap<Vec<u8>, Option<Vec<u8>>>,
fs_impl: &impl PreprocessorFSAbstraction,
) -> Result<PreprocessedLineAction> {
let mut slice = &bytes[start..];
// Workarounds for preprocessor linemarker bugs in GCC version 6.
if slice.get(2) == Some(&b'3') {
if slice.starts_with(HASH_31_COMMAND_LINE_NEWLINE) {
// Bogus extra line with #31, after the regular #1:
// Ignore the whole line, and continue parsing.
digest.update(&bytes[hash_start..start]);
while start < hash_start && slice[0] != b'\n' {
start += 1;
}
start += 1;
hash_start = start;
return Ok(ControlFlow::Break((start, hash_start, true)));
} else if slice.starts_with(HASH_32_COMMAND_LINE_2_NEWLINE) {
// Bogus wrong line with #32, instead of regular #1:
// Replace the line number with the usual one.
digest.update(&bytes[hash_start..start]);
start += 1;
bytes[start..=start + 2].copy_from_slice(b"# 1");
hash_start = start;
slice = &bytes[start..];
}
}
while start < total_len && slice[0] != b'"' && slice[0] != b'\n' {
start += 1;
if start < total_len {
slice = &bytes[start..];
}
}
slice = &bytes[start..];
if start < total_len && slice[0] == b'\n' {
// a newline before the quotation mark -> no match
return Ok(ControlFlow::Break((start, hash_start, true)));
}
start += 1;
if start >= total_len {
bail!("Failed to parse included file path");
}
// `start` points to the beginning of an include file path
digest.update(&bytes[hash_start..start]);
hash_start = start;
slice = &bytes[start..];
while start < total_len && slice[0] != b'"' {
start += 1;
if start < total_len {
slice = &bytes[start..];
}
}
if start == hash_start {
// Skip empty file name.
return Ok(ControlFlow::Break((start, hash_start, true)));
}
// Look for preprocessor flags, after the "filename".
let mut system = false;
let mut pointer = start + 1;
while pointer < total_len && bytes[pointer] != b'\n' {
if bytes[pointer] == b'3' {
// System header.
system = true;
}
pointer += 1;
}
// `hash_start` and `start` span the include file path.
let include_path = &bytes[hash_start..start];
// We need to normalize the path now since it's part of the
// hash and since we need to deduplicate the include files.
// We cache the results since they are often quite a bit repeated.
let include_path: &[u8] = if let Some(opt) = normalized_include_paths.get(include_path) {
match opt {
Some(normalized) => normalized,
None => include_path,
}
} else {
let path_buf = decode_path(include_path)?;
let normalized = normalize_path(&path_buf);
if normalized == path_buf {
// `None` is a marker that the normalization is the same
normalized_include_paths.insert(include_path.to_owned(), None);
include_path
} else {
let mut encoded = Vec::with_capacity(include_path.len());
encode_path(&mut encoded, &normalized)?;
normalized_include_paths.insert(include_path.to_owned(), Some(encoded));
// No entry API on hashmaps, so we need to query again
normalized_include_paths
.get(include_path)
.unwrap()
.as_ref()
.unwrap()
}
};
if !remember_include_file(
include_path,
input_file,
cwd,
included_files,
digest,
system,
config,
time_of_compilation,
fs_impl,
)? {
return Ok(ControlFlow::Break((start, hash_start, false)));
};
// Everything of interest between hash_start and start has been hashed now.
hash_start = start;
Ok(ControlFlow::Continue((start, hash_start)))
}
/// Copied from cargo.
///
/// Normalize a path, removing things like `.` and `..`.
///
/// CAUTION: This does not resolve symlinks (unlike
/// [`std::fs::canonicalize`]).
pub fn normalize_path(path: &Path) -> PathBuf {
use std::path::Component;
let mut components = path.components().peekable();
let mut ret = if let Some(c @ Component::Prefix(..)) = components.peek().cloned() {
components.next();
PathBuf::from(c.as_os_str())
} else {
PathBuf::new()
};
for component in components {
match component {
Component::Prefix(..) => unreachable!(),
Component::RootDir => {
ret.push(component.as_os_str());
}
Component::CurDir => {}
Component::ParentDir => {
ret.pop();
}
Component::Normal(c) => {
ret.push(c);
}
}
}
ret
}
/// Limited abstraction of `std::fs::Metadata`, allowing us to create fake
/// values during testing.
#[derive(Debug, Eq, PartialEq, Clone)]
struct PreprocessorFileMetadata {
is_dir: bool,
is_file: bool,
modified: Option<Timestamp>,
ctime_or_creation: Option<Timestamp>,
}
impl From<std::fs::Metadata> for PreprocessorFileMetadata {
fn from(meta: std::fs::Metadata) -> Self {
Self {
is_dir: meta.is_dir(),
is_file: meta.is_file(),
modified: meta.modified().ok().map(Into::into),
ctime_or_creation: meta.ctime_or_creation().ok(),
}
}
}
/// An abstraction to filesystem access for use during the preprocessor
/// caching phase, to make testing easier.
///
/// This may help non-local preprocessor caching in the future, if it ends up
/// being viable.
trait PreprocessorFSAbstraction {
fn metadata(&self, path: impl AsRef<Path>) -> io::Result<PreprocessorFileMetadata> {
std::fs::metadata(path).map(Into::into)
}
fn open(&self, path: impl AsRef<Path>) -> io::Result<Box<dyn std::io::Read>> {
Ok(Box::new(std::fs::File::open(path)?))
}
}
/// Provides filesystem access with the expected standard library functions.
struct StandardFsAbstraction;
impl PreprocessorFSAbstraction for StandardFsAbstraction {}
// Returns false if the include file was "too new" (meaning modified during or
// after the start of the compilation) and therefore should disable
// the preprocessor cache mode, otherwise true.
#[allow(clippy::too_many_arguments)]