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
pub mod multi;
pub use multi::MultiStats;
use serde::{Deserialize, Serialize};
use alloc::{string::String, vec::Vec};
use core::{fmt, time, time::Duration};
use hashbrown::HashMap;
#[cfg(feature = "introspection")]
use alloc::string::ToString;
#[cfg(feature = "introspection")]
use core::convert::TryInto;
use crate::bolts::current_time;
const CLIENT_STATS_TIME_WINDOW_SECS: u64 = 5;
#[derive(Serialize, Deserialize, Debug, Clone)]
pub enum UserStats {
Number(u64),
String(String),
Ratio(u64, u64),
}
impl fmt::Display for UserStats {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
UserStats::Number(n) => write!(f, "{}", n),
UserStats::String(s) => write!(f, "{}", s),
UserStats::Ratio(a, b) => {
if *b == 0 {
write!(f, "{}/{}", a, b)
} else {
write!(f, "{}/{} ({}%)", a, b, a * 100 / b)
}
}
}
}
}
#[derive(Debug, Clone, Default)]
pub struct ClientStats {
pub corpus_size: u64,
pub executions: u64,
pub objective_size: u64,
pub last_window_executions: u64,
pub last_window_time: time::Duration,
pub last_execs_per_sec: f32,
pub user_stats: HashMap<String, UserStats>,
#[cfg(feature = "introspection")]
pub introspection_stats: ClientPerfStats,
}
impl ClientStats {
pub fn update_executions(&mut self, executions: u64, cur_time: time::Duration) {
let diff = cur_time
.checked_sub(self.last_window_time)
.map_or(0, |d| d.as_secs());
if diff > CLIENT_STATS_TIME_WINDOW_SECS {
let _ = self.execs_per_sec(cur_time);
self.last_window_time = cur_time;
self.last_window_executions = self.executions;
}
self.executions = executions;
}
pub fn update_corpus_size(&mut self, corpus_size: u64) {
self.corpus_size = corpus_size;
}
pub fn update_objective_size(&mut self, objective_size: u64) {
self.objective_size = objective_size;
}
#[allow(clippy::cast_sign_loss, clippy::cast_precision_loss)]
pub fn execs_per_sec(&mut self, cur_time: time::Duration) -> u64 {
if self.executions == 0 {
return 0;
}
let elapsed = cur_time
.checked_sub(self.last_window_time)
.map_or(0, |d| d.as_secs());
if elapsed == 0 {
return self.last_execs_per_sec as u64;
}
let cur_avg = ((self.executions - self.last_window_executions) as f32) / (elapsed as f32);
if self.last_window_executions == 0 {
self.last_execs_per_sec = cur_avg;
return self.last_execs_per_sec as u64;
}
if cur_avg * 5.0 < self.last_execs_per_sec || cur_avg / 5.0 > self.last_execs_per_sec {
self.last_execs_per_sec = cur_avg;
}
self.last_execs_per_sec =
self.last_execs_per_sec * (1.0 - 1.0 / 16.0) + cur_avg * (1.0 / 16.0);
self.last_execs_per_sec as u64
}
pub fn update_user_stats(&mut self, name: String, value: UserStats) {
self.user_stats.insert(name, value);
}
pub fn get_user_stats(&mut self, name: &str) -> Option<&UserStats> {
self.user_stats.get(name)
}
#[cfg(feature = "introspection")]
pub fn update_introspection_stats(&mut self, introspection_stats: ClientPerfStats) {
self.introspection_stats = introspection_stats;
}
}
pub trait Stats {
fn client_stats_mut(&mut self) -> &mut Vec<ClientStats>;
fn client_stats(&self) -> &[ClientStats];
fn start_time(&mut self) -> time::Duration;
fn display(&mut self, event_msg: String, sender_id: u32);
fn corpus_size(&self) -> u64 {
self.client_stats()
.iter()
.fold(0_u64, |acc, x| acc + x.corpus_size)
}
fn objective_size(&self) -> u64 {
self.client_stats()
.iter()
.fold(0_u64, |acc, x| acc + x.objective_size)
}
#[inline]
fn total_execs(&mut self) -> u64 {
self.client_stats()
.iter()
.fold(0_u64, |acc, x| acc + x.executions)
}
#[inline]
fn execs_per_sec(&mut self) -> u64 {
let cur_time = current_time();
self.client_stats_mut()
.iter_mut()
.fold(0_u64, |acc, x| acc + x.execs_per_sec(cur_time))
}
fn client_stats_mut_for(&mut self, client_id: u32) -> &mut ClientStats {
let client_stat_count = self.client_stats().len();
for _ in client_stat_count..(client_id + 1) as usize {
self.client_stats_mut().push(ClientStats {
last_window_time: current_time(),
..ClientStats::default()
});
}
&mut self.client_stats_mut()[client_id as usize]
}
}
pub struct NopStats {
start_time: Duration,
client_stats: Vec<ClientStats>,
}
impl Stats for NopStats {
fn client_stats_mut(&mut self) -> &mut Vec<ClientStats> {
&mut self.client_stats
}
fn client_stats(&self) -> &[ClientStats] {
&self.client_stats
}
fn start_time(&mut self) -> time::Duration {
self.start_time
}
fn display(&mut self, _event_msg: String, _sender_id: u32) {}
}
impl NopStats {
#[must_use]
pub fn new() -> Self {
Self {
start_time: current_time(),
client_stats: vec![],
}
}
}
impl Default for NopStats {
fn default() -> Self {
Self::new()
}
}
#[derive(Clone, Debug)]
pub struct SimpleStats<F>
where
F: FnMut(String),
{
print_fn: F,
start_time: Duration,
corpus_size: usize,
client_stats: Vec<ClientStats>,
}
impl<F> Stats for SimpleStats<F>
where
F: FnMut(String),
{
fn client_stats_mut(&mut self) -> &mut Vec<ClientStats> {
&mut self.client_stats
}
fn client_stats(&self) -> &[ClientStats] {
&self.client_stats
}
fn start_time(&mut self) -> time::Duration {
self.start_time
}
fn display(&mut self, event_msg: String, sender_id: u32) {
let fmt = format!(
"[{} #{}] clients: {}, corpus: {}, objectives: {}, executions: {}, exec/sec: {}",
event_msg,
sender_id,
self.client_stats().len(),
self.corpus_size(),
self.objective_size(),
self.total_execs(),
self.execs_per_sec()
);
(self.print_fn)(fmt);
#[cfg(feature = "introspection")]
{
let fmt = format!(
"Client {:03}:\n{}",
sender_id, self.client_stats[sender_id as usize].introspection_stats
);
(self.print_fn)(fmt);
(self.print_fn)("".to_string());
}
}
}
impl<F> SimpleStats<F>
where
F: FnMut(String),
{
pub fn new(print_fn: F) -> Self {
Self {
print_fn,
start_time: current_time(),
corpus_size: 0,
client_stats: vec![],
}
}
pub fn with_time(print_fn: F, start_time: time::Duration) -> Self {
Self {
print_fn,
start_time,
corpus_size: 0,
client_stats: vec![],
}
}
}
#[macro_export]
macro_rules! start_timer {
($state:expr) => {{
#[cfg(feature = "introspection")]
$state.introspection_stats_mut().start_timer();
}};
}
#[macro_export]
macro_rules! mark_feature_time {
($state:expr, $feature:expr) => {{
#[cfg(feature = "introspection")]
$state.introspection_stats_mut().mark_feature_time($feature);
}};
}
#[macro_export]
macro_rules! mark_feedback_time {
($state:expr) => {{
#[cfg(feature = "introspection")]
$state.introspection_stats_mut().mark_feedback_time();
}};
}
#[derive(Serialize, Deserialize, Debug, Clone)]
pub struct ClientPerfStats {
start_time: u64,
current_time: u64,
scheduler: u64,
manager: u64,
curr_stage: u8,
stages_used: Vec<bool>,
stages: Vec<[u64; PerfFeature::Count as usize]>,
feedbacks: HashMap<String, u64>,
timer_start: Option<u64>,
}
#[derive(Serialize, Deserialize, Debug, Clone)]
#[repr(u8)]
pub enum PerfFeature {
GetInputFromCorpus = 0,
Mutate = 1,
MutatePostExec = 2,
TargetExecution = 3,
PreExec = 4,
PostExec = 5,
PreExecObservers = 6,
PostExecObservers = 7,
GetFeedbackInterestingAll = 8,
GetObjectivesInterestingAll = 9,
Count,
}
impl From<PerfFeature> for usize {
fn from(val: PerfFeature) -> usize {
match val {
PerfFeature::GetInputFromCorpus => PerfFeature::GetInputFromCorpus as usize,
PerfFeature::Mutate => PerfFeature::Mutate as usize,
PerfFeature::MutatePostExec => PerfFeature::MutatePostExec as usize,
PerfFeature::TargetExecution => PerfFeature::TargetExecution as usize,
PerfFeature::PreExec => PerfFeature::PreExec as usize,
PerfFeature::PostExec => PerfFeature::PostExec as usize,
PerfFeature::PreExecObservers => PerfFeature::PreExecObservers as usize,
PerfFeature::PostExecObservers => PerfFeature::PostExecObservers as usize,
PerfFeature::GetFeedbackInterestingAll => {
PerfFeature::GetFeedbackInterestingAll as usize
}
PerfFeature::GetObjectivesInterestingAll => {
PerfFeature::GetObjectivesInterestingAll as usize
}
PerfFeature::Count => PerfFeature::Count as usize,
}
}
}
impl From<usize> for PerfFeature {
fn from(val: usize) -> PerfFeature {
match val {
0 => PerfFeature::GetInputFromCorpus,
1 => PerfFeature::Mutate,
2 => PerfFeature::MutatePostExec,
3 => PerfFeature::TargetExecution,
4 => PerfFeature::PreExec,
5 => PerfFeature::PostExec,
6 => PerfFeature::PreExecObservers,
7 => PerfFeature::PostExecObservers,
8 => PerfFeature::GetFeedbackInterestingAll,
9 => PerfFeature::GetObjectivesInterestingAll,
_ => panic!("Unknown PerfFeature: {}", val),
}
}
}
#[cfg(feature = "introspection")]
pub const NUM_PERF_FEATURES: usize = PerfFeature::Count as usize;
#[cfg(feature = "introspection")]
impl ClientPerfStats {
#[must_use]
pub fn new() -> Self {
let start_time = crate::bolts::cpu::read_time_counter();
Self {
start_time,
current_time: start_time,
scheduler: 0,
manager: 0,
curr_stage: 0,
stages: vec![],
stages_used: vec![],
feedbacks: HashMap::new(),
timer_start: None,
}
}
#[inline]
pub fn set_current_time(&mut self, time: u64) {
self.current_time = time;
}
#[inline]
pub fn start_timer(&mut self) {
self.timer_start = Some(crate::bolts::cpu::read_time_counter());
}
pub fn update(&mut self, stats: &ClientPerfStats) {
self.set_current_time(stats.current_time);
self.update_scheduler(stats.scheduler);
self.update_manager(stats.manager);
self.update_stages(&stats.stages);
self.update_feedbacks(&stats.feedbacks);
}
#[inline]
fn mark_time(&mut self) -> u64 {
match self.timer_start {
None => {
#[cfg(feature = "std")]
eprint!("Attempted to `mark_time` without starting timer first.");
0
}
Some(timer_start) => {
let elapsed = crate::bolts::cpu::read_time_counter() - timer_start;
self.timer_start = None;
elapsed
}
}
}
#[inline]
pub fn mark_scheduler_time(&mut self) {
let elapsed = self.mark_time();
self.update_scheduler(elapsed);
}
#[inline]
pub fn mark_manager_time(&mut self) {
let elapsed = self.mark_time();
self.update_manager(elapsed);
}
#[inline]
pub fn mark_feature_time(&mut self, feature: PerfFeature) {
let elapsed = self.mark_time();
self.update_feature(feature, elapsed);
}
#[inline]
pub fn update_scheduler(&mut self, time: u64) {
self.scheduler = self
.scheduler
.checked_add(time)
.expect("update_scheduler overflow");
}
#[inline]
pub fn update_manager(&mut self, time: u64) {
self.manager = self
.manager
.checked_add(time)
.expect("update_manager overflow");
}
#[inline]
pub fn finish_stage(&mut self) {
self.curr_stage += 1;
}
#[inline]
pub fn reset_stage_index(&mut self) {
self.curr_stage = 0;
}
pub fn update_feedback(&mut self, name: &str, time: u64) {
self.feedbacks.insert(
name.into(),
self.feedbacks
.get(name)
.unwrap_or(&0)
.checked_add(time)
.expect("update_feedback overflow"),
);
}
pub fn update_feedbacks(&mut self, feedbacks: &HashMap<String, u64>) {
for (key, value) in feedbacks {
self.update_feedback(key, *value);
}
}
pub fn update_stages(&mut self, stages: &[[u64; PerfFeature::Count as usize]]) {
if self.stages.len() < stages.len() {
self.stages
.resize(stages.len(), [0; PerfFeature::Count as usize]);
self.stages_used.resize(stages.len(), false);
}
for (stage_index, features) in stages.iter().enumerate() {
for (feature_index, feature) in features.iter().enumerate() {
self.stages[stage_index][feature_index] = self.stages[stage_index][feature_index]
.checked_add(*feature)
.expect("Stage overflow");
}
}
}
pub fn update_feature(&mut self, feature: PerfFeature, time: u64) {
let stage_index: usize = self.curr_stage.try_into().unwrap();
let feature_index: usize = feature.try_into().unwrap();
if stage_index >= self.stages.len() {
self.stages
.resize(stage_index + 1, [0; PerfFeature::Count as usize]);
self.stages_used.resize(stage_index + 1, false);
}
self.stages[stage_index][feature_index] = self.stages[stage_index][feature_index]
.checked_add(time)
.expect("Stage overflow");
self.stages_used[stage_index] = true;
}
#[must_use]
pub fn elapsed_cycles(&self) -> u64 {
self.current_time - self.start_time
}
#[must_use]
pub fn manager_cycles(&self) -> u64 {
self.manager
}
#[must_use]
pub fn scheduler_cycles(&self) -> u64 {
self.scheduler
}
pub fn used_stages(
&self,
) -> impl Iterator<Item = (usize, &[u64; PerfFeature::Count as usize])> {
let used = self.stages_used.clone();
self.stages
.iter()
.enumerate()
.filter(move |(stage_index, _)| used[*stage_index as usize])
}
#[must_use]
pub fn feedbacks(&self) -> &HashMap<String, u64> {
&self.feedbacks
}
}
#[cfg(feature = "introspection")]
impl core::fmt::Display for ClientPerfStats {
#[allow(clippy::cast_precision_loss)]
fn fmt(&self, f: &mut core::fmt::Formatter) -> Result<(), core::fmt::Error> {
let elapsed: f64 = self.elapsed_cycles() as f64;
let scheduler_percent = self.scheduler as f64 / elapsed;
let manager_percent = self.manager as f64 / elapsed;
let mut other_percent = 1.0;
other_percent -= scheduler_percent;
other_percent -= manager_percent;
writeln!(
f,
" {:6.4}: Scheduler\n {:6.4}: Manager",
scheduler_percent, manager_percent
)?;
for (stage_index, features) in self.used_stages() {
writeln!(f, " Stage {}:", stage_index)?;
for (feature_index, feature) in features.iter().enumerate() {
let feature_percent = *feature as f64 / elapsed;
if feature_percent == 0.0 {
continue;
}
other_percent -= feature_percent;
let feature: PerfFeature = feature_index.into();
writeln!(f, " {:6.4}: {:?}", feature_percent, feature)?;
}
}
writeln!(f, " Feedbacks:")?;
for (feedback_name, feedback_time) in self.feedbacks() {
let feedback_percent = *feedback_time as f64 / elapsed;
if feedback_percent == 0.0 {
continue;
}
other_percent -= feedback_percent;
writeln!(f, " {:6.4}: {}", feedback_percent, feedback_name)?;
}
write!(f, " {:6.4}: Not Measured", other_percent)?;
Ok(())
}
}
#[cfg(feature = "introspection")]
impl Default for ClientPerfStats {
#[must_use]
fn default() -> Self {
Self::new()
}
}