#!/bin/bash
# #6 覆盖-时间曲线:等 #4 跑完(共用 afl-fuzz,不能并行),再 afl-parallel libarchive 3600s,
# 读 fuzzer01/plot_data 取 {60,120,300,900,3600}s 的边覆盖,回答"300s 是否饱和"。
set -u
cd /home/ubuntu/code/symcc
LAVA_OUT=/tmp/claude-1000/-home-ubuntu-code-symcc/ba111467-440e-48b7-88eb-2622f7533f6f/scratchpad/lava_bugs.out
echo "[curve] 等待 #4(LAVA bug 计数)完成..."
until grep -qa "LAVABUGS_DONE" "$LAVA_OUT" 2>/dev/null; do sleep 20; done
echo "[curve] #4 完成,清残留 afl 后启动曲线"
pkill -9 -x afl-fuzz 2>/dev/null; sleep 4

OUT=/tmp/curve; rm -rf "$OUT"; mkdir -p "$OUT/afl_out"
BIN=$(realpath benchmark/public/bin/libarchive-afl/archive_fuzzer)   # shmem-persistent,无 @@
SEEDS=$(realpath benchmark/public/seeds/libarchive/archive_fuzzer)
export AFL_NO_UI=1 AFL_SKIP_CPUFREQ=1 AFL_I_DONT_CARE_ABOUT_MISSING_CRASHES=1
echo "[curve] libarchive 8 并行 AFL,3600s,$(date +%H:%M:%S)"
afl-fuzz -M f01 -i "$SEEDS" -o "$OUT/afl_out" -m none -- "$BIN" >"$OUT/f01.log" 2>&1 &
for i in $(seq 2 8); do afl-fuzz -S "f0$i" -i "$SEEDS" -o "$OUT/afl_out" -m none -- "$BIN" >"$OUT/f0$i.log" 2>&1 & done
sleep 8; echo "  alive=$(pgrep -x afl-fuzz|wc -l)/8"
sleep 3600
pkill -9 -x afl-fuzz 2>/dev/null; sleep 3

echo "[curve] 解析 fuzzer01/plot_data 于 {60,120,300,900,3600}s"
python3 - "$OUT/afl_out/f01/plot_data" <<'PY'
import sys, csv
p=sys.argv[1]
rows=[]
try:
    for line in open(p):
        line=line.strip()
        if not line or line.startswith("#"): continue
        rows.append([x.strip() for x in line.split(",")])
except IOError:
    print("  无 plot_data"); sys.exit()
# AFL++ plot_data 列: relative_time, cycles, cur_item, corpus_count, pending_total, pending_favs,
#   map_size(%), saved_crashes, saved_hangs, max_depth, execs_per_sec, total_execs, edges_found
def col(r,i):
    try: return r[i]
    except: return ""
print(f"  plot_data 行数={len(rows)}, 末行时间={col(rows[-1],0) if rows else '?'}s")
targets=[60,120,300,900,3600]
print(f"  {'t(s)':>6}{'map_size%':>12}{'edges_found':>13}")
for t in targets:
    # 取 relative_time 最接近且<=t 的行
    best=None
    for r in rows:
        try: rt=float(r[0])
        except: continue
        if rt<=t: best=r
    if best:
        print(f"  {t:>6}{col(best,6):>12}{col(best,12):>13}")
    else:
        print(f"  {t:>6}{'(未到)':>12}")
print("  → 若 300→900→3600 仍在涨=未饱和;若 300 后基本持平=已饱和")
PY
echo "CURVE_DONE"
