-
Notifications
You must be signed in to change notification settings - Fork 4
/
main.rs
2975 lines (2641 loc) · 111 KB
/
main.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
#![feature(variant_count)]
mod flags;
/// Run rustc its own tests with different parameters
/// If an ICE (internal compiler error/crash/panic) is found, find out
/// the smallest combination of responsible flags and save data about the crash
///
/// The programm is not limited to run rustc, but can also run clippy or rustdoc:
/// rustc: icemaker
/// clippy: icemaker -c
/// rustfmt: icemaker -f
/// rust-analyzer: icemaker -a
/// rustdoc: icemaker -r
// convert glacier scripts into .rs files:
//
// for i in `rg EOF . | grep -o "^.*.sh"`; do ; CONTENT=` cat $i | pcregrep --no-messages -M '.*<<.*EOF:*(\n|.)*EOF' | grep -v ".*EOF.*"` ; echo $CONTENT >| `echo $i | sed -e s/\.sh/\.rs/` ; done
// check out every single file that exists in a repo:
//
// for object_hash in `git cat-file --batch-all-objects --batch-check | grep blob | cut -d' ' -f1` ; do
// git cat-file $object_hash -p > ${object_hash}.rs
// done
// get the first 275000 smallest files
// git cat-file --batch-all-objects --batch-check | grep blob | cut -d' ' -f1,3 | awk '{for(i=NF;i>=1;i--) printf "%s ", $i;print ""}' | sort -n | head -n 275000| cut -d' ' -f2 | parallel -I% "git cat-file % -p > %.rs"
// all the interesting miri findings:
//
// for file in `cat errors.json | grep file.: | cut -d' ' -f6 | sed s/\"//g | sed s/,//` ; do; echo -n "$file " ; grep "unsafe\|simd\|no_core\|transmute\|Box::\|rustc_variance" -c $file ; done | grep 0$
//
mod fuzz;
mod fuzz2;
mod fuzz_tree_splicer;
mod ice;
mod library;
mod printing;
mod run_commands;
mod smolfuzz;
use crate::flags::*;
use crate::fuzz::*;
use crate::fuzz_tree_splicer::*;
use crate::ice::*;
use crate::library::*;
use crate::printing::*;
use crate::run_commands::*;
use crate::smolfuzz::*;
use std::collections::HashSet;
use std::ffi::{OsStr, OsString};
use std::io::BufRead;
use std::io::Write;
use std::path::{Path, PathBuf};
use std::process::{Command, Output, Stdio};
use std::sync::atomic::{AtomicUsize, Ordering};
use std::sync::{Arc, Mutex};
use std::time::Instant;
use clap::Parser;
use colored::Colorize;
use lazy_static::lazy_static;
use rayon::prelude::*;
use regex::Regex;
use sha2::{Digest, Sha256};
use tempdir::TempDir;
use walkdir::WalkDir;
// local debug assertions: run with:
// LD_LIBRARY_PATH=/home/matthias/vcs/github/rust_debug_assertions/build/x86_64-unknown-linux-gnu/stage1/lib/rustlib/x86_64-unknown-linux-gnu/lib/
lazy_static! {
static ref ALL_ICES_WITH_FLAGS: Mutex<Vec<Vec<OsString>>> =
Mutex::new(vec![vec![OsString::new()]]);
}
static PRINTER: Printer = printing::Printer::new();
impl From<&Args> for Executable {
#[allow(clippy::if_same_then_else)]
fn from(args: &Args) -> Self {
if args.clippy {
Executable::Clippy
} else if args.clippy_fix {
Executable::ClippyFix
} else if args.rust_fix {
Executable::RustFix
} else if args.rustdoc {
Executable::Rustdoc
} else if args.analyzer {
Executable::RustAnalyzer
} else if args.rustfmt {
Executable::Rustfmt
} else if args.miri {
Executable::Miri
} else if args.rustc {
Executable::Rustc
} else if (args).cranelift {
// from local-debug-assertions build, -Zcodegen-backend=cranelift
Executable::Cranelift
} else if (args).kani {
Executable::Kani
} else if args.rustc_codegen_gcc {
Executable::RustcCodegenGCC
} else {
Executable::Rustc
}
}
}
/// run on a project, each project having its own errors.json
fn check_dir(
root_path: &PathBuf,
args: &Args,
global_tempdir_path: &PathBuf,
timer: &Timer,
errors_json_tmp: &Arc<Mutex<std::fs::File>>,
) -> Vec<PathBuf> {
// read in existing errors
// read the string INTO Vec<ICE>
let errors_json = root_path.join("errors.json");
let errors_before: Vec<ICE> = if errors_json.exists() {
let read = match std::fs::read_to_string(&errors_json) {
Ok(content) => content,
Err(_) => panic!("failed to read '{}'", errors_json.display()),
};
match serde_json::from_str(&read) {
Ok(previous_errors) => previous_errors,
Err(e) => {
// this can happen if we for example change the representation of Ice so that that the previous file is no longer compatible with the new format
eprintln!("Failed to parse errors.json, is it a json file?");
eprintln!("origina error: '{e:?}'");
Vec::new()
}
}
} else {
// we don't have a file, start blank
Vec::new()
};
let executable = Executable::from(args);
let executables = if !matches!(executable, Executable::Rustc) || /* may have passed --rustc to disable clippy rustdoc etc */ args.rustc
{
// assume that we passed something, do not take the default Rustc
vec![&executable]
} else {
// default Executables
// dont run cranelift by default, maybe wait until we have an official rustup component
if cfg!(feature = "ci") {
// on ci, don't run miri
vec![
&Executable::Rustc,
&Executable::Rustdoc,
&Executable::Clippy,
&Executable::Rustfmt,
]
} else if args.local_debug_assertions {
vec![
&Executable::Rustc,
&Executable::Rustdoc,
&Executable::Rustfmt,
&Executable::ClippyFix,
&Executable::Miri,
&Executable::Cranelift,
]
} else {
vec![
&Executable::Rustc,
&Executable::Rustdoc,
&Executable::Rustfmt,
&Executable::ClippyFix,
// &Executable::Miri,
]
}
};
if args.codegen {
codegen_git_original_dirs();
std::process::exit(0);
}
if args.smolfuzz {
codegen_smolfuzz();
return Vec::new();
}
if executables.contains(&&Executable::Miri) || matches!(executable, Executable::Miri) {
println!("Running cargo miri setup");
let _ = std::process::Command::new("cargo")
.arg(if args.local_debug_assertions {
"+local-debug-assertions"
} else {
"+master"
})
.arg("miri")
.arg("setup")
.status()
.unwrap()
.success();
}
if args.heat {
let chain_order = args.chain_order;
let _ = run_space_heater(executable, chain_order, global_tempdir_path);
return Vec::new();
}
if args.codegen_splice {
codegen_tree_splicer();
std::process::exit(0);
}
if args.codegen_splice_omni {
codegen_tree_splicer_omni();
std::process::exit(0);
}
if args.fuzz {
let _ = run_random_fuzz(executable, global_tempdir_path);
return Vec::new();
} else if args.fuzz2 {
crate::fuzz2::fuzz2::fuzz2main();
return Vec::new();
}
if args.incr_fuzz {
tree_splice_incr_fuzz(global_tempdir_path);
std::process::exit(1);
}
if (args).reduce {
reduce_all(global_tempdir_path);
std::process::exit(0);
}
// search for rust files inside CWD
let mut files = WalkDir::new(root_path)
.into_iter()
.par_bridge()
.filter_map(|e| e.ok())
.filter(|f| f.path().extension() == Some(OsStr::new("rs")))
.map(|f| f.path().to_owned())
.collect::<Vec<PathBuf>>();
// check biggest files first
files.par_sort_by_cached_key(|file| std::fs::metadata(file).unwrap().len());
files.reverse();
/*
eprintln!("\n\nSTART\n\n");
// files that compile
let files_that_compile = files
.iter()
// filter(|f| EXCEPTIONS.)
.filter(|f| file_compiles(f, &Executable::Rustc.path()))
.collect::<Vec<&PathBuf>>();
eprintln!("\n\nDONE\n\n");
*/
//let exec_path = executable.path();
executables.iter().for_each(|executable| {
println!("Using {:?}: {}", executable, executable.path());
});
if matches!(executable, Executable::Rustc) {
println!(
"checking: {} files x {} flags, {} executables\n\n",
files.len(),
RUSTC_FLAGS.len() + 2, // incremental
executables.len()
);
} else {
println!("checking: {} files\n", files.len(),);
}
// files that take too long (several minutes) to check or cause other problems
#[allow(non_snake_case)]
let EXCEPTION_LIST: Vec<PathBuf> = EXCEPTIONS
.iter()
.map(PathBuf::from)
// otherwise we don't match
.map(|p| root_path.join(p))
.collect();
#[allow(non_snake_case)]
let MIRI_EXCEPTION_LIST: Vec<PathBuf> = MIRI_EXCEPTIONS
.iter()
.map(PathBuf::from)
// otherwise we don't match
.map(|p| root_path.join(p))
.collect();
// count progress
let counter = std::sync::atomic::AtomicUsize::new(0);
// type Timer<'a> = (&'a Executable, AtomicUsize);
let rustc_exec_path = Executable::Rustc.path();
if args.incremental_test {
eprintln!("checking which files compile...");
let files = files
.par_iter()
.filter(|file| !EXCEPTION_LIST.contains(file))
.filter(|file| file_compiles(file, &rustc_exec_path, global_tempdir_path))
.cloned()
.collect::<Vec<_>>();
eprintln!("checking {} files...", files.len());
let incr_crashes = files
.par_iter()
.filter(|file| !EXCEPTION_LIST.contains(file))
.panic_fuse()
.filter(|file| !EXCEPTION_LIST.contains(file))
.filter_map(|file_a| {
let (output, _cmd_str, _actual_args, file_a, file_b) =
incremental_stress_test(file_a, &files, &rustc_exec_path, global_tempdir_path)?;
let is_ice = find_ICE_string(&file_a, &Executable::Rustc, output.clone());
if is_ice.is_some() {
eprintln!("\nINCRCOMP ICE: {},{}", file_a.display(), file_b.display());
Some((file_a, file_b, output))
} else {
None
}
})
.collect::<Vec<_>>();
dbg!(incr_crashes);
return Vec::new();
}
// main loop that checks all the files
let mut errors: Vec<ICE> = files
.par_iter()
.flat_map(|file| {
// for each file, increment counter by one
let _ = counter.fetch_add(1, Ordering::SeqCst);
executables
.par_iter()
.panic_fuse()
// don't check anything that is contained in the exception list
.filter(|executable| {
!EXCEPTION_LIST.contains(file)
|| (matches!(executable, Executable::Miri)
|| (matches!(executable, Executable::Cranelift))
&& !MIRI_EXCEPTION_LIST.contains(file))
})
.map(|executable| {
let executable_start_time = Instant::now();
let exec_path = executable.path();
match executable {
Executable::Rustc
/* | Executable::CraneliftLocal */ => {
// with expensive flags, run on each of the editions separately
let editions = if args.expensive_flags {
vec!["--edition=2015", "--edition=2018", "--edition=2021"]
} else {
// FIXME need to have somehting here to at least iter once :/
vec!["-Ccodegen-units=1"]
};
// for each file, run every chunk of RUSTC_FLAGS and check it and see if it crashes
RUSTC_FLAGS
// note: this can be dangerous in case of max memory usage, if a file needs a lot
.par_iter()
.panic_fuse()
.map(|flag_combinations| flag_combinations.iter())
// need shit to flat map a sequential iter into a par_iter
.flat_map_iter(|flag_combinations| {
editions.iter().map(move |x| {
if args.expensive_flags {
flag_combinations
.clone()
.chain(std::iter::once(x).take(1))
} else {
flag_combinations
.clone()
.chain(std::iter::once(&"").take(0))
}
})
})
.map(|flag_combination| {
let ice = ICE::discover(
file,
&exec_path,
executable,
flag_combination,
&[],
false,
&counter,
files.len(),
args.silent,
global_tempdir_path,
);
let seconds_elapsed =
executable_start_time.elapsed().as_millis() as usize;
timer.update_from_executable(executable, seconds_elapsed);
ice
})
.collect::<Vec<Option<ICE>>>()
}
Executable::Miri => MIRIFLAGS
.par_iter()
.map(|miri_flag_combination| {
MIRI_RUSTFLAGS
.par_iter()
.panic_fuse()
.map(|miri_rustflag| {
let ice = ICE::discover(
file,
&exec_path,
executable,
*miri_rustflag,
miri_flag_combination,
false,
&counter,
files.len(),
args.silent,
global_tempdir_path,
);
let seconds_elapsed =
executable_start_time.elapsed().as_millis() as usize;
timer.update_from_executable(executable, seconds_elapsed);
ice
})
.find_any(|ice| ice.is_some())
})
.flatten()
.collect::<Vec<Option<ICE>>>(),
_ => {
// if we run clippy/rustfmt/rla .. we dont need to check multiple combinations of RUSTFLAGS
let ice = vec![ICE::discover(
file,
&exec_path,
executable,
// run with no flags
&[],
&[],
false,
&counter,
files.len(),
args.silent,
global_tempdir_path,
)];
let seconds_elapsed =
executable_start_time.elapsed().as_millis() as usize;
timer.update_from_executable(executable, seconds_elapsed);
ice
}
}
})
.flatten()
.filter(|opt_ice| opt_ice.is_some())
.map(|ice| ice.unwrap())
.map(|ice| {
let ice_json =
serde_json::to_string_pretty(&ice).expect("failed ot jsonify ICE");
let errors_tmp = Arc::clone(errors_json_tmp);
let mut f = errors_tmp.lock().unwrap();
writeln!(f, "{}", ice_json)
.expect("failed to write to mutex locked errors_tmp.json");
ice
})
.collect::<Vec<ICE>>()
})
.collect();
// dedupe equal ICEs, before sorting
errors.dedup();
let flagless_ices = errors
.iter()
.filter(|ice| ice.args.is_empty())
.cloned()
.collect::<Vec<ICE>>();
flagless_ices.iter().for_each(|flglice| {
// if we have an ICE where the msg and the file is equal to a flagless ice (but the ice is not the flagless ice), assume that the flags are unrelated
// remove the ice from "errors"
errors.retain(|ice| {
!(ice.file == flglice.file && ice.ice_msg == flglice.ice_msg && !ice.args.is_empty())
});
});
// sort by filename first and then by ice so that identical ICES are grouped up
errors.sort_by_key(|ice| ice.file.clone());
errors.dedup();
errors.sort_by_key(|ice| ice.ice_msg.clone());
// dedupe equal ICEs
errors.dedup();
// if we have the same file, same error_msg and same error_reason, this also gotta be an identical ICE
errors.sort_by_key(|ice| {
format!(
"file: {} error_reason: {} ice_msg: {}",
ice.file.display(),
ice.error_reason,
ice.ice_msg
)
});
errors.dedup_by_key(|ice| {
format!(
"file: {} error_reason: {} ice_msg: {}",
ice.file.display(),
ice.error_reason,
ice.ice_msg
)
});
// original sorting again
errors.sort_by_key(|ice| ice.file.clone());
errors.sort_by_key(|ice| ice.ice_msg.clone());
// sort by command
// errors.sort_by_key(|ice| ice.cmd.clone());
// if we are done, print all errors
println!("errors:\n");
/*
errors.iter().for_each(|f| {
let mut debug = format!("{:?}", f);
debug.truncate(300);
println!("{}", debug);
});
*/
// if the ices start with the root path, we need to strip the root path
errors.iter_mut().for_each(|ice| {
let mut ice_path = ice.file.clone();
if ice_path.starts_with(root_path) {
ice_path = ice_path
.strip_prefix(root_path)
.expect("strip_prefix failed, could not fix ice.file")
.to_owned();
// readd the leading "./" that was stripped previously
ice.file = PathBuf::from("./").join(ice_path);
}
});
// errors.iter().for_each(|ice| ice.to_disk());
// in the end, save all the errors to a file
let errors_new = serde_json::to_string_pretty(&errors).unwrap();
std::fs::write(&errors_json, &errors_new)
.unwrap_or_else(|_| panic!("error: failed to write to {}", errors_json.display()));
println!("\ndiff: \n");
// get the diff
let diff = diff::lines(
&serde_json::to_string_pretty(&errors_before).unwrap(),
&errors_new,
)
.iter()
.map(|diff| match diff {
diff::Result::Left(l) => format!("-{l}\n"),
diff::Result::Both(l, _) => format!(" {l}\n"),
diff::Result::Right(r) => format!("+{r}\n"),
})
.collect::<String>();
println!("{diff}");
// write the diff into report folder
let reports_dir = crate::ice::REPORTS_DIR.to_owned();
if !PathBuf::from(&reports_dir).exists() {
std::fs::create_dir_all(&reports_dir).expect("failed to create icemaker reports dir!");
}
let diff_path = reports_dir.join("errors.diff");
let mut file =
std::fs::File::create(diff_path).expect("report.to_disk() failed to create file");
file.write_all(diff.as_bytes())
.expect("failed to write report");
let new_ices = errors
.iter()
.filter(|new_ice| !errors_before.contains(new_ice))
.collect::<Vec<&ICE>>();
// TODO do the same for removed ices?
println!("NEW ICES:\n{new_ices:#?}");
if new_ices.len() == 0 {
eprintln!("No new, ices, skipping reports...");
} else {
eprintln!("Generating reports...");
}
new_ices
.into_iter()
.map(|ice| {
let ice = ice.clone();
ice.into_report(global_tempdir_path)
})
.for_each(|ice_report| ice_report.to_disk());
eprintln!("done");
/*
let root_path_string = root_path.display().to_string();
// crashing commands
ALL_ICES_WITH_FLAGS
.lock()
.unwrap()
.iter()
.map(|flags| {
let flags = flags
.iter()
.map(|x| x.to_str().unwrap().to_string())
.collect::<Vec<String>>();
// miri for example has no flags, don't spam a bunch of empty lines into stdout
flags
})
.filter(|flags| !flags.is_empty())
.map(|flags| flags.join(" "))
.filter(|flag| flag.starts_with(&root_path_string))
.for_each(|_line| {
// @HERE avoid spam
// println!("{}", line);
});
*/
files
}
#[derive(Debug, Default)]
struct Timer {
rustc_time: AtomicUsize,
clippy_time: AtomicUsize,
rustdoc_time: AtomicUsize,
rla_time: AtomicUsize,
rustfmt_time: AtomicUsize,
miri_time: AtomicUsize,
craneliftlocal_time: AtomicUsize,
clippyfix_time: AtomicUsize,
rustfix_time: AtomicUsize,
kani_time: AtomicUsize,
rustc_codegen_gcc: AtomicUsize,
}
impl Timer {
fn update_from_executable(&self, exe: &Executable, elapsed_duration: usize) {
match exe {
Executable::Rustc => {
let _ = self
.rustc_time
.fetch_add(elapsed_duration, Ordering::SeqCst);
}
Executable::Clippy => {
let _ = self
.clippy_time
.fetch_add(elapsed_duration, Ordering::SeqCst);
}
Executable::Rustdoc => {
let _ = self
.rustdoc_time
.fetch_add(elapsed_duration, Ordering::SeqCst);
}
Executable::RustAnalyzer => {
let _ = self.rla_time.fetch_add(elapsed_duration, Ordering::SeqCst);
}
Executable::Rustfmt => {
let _ = self
.rustfmt_time
.fetch_add(elapsed_duration, Ordering::SeqCst);
}
Executable::Miri => {
let _ = self.miri_time.fetch_add(elapsed_duration, Ordering::SeqCst);
}
Executable::Cranelift => {
let _ = self
.craneliftlocal_time
.fetch_add(elapsed_duration, Ordering::SeqCst);
}
Executable::ClippyFix => {
let _ = self
.clippyfix_time
.fetch_add(elapsed_duration, Ordering::SeqCst);
}
Executable::RustFix => {
let _ = self
.rustfix_time
.fetch_add(elapsed_duration, Ordering::SeqCst);
}
Executable::Kani => {
let _ = self.kani_time.fetch_add(elapsed_duration, Ordering::SeqCst);
}
Executable::RustcCodegenGCC => {
let _ = self
.rustc_codegen_gcc
.fetch_add(elapsed_duration, Ordering::SeqCst);
}
}
}
fn new() -> Self {
Timer::default()
}
fn into_seconds(self) -> Self {
use std::time::Duration;
Timer {
rustc_time: AtomicUsize::new(
Duration::from_millis(self.rustc_time.into_inner() as u64).as_secs() as usize,
),
clippy_time: AtomicUsize::new(
Duration::from_millis(self.clippy_time.into_inner() as u64).as_secs() as usize,
),
rustdoc_time: AtomicUsize::new(
Duration::from_millis(self.rustdoc_time.into_inner() as u64).as_secs() as usize,
),
rla_time: AtomicUsize::new(
Duration::from_millis(self.rla_time.into_inner() as u64).as_secs() as usize,
),
rustfmt_time: AtomicUsize::new(
Duration::from_millis(self.rustfmt_time.into_inner() as u64).as_secs() as usize,
),
miri_time: AtomicUsize::new(
Duration::from_millis(self.miri_time.into_inner() as u64).as_secs() as usize,
),
craneliftlocal_time: AtomicUsize::new(
Duration::from_millis(self.craneliftlocal_time.into_inner() as u64).as_secs()
as usize,
),
clippyfix_time: AtomicUsize::new(
Duration::from_millis(self.clippyfix_time.into_inner() as u64).as_secs() as usize,
),
rustfix_time: AtomicUsize::new(
Duration::from_millis(self.rustfix_time.into_inner() as u64).as_secs() as usize,
),
kani_time: AtomicUsize::new(
Duration::from_millis(self.kani_time.into_inner() as u64).as_secs() as usize,
),
rustc_codegen_gcc: AtomicUsize::new(
Duration::from_millis(self.rustc_codegen_gcc.into_inner() as u64).as_secs()
as usize,
),
}
}
}
fn main() {
// how long did we take?
let global_start_time = Instant::now();
// do not dump backtraces to disk all the time
// RUSTC_ICE=..
// https://github.com/rust-lang/rust/pull/108714
std::env::set_var("RUSTC_ICE", "0");
let args = Args::parse();
let global_tempdir = if let Some(ref custom_tempdir_path) = args.global_tempdir_path {
let mut custom_tmpdir = std::path::PathBuf::from(&custom_tempdir_path);
let dir_display = custom_tmpdir.display();
assert!(
custom_tmpdir.is_dir(),
"global tempdir '{}' not found",
dir_display
);
// otherwise tempdir would be foo.af32ed2 and not foo/af32ed2
custom_tmpdir.push("dir");
let dir_display = custom_tmpdir.display();
TempDir::new_in("icemaker_global_tempdir", &format!("{}", dir_display))
.expect("failed to create global icemaker tempdir")
} else {
TempDir::new("icemaker_global_tempdir").expect("failed to create global icemaker tempdir")
};
let global_tempdir_path_closure: PathBuf = global_tempdir.path().to_owned();
let global_tempdir_path: PathBuf = global_tempdir_path_closure.clone();
//dbg!(&global_tempdir_path);
println!(
"using {} threads",
if args.threads != 0 {
args.threads
} else if let Ok(threads) = std::thread::available_parallelism() {
threads.get()
} else {
// failed to get threads, eh
0
}
);
// rayon thread pool so we can configure number of threads easily
rayon::ThreadPoolBuilder::new()
.num_threads(args.threads)
.build_global()
.unwrap();
// set up ctrl c handler so we can print ICEs so far when ctrl+'ing
ctrlc::set_handler(move || {
println!("\n\nCtrl+C: TERMINATED\n");
eprintln!("triyng to rm tempdir:");
dbg!(&global_tempdir_path_closure.clone());
if std::fs::remove_dir_all(global_tempdir_path_closure.clone()).is_err() {
eprintln!(
"WARNING: failed to remove global tempdir '{}'",
global_tempdir_path_closure.display()
);
}
ALL_ICES_WITH_FLAGS
.lock()
.unwrap()
.iter()
.for_each(|flags| {
let flags = flags
.iter()
.map(|x| x.to_str().unwrap().to_string())
.collect::<Vec<String>>();
if !flags.is_empty() {
println!("{}", flags.join(" "))
}
});
//dbg!(&global_tempdir_path_closure);
std::process::exit(42);
})
.expect("Error setting Ctrl-C handler");
// a path with rustc files that we want to check
type ProjectDir = PathBuf;
let projs: Vec<ProjectDir> = args.projects.to_vec();
let projects: Vec<ProjectDir> = if projs.is_empty() {
// if we didn't get anything passed, use cwd
vec![std::env::current_dir().expect("cwd not found or does not exist!")]
} else {
println!(
"checking projects: {}",
projs
.iter()
.map(|p| p.display().to_string())
.collect::<Vec<String>>()
.join(", ")
);
projs
};
// assert these are all valid directories
if let Some(invalid_path) = projects.iter().find(|proj_path| !proj_path.is_dir()) {
eprintln!(
"ERROR: --projects '{}' is not a directory",
invalid_path.display()
);
std::process::exit(1);
}
let timer: Timer = Timer::new();
let root_path = std::env::current_dir().expect("could not get CWD!");
let tmp_file = root_path.join("errors_tmp.json");
let errors_json_tmp = Arc::new(Mutex::new(std::fs::File::create(tmp_file).unwrap()));
// all checked files
let files = projects
.iter()
.map(|dir| check_dir(dir, &args, &global_tempdir_path, &timer, &errors_json_tmp))
.flat_map(|v| v.into_iter())
.collect::<Vec<PathBuf>>();
let seconds_elapsed = global_start_time.elapsed().as_secs();
let number_of_checked_files = files.len();
if seconds_elapsed == 0 {
println!("Checked {number_of_checked_files} files in <1 second");
return;
}
let files_per_second = number_of_checked_files as f64 / seconds_elapsed as f64;
println!(
"\nChecked {} files in {:.2} minutes, {:.2} files/second",
number_of_checked_files,
seconds_elapsed as f64 / 60_f64,
files_per_second
);
eprintln!("Timings in seconds:\n{:?}", timer.into_seconds());
eprintln!("\n\nALL CRASHES\n\n");
ALL_ICES_WITH_FLAGS
.lock()
.unwrap()
.iter()
.for_each(|flags| {
let flags = flags
.iter()
.map(|x| x.to_str().unwrap().to_string())
.collect::<Vec<String>>();
// miri for example has no flags, don't spam a bunch of empty lines into stdout
if !flags.is_empty() {
// @FIXME ? this might no longer be needed
// println!("{}", flags.join(" "))
}
});
}
impl ICE {
/// find out if a file crashes rustc with the given flags
#[allow(clippy::too_many_arguments)]
fn discover<'f, F: IntoIterator<Item = &'f &'f str>>(
file: &Path,
exec_path: &str,
executable: &Executable,
compiler_flags: F,
miri_flags: &[&str],
incremental: bool,
counter: &AtomicUsize,
total_number_of_files: usize,
silent: bool,
global_tempdir_path: &PathBuf,
) -> Option<Self> {
// convert IntoIterator<Item &&str> to &[&str]
let compiler_flags = &compiler_flags.into_iter().cloned().collect::<Vec<&str>>()[..];
let thread_start = Instant::now();
const SECONDS_LIMIT: u64 = PROCESS_TIMEOUT_S as u64;
const _SECONDS_LIMIT_MIRI: u64 = 20;
let incremental = if compiler_flags == ["INCR_COMP"] {
true
} else {
incremental
};
// run the command with some flags (actual_args)
let index = counter.load(Ordering::SeqCst); // the current file number
let file_name = file.display().to_string();
// print Checking ... + progress percentage for each file we are checking
if !silent {
PRINTER.log(PrintMessage::Progress {
index,
total_number_of_files,
file_name,
});
}
// note: `actual_args` are the VERY ORIGINAL ARGS so this contains something like -otmpdir_foo.AFXIU/outfile which will no longer be
// a valid path as soon as the tempdir goes out of scope
let (cmd_output, _cmd, actual_args) = match executable {
Executable::Clippy => run_clippy(exec_path, file, global_tempdir_path),
Executable::ClippyFix => run_clippy_fix(exec_path, file, global_tempdir_path),
Executable::RustFix => run_rustfix(exec_path, file, global_tempdir_path),
// Executable::Rustc => run_rustc_lazy_type_alias(exec_path, file, global_tempdir_path),
Executable::Rustc => run_rustc(
exec_path,
file,
incremental,
compiler_flags,
global_tempdir_path,
),
Executable::Rustdoc => run_rustdoc(exec_path, file, global_tempdir_path),
Executable::RustAnalyzer => run_rust_analyzer(exec_path, file, global_tempdir_path),
Executable::Rustfmt => run_rustfmt(exec_path, file, global_tempdir_path),
Executable::Miri => run_miri(
exec_path,
file,
miri_flags,
compiler_flags,
global_tempdir_path,
),
Executable::Cranelift => {
let mut compiler_flags = compiler_flags.to_vec();
compiler_flags.push("-Zcodegen-backend=cranelift");
run_rustc(
exec_path,
file,
incremental,
&compiler_flags,
global_tempdir_path,
)
}
Executable::Kani => run_kani(
exec_path,
file,
miri_flags, // hack
compiler_flags,
global_tempdir_path,
),
Executable::RustcCodegenGCC => {
rustc_codegen_gcc_local(exec_path, file, false, compiler_flags, global_tempdir_path)
}
}
.unwrap();