-
Notifications
You must be signed in to change notification settings - Fork 558
/
Copy pathmsvc.rs
2645 lines (2510 loc) · 92.9 KB
/
msvc.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::args::*;
use crate::compiler::c::{ArtifactDescriptor, CCompilerImpl, CCompilerKind, ParsedArguments};
use crate::compiler::{
clang, gcc, write_temp_file, CCompileCommand, Cacheable, ColorMode, CompileCommand,
CompilerArguments, Language, SingleCompileCommand,
};
use crate::mock_command::{CommandCreatorSync, RunCommand};
use crate::util::{encode_path, run_input_output, OsStrExt};
use crate::{counted_array, dist};
use async_trait::async_trait;
use fs::File;
use fs_err as fs;
use log::Level::Debug;
use std::collections::{HashMap, HashSet};
use std::ffi::{OsStr, OsString};
use std::io::{self, BufWriter, Read, Write};
use std::path::{Path, PathBuf};
use std::process::{self, Stdio};
use crate::errors::*;
/// A struct on which to implement `CCompilerImpl`.
///
/// Needs a little bit of state just to persist `includes_prefix`.
#[derive(Debug, PartialEq, Eq, Clone)]
pub struct Msvc {
/// The prefix used in the output of `-showIncludes`.
pub includes_prefix: String,
pub is_clang: bool,
pub version: Option<String>,
}
#[async_trait]
impl CCompilerImpl for Msvc {
fn kind(&self) -> CCompilerKind {
CCompilerKind::Msvc
}
fn plusplus(&self) -> bool {
false
}
fn version(&self) -> Option<String> {
self.version.clone()
}
fn parse_arguments(
&self,
arguments: &[OsString],
cwd: &Path,
_env_vars: &[(OsString, OsString)],
) -> CompilerArguments<ParsedArguments> {
parse_arguments(arguments, cwd, self.is_clang)
}
#[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,
{
preprocess(
creator,
executable,
parsed_args,
cwd,
env_vars,
may_dist,
&self.includes_prefix,
rewrite_includes_only,
self.is_clang,
)
.await
}
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,
{
generate_compile_commands(path_transformer, executable, parsed_args, cwd, env_vars).map(
|(command, dist_command, cacheable)| {
(CCompileCommand::new(command), dist_command, cacheable)
},
)
}
}
#[cfg(not(windows))]
fn from_local_codepage(multi_byte_str: &[u8]) -> io::Result<String> {
String::from_utf8(multi_byte_str.to_vec())
.map_err(|e| io::Error::new(io::ErrorKind::InvalidInput, e))
}
#[cfg(windows)]
pub fn from_local_codepage(multi_byte_str: &[u8]) -> io::Result<String> {
use windows_sys::Win32::Globalization::{MultiByteToWideChar, CP_OEMCP, MB_ERR_INVALID_CHARS};
let codepage = CP_OEMCP;
let flags = MB_ERR_INVALID_CHARS;
// Empty string
if multi_byte_str.is_empty() {
return Ok(String::new());
}
unsafe {
// Get length of UTF-16 string
let len = MultiByteToWideChar(
codepage,
flags,
multi_byte_str.as_ptr() as _,
multi_byte_str.len() as i32,
std::ptr::null_mut(),
0,
);
if len > 0 {
// Convert to UTF-16
let mut wstr: Vec<u16> = Vec::with_capacity(len as usize);
let len = MultiByteToWideChar(
codepage,
flags,
multi_byte_str.as_ptr() as _,
multi_byte_str.len() as i32,
wstr.as_mut_ptr() as _,
len,
);
if len > 0 {
// wstr's contents have now been initialized
wstr.set_len(len as usize);
return String::from_utf16(&wstr[0..(len as usize)])
.map_err(|e| io::Error::new(io::ErrorKind::InvalidInput, e));
}
}
Err(io::Error::last_os_error())
}
}
/// Detect the prefix included in the output of MSVC's -showIncludes output.
pub async fn detect_showincludes_prefix<T>(
creator: &T,
exe: &OsStr,
is_clang: bool,
env: Vec<(OsString, OsString)>,
pool: &tokio::runtime::Handle,
) -> Result<String>
where
T: CommandCreatorSync,
{
let (tempdir, input) =
write_temp_file(pool, "test.c".as_ref(), b"#include \"test.h\"\n".to_vec()).await?;
let exe = exe.to_os_string();
let mut creator = creator.clone();
let pool = pool.clone();
let header = tempdir.path().join("test.h");
let tempdir = pool
.spawn_blocking(move || {
let mut file = File::create(&header)?;
file.write_all(b"/* empty */\n")?;
Ok::<_, std::io::Error>(tempdir)
})
.await?
.context("Failed to write temporary file")?;
let mut cmd = creator.new_command_sync(&exe);
// clang.exe on Windows reports the same set of built-in preprocessor defines as clang-cl,
// but it doesn't accept MSVC commandline arguments unless you pass --driver-mode=cl.
// clang-cl.exe will accept this argument as well, so always add it in this case.
if is_clang {
cmd.arg("--driver-mode=cl");
}
cmd.args(&["-nologo", "-showIncludes", "-c", "-Fonul", "-I."])
.arg(&input)
.current_dir(tempdir.path())
// The MSDN docs say the -showIncludes output goes to stderr,
// but that's not true unless running with -E.
.stdout(Stdio::piped())
.stderr(Stdio::null());
for (k, v) in env {
cmd.env(k, v);
}
trace!("detect_showincludes_prefix: {:?}", cmd);
let output = run_input_output(cmd, None).await?;
if !output.status.success() {
bail!("Failed to detect showIncludes prefix")
}
let process::Output {
stdout: stdout_bytes,
..
} = output;
let stdout = from_local_codepage(&stdout_bytes)
.context("Failed to convert compiler stdout while detecting showIncludes prefix")?;
for line in stdout.lines() {
if !line.ends_with("test.h") {
continue;
}
for (i, c) in line.char_indices().rev() {
if c != ' ' {
continue;
}
let path = tempdir.path().join(&line[i + 1..]);
// See if the rest of this line is a full pathname.
if path.exists() {
// Everything from the beginning of the line
// to this index is the prefix.
return Ok(line[..=i].to_owned());
}
}
}
drop(tempdir);
debug!(
"failed to detect showIncludes prefix with output: {}",
stdout
);
bail!("Failed to detect showIncludes prefix")
}
ArgData! {
TooHardFlag,
TooHard(OsString),
TooHardPath(PathBuf),
PreprocessorArgument(OsString),
PreprocessorArgumentPath(PathBuf),
SuppressCompilation,
DoCompilation,
ShowIncludes,
Output(PathBuf),
DepFile(PathBuf),
ProgramDatabase(PathBuf),
DebugInfo,
PassThrough, // Miscellaneous flags that don't prevent caching.
PassThroughWithPath(PathBuf), // As above, recognised by prefix.
PassThroughWithSuffix(OsString), // As above, recognised by prefix.
Ignore, // The flag is not passed to the compiler.
IgnoreWithSuffix(OsString), // As above, recognized by prefix.
ExtraHashFile(PathBuf),
XClang(OsString), // -Xclang ...
Clang(OsString), // -clang:...
ExternalIncludePath(PathBuf),
}
use self::ArgData::*;
macro_rules! msvc_args {
(static ARGS: [$t:ty; _] = [$($macro:ident ! ($($v:tt)*),)*]) => {
counted_array!(static ARGS: [$t; _] = [$(msvc_args!(@one "-", $macro!($($v)*)),)*]);
counted_array!(static SLASH_ARGS: [$t; _] = [$(msvc_args!(@one "/", $macro!($($v)*)),)*]);
};
(@one $prefix:expr, msvc_take_arg!($s:expr, $($t:tt)*)) => {
take_arg!(concat!($prefix, $s), $($t)+)
};
(@one $prefix:expr, msvc_flag!($s:expr, $($t:tt)+)) => {
flag!(concat!($prefix, $s), $($t)+)
};
(@one $prefix:expr, $other:expr) => { $other };
}
// Reference:
// https://docs.microsoft.com/en-us/cpp/build/reference/compiler-options-listed-alphabetically?view=vs-2019
msvc_args!(static ARGS: [ArgInfo<ArgData>; _] = [
msvc_flag!("?", SuppressCompilation),
msvc_flag!("Brepro", PassThrough),
msvc_flag!("C", PassThrough), // Ignored unless a preprocess-only flag is specified.
msvc_take_arg!("D", OsString, CanBeSeparated, PreprocessorArgument),
msvc_flag!("E", SuppressCompilation),
msvc_take_arg!("EH", OsString, Concatenated, PassThroughWithSuffix), // /EH[acsr\-]+ - TODO: use a regex?
msvc_flag!("EP", SuppressCompilation),
msvc_take_arg!("F", OsString, Concatenated, PassThroughWithSuffix),
msvc_take_arg!("FA", OsString, Concatenated, TooHard),
msvc_flag!("FC", PassThrough), // Use absolute paths in error messages, does not affect caching, only the debug output of the build
msvc_take_arg!("FI", PathBuf, CanBeSeparated, PreprocessorArgumentPath),
msvc_take_arg!("FR", PathBuf, Concatenated, TooHardPath),
msvc_flag!("FS", Ignore),
msvc_take_arg!("FU", PathBuf, CanBeSeparated, TooHardPath),
msvc_take_arg!("Fa", PathBuf, Concatenated, TooHardPath),
msvc_take_arg!("Fd", PathBuf, Concatenated, ProgramDatabase),
msvc_take_arg!("Fe", PathBuf, Concatenated, TooHardPath),
msvc_take_arg!("Fi", PathBuf, Concatenated, TooHardPath),
msvc_take_arg!("Fm", PathBuf, Concatenated, PassThroughWithPath), // No effect if /c is specified.
msvc_take_arg!("Fo", PathBuf, Concatenated, Output),
msvc_take_arg!("Fp", PathBuf, Concatenated, TooHardPath), // allows users to specify the name for a PCH (when using /Yu or /Yc), PCHs are not supported in sccache.
msvc_take_arg!("Fr", PathBuf, Concatenated, TooHardPath),
msvc_flag!("Fx", TooHardFlag),
msvc_flag!("GA", PassThrough),
msvc_flag!("GF", PassThrough),
msvc_flag!("GH", PassThrough),
msvc_flag!("GL", PassThrough),
msvc_flag!("GL-", PassThrough),
msvc_flag!("GR", PassThrough),
msvc_flag!("GR-", PassThrough),
msvc_flag!("GS", PassThrough),
msvc_flag!("GS-", PassThrough),
msvc_flag!("GT", PassThrough),
msvc_flag!("GX", PassThrough),
msvc_flag!("GZ", PassThrough),
msvc_flag!("Gd", PassThrough),
msvc_flag!("Ge", PassThrough),
msvc_flag!("Gh", PassThrough),
msvc_flag!("Gm", TooHardFlag), // enable minimal rebuild, we do not support this
msvc_flag!("Gm-", PassThrough), // disable minimal rebuild; we prefer no minimal rebuild, so marking it as disabled is fine
msvc_flag!("Gr", PassThrough),
msvc_take_arg!("Gs", OsString, Concatenated, PassThroughWithSuffix),
msvc_flag!("Gv", PassThrough),
msvc_flag!("Gw", PassThrough),
msvc_flag!("Gw-", PassThrough),
msvc_flag!("Gy", PassThrough),
msvc_flag!("Gy-", PassThrough),
msvc_flag!("Gz", PassThrough),
msvc_take_arg!("H", OsString, Concatenated, PassThroughWithSuffix),
msvc_flag!("HELP", SuppressCompilation),
msvc_take_arg!("I", PathBuf, CanBeSeparated, PreprocessorArgumentPath),
msvc_flag!("J", PassThrough),
msvc_flag!("JMC", PassThrough),
msvc_flag!("JMC-", PassThrough),
msvc_flag!("LD", PassThrough),
msvc_flag!("LDd", PassThrough),
msvc_flag!("MD", PassThrough),
msvc_flag!("MDd", PassThrough),
msvc_take_arg!("MP", OsString, Concatenated, IgnoreWithSuffix),
msvc_flag!("MT", PassThrough),
msvc_flag!("MTd", PassThrough),
msvc_flag!("O1", PassThrough),
msvc_flag!("O2", PassThrough),
msvc_flag!("Ob0", PassThrough),
msvc_flag!("Ob1", PassThrough),
msvc_flag!("Ob2", PassThrough),
msvc_flag!("Ob3", PassThrough),
msvc_flag!("Od", PassThrough),
msvc_flag!("Og", PassThrough),
msvc_flag!("Oi", PassThrough),
msvc_flag!("Oi-", PassThrough),
msvc_flag!("Os", PassThrough),
msvc_flag!("Ot", PassThrough),
msvc_flag!("Ox", PassThrough),
msvc_flag!("Oy", PassThrough),
msvc_flag!("Oy-", PassThrough),
msvc_flag!("P", SuppressCompilation),
msvc_flag!("QIfist", PassThrough),
msvc_flag!("QIntel-jcc-erratum", PassThrough),
msvc_flag!("Qfast_transcendentals", PassThrough),
msvc_flag!("Qimprecise_fwaits", PassThrough),
msvc_flag!("Qpar", PassThrough),
msvc_flag!("Qpar-", PassThrough),
msvc_flag!("Qsafe_fp_loads", PassThrough),
msvc_flag!("Qspectre", PassThrough),
msvc_flag!("Qspectre-load", PassThrough),
msvc_flag!("Qspectre-load-cf", PassThrough),
msvc_flag!("Qvec-report:1", PassThrough),
msvc_flag!("Qvec-report:2", PassThrough),
msvc_take_arg!("RTC", OsString, Concatenated, PassThroughWithSuffix),
msvc_flag!("TC", PassThrough), // TODO: disable explicit language check, hope for the best for now? Also, handle /Tc & /Tp.
msvc_flag!("TP", PassThrough), // As above.
msvc_take_arg!("U", OsString, Concatenated, PreprocessorArgument),
msvc_take_arg!("V", OsString, Concatenated, PassThroughWithSuffix),
msvc_flag!("W0", PassThrough),
msvc_flag!("W1", PassThrough),
msvc_flag!("W2", PassThrough),
msvc_flag!("W3", PassThrough),
msvc_flag!("W4", PassThrough),
msvc_flag!("WL", PassThrough),
msvc_flag!("WX", PassThrough),
msvc_flag!("WX-", PassThrough),
msvc_flag!("Wall", PassThrough),
msvc_take_arg!("Wv:", OsString, Concatenated, PassThroughWithSuffix),
msvc_flag!("X", PassThrough),
msvc_take_arg!("Xclang", OsString, Separated, XClang),
msvc_take_arg!("Yc", PathBuf, Concatenated, TooHardPath), // Compile PCH - not yet supported.
msvc_flag!("Yd", PassThrough),
msvc_flag!("Z7", PassThrough), // Add debug info to .obj files.
msvc_take_arg!("ZH:", OsString, Concatenated, PassThroughWithSuffix),
msvc_flag!("ZI", DebugInfo), // Implies /FC, which puts absolute paths in error messages -> TooHardFlag?
msvc_flag!("ZW", PassThrough),
msvc_flag!("Za", PassThrough),
msvc_take_arg!("Zc:", OsString, Concatenated, PassThroughWithSuffix),
msvc_flag!("Ze", PassThrough),
msvc_flag!("Zi", DebugInfo),
msvc_take_arg!("Zm", OsString, Concatenated, PassThroughWithSuffix),
msvc_flag!("Zo", PassThrough),
msvc_flag!("Zo-", PassThrough),
msvc_flag!("Zp1", PassThrough),
msvc_flag!("Zp16", PassThrough),
msvc_flag!("Zp2", PassThrough),
msvc_flag!("Zp4", PassThrough),
msvc_flag!("Zp8", PassThrough),
msvc_flag!("Zs", SuppressCompilation),
msvc_flag!("analyze", PassThrough),
msvc_flag!("analyze-", PassThrough),
msvc_take_arg!("analyze:", OsString, Concatenated, PassThroughWithSuffix),
msvc_take_arg!("arch:", OsString, Concatenated, PassThroughWithSuffix),
msvc_flag!("await", PassThrough),
msvc_flag!("bigobj", PassThrough),
msvc_flag!("c", DoCompilation),
msvc_take_arg!("cgthreads", OsString, Concatenated, PassThroughWithSuffix),
msvc_take_arg!("clang:", OsString, Concatenated, Clang),
msvc_flag!("clr", PassThrough),
msvc_take_arg!("clr:", OsString, Concatenated, PassThroughWithSuffix),
msvc_take_arg!("constexpr:", OsString, Concatenated, PassThroughWithSuffix),
msvc_take_arg!("deps", PathBuf, Concatenated, DepFile),
msvc_take_arg!("diagnostics:", OsString, Concatenated, PassThroughWithSuffix),
msvc_take_arg!("doc", PathBuf, Concatenated, TooHardPath), // Creates an .xdc file.
msvc_take_arg!("errorReport:", OsString, Concatenated, PassThroughWithSuffix), // Deprecated.
msvc_take_arg!("execution-charset:", OsString, Concatenated, PassThroughWithSuffix),
msvc_flag!("experimental:deterministic", PassThrough),
msvc_flag!("experimental:external", PassThrough),
msvc_flag!("experimental:module", TooHardFlag),
msvc_flag!("experimental:module-", PassThrough), // Explicitly disabled modules.
msvc_take_arg!("experimental:preprocessor", OsString, Concatenated, PassThroughWithSuffix),
msvc_take_arg!("external:I", PathBuf, CanBeSeparated, ExternalIncludePath),
msvc_flag!("external:W0", PassThrough),
msvc_flag!("external:W1", PassThrough),
msvc_flag!("external:W2", PassThrough),
msvc_flag!("external:W3", PassThrough),
msvc_flag!("external:W4", PassThrough),
msvc_flag!("external:anglebrackets", PassThrough),
msvc_take_arg!("favor:", OsString, Concatenated, PassThroughWithSuffix),
msvc_take_arg!("fp:", OsString, Concatenated, PassThroughWithSuffix),
msvc_take_arg!("fsanitize-blacklist", PathBuf, Concatenated('='), ExtraHashFile),
msvc_flag!("fsanitize=address", PassThrough),
msvc_flag!("fsyntax-only", SuppressCompilation),
msvc_take_arg!("guard:cf", OsString, Concatenated, PassThroughWithSuffix),
msvc_flag!("homeparams", PassThrough),
msvc_flag!("hotpatch", PassThrough),
msvc_take_arg!("imsvc", PathBuf, CanBeSeparated, PreprocessorArgumentPath),
msvc_flag!("kernel", PassThrough),
msvc_flag!("kernel-", PassThrough),
msvc_flag!("nologo", PassThrough),
msvc_take_arg!("o", PathBuf, Separated, Output), // Deprecated but valid
msvc_flag!("openmp", PassThrough),
msvc_flag!("openmp-", PassThrough),
msvc_flag!("openmp:experimental", PassThrough),
msvc_flag!("permissive", PassThrough),
msvc_flag!("permissive-", PassThrough),
msvc_flag!("sdl", PassThrough),
msvc_flag!("sdl-", PassThrough),
msvc_flag!("showIncludes", ShowIncludes),
msvc_take_arg!("source-charset:", OsString, Concatenated, PassThroughWithSuffix),
msvc_take_arg!("sourceDependencies", PathBuf, CanBeSeparated, DepFile),
msvc_take_arg!("std:", OsString, Concatenated, PassThroughWithSuffix),
msvc_flag!("u", PassThrough),
msvc_flag!("utf-8", PassThrough),
msvc_flag!("validate-charset", PassThrough),
msvc_flag!("validate-charset-", PassThrough),
msvc_flag!("vd0", PassThrough),
msvc_flag!("vd1", PassThrough),
msvc_flag!("vd2", PassThrough),
msvc_flag!("vmb", PassThrough),
msvc_flag!("vmg", PassThrough),
msvc_flag!("vmm", PassThrough),
msvc_flag!("vms", PassThrough),
msvc_flag!("vmv", PassThrough),
msvc_flag!("volatile:iso", PassThrough),
msvc_flag!("volatile:ms", PassThrough),
msvc_flag!("w", PassThrough),
msvc_take_arg!("w1", OsString, Concatenated, PassThroughWithSuffix),
msvc_take_arg!("w2", OsString, Concatenated, PassThroughWithSuffix),
msvc_take_arg!("w3", OsString, Concatenated, PassThroughWithSuffix),
msvc_take_arg!("w4", OsString, Concatenated, PassThroughWithSuffix),
msvc_take_arg!("wd", OsString, Concatenated, PassThroughWithSuffix),
msvc_take_arg!("we", OsString, Concatenated, PassThroughWithSuffix),
msvc_take_arg!("winsysroot", PathBuf, CanBeSeparated, PassThroughWithPath),
msvc_take_arg!("wo", OsString, Concatenated, PassThroughWithSuffix),
take_arg!("@", PathBuf, Concatenated, TooHardPath),
]);
// TODO: what do do with precompiled header flags? eg: /Y-, /Yc, /YI, /Yu, /Zf, /Zm
pub fn parse_arguments(
arguments: &[OsString],
cwd: &Path,
is_clang: bool,
) -> CompilerArguments<ParsedArguments> {
let mut output_arg = None;
let mut input_arg = None;
let mut double_dash_input = false;
let mut common_args = vec![];
let mut unhashed_args = vec![];
let mut preprocessor_args = vec![];
let mut dependency_args = vec![];
let mut extra_hash_files = vec![];
let mut compilation = false;
let mut compilation_flag = OsString::new();
let mut debug_info = false;
let mut pdb = None;
let mut depfile = None;
let mut show_includes = false;
let mut xclangs: Vec<OsString> = vec![];
let mut clangs: Vec<OsString> = vec![];
let mut profile_generate = false;
let mut multiple_input = false;
let mut multiple_input_files = Vec::new();
// Custom iterator to expand `@` arguments which stand for reading a file
// and interpreting it as a list of more arguments.
let it = ExpandIncludeFile::new(cwd, arguments);
let mut it = ArgsIter::new(it, (&ARGS[..], &SLASH_ARGS[..]));
if is_clang {
it = it.with_double_dashes();
}
for arg in it {
let arg = try_or_cannot_cache!(arg, "argument parse");
match arg.get_data() {
Some(PassThrough) | Some(PassThroughWithPath(_)) | Some(PassThroughWithSuffix(_)) => {}
Some(TooHardFlag) | Some(TooHard(_)) | Some(TooHardPath(_)) => {
cannot_cache!(arg.flag_str().expect("Can't be Argument::Raw/UnknownFlag",))
}
Some(DoCompilation) => {
compilation = true;
compilation_flag =
OsString::from(arg.flag_str().expect("Compilation flag expected"));
}
Some(ShowIncludes) => {
show_includes = true;
dependency_args.push(arg.to_os_string());
}
Some(Output(out)) => {
output_arg = Some(out.clone());
// Can't usefully cache output that goes to nul anyway,
// and it breaks reading entries from cache.
if out.as_os_str() == "nul" {
cannot_cache!("output to nul")
}
}
Some(DepFile(p)) => depfile = Some(p.clone()),
Some(ProgramDatabase(p)) => pdb = Some(p.clone()),
Some(DebugInfo) => debug_info = true,
Some(PreprocessorArgument(_))
| Some(PreprocessorArgumentPath(_))
| Some(ExtraHashFile(_))
| Some(Ignore)
| Some(IgnoreWithSuffix(_))
| Some(ExternalIncludePath(_)) => {}
Some(SuppressCompilation) => {
return CompilerArguments::NotCompilation;
}
Some(XClang(s)) => xclangs.push(s.clone()),
Some(Clang(s)) => clangs.push(s.clone()),
None => {
match arg {
Argument::Raw(ref val) if val == "--" => {
if input_arg.is_none() {
double_dash_input = true;
}
}
Argument::Raw(ref val) => {
if input_arg.is_some() {
// Can't cache compilations with multiple inputs.
multiple_input = true;
multiple_input_files.push(val.clone());
}
input_arg = Some(val.clone());
}
Argument::UnknownFlag(ref flag) => common_args.push(flag.clone()),
_ => unreachable!(),
}
}
}
match arg.get_data() {
Some(PreprocessorArgument(_)) | Some(PreprocessorArgumentPath(_)) => preprocessor_args
.extend(
arg.normalize(NormalizedDisposition::Concatenated)
.iter_os_strings(),
),
Some(ProgramDatabase(_))
| Some(DebugInfo)
| Some(PassThrough)
| Some(PassThroughWithPath(_))
| Some(PassThroughWithSuffix(_)) => common_args.extend(
arg.normalize(NormalizedDisposition::Concatenated)
.iter_os_strings(),
),
Some(ExtraHashFile(path)) => {
extra_hash_files.push(cwd.join(path));
common_args.extend(
arg.normalize(NormalizedDisposition::Concatenated)
.iter_os_strings(),
)
}
Some(ExternalIncludePath(_)) => common_args.extend(
arg.normalize(NormalizedDisposition::Separated)
.iter_os_strings(),
),
// We ignore -MP and -FS and never pass them down to the compiler.
//
// -MP tells the compiler to build with multiple processes and is used
// to spread multiple compilations when there are multiple inputs.
// Either we have multiple inputs on the command line, and we're going
// to bail out and not cache, or -MP is not going to be useful.
// -MP also implies -FS.
//
// -FS forces synchronous access to PDB files via a MSPDBSRV process.
// This option is only useful when multiple compiler invocations are going
// to share the same PDB file, which is not supported by sccache. So either
// -Fd was passed with a pdb that is not shared and sccache is going to
// handle the compile, in which case -FS is not needed, or -Fd was not passed
// and we're going to bail out and not cache.
//
// In both cases, the flag is not going to be useful if we are going to cache,
// so we just skip them entirely. -FS may also have a side effect of creating
// race conditions in which we may try to read the PDB before MSPDBSRC is done
// writing it, so we're better off ignoring the flags.
Some(Ignore) | Some(IgnoreWithSuffix(_)) => {}
_ => {}
}
}
// TODO: doing this here reorders the arguments, hopefully that doesn't affect the meaning
fn xclang_append(arg: OsString, args: &mut Vec<OsString>) {
args.push("-Xclang".into());
args.push(arg);
}
fn dash_clang_append(arg: OsString, args: &mut Vec<OsString>) {
let mut a = OsString::from("-clang:");
a.push(arg);
args.push(a);
}
for (args, append_fn) in Iterator::zip(
[xclangs, clangs].iter(),
&[xclang_append, dash_clang_append],
) {
let it = gcc::ExpandIncludeFile::new(cwd, args);
for arg in ArgsIter::new(it, (&gcc::ARGS[..], &clang::ARGS[..])) {
let arg = try_or_cannot_cache!(arg, "argument parse");
// Eagerly bail if it looks like we need to do more complicated work
use crate::compiler::gcc::ArgData::*;
let args = match arg.get_data() {
Some(SplitDwarf) | Some(TestCoverage) | Some(Coverage) | Some(DoCompilation)
| Some(Language(_)) | Some(Output(_)) | Some(TooHardFlag) | Some(XClang(_))
| Some(TooHard(_)) => cannot_cache!(arg
.flag_str()
.unwrap_or("Can't handle complex arguments through clang",)),
None => match arg {
Argument::Raw(_) | Argument::UnknownFlag(_) => &mut common_args,
_ => unreachable!(),
},
Some(DiagnosticsColor(_))
| Some(DiagnosticsColorFlag)
| Some(NoDiagnosticsColorFlag)
| Some(Arch(_))
| Some(PassThroughFlag)
| Some(PassThrough(_))
| Some(PassThroughPath(_))
| Some(PedanticFlag)
| Some(Standard(_))
| Some(SerializeDiagnostics(_)) => &mut common_args,
Some(UnhashedFlag) | Some(Unhashed(_)) => &mut unhashed_args,
Some(ProfileGenerate) => {
profile_generate = true;
&mut common_args
}
Some(ClangProfileUse(path)) => {
extra_hash_files.push(clang::resolve_profile_use_path(path, cwd));
&mut common_args
}
Some(ExtraHashFile(path)) => {
extra_hash_files.push(cwd.join(path));
&mut common_args
}
Some(PreprocessorArgumentFlag)
| Some(PreprocessorArgument(_))
| Some(PreprocessorArgumentPath(_)) => &mut preprocessor_args,
Some(DepArgumentPath(_)) | Some(DepTarget(_)) | Some(NeedDepTarget) => {
&mut dependency_args
}
};
// Normalize attributes such as "-I foo", "-D FOO=bar", as
// "-Ifoo", "-DFOO=bar", etc. and "-includefoo", "idirafterbar" as
// "-include foo", "-idirafter bar", etc.
let norm = match arg.flag_str() {
Some(s) if s.len() == 2 => NormalizedDisposition::Concatenated,
_ => NormalizedDisposition::Separated,
};
for arg in arg.normalize(norm).iter_os_strings() {
append_fn(arg, args);
}
}
}
// We only support compilation.
if !compilation {
return CompilerArguments::NotCompilation;
}
// Can't cache compilations with multiple inputs.
if multiple_input {
cannot_cache!(
"multiple input files",
format!("{:?}", multiple_input_files)
);
}
let (input, language) = match input_arg {
Some(i) => match Language::from_file_name(Path::new(&i)) {
Some(l) => (i.to_owned(), l),
None => cannot_cache!("unknown source language"),
},
// We can't cache compilation without an input.
None => cannot_cache!("no input file"),
};
let mut outputs = HashMap::new();
match output_arg {
// If output file name is not given, use default naming rule
None => {
outputs.insert(
"obj",
ArtifactDescriptor {
path: Path::new(&input).with_extension("obj"),
optional: false,
},
);
}
Some(o) => {
if o.extension().is_none() && compilation {
outputs.insert(
"obj",
ArtifactDescriptor {
path: o.with_extension("obj"),
optional: false,
},
);
} else {
outputs.insert(
"obj",
ArtifactDescriptor {
path: o,
optional: false,
},
);
}
}
}
if language == Language::Cxx {
if let Some(obj) = outputs.get("obj") {
// MSVC can produce "type library headers"[1], with the extensions "tlh" and "tli".
// These files can be used in later compilation steps to interact with COM interfaces.
//
// These files are only created when the `#import` directive is used.
// Figuring out if an import directive is used would require parsing C++, which would be a lot of work.
// To avoid that problem, we just optionally cache these headers if they happen to be produced.
// This isn't perfect, but it is easy!
//
// [1]: https://learn.microsoft.com/en-us/cpp/preprocessor/hash-import-directive-cpp?view=msvc-170#_predir_the_23import_directive_header_files_created_by_import
let tlh = obj.path.with_extension("tlh");
let tli = obj.path.with_extension("tli");
// Primary type library header
outputs.insert(
"tlh",
ArtifactDescriptor {
path: tlh,
optional: true,
},
);
// Secondary type library header
outputs.insert(
"tli",
ArtifactDescriptor {
path: tli,
optional: true,
},
);
}
}
// -Fd is not taken into account unless -Zi or -ZI are given
// Clang is currently unable to generate PDB files
if debug_info && !is_clang {
match pdb {
Some(p) => outputs.insert(
"pdb",
ArtifactDescriptor {
path: p,
optional: false,
},
),
None => {
// -Zi and -ZI without -Fd defaults to vcxxx.pdb (where xxx depends on the
// MSVC version), and that's used for all compilations with the same
// working directory. We can't cache such a pdb.
cannot_cache!("shared pdb");
}
};
}
CompilerArguments::Ok(ParsedArguments {
input: input.into(),
double_dash_input,
language,
compilation_flag,
depfile,
outputs,
dependency_args,
preprocessor_args,
common_args,
arch_args: vec![],
unhashed_args,
extra_dist_files: vec![],
extra_hash_files,
msvc_show_includes: show_includes,
profile_generate,
// FIXME: implement color_mode for msvc.
color_mode: ColorMode::Auto,
suppress_rewrite_includes_only: false,
too_hard_for_preprocessor_cache_mode: None,
})
}
#[cfg(windows)]
fn normpath(path: &str) -> String {
use std::os::windows::ffi::OsStringExt;
use std::os::windows::io::AsRawHandle;
use std::ptr;
use windows_sys::Win32::Storage::FileSystem::GetFinalPathNameByHandleW;
File::open(path)
.and_then(|f| {
let handle = f.as_raw_handle() as _;
let size = unsafe { GetFinalPathNameByHandleW(handle, ptr::null_mut(), 0, 0) };
if size == 0 {
return Err(io::Error::last_os_error());
}
let mut wchars = vec![0; size as usize];
if unsafe {
GetFinalPathNameByHandleW(handle, wchars.as_mut_ptr(), wchars.len() as u32, 0)
} == 0
{
return Err(io::Error::last_os_error());
}
// The return value of GetFinalPathNameByHandleW uses the
// '\\?\' prefix.
let o = OsString::from_wide(&wchars[4..wchars.len() - 1]);
o.into_string()
.map(|s| s.replace('\\', "/"))
.map_err(|_| io::Error::new(io::ErrorKind::Other, "Error converting string"))
})
.unwrap_or_else(|_| path.replace('\\', "/"))
}
#[cfg(not(windows))]
fn normpath(path: &str) -> String {
path.to_owned()
}
#[allow(clippy::too_many_arguments)]
pub fn preprocess_cmd<T>(
cmd: &mut T,
parsed_args: &ParsedArguments,
cwd: &Path,
env_vars: &[(OsString, OsString)],
may_dist: bool,
rewrite_includes_only: bool,
is_clang: bool,
) where
T: RunCommand,
{
// When performing distributed compilation, line number info is important for error
// reporting and to not cause spurious compilation failure (e.g. no exceptions build
// fails due to exceptions transitively included in the stdlib).
// With -fprofile-generate line number information is important, so use -E.
// Otherwise, use -EP to maximize cache hits (because no absolute file paths are
// emitted) and improve performance.
if may_dist || parsed_args.profile_generate {
cmd.arg("-E");
} else {
cmd.arg("-EP");
}
cmd.arg("-nologo")
.args(&parsed_args.preprocessor_args)
.args(&parsed_args.dependency_args)
.args(&parsed_args.common_args)
.env_clear()
.envs(env_vars.to_vec())
.current_dir(cwd);
if is_clang {
if parsed_args.depfile.is_some() && !parsed_args.msvc_show_includes {
cmd.arg("-showIncludes");
}
} else {
// cl.exe can product the dep list itself, in a JSON format that some tools will be expecting.
if let Some(ref depfile) = parsed_args.depfile {
cmd.arg("/sourceDependencies");
cmd.arg(depfile);
}
// Windows SDK generates C4668 during preprocessing, but compiles fine.
// Read for more info: https://github.com/mozilla/sccache/issues/1725
// And here: https://github.com/mozilla/sccache/issues/2250
cmd.arg("/WX-");
}
if rewrite_includes_only && is_clang {
cmd.arg("-clang:-frewrite-includes");
}
if parsed_args.double_dash_input {
cmd.arg("--");
}
cmd.arg(&parsed_args.input);
}
#[allow(clippy::too_many_arguments)]
pub async fn preprocess<T>(
creator: &T,
executable: &Path,
parsed_args: &ParsedArguments,
cwd: &Path,
env_vars: &[(OsString, OsString)],
may_dist: bool,
includes_prefix: &str,
rewrite_includes_only: bool,
is_clang: bool,
) -> Result<process::Output>
where
T: CommandCreatorSync,
{
let mut cmd = creator.clone().new_command_sync(executable);
preprocess_cmd(
&mut cmd,
parsed_args,
cwd,
env_vars,
may_dist,
rewrite_includes_only,
is_clang,
);
if log_enabled!(Debug) {
debug!("preprocess: {:?}", cmd);
}
let parsed_args = parsed_args.clone();
let includes_prefix = includes_prefix.to_string();
let cwd = cwd.to_owned();
let output = run_input_output(cmd, None).await?;
if !is_clang {
return Ok(output);
}
let parsed_args = &parsed_args;
if let (Some(obj), Some(depfile)) = (parsed_args.outputs.get("obj"), &parsed_args.depfile) {
let objfile = &obj.path;
let f = File::create(cwd.join(depfile))?;
let mut f = BufWriter::new(f);
encode_path(&mut f, objfile)
.with_context(|| format!("Couldn't encode objfile filename: '{:?}'", objfile))?;
write!(f, ": ")?;
encode_path(&mut f, &parsed_args.input)
.with_context(|| format!("Couldn't encode input filename: '{:?}'", objfile))?;
write!(f, " ")?;
let process::Output {
status,
stdout,
stderr: stderr_bytes,
} = output;
let stderr =
from_local_codepage(&stderr_bytes).context("Failed to convert preprocessor stderr")?;
let mut deps = HashSet::new();
let mut stderr_bytes = vec![];