-
Notifications
You must be signed in to change notification settings - Fork 29
/
Copy pathcasr-cli.rs
1177 lines (1063 loc) · 36.9 KB
/
casr-cli.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
use clap::{Arg, ArgAction};
use colored::Colorize;
use cursive::event::EventTrigger;
use cursive::View;
use regex::Regex;
use serde_json::Value;
use std::collections::{BTreeMap, HashSet};
use std::fmt::Write;
use std::fs;
use std::fs::{File, OpenOptions};
use std::io::prelude::*;
use std::io::{BufReader, Write as BufWrite};
use std::path::{Path, PathBuf};
use anyhow::{bail, Context, Result};
use cursive::align::Align;
use cursive::event::EventResult;
use cursive::theme::BaseColor;
use cursive::theme::Color;
use cursive::theme::Color::*;
use cursive::theme::Effect;
use cursive::theme::PaletteColor::*;
use cursive::theme::Style;
use cursive::utils::markup::StyledString;
use cursive::view::{Resizable, SizeConstraint};
use cursive::views::{
LinearLayout, OnEventView, Panel, ResizedView, ScrollView, SelectView, TextContent, TextView,
};
use cursive::CursiveRunnable;
use cursive_tree_view::*;
use walkdir::WalkDir;
use libcasr::report::CrashReport;
use libcasr::sarif::SarifReport;
use casr::util::report_from_file;
fn main() -> Result<()> {
let matches = clap::Command::new("casr-cli")
.version(clap::crate_version!())
.about("App provides text-based user interface to view CASR reports, prints joint statistics for all reports, and converts CASR reports to SARIF format.")
.term_width(90)
.arg(
Arg::new("view")
.long("view")
.short('v')
.action(ArgAction::Set)
.value_name("MODE")
.default_value("tree")
.help("View mode")
.value_parser(["tree", "slider", "stdout"]),
)
.arg(
Arg::new("target")
.action(ArgAction::Set)
.required(true)
.value_name("REPORT|DIR")
.value_parser(clap::value_parser!(PathBuf))
.help("CASR report file to view or directory with reports"),
)
.arg(
Arg::new("unique")
.long("unique")
.action(ArgAction::SetTrue)
.short('u')
.help("Print only unique crash lines in joint statistics"),
)
.arg(
Arg::new("sarif")
.long("sarif")
.requires("source-root")
.value_name("OUTPUT")
.value_parser(clap::value_parser!(PathBuf))
.action(ArgAction::Set)
.help("Generate SARIF report from CASR reports"),
)
.arg(
Arg::new("source-root")
.long("source-root")
.requires("sarif")
.value_name("PATH")
.action(ArgAction::Set)
.help("Source root path in CASR reports for SARIF report generation"),
)
.arg(
Arg::new("tool")
.long("tool")
.requires("sarif")
.value_name("NAME")
.default_value("CASR")
.action(ArgAction::Set)
.help("Tool name that detected crashes/errors for SARIF report"),
)
.arg(
Arg::new("strip-path")
.long("strip-path")
.env("CASR_STRIP_PATH")
.action(ArgAction::Set)
.value_name("PREFIX")
.help("Path prefix to strip from crash path in joint report statistics"),
)
.get_matches();
let report_path = matches.get_one::<PathBuf>("target").unwrap();
if let Some(sarif_report) = matches.get_one::<PathBuf>("sarif") {
let report = sarif(
report_path,
matches.get_one::<String>("source-root").unwrap(),
matches.get_one::<String>("tool").unwrap(),
)?;
if let Ok(mut file) = OpenOptions::new()
.create(true)
.truncate(true)
.write(true)
.open(sarif_report)
{
file.write_all(
serde_json::to_string_pretty(&report.json)
.unwrap()
.as_bytes(),
)
.with_context(|| format!("Couldn't write data to file `{}`", sarif_report.display()))?;
} else {
bail!("Couldn't save report to file: {}", sarif_report.display());
}
return Ok(());
}
if report_path.is_dir() {
print_summary(
report_path,
matches.get_flag("unique"),
matches.get_one::<String>("strip-path"),
);
return Ok(());
}
let mut file = File::open(report_path)
.with_context(|| format!("Couldn't open report file: {}", &report_path.display()))?;
let mut report_string = String::new();
file.read_to_string(&mut report_string)
.with_context(|| format!("Couldn't read report file: {}", &report_path.display()))?;
let report: CrashReport = serde_json::from_str(&report_string)
.with_context(|| format!("Couldn't deserialize report: {}", &report_path.display()))?;
let mut header_string = StyledString::plain("Crash Report for ");
header_string.append(StyledString::styled(
&report.executable_path,
Style::from(Color::Light(BaseColor::Blue)),
));
if !report.package.is_empty() && !report.package_version.is_empty() {
header_string.append(format!(
" from {} {}",
report.package, report.package_version
));
}
let severity_type_string = format!(
"{}: {}",
report.execution_class.severity, report.execution_class.short_description
);
let styled_severity_string = match severity_type_string.as_str() {
"CRITICAL" => StyledString::styled(
severity_type_string,
Style::from(Color::Light(BaseColor::Red)).combine(Effect::Bold),
),
"POSSIBLE_CRITICAL" => StyledString::styled(
severity_type_string,
Style::from(Color::Light(BaseColor::Yellow)).combine(Effect::Bold),
),
_ => StyledString::styled(
severity_type_string,
Style::from(Color::Light(BaseColor::Green)).combine(Effect::Bold),
),
};
// Initialize terminal.
let mut theme = cursive::theme::load_default();
theme.palette[Background] = TerminalDefault;
theme.palette[View] = TerminalDefault;
theme.palette[Primary] = TerminalDefault;
let mut siv = cursive::default();
siv.set_theme(theme);
let header_content = TextContent::new(header_string);
header_content.append("\nSeverity: ");
header_content.append(styled_severity_string);
let header = Panel::new(TextView::new_with_content(header_content.clone()));
let footer = TextView::new("Press q to exit").align(Align::bot_right());
let view = matches.get_one::<String>("view").unwrap();
match view.as_str() {
"tree" => build_tree_report(&mut siv, header, footer, &report),
"slider" => build_slider_report(&mut siv, header, footer, &report),
_ => println!(
"{}\n{}",
&mut String::from(header_content.get_content().source()),
report
),
}
Ok(())
}
/// Create tree view for casr report
///
/// # Arguments
///
/// * 'siv' - main view
///
/// * 'header' - header
///
/// * 'footer' - footer
///
/// * 'report' - casr report
fn build_tree_report(
siv: &mut CursiveRunnable,
mut header: Panel<TextView>,
footer: TextView,
report: &CrashReport,
) {
let mut layout = LinearLayout::vertical();
// Add report to tree.
let mut tree = TreeView::new();
let mut row: usize = 0;
if !report.date.is_empty() {
tree.insert_item("Date".to_string(), Placement::Parent, row)
.unwrap();
tree.insert_item(report.date.clone(), Placement::LastChild, row)
.unwrap();
tree.collapse_item(row);
}
if !report.uname.is_empty() {
row = tree
.insert_item("Uname".to_string(), Placement::After, row)
.unwrap();
tree.insert_item(report.uname.clone(), Placement::LastChild, row)
.unwrap();
tree.collapse_item(row);
}
if !report.os.is_empty() {
row = tree
.insert_item("OS".to_string(), Placement::After, row)
.unwrap();
tree.insert_item(report.os.clone(), Placement::LastChild, row)
.unwrap();
}
if !report.os_release.is_empty() {
row = tree
.insert_item("OSRelease".to_string(), Placement::After, row)
.unwrap();
tree.insert_item(report.os_release.clone(), Placement::LastChild, row)
.unwrap();
}
if !report.architecture.is_empty() {
row = tree
.insert_item("Architecture".to_string(), Placement::After, row)
.unwrap();
tree.insert_item(report.architecture.clone(), Placement::LastChild, row)
.unwrap();
tree.collapse_item(row);
}
if !report.executable_path.is_empty() {
row = tree
.insert_item("ExecutablePath".to_string(), Placement::After, row)
.unwrap();
tree.insert_item(report.executable_path.clone(), Placement::LastChild, row)
.unwrap();
tree.collapse_item(row);
}
if !report.proc_cmdline.is_empty() {
row = tree
.insert_item("ProcCmdline".to_string(), Placement::After, row)
.unwrap();
tree.insert_item(report.proc_cmdline.clone(), Placement::LastChild, row)
.unwrap();
}
if !report.stdin.is_empty() {
row = tree
.insert_item("Stdin".to_string(), Placement::After, row)
.unwrap();
tree.insert_item(report.stdin.clone(), Placement::LastChild, row)
.unwrap();
}
if !report.proc_fd.is_empty() {
row = tree
.insert_item("ProcFiles".to_string(), Placement::After, row)
.unwrap();
report.proc_fd.iter().for_each(|file| {
tree.insert_item(file.clone(), Placement::LastChild, row);
});
}
if !report.network_connections.is_empty() {
row = tree
.insert_item("NetworkConnections".to_string(), Placement::After, row)
.unwrap();
report.network_connections.iter().for_each(|connection| {
tree.insert_item(connection.clone(), Placement::LastChild, row);
});
}
row = tree
.insert_item("CrashSeverity".to_string(), Placement::After, row)
.unwrap();
tree.insert_item(
report.execution_class.severity.to_string(),
Placement::LastChild,
row,
);
tree.insert_item(
report.execution_class.short_description.to_string(),
Placement::LastChild,
row,
);
tree.insert_item(
report.execution_class.description.to_string(),
Placement::LastChild,
row,
);
if !report.execution_class.explanation.is_empty() {
tree.insert_item(
report.execution_class.explanation.to_string(),
Placement::LastChild,
row,
);
}
if !report.proc_maps.is_empty() {
row = tree
.insert_container_item("ProcMaps".to_string(), Placement::After, row)
.unwrap();
report.proc_maps.iter().for_each(|line| {
tree.insert_item(line.clone(), Placement::LastChild, row);
});
tree.collapse_item(row);
}
if !report.proc_environ.is_empty() {
row = tree
.insert_container_item("ProcEnviron".to_string(), Placement::After, row)
.unwrap();
report
.proc_environ
.iter()
.filter(|e| !e.contains("LS_COLORS"))
.for_each(|line| {
tree.insert_item(line.clone(), Placement::LastChild, row);
});
tree.collapse_item(row);
}
if !report.proc_status.is_empty() {
row = tree
.insert_container_item("ProcStatus".to_string(), Placement::After, row)
.unwrap();
report.proc_status.iter().for_each(|line| {
tree.insert_item(line.clone(), Placement::LastChild, row);
});
tree.collapse_item(row);
}
if !report.registers.is_empty() || !report.disassembly.is_empty() {
row = tree
.insert_container_item("CrashState".to_string(), Placement::After, row)
.unwrap();
report.registers.iter().for_each(|(k, v)| {
tree.insert_item(format!("{k}: 0x{v:x}"), Placement::LastChild, row);
});
if !report.disassembly.is_empty() && !report.registers.is_empty() {
tree.insert_item("".to_string(), Placement::LastChild, row);
}
for line in report.disassembly.iter() {
tree.insert_item(line.replace('\t', " "), Placement::LastChild, row);
}
}
if !report.stacktrace.is_empty() {
row = tree
.insert_container_item("Stacktrace".to_string(), Placement::After, row)
.unwrap();
report.stacktrace.iter().for_each(|e| {
tree.insert_item(e.clone(), Placement::LastChild, row);
});
tree.expand_item(row);
}
if !report.asan_report.is_empty() {
row = tree
.insert_container_item("AsanReport".to_string(), Placement::After, row)
.unwrap();
report.asan_report.iter().for_each(|e| {
tree.insert_item(e.clone(), Placement::LastChild, row);
});
tree.expand_item(row);
}
if !report.ubsan_report.is_empty() {
row = tree
.insert_container_item("UbsanReport".to_string(), Placement::After, row)
.unwrap();
report.ubsan_report.iter().for_each(|e| {
tree.insert_item(e.clone(), Placement::LastChild, row);
});
tree.expand_item(row);
}
if !report.python_report.is_empty() {
row = tree
.insert_container_item("PythonReport".to_string(), Placement::After, row)
.unwrap();
report.python_report.iter().for_each(|e| {
tree.insert_item(e.clone(), Placement::LastChild, row);
});
tree.collapse_item(row);
}
if !report.lua_report.is_empty() {
row = tree
.insert_container_item("LuaReport".to_string(), Placement::After, row)
.unwrap();
report.lua_report.iter().for_each(|e| {
tree.insert_item(e.clone(), Placement::LastChild, row);
});
tree.collapse_item(row);
}
if !report.java_report.is_empty() {
row = tree
.insert_container_item("JavaReport".to_string(), Placement::After, row)
.unwrap();
report.java_report.iter().for_each(|e| {
tree.insert_item(e.clone(), Placement::LastChild, row);
});
tree.collapse_item(row);
}
if !report.go_report.is_empty() {
row = tree
.insert_container_item("GoReport".to_string(), Placement::After, row)
.unwrap();
report.go_report.iter().for_each(|e| {
tree.insert_item(e.clone(), Placement::LastChild, row);
});
tree.collapse_item(row);
}
if !report.rust_report.is_empty() {
row = tree
.insert_container_item("RustReport".to_string(), Placement::After, row)
.unwrap();
report.rust_report.iter().for_each(|e| {
tree.insert_item(e.clone(), Placement::LastChild, row);
});
tree.collapse_item(row);
}
if !report.js_report.is_empty() {
row = tree
.insert_container_item("JsReport".to_string(), Placement::After, row)
.unwrap();
report.js_report.iter().for_each(|e| {
tree.insert_item(e.clone(), Placement::LastChild, row);
});
tree.collapse_item(row);
}
if !report.csharp_report.is_empty() {
row = tree
.insert_container_item("CSharpReport".to_string(), Placement::After, row)
.unwrap();
report.csharp_report.iter().for_each(|e| {
tree.insert_item(e.clone(), Placement::LastChild, row);
});
tree.collapse_item(row);
}
if !report.source.is_empty() {
row = tree
.insert_container_item("Source".to_string(), Placement::After, row)
.unwrap();
report.source.iter().for_each(|e| {
tree.insert_item(e.clone(), Placement::LastChild, row);
});
tree.expand_item(row);
}
if !report.package.is_empty() {
row = tree
.insert_container_item("Package".to_string(), Placement::After, row)
.unwrap();
tree.insert_item(report.package.clone(), Placement::LastChild, row);
}
if !report.package_version.is_empty() {
row = tree
.insert_container_item("PackageVersion".to_string(), Placement::After, row)
.unwrap();
tree.insert_item(report.package_version.clone(), Placement::LastChild, row);
}
if !report.package_description.is_empty() {
row = tree
.insert_item("PackageDescription".to_string(), Placement::After, row)
.unwrap();
tree.insert_item(
report.package_description.clone(),
Placement::LastChild,
row,
)
.unwrap();
tree.collapse_item(row);
}
if !report.crashline.is_empty() {
let textcontent = header.get_inner_mut().get_shared_content();
textcontent.append(format!("\nCrash line: {}", &report.crashline));
}
let scroll = ScrollView::new(tree).scroll_x(true);
layout.add_child(header);
layout.add_child(scroll);
layout.add_child(footer);
siv.add_fullscreen_layer(layout);
siv.add_global_callback('q', |s| s.quit());
siv.run();
}
/// Creates slider view for casr report
///
/// # Arguments
///
/// * 'siv' - main view
///
/// * 'header' - header
///
/// * 'footer' - footer
///
/// * 'report' - casr report
fn build_slider_report(
siv: &mut CursiveRunnable,
mut header: Panel<TextView>,
footer: TextView,
report: &CrashReport,
) {
let mut select = SelectView::new();
if !report.date.is_empty() {
select.add_item("Date", report.date.clone());
}
if !report.uname.is_empty() {
select.add_item("Uname", report.uname.clone());
}
if !report.os.is_empty() {
select.add_item("OS", report.os.clone());
}
if !report.os_release.is_empty() {
select.add_item("OSRelease", report.os_release.clone());
}
if !report.architecture.is_empty() {
select.add_item("Architecture", report.architecture.clone());
}
if !report.executable_path.is_empty() {
select.add_item("ExecutablePath", report.executable_path.clone());
}
if !report.proc_cmdline.is_empty() {
select.add_item("ProcCmdline", report.proc_cmdline.clone());
}
if !report.stdin.is_empty() {
select.add_item("Stdin", report.stdin.clone());
}
if !report.proc_fd.is_empty() {
select.add_item("ProcFiles", report.proc_fd.join("\n"));
}
if !report.network_connections.is_empty() {
select.add_item("NetworkConnections", report.network_connections.join("\n"));
}
let explanation = if !report.execution_class.explanation.is_empty() {
format!("{}\n", report.execution_class.explanation)
} else {
"".to_string()
};
select.add_item(
"CrashSeverity",
format!(
"{}\n{}\n{}\n{}",
report.execution_class.severity,
report.execution_class.short_description,
report.execution_class.description,
explanation
),
);
if !report.proc_maps.is_empty() {
select.add_item("ProcMaps", report.proc_maps.join("\n"));
}
if !report.proc_environ.is_empty() {
select.add_item("ProcEnviron", report.proc_environ.join("\n"));
}
if !report.proc_status.is_empty() {
select.add_item("ProcStatus", report.proc_status.join("\n"));
}
let mut state = report
.registers
.iter()
.fold(String::new(), |mut output, (k, v)| {
let _ = writeln!(output, "{k}: 0x{v:x}");
output
});
if !report.disassembly.is_empty() {
state.push_str(&format!(
"\n{}",
&report.disassembly.join("\n").replace('\t', " ")
));
}
if !state.is_empty() {
select.add_item("CrashState", state);
}
if !report.stacktrace.is_empty() {
select.add_item("Stacktrace", report.stacktrace.join("\n"));
}
if !report.asan_report.is_empty() {
select.add_item("AsanReport", report.asan_report.join("\n"));
}
if !report.ubsan_report.is_empty() {
select.add_item("UbsanReport", report.ubsan_report.join("\n"));
}
if !report.python_report.is_empty() {
select.add_item("PythonReport", report.python_report.join("\n"));
}
if !report.lua_report.is_empty() {
select.add_item("LuaReport", report.lua_report.join("\n"));
}
if !report.java_report.is_empty() {
select.add_item("JavaReport", report.java_report.join("\n"));
}
if !report.go_report.is_empty() {
select.add_item("GoReport", report.go_report.join("\n"));
}
if !report.rust_report.is_empty() {
select.add_item("RustReport", report.rust_report.join("\n"));
}
if !report.js_report.is_empty() {
select.add_item("JsReport", report.js_report.join("\n"));
}
if !report.csharp_report.is_empty() {
select.add_item("CSharpReport", report.csharp_report.join("\n"));
}
if !report.source.is_empty() {
select.add_item("Source", report.source.join("\n"));
}
if !report.package.is_empty() {
select.add_item("Package", report.package.clone());
}
if !report.package_version.is_empty() {
select.add_item("PackageVersion", report.package_version.clone());
}
if !report.package_description.is_empty() {
select.add_item("PackageDescription", report.package_description.clone());
}
if !report.crashline.is_empty() {
let textcontent = header.get_inner_mut().get_shared_content();
textcontent.append(format!("\nCrash line: {}", &report.crashline));
}
let scroll = ScrollView::new(select.fixed_width(20));
let content = ResizedView::new(
SizeConstraint::Full,
SizeConstraint::Full,
TextView::new("".to_string()),
);
let hl = LinearLayout::horizontal()
.child(Panel::new(scroll))
.child(Panel::new(ScrollView::new(content)));
let layout = LinearLayout::vertical()
.child(header)
.child(hl)
.child(footer);
let layout = OnEventView::new(layout)
.on_pre_event_inner(
cursive::event::Key::Up,
|layout1: &mut LinearLayout, _e: &cursive::event::Event| {
change_text_view(layout1, Action::Arrow(1))
},
)
.on_pre_event_inner(
cursive::event::Key::Down,
|layout1: &mut LinearLayout, _e: &cursive::event::Event| {
change_text_view(layout1, Action::Arrow(0))
},
)
.on_pre_event_inner(
EventTrigger::mouse(),
|layout1: &mut LinearLayout, e: &cursive::event::Event| {
if let &cursive::event::Event::Mouse {
event: cursive::event::MouseEvent::Release(_),
..
} = e
{
change_text_view(layout1, Action::Mouse(e.clone()))
} else {
None
}
},
);
siv.add_global_callback('q', |s| s.quit());
siv.add_fullscreen_layer(layout);
siv.on_event(cursive::event::Event::Key(cursive::event::Key::Up));
siv.run();
}
enum Action {
Arrow(i32),
Mouse(cursive::event::Event),
}
/// Function changes the Text view according to the selected item
///
/// # Arguments
///
/// * 'layout1' - main linear layout
///
/// * 'act' - change direction(up/down) or mouse click
///
fn change_text_view(layout1: &mut LinearLayout, act: Action) -> Option<EventResult> {
let layout2 = (*layout1.get_child_mut(1).unwrap())
.downcast_mut::<LinearLayout>()
.unwrap();
if layout2.get_focus_index() == 1 {
return None;
}
let select = layout2
.get_child_mut(0)
.unwrap()
.downcast_mut::<Panel<ScrollView<ResizedView<SelectView>>>>()
.unwrap()
.get_inner_mut()
.get_inner_mut()
.get_inner_mut();
match act {
Action::Arrow(arrow) => {
if arrow == 1 {
select.select_up(1);
} else {
select.select_down(1);
}
}
Action::Mouse(ref e) => {
select.on_event(e.clone());
}
};
let totxt = String::from(select.get_item(select.selected_id().unwrap()).unwrap().1);
let text = layout2
.get_child_mut(1)
.unwrap()
.downcast_mut::<Panel<ScrollView<ResizedView<TextView>>>>()
.unwrap()
.get_inner_mut()
.get_inner_mut()
.get_inner_mut();
*text = TextView::new(totxt);
match act {
Action::Arrow(_) => Some(EventResult::with_cb(|_s| {})),
Action::Mouse(_) => None,
}
}
/// Print common statistic all over reports in directory
///
/// # Arguments
///
/// * 'dir' - directory with reports
///
/// * 'unique_crash_line' - print summary only for unique crash lines
///
/// * 'strip_path' - strip prefix from crash paths
///
fn print_summary(dir: &Path, unique_crash_line: bool, strip_path: Option<&String>) {
// Hash each class in whole casr directory
let mut casr_classes: BTreeMap<String, i32> = BTreeMap::new();
// Unique crash lines hash
let mut crash_lines: HashSet<String> = HashSet::new();
// Line and column regex
let line_column = Regex::new(r"\d+:\d+$").unwrap();
// Return true when crash should be omitted in summary because it has
// non-unique crash line
let mut skip_crash = |line: &str| {
if !unique_crash_line || line.is_empty() {
return false;
}
let l = if line_column.is_match(line) {
line.rsplit_once(':').unwrap().0
} else {
line
};
!crash_lines.insert(l.to_string())
};
let mut corrupted_reports = Vec::new();
let mut clusters: Vec<(PathBuf, i32)> = Vec::new();
for cl_path in fs::read_dir(dir).unwrap().flatten() {
let cluster = cl_path.path();
let filename = cluster.file_name().unwrap().to_str().unwrap();
// check dir name
if !filename.starts_with("cl") || !cluster.is_dir() || filename.starts_with("clerr") {
continue;
} else {
clusters.push((cluster.to_path_buf(), filename[2..].parse::<i32>().unwrap()));
}
}
clusters.sort_by(|a, b| a.1.cmp(&b.1));
if clusters.is_empty()
&& fs::read_dir(dir)
.unwrap()
.filter(|res| res.is_ok())
.map(|res| res.unwrap().path())
.any(|e| e.extension().is_some() && e.extension().unwrap() == "casrep")
{
// Try to canonocalize directory path to avoid paths with empty file_name.
if let Ok(canon_dir) = dir.canonicalize() {
clusters.push((canon_dir.to_path_buf(), 0));
} else {
clusters.push((dir.to_path_buf(), 0));
}
}
for (clpath, _) in clusters {
let cluster = clpath.as_path();
// file_name may be empty if path ends with '.', '..', or '/'.
// Take the whole path as filename then.
let filename = if let Some(cl_filename) = cluster.file_name() {
cl_filename.to_str().unwrap()
} else {
cluster.to_str().unwrap()
};
// Ubsan indicator for minimize logging
let mut ubsan = true;
// Hash each crash in cluster
let mut cluster_hash: BTreeMap<String, (Vec<String>, i32)> = BTreeMap::new();
// Hash each class in cluster
let mut cluster_classes: BTreeMap<String, i32> = BTreeMap::new();
// Hash files
let mut filestems: HashSet<PathBuf> = HashSet::new();
for report in WalkDir::new(cluster)
.max_depth(1)
.sort_by_file_name()
.into_iter()
.filter_map(|file| file.ok())
.filter(|file| file.metadata().unwrap().is_file())
.map(|file| file.path().to_path_buf())
.filter(|file| file.extension().is_some())
.filter(|file| file.extension().unwrap() == "casrep")
{
// report == .*/crash.gdb.casrep
let mut input = report.canonicalize().unwrap().with_extension("");
// input == .*/crash.gdb
if input.extension().is_some() && input.extension().unwrap() == "gdb" {
input.set_extension("");
}
// input == .*/crash
if !filestems.insert(input.clone()) {
continue;
}
let mut result: Vec<String> = Vec::new();
let crash = if input.exists() {
input.clone()
} else {
report
}
.to_str()
.unwrap()
.to_string();
let mut report = input.to_str().unwrap().to_string();
report.push_str(".casrep");
let (san_desc, san_line) = if let Some((report_sum, san_desc, san_line, ubsan_flag)) =
process_report(&report, "casrep", strip_path)
{
if !ubsan_flag {
ubsan = false;
}
if skip_crash(&san_line) {
continue;
}
result.push(report_sum);
(san_desc, san_line)
} else {
(String::new(), String::new())
};
let report = report.replace(".casrep", ".gdb.casrep");
let (casr_gdb_desc, casr_gdb_line) =
if let Some((report_sum, casr_gdb_desc, casr_gdb_line, _)) =
process_report(&report, "gdb.casrep", strip_path)
{
ubsan = false;
if san_line.is_empty() && skip_crash(&casr_gdb_line) {
continue;
}
result.push(report_sum);
(casr_gdb_desc, casr_gdb_line)
} else {
(String::new(), String::new())
};
if result.is_empty() {
corrupted_reports.push(format!("Cannot read casrep: {report}"));
continue;
} else {
result.push(crash);
}
let mut hash = String::new();
hash.push_str(san_desc.as_str());
hash.push_str(san_line.as_str());
hash.push_str(casr_gdb_desc.as_str());
hash.push_str(casr_gdb_line.as_str());
if !san_desc.is_empty() {
let san_cnt = cluster_classes.get(&san_desc).unwrap_or(&0) + 1;
cluster_classes.insert(san_desc, san_cnt);
}
if !casr_gdb_desc.is_empty() {
let casr_gdb_cnt = cluster_classes.get(&casr_gdb_desc).unwrap_or(&0) + 1;
cluster_classes.insert(casr_gdb_desc, casr_gdb_cnt);
}
let value = if let Some(res) = cluster_hash.get(&hash) {
(res.0.clone(), res.1 + 1)
} else {
(result, 1)
};
cluster_hash.insert(hash, value);
}
if cluster_hash.is_empty() {
continue;
}
println!("==> <{}>", filename.magenta());
for info in cluster_hash.values() {
let mut path = info.0.last().unwrap().clone();
if let Some(prefix) = strip_path {