/*
 * fuzz-acfg.c -- fuzzing harness for the ACFG parser, plus a standalone driver
 *                for toolchains that have the sanitizers but not libFuzzer.
 *
 * Chapter 70 -- Vulnerability Research, examples/
 *
 * PURPOSE
 *   Expose acfg_parse() to a byte-oriented fuzzer through the standard
 *   libFuzzer entry point, and give the same harness a way to run when
 *   libFuzzer is unavailable.
 *
 * USAGE
 *
 *   (a) With clang and libFuzzer -- the normal case:
 *         clang -g -O1 -fsanitize=fuzzer,address,undefined \
 *               fuzz-acfg.c acfg-vulnerable.c -o fuzz_acfg
 *         mkdir -p /tmp/corpus && ./fuzz_acfg /tmp/corpus -max_len=512
 *
 *   (b) With a toolchain that has ASan but NOT libFuzzer (gcc, and MSVC's
 *       ASan). Define ACFG_STANDALONE to get a main():
 *         gcc -g -O1 -fsanitize=address,undefined -DACFG_STANDALONE \
 *             fuzz-acfg.c acfg-vulnerable.c -o fuzz_acfg_standalone
 *
 *       Two modes:
 *         ./fuzz_acfg_standalone file1 file2 ...          # replay inputs
 *         ./fuzz_acfg_standalone -m 200000 42 seed.bin outdir  # mutate + run
 *
 *   Requirements: a C11 compiler with AddressSanitizer. libFuzzer is optional.
 *
 * WHAT THIS WILL NOT TELL YOU
 *   - It will not tell you the parser is safe. A fuzzing run that finds nothing
 *     is a statement about the fuzzer, the corpus and the clock, not about the
 *     code. Fuzzing is evidence of presence only.
 *   - The standalone mutator in mode (b) is NOT coverage-guided. It has no
 *     feedback, no corpus scheduling, no dictionary and no structure awareness.
 *     It finds a planted bug in a 76-byte format in seconds and would find
 *     essentially nothing in a real codec. Do not mistake it for a fuzzer;
 *     it is a demonstration of what libFuzzer's outer loop does, written out
 *     so you can see it. Section 7.4 explains exactly what coverage feedback
 *     adds and why the difference is many orders of magnitude, not a few
 *     percent.
 *   - It will not tell you whether a crash matters. That is triage, and it is
 *     a separate pass -- ../scripts/triage-asan.py and section 8.
 *
 * WHY THE HARNESS LOOKS LIKE THIS
 *   Three rules, all of which have cost real projects real time when broken:
 *
 *   1. NO GLOBAL STATE ACROSS CALLS. LLVMFuzzerTestOneInput is invoked
 *      millions of times in one process. Anything that persists between calls
 *      makes crashes depend on execution ORDER, which destroys
 *      reproducibility: the saved input replays clean and you conclude the
 *      crash was a fluke. Every allocation here is freed on every path.
 *
 *   2. NO OUTPUT PER ITERATION. A printf per execution costs more than the
 *      parse and drops throughput by orders of magnitude. Fuzzers are judged
 *      in executions per second.
 *
 *   3. NO ARTIFICIAL CRASHES. The harness must never abort() on input it
 *      merely dislikes; every such abort is a false finding that a human then
 *      has to triage. Rejecting a malformed blob is CORRECT parser behaviour
 *      and the harness treats every negative return code as success.
 */

#include "acfg.h"

#include <stdint.h>
#include <stddef.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

/* -------------------------------------------------------------------------
 * The fuzz target itself. This is the entire interface libFuzzer, AFL++ in
 * its libFuzzer-compatible mode, honggfuzz, and Google's Android fuzzing
 * infrastructure all consume.
 * ------------------------------------------------------------------------- */

int LLVMFuzzerTestOneInput(const uint8_t *data, size_t size);

/*
 * A file-scope volatile sink for values the harness reads out of the parsed
 * object. It has to be volatile, or the optimiser deletes every read that
 * feeds it and the coverage those reads would have generated vanishes -- a
 * harness that tests less the more you optimise it.
 *
 * It has to be at FILE SCOPE rather than a function-local static, because
 * clang's -Wunused-but-set-variable fires on a local that is only ever
 * written, and a harness built with -Werror then does not compile at all.
 * Measured: gcc 11.4 accepts the local form, clang 14 (NDK r25c) rejects it.
 * Two toolchains, one file -- this is the kind of thing that makes a harness
 * "work on my machine" and fail in the vendor's CI.
 */
