Skip to content
suit Artifact [f83f799465]
Login

Artifact [f83f799465]

Artifact f83f799465175c7c855eb85facf2f11a4a995af50889732723ea580f22cb242d:


#!/usr/bin/env python3
"""Fold a fuzz target's minimized corpus into test/corpus/TARGET.

usage: corpus.py TARGET MERGED_DIR CORPUS_DIR

MERGED_DIR holds what libFuzzer's merge mode kept: the smallest set of inputs
that reaches everything the grown corpus and the seeds reach. The hand-written
seeds in CORPUS_DIR stay. Earlier grown-* files are replaced by the merged
inputs that are not already a seed, smallest first, until the target holds
300 files or 1 MiB, whichever comes first.
"""
import hashlib
import os
import sys

MAX_FILES = 300
MAX_BYTES = 1 << 20


def read(path):
    with open(path, "rb") as f:
        return f.read()


def main():
    target, merged, corpus = sys.argv[1:4]
    for name in os.listdir(corpus):
        if name.startswith("grown-"):
            os.remove(os.path.join(corpus, name))
    seeds = {name: read(os.path.join(corpus, name)) for name in os.listdir(corpus)}
    seed_bodies = set(seeds.values())
    files = len(seeds)
    size = sum(len(b) for b in seeds.values())

    candidates = []
    for name in os.listdir(merged):
        body = read(os.path.join(merged, name))
        if body not in seed_bodies:
            candidates.append(body)
    candidates.sort(key=lambda b: (len(b), b))

    kept = 0
    for body in candidates:
        if files >= MAX_FILES or size + len(body) > MAX_BYTES:
            break
        name = "grown-" + hashlib.sha1(body).hexdigest()[:12]
        with open(os.path.join(corpus, name), "wb") as f:
            f.write(body)
        files += 1
        size += len(body)
        kept += 1
    print("corpus %s: %d seeds, %d merged inputs offered, %d kept; %d files, %d bytes in all"
          % (target, len(seeds), len(candidates), kept, files, size))


main()