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
//! LLVM SanitizerCoverage (`inline-8bit-counters`) for code edge coverage.
//!
//! This module hooks into LLVM's SanitizerCoverage instrumentation to track
//! which code edges the simulation actually executes. The explorer uses this
//! as a second coverage signal — alongside the assertion-path fork bitmap —
//! to decide whether a forked timeline discovered something new. Together,
//! the two signals make the adaptive loop significantly more precise at
//! distinguishing productive forks from barren ones.
//!
//! All public functions are no-ops when sancov instrumentation is not
//! present (i.e., `COUNTERS_PTR` is null).
//!
//! # Why two coverage systems?
//!
//! The explorer has two independent coverage tracking mechanisms:
//!
//! ```text
//! System Where it lives What it tracks
//! ──────────────────── ───────────────────── ─────────────────────────────────
//! Fork bitmap coverage.rs Which assert_sometimes! /
//! (8192 bits) assert_sometimes_each! fired.
//! Hash-based, high collision rate.
//!
//! Sancov edge coverage sancov.rs (this file) Which branches/loops/conditions
//! (one u8 per edge) in the Rust source were executed.
//! LLVM-instrumented, no collisions.
//! ```
//!
//! The fork bitmap answers "did we trigger a new assertion path?" while
//! sancov answers "did we execute new code?". Two timelines can trigger
//! the exact same assertions but take radically different code paths through
//! the system under test — sancov catches that.
//!
//! Both signals feed into the adaptive loop's `batch_has_new` flag in
//! [`split_loop`](crate::split_loop). A timeline is considered productive
//! if it contributes new bits to **either** system:
//!
//! ```text
//! batch_has_new |= fork_bitmap.has_new_bits() // assertion-level
//! batch_has_new |= has_new_sancov_coverage() // code-edge-level
//! ```
//!
//! # How LLVM inline-8bit-counters work
//!
//! When you compile with the right flags, LLVM inserts a `counter[edge_id]++`
//! instruction at every control-flow edge in the program. The counters live
//! in a BSS array (zero-initialized, process-global):
//!
//! ```text
//! rustc + LLVM passes
//! │
//! ▼
//! BSS counter array (one u8 per code edge)
//! │
//! ▼ __sanitizer_cov_8bit_counters_init(start, stop)
//! │ called during static constructors, before main()
//! │
//! ▼
//! COUNTERS_PTR + COUNTERS_LEN captured in global atomics
//! ```
//!
//! Multiple compilation units each call the init callback with their own
//! array bounds. We merge them via `min(start)` / `max(stop)` so a single
//! contiguous range covers all TUs. See [`__sanitizer_cov_8bit_counters_init`].
//!
//! # Selective instrumentation with `SANCOV_CRATES`
//!
//! You don't want to instrument *everything* — the simulation runtime,
//! exploration engine, and chaos framework have thousands of edges that
//! are irrelevant to the system under test. Instrumenting only the
//! application crate(s) keeps the edge count small and meaningful.
//!
//! The build pipeline:
//!
//! ```text
//! flake.nix
//! └── RUSTC_WRAPPER="$PWD/scripts/sancov-rustc.sh"
//!
//! sancov-rustc.sh intercepts every rustc invocation:
//! 1. Reads --crate-name from args
//! 2. Checks if crate is in SANCOV_CRATES (comma-separated whitelist)
//! 3. If yes → adds LLVM flags:
//! -Cpasses=sancov-module
//! -Cllvm-args=-sanitizer-coverage-level=3
//! -Cllvm-args=-sanitizer-coverage-inline-8bit-counters
//! -Ccodegen-units=1
//! 4. If no → pass-through (no instrumentation)
//! 5. Build scripts and proc-macros are never instrumented
//! ```
//!
//! When `SANCOV_CRATES` is unset or empty, the wrapper is a pure
//! pass-through and all functions in this module are no-ops.
//!
//! The `xtask` runner (`cargo xtask sim`) sets `SANCOV_CRATES` per binary
//! and builds into `target/sancov` to avoid cache conflicts with normal
//! (non-instrumented) builds.
//!
//! # The shared memory data flow
//!
//! The BSS counters are process-local — a forked child increments its own
//! copy, but the parent can't see them. Shared memory bridges the gap:
//!
//! ```text
//! CHILD process PARENT process
//! ───────────── ──────────────
//! BSS counters increment
//! during simulation
//! │
//! ▼ copy_counters_to_shared()
//! TRANSFER buffer ──── MAP_SHARED ────────── classify_counts()
//! (or pool slot) bucketed values
//! │
//! ▼ has_new_coverage_inner()
//! HISTORY map ── global max per edge
//! │
//! batch_has_new = true if any
//! bucketed > history[i]
//! ```
//!
//! Three shared memory regions:
//!
//! - **Transfer buffer** ([`SANCOV_TRANSFER`]): child writes raw counters
//! via [`copy_counters_to_shared`] before `_exit()`. In sequential mode,
//! one buffer is reused. In parallel mode, each concurrent child gets
//! its own pool slot instead.
//!
//! - **History map** (`SANCOV_HISTORY`): global maximum of bucketed values
//! per edge. Never reset within a seed. Preserved across seeds by
//! [`prepare_next_seed()`](crate::prepare_next_seed) (cumulative, like
//! the explored map).
//!
//! - **Pool** ([`SANCOV_POOL`]): parallel mode allocates
//! `slot_count × edge_count` bytes. Each concurrent child writes to its
//! own slot. Parent reads the slot after `waitpid()`. Allocated lazily
//! by [`get_or_init_sancov_pool`].
//!
//! # AFL-style bucketing
//!
//! Raw counter values are noisy — an edge hit 5 times vs 7 times is the
//! same execution pattern, but hit 1 time vs 5 times is meaningfully
//! different. The `COUNT_CLASS_LOOKUP` table maps raw counts to coarser
//! buckets, following AFL's proven approach:
//!
//! ```text
//! Raw count Bucket Meaning
//! ───────── ────── ─────────────────────
//! 0 0 not hit
//! 1 1 hit once
//! 2 2 hit twice
//! 3 4 hit a few times
//! 4–7 8 hit several times
//! 8–15 16 hit many times
//! 16–31 32 hit frequently
//! 32–127 64 hit very frequently
//! 128–255 128 hit extremely often
//! ```
//!
//! This means: an edge going from 5 hits to 7 hits (both bucket 8) is
//! not novel. But going from 1 hit to 5 hits (bucket 1 → bucket 8) *is*
//! novel — the code exercised that edge in a meaningfully different way.
//!
//! Bucketing is applied in-place by `classify_counts` before comparison.
//!
//! # Novelty detection
//!
//! `has_new_coverage_inner` is the core novelty check:
//!
//! 1. Apply AFL bucketing to the buffer in-place
//! 2. For each edge: if `bucketed > history[i]`, update history and mark novel
//! 3. Does **not** early-return — must update all history entries in one pass
//! (otherwise a novel edge in position 100 would cause edges 101+ to
//! be skipped, leaving stale history values)
//! 4. Zero entries (unvisited edges) are skipped
//!
//! The public API has two entry points:
//! - [`has_new_sancov_coverage`]: reads from the transfer buffer (sequential)
//! - [`has_new_sancov_coverage_from`]: reads from a specific pool slot (parallel)
//!
//! Novelty feeds into `batch_has_new` in [`split_loop`](crate::split_loop)
//! alongside the fork bitmap's
//! [`has_new_bits()`](crate::coverage::ExploredMap::has_new_bits).
//!
//! # Integration with the fork loop
//!
//! This module hooks into [`split_loop`](crate::split_loop) at five points:
//!
//! ```text
//! setup_child() After fork: reset_bss_counters() so child
//! captures only its OWN edges. Reset pool pointers
//! so nested splits allocate fresh pools.
//!
//! exit_child() Before _exit(): copy_counters_to_shared() so
//! the parent can read the child's coverage.
//!
//! Sequential reap After waitpid: has_new_sancov_coverage() checks
//! the transfer buffer for novelty.
//!
//! Parallel reap After waitpid: has_new_sancov_coverage_from(slot)
//! checks the child's pool slot for novelty.
//!
//! batch_has_new Both coverage signals are OR'd together:
//! batch_has_new |= sancov_novelty
//! A barren/productive decision uses BOTH signals.
//! ```
//!
//! # Why binary targets? (sancov requires `main()`)
//!
//! LLVM calls [`__sanitizer_cov_8bit_counters_init`] during static
//! constructors, before `main()`. In `cargo test`, the test harness is
//! `main()` — the counter array is initialized once for the harness, not
//! for each `#[test]` function. Worse, the BSS counters are process-global
//! state that accumulates across test functions, making per-test
//! measurement impossible. And `fork()` in a test harness interacts badly
//! with the harness's own process management.
//!
//! Solution: each simulation runs as a standalone `[[bin]]` target
//! managed by `cargo xtask sim`. The `xtask` sets `SANCOV_CRATES` per
//! binary and uses `--target-dir target/sancov` to separate instrumented
//! from non-instrumented builds.
//!
//! # Reporting
//!
//! Coverage stats flow through the reporting pipeline:
//!
//! - [`sancov_edge_count`] and [`sancov_edges_covered`] provide the raw numbers
//! - [`ExplorationStats`](crate::shared_stats::ExplorationStats) includes
//! `sancov_edges_total` and `sancov_edges_covered`
//! - `ExplorationReport` carries them to the `SimulationReport`
//! - The terminal display shows a "Code Cov" progress bar alongside
//! the "Exploration" (fork bitmap) progress bar
//! - Percentage = `edges_covered / edges_total`
//!
//! # Running code coverage
//!
//! ```bash
//! # Run all simulations with sancov:
//! cargo xtask sim run-all
//!
//! # Run a specific simulation:
//! cargo xtask sim run maze
//!
//! # List available binaries:
//! cargo xtask sim list
//!
//! # Instrument specific crates manually:
//! SANCOV_CRATES=moonpool_sim_examples cargo run \
//! --bin sim-maze-explore --target-dir target/sancov
//! ```
//!
//! # Lifecycle summary
//!
//! ```text
//! init_sancov_shared() allocate transfer + history in MAP_SHARED
//! │
//! ├── per-child:
//! │ reset_bss_counters() zero BSS array after fork
//! │ ... simulation runs ... BSS counters increment
//! │ copy_counters_to_shared() copy BSS → transfer/pool slot
//! │ exit_child() _exit()
//! │
//! ├── per-reap:
//! │ has_new_sancov_coverage() bucket + compare against history
//! │
//! ├── prepare_next_seed():
//! │ clear_transfer_buffer() zero transfer buffer
//! │ reset_bss_counters() zero BSS array
//! │ (history preserved) cumulative across seeds
//! │
//! └── cleanup_sancov_shared() free transfer + history + pool
//! ```
use Cell;
use ;
// ---------------------------------------------------------------------------
// Global statics — set during static init, before main()
// ---------------------------------------------------------------------------
/// Pointer to the LLVM-generated BSS counter array.
///
/// Set by [`__sanitizer_cov_8bit_counters_init`] during static
/// constructors. Remains null if sancov is not enabled.
static COUNTERS_PTR: = new;
/// Number of edges (counters) in the instrumented binary.
static COUNTERS_LEN: AtomicUsize = new;
// ---------------------------------------------------------------------------
// Thread-local state — set during init() from main()
// ---------------------------------------------------------------------------
thread_local!
// ---------------------------------------------------------------------------
// LLVM callbacks
// ---------------------------------------------------------------------------
/// Called by LLVM during static initialization for each compilation unit.
///
/// Merges ranges via min(start)/max(stop) so multiple TUs are handled.
///
/// # Safety
///
/// `start` and `stop` must point to valid memory. `stop` must be ≥ `start`.
/// This is only called by LLVM instrumentation infrastructure.
pub unsafe extern "C"
/// Called by LLVM for PC table initialization. Stub — we don't use PC info.
///
/// # Safety
///
/// Only called by LLVM instrumentation infrastructure.
pub unsafe extern "C"
// ---------------------------------------------------------------------------
// AFL bucketing
// ---------------------------------------------------------------------------
/// AFL-style hit-count bucketing table.
///
/// Maps raw edge counts to coarser buckets to reduce noise from
/// minor count variations. The mapping is:
/// - 0 → 0 (not hit)
/// - 1 → 1 (hit once)
/// - 2 → 2 (hit twice)
/// - 3 → 4
/// - 4..=7 → 8
/// - 8..=15 → 16
/// - 16..=31 → 32
/// - 32..=127 → 64
/// - 128..=255 → 128
const COUNT_CLASS_LOOKUP: = ;
/// Apply AFL bucketing to a buffer of edge counts in-place.
// ---------------------------------------------------------------------------
// Novelty detection
// ---------------------------------------------------------------------------
/// Check for novel coverage in a buffer against a history map.
///
/// Applies AFL bucketing to `buffer` in-place, then compares each
/// bucketed entry against `history`. If `bucketed > history[i]`,
/// updates history and marks novelty found.
///
/// Does NOT early-return: must update all history entries in one pass.
/// Skips zero entries (unvisited edges).
/// Check for novel sancov coverage in the transfer buffer (sequential path).
///
/// Returns `false` when sancov is unavailable.
/// Check for novel sancov coverage from a specific pool slot (parallel path).
///
/// Returns `false` when sancov is unavailable.
// ---------------------------------------------------------------------------
// Public query API
// ---------------------------------------------------------------------------
/// Check if LLVM sancov instrumentation is present.
///
/// Returns `true` when the binary was compiled with sancov and the
/// LLVM callback has registered the counter array.
/// Return the number of instrumented edges.
///
/// Returns 0 when sancov is unavailable.
/// Count non-zero entries in the history map (edges ever covered).
///
/// Returns 0 when sancov is unavailable or history is not initialized.
// ---------------------------------------------------------------------------
// Lifecycle
// ---------------------------------------------------------------------------
/// Initialize sancov shared memory buffers (transfer + history).
///
/// No-op when sancov instrumentation is not available.
///
/// # Errors
///
/// Returns an error if shared memory allocation fails.
/// Free sancov shared memory (transfer, history, and pool).
///
/// Nulls all pointers after freeing. No-op if not initialized.
/// Zero the transfer buffer before forking a child.
///
/// No-op when sancov is unavailable or transfer buffer is null.
// ---------------------------------------------------------------------------
// Child operations
// ---------------------------------------------------------------------------
/// Copy BSS counters to the shared transfer buffer.
///
/// Call in the child process before `_exit()` so the parent can
/// inspect coverage. No-op when sancov is unavailable.
/// Zero BSS counters after fork.
///
/// Call in the child process immediately after `fork()` so the child's
/// counters start from zero. No-op when sancov is unavailable.
// ---------------------------------------------------------------------------
// Parallel pool
// ---------------------------------------------------------------------------
/// Get or initialize the sancov pool for parallel exploration.
///
/// Returns the pool base pointer. Reuses the existing pool if it has
/// enough slots; otherwise frees and reallocates.
/// Returns null if sancov is unavailable or allocation fails.
/// Return a pointer to slot `idx` within the sancov pool.
///
/// # Safety
///
/// Caller must ensure `idx < slot_count` and `pool_base` was returned
/// by [`get_or_init_sancov_pool`].
pub unsafe
// ---------------------------------------------------------------------------
// Tests
// ---------------------------------------------------------------------------