static volatile size_t g_sink;

int LLVMFuzzerTestOneInput(const uint8_t *data, size_t size)
{
    acfg_blob blob;
    int rc;

    /* An empty input is legal to hand to the target and the parser must cope.
     * Returning early here would leave that path untested -- and "parser
     * crashes on a zero-length buffer" is a finding somebody gets paid for
     * every year. */
    rc = acfg_parse(data, size, &blob);

    if (rc == ACFG_OK) {
        /* Touch what the parser produced. A harness that parses and
         * immediately frees exercises only the parser; a lot of real bugs are
         * in the ACCESSORS, and they stay invisible unless something reads the
         * fields. Reading `name` as a C string is also what makes a missing
         * terminator observable to the sanitizer rather than silently benign.
         *
         * Reading `name` with strlen is what makes a MISSING terminator
         * observable. Without that read, a parser that forgets to terminate
         * the string produces no symptom at all inside the harness, and the
         * bug ships. */
        uint16_t i;
        size_t   acc = 0;

        for (i = 0; i < blob.built; i++) {
            const acfg_record *r = &blob.records[i];
            acc += strlen(r->name);
            acc += r->type;
            if (r->value != NULL && r->value_len > 0)
                acc += r->value[r->value_len - 1];
        }

        g_sink = acc;
    }

    /* Free on every path, success or failure. acfg_free is documented as safe
     * on a zeroed blob, and calling it unconditionally is what tests that
     * promise. */
    acfg_free(&blob);

    /* libFuzzer requires 0. Non-zero return values are reserved. */
    return 0;
}

/* -------------------------------------------------------------------------
 * Standalone driver. Compiled only when ACFG_STANDALONE is defined, so the
 * same file links cleanly under -fsanitize=fuzzer (which supplies its own
 * main) and under plain gcc (which does not).
 * ------------------------------------------------------------------------- */

#ifdef ACFG_STANDALONE

#define MAX_INPUT (64 * 1024)

static unsigned char g_buf[MAX_INPUT];
static unsigned char g_seed[MAX_INPUT];

static size_t read_file(const char *path, unsigned char *dst, size_t cap)
{
    FILE *f = fopen(path, "rb");
    size_t n;

    if (f == NULL) {
        fprintf(stderr, "cannot open %s\n", path);
        return (size_t)-1;
    }
    n = fread(dst, 1, cap, f);
    fclose(f);
    return n;
}

static int write_file(const char *path, const unsigned char *src, size_t n)
{
    FILE *f = fopen(path, "wb");
    if (f == NULL)
        return -1;
    fwrite(src, 1, n, f);
    fclose(f);
    return 0;
}

/* xorshift64star. A named, reproducible PRNG rather than rand(), because
 * "reproduce it with the same seed" has to actually work across machines and
 * rand() is not specified to. Reproducibility is not a nicety in fuzzing; a
 * campaign you cannot replay is a campaign you cannot triage. */
static uint64_t g_state;

static uint64_t xs64(void)
{
    uint64_t x = g_state;
    x ^= x >> 12;
    x ^= x << 25;
    x ^= x >> 27;
    g_state = x;
    return x * 0x2545F4914F6CDD1DULL;
}

static uint32_t rnd(uint32_t bound)
{
    return (uint32_t)(xs64() % (bound ? bound : 1));
}

/*
 * A deliberately minimal mutator: five operators, no feedback. libFuzzer's
 * mutator has around a dozen and, crucially, chooses WHICH INPUT to mutate
 * based on coverage. That choice is the entire difference.
 */
static size_t mutate(const unsigned char *seed, size_t seed_len,
                     unsigned char *dst, size_t cap)
{
    size_t len = seed_len;
    uint32_t rounds, k;

    if (len > cap)
        len = cap;
    memcpy(dst, seed, len);

    rounds = 1 + rnd(4);

    for (k = 0; k < rounds; k++) {
        switch (rnd(5)) {
        case 0:                                   /* flip a bit */
            if (len) {
                size_t p = rnd((uint32_t)len);
                dst[p] ^= (unsigned char)(1u << rnd(8));
            }
            break;
        case 1:                                   /* set a random byte */
            if (len) {
                size_t p = rnd((uint32_t)len);
                dst[p] = (unsigned char)rnd(256);
            }
            break;
        case 2:                                   /* interesting value */
            if (len) {
                static const unsigned char interesting[] = {
                    0x00, 0x01, 0x7f, 0x80, 0xff, 0xfe, 0x20, 0x40
                };
                size_t p = rnd((uint32_t)len);
                dst[p] = interesting[rnd(sizeof interesting)];
            }
            break;
        case 3:                                   /* grow */
            if (len < cap) {
                size_t add = 1 + rnd(32);
                size_t i;
                if (len + add > cap)
                    add = cap - len;
                for (i = 0; i < add; i++)
                    dst[len + i] = (unsigned char)rnd(256);
                len += add;
            }
            break;
        default:                                  /* shrink */
            if (len > 1)
                len -= 1 + rnd((uint32_t)(len - 1));
            break;
        }
    }

    return len;
}

static void usage(const char *argv0)
{
    fprintf(stderr,
        "usage:\n"
        "  %s <file> [file ...]                       replay inputs, exit 0 if all clean\n"
        "  %s -m <iters> <prng-seed> <seedfile> <outdir>  mutate and run\n",
        argv0, argv0);
}

int main(int argc, char **argv)
{
    if (argc < 2) {
        usage(argv[0]);
        return 2;
    }

    /* ---- mutation mode ---- */
    if (strcmp(argv[1], "-m") == 0) {
        long iters;
        size_t seed_len;
        char cur_path[512];
        char idx_path[512];
        long i;

        if (argc != 6) {
            usage(argv[0]);
            return 2;
        }

        iters   = strtol(argv[2], NULL, 10);
        g_state = strtoull(argv[3], NULL, 10);
        if (g_state == 0)
            g_state = 0x9E3779B97F4A7C15ULL;

        seed_len = read_file(argv[4], g_seed, sizeof g_seed);
        if (seed_len == (size_t)-1)
            return 2;

        snprintf(cur_path, sizeof cur_path, "%s/current.bin", argv[5]);
        snprintf(idx_path, sizeof idx_path, "%s/current.idx", argv[5]);

        fprintf(stderr, "[*] %ld iterations, prng seed %s, seed file %s (%zu bytes)\n",
                iters, argv[3], argv[4], seed_len);

        for (i = 0; i < iters; i++) {
            size_t n = mutate(g_seed, seed_len, g_buf, sizeof g_buf);

            /*
             * Persist the candidate BEFORE executing it.
             *
             * This is the single most important line in the driver. When the
             * sanitizer detects a fault it calls _Exit and no cleanup code of
             * yours runs -- so an input held only in memory is gone, and you
             * are left with a stack trace and no reproducer. libFuzzer solves
             * this by writing crash-<sha1> from inside its own signal path;
             * a hand-rolled driver has to write the file first and accept the
             * I/O cost. Every fuzzing harness anyone writes gets this wrong
             * exactly once.
             */
            write_file(cur_path, g_buf, n);

            /* And the execution index, for the same reason: "it crashed
             * somewhere between the 140,000th and 160,000th execution" is not
             * a reproduction step. Two small writes per iteration is a large
             * fraction of this driver's run time, which is itself a lesson in
             * why real fuzzers keep the reproducer in memory and serialise it
             * from a signal handler instead. */
            {
                char idx_buf[32];
                int  idx_len = snprintf(idx_buf, sizeof idx_buf, "%ld\n", i);
                if (idx_len > 0)
                    write_file(idx_path, (const unsigned char *)idx_buf,
                               (size_t)idx_len);
            }

            LLVMFuzzerTestOneInput(g_buf, n);

            if ((i % 20000) == 0 && i != 0)
                fprintf(stderr, "[*] %ld execs, no fault yet\n", i);
        }

        fprintf(stderr, "[*] completed %ld executions with no fault.\n", iters);
        fprintf(stderr, "[*] This is NOT a clean bill of health. See section 13.\n");
        return 0;
    }

    /* ---- replay mode ---- */
    {
        int i;
        for (i = 1; i < argc; i++) {
            size_t n = read_file(argv[i], g_buf, sizeof g_buf);
            if (n == (size_t)-1)
                return 2;
            fprintf(stderr, "[*] replaying %s (%zu bytes)\n", argv[i], n);
            LLVMFuzzerTestOneInput(g_buf, n);
            fprintf(stderr, "[+] %s: no fault\n", argv[i]);
        }
    }

    return 0;
}

#endif /* ACFG_STANDALONE */
