/*
 * DF-2664 — LZ4_decompress_safe() 1-byte OOB source read when inputSize==0
 *           + margin-discipline fuzz (negative proof for the rest of the
 *           decoder on LP64).
 *
 * TARGET CODE (verbatim excerpt): sys/vfs/hammer2/hammer2_lz4.c:372-525
 * The decompressor compiled here is byte-for-byte the logic of the in-tree
 * hammer2 LZ4 (upstream LZ4 r97, 2013-06-10) — same macros, same checks,
 * LZ4_ARCH64=1 (x86-64, the only DragonFly platform: pc64/vkernel64).
 *
 * TEST A (the finding):
 *   LZ4_decompress_safe(source, dest, 0, outSize) — the very first
 *   statement of the main loop is `token = *ip++;`
 *   (hammer2_lz4.c:418) with NO preceding `ip < iend` check; the only
 *   pre-loop guard is `outputSize==0` (hammer2_lz4.c:407). With
 *   inputSize==0, iend==source, so the token fetch dereferences
 *   source[0] — one byte past the declared input buffer.
 *
 *   Proof layout: [ RW page | PROT_NONE guard ]; source = END of the RW
 *   page. The token fetch reads the first byte of the guard page ->
 *   SIGSEGV inside LZ4_decompress_safe. This violates the documented
 *   contract at sys/vfs/hammer2/hammer2_lz4.h:62-65:
 *     "This function is protected against any kind of buffer overflow
 *      attemps (never writes outside of output buffer, and never reads
 *      outside of input buffer)."
 *
 *   In-kernel reachability (hammer2_strategy.c:198-205): an on-media LZ4
 *   block with compressed_size==0 passes the KKASSERT at :199
 *   ((uint32_t)0 <= bytes - 4) on INVARIANTS kernels and reaches
 *   LZ4_decompress_safe(&data[4], ..., 0, b_bufsize). See trigger script.
 *
 * TEST A2 (control): inputSize==1, source={0x00} — the canonical "null"
 *   LZ4 stream per upstream r96's comment ("A correctly formed
 *   null-compressed LZ4 must have at least one byte (token=0)") decodes
 *   cleanly to 0 bytes. Only the inputSize==0 case is broken.
 *
 * TEST B (negative proof / margin discipline):
 *   1,000,000+ randomized AND adversarially-structured LZ4 streams with
 *   HONEST inputSize/outputSize, wrapped in PROT_NONE guard pages:
 *     - source ends flush at a page boundary with a guard page after:
 *       ANY read at iend[0] or beyond faults.
 *     - dest page starts after a guard page (catches ref<dest class) and
 *       carries a canary region [oend, page_end) checked after each run:
 *       ANY write at oend[0] or beyond is detected (analysis bound: all
 *       writes stay <= oend-1; wildcopy packets stop at oend-5..oend-1).
 *   Result: zero faults => given honest sizes the r97 decoder is
 *   memory-safe on LP64 (what DF-0805's caller fails to provide).
 *
 * Compile: cc -O2 -Wall -o lz4_zero_input_harness lz4_zero_input_harness.c
 * Run:     ./lz4_zero_input_harness [fuzz_iterations]
 */

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <signal.h>
#include <setjmp.h>
#include <sys/mman.h>
#include <stdint.h>

/* =====================================================================
 * Verbatim excerpt of sys/vfs/hammer2/hammer2_lz4.c — decompression only.
 * ===================================================================== */

#define MEMORY_USAGE 14
#define LZ4_ARCH64 1                    /* x86_64: pc64 + vkernel64 only */

#if defined (__STDC_VERSION__) && __STDC_VERSION__ >= 199901L
   typedef uint8_t  BYTE;
   typedef uint16_t U16;
   typedef uint32_t U32;
   typedef  int32_t S32;
   typedef uint64_t U64;
#else
   typedef unsigned char       BYTE;
   typedef unsigned short      U16;
   typedef unsigned int        U32;
   typedef   signed int        S32;
   typedef unsigned long long  U64;
#endif

#define _PACKED __attribute__ ((packed))
typedef struct _U16_S { U16 v; } _PACKED U16_S;
typedef struct _U32_S { U32 v; } _PACKED U32_S;
typedef struct _U64_S { U64 v; } _PACKED U64_S;
#define A64(x) (((U64_S *)(x))->v)
#define A32(x) (((U32_S *)(x))->v)
#define A16(x) (((U16_S *)(x))->v)

#define MINMATCH 4
#define COPYLENGTH 8
#define LASTLITERALS 5
#define MFLIMIT (COPYLENGTH+MINMATCH)
#define ML_BITS  4
#define ML_MASK  ((1U<<ML_BITS)-1)
#define RUN_BITS (8-ML_BITS)
#define RUN_MASK ((1U<<RUN_BITS)-1)

#if LZ4_ARCH64
#  define STEPSIZE 8
#  define LZ4_COPYSTEP(s,d)       A64(d) = A64(s); d+=8; s+=8;
#  define LZ4_COPYPACKET(s,d)     LZ4_COPYSTEP(s,d)
#  define LZ4_SECURECOPY(s,d,e)   if (d<e) LZ4_WILDCOPY(s,d,e)
#else
#  define STEPSIZE 4
#  define LZ4_COPYSTEP(s,d)       A32(d) = A32(s); d+=4; s+=4;
#  define LZ4_COPYPACKET(s,d)     LZ4_COPYSTEP(s,d); LZ4_COPYSTEP(s,d);
#  define LZ4_SECURECOPY          LZ4_WILDCOPY
#endif

#define LZ4_WILDCOPY(s,d,e)     do { LZ4_COPYPACKET(s,d) } while (d<e);
#define LZ4_BLINDCOPY(s,d,l)    { BYTE* e=(d)+(l); LZ4_WILDCOPY(s,d,e); d=e; }

#define LZ4_READ_LITTLEENDIAN_16(d,s,p) { d = (s) - A16(p); }

#define GCC_VERSION (__GNUC__ * 100 + __GNUC_MINOR__)
#if (GCC_VERSION >= 302) || defined(__clang__)
#  define expect(expr,value)    (__builtin_expect ((expr),(value)) )
#else
#  define expect(expr,value)    (expr)
#endif
#define likely(expr)     expect((expr) != 0, 1)
#define unlikely(expr)   expect((expr) != 0, 0)

typedef enum { noPrefix = 0, withPrefix = 1 } prefix64k_directive;
typedef enum { endOnOutputSize = 0, endOnInputSize = 1 } end_directive;
typedef enum { full = 0, partial = 1 } exit_directive;

/* Verbatim from sys/vfs/hammer2/hammer2_lz4.c:372-517 */
static inline int LZ4_decompress_generic(
                 char* source,
                 char* dest,
                 int inputSize,
                 int outputSize,
                 int endOnInput,
                 int prefix64k,
                 int partialDecoding,
                 int targetOutputSize)
{
    BYTE* restrict ip = (BYTE*) source;
    BYTE* ref;
    BYTE* iend = ip + inputSize;

    BYTE* op = (BYTE*) dest;
    BYTE* oend = op + outputSize;
    BYTE* cpy;
    BYTE* oexit = op + targetOutputSize;

    size_t dec32table[] = {0, 3, 2, 3, 0, 0, 0, 0};
#if LZ4_ARCH64
    size_t dec64table[] = {0, 0, 0, (size_t)-1, 0, 1, 2, 3};
#endif

    if ((partialDecoding) && (oexit> oend-MFLIMIT)) oexit = oend-MFLIMIT;
    if unlikely(outputSize==0) goto _output_error;
    if ((endOnInput) && unlikely(inputSize==0)) goto _output_error;   /* FIX DF-2664: r96/v1.9.4 guard */

    while (1)
    {
        unsigned token;
        size_t length;

        token = *ip++;                          /* <-- hammer2_lz4.c:418 */
        if ((length=(token>>ML_BITS)) == RUN_MASK)
        {
            unsigned s=255;
            while (((endOnInput)?ip<iend:1) && (s==255))
            {
                s = *ip++;
                length += s;
            }
        }

        cpy = op+length;
        if (((endOnInput) && ((cpy>(partialDecoding?oexit:oend-MFLIMIT))
                        || (ip+length>iend-(2+1+LASTLITERALS))) )
            || ((!endOnInput) && (cpy>oend-COPYLENGTH)))
        {
            if (partialDecoding)
            {
                if (cpy > oend) goto _output_error;
                if ((endOnInput) && (ip+length > iend)) goto _output_error;
            }
            else
            {
                if ((!endOnInput) && (cpy != oend)) goto _output_error;
                if ((endOnInput) && ((ip+length != iend) || (cpy > oend)))
                    goto _output_error;
            }
            memcpy(op, ip, length);
            ip += length;
            op += length;
            break;
        }
        LZ4_WILDCOPY(ip, op, cpy); ip -= (op-cpy); op = cpy;

        LZ4_READ_LITTLEENDIAN_16(ref,cpy,ip); ip+=2;
        if ((prefix64k==noPrefix) && unlikely(ref < (BYTE*)dest))
            goto _output_error;

        if ((length=(token&ML_MASK)) == ML_MASK)
        {
            while (endOnInput ? ip<iend-(LASTLITERALS+1) : 1)
            {
                unsigned s = *ip++;
                length += s;
                if (s==255) continue;
                break;
            }
        }

        if unlikely((op-ref)<STEPSIZE)
        {
#if LZ4_ARCH64
            size_t dec64 = dec64table[op-ref];
#else
            const size_t dec64 = 0;
#endif
            op[0] = ref[0];
            op[1] = ref[1];
            op[2] = ref[2];
            op[3] = ref[3];
            op += 4, ref += 4; ref -= dec32table[op-ref];
            A32(op) = A32(ref);
            op += STEPSIZE-4; ref -= dec64;
        } else { LZ4_COPYSTEP(ref,op); }
        cpy = op + length - (STEPSIZE-4);

        if unlikely(cpy>oend-(COPYLENGTH)-(STEPSIZE-4))
        {
            if (cpy > oend-LASTLITERALS) goto _output_error;
            LZ4_SECURECOPY(ref, op, (oend-COPYLENGTH));
            while(op<cpy) *op++=*ref++;
            op=cpy;
            continue;
        }
        LZ4_WILDCOPY(ref, op, cpy);
        op=cpy;
    }

    if (endOnInput)
       return (int) (((char*)op)-dest);
    else
       return (int) (((char*)ip)-source);

_output_error:
    return (int) (-(((char*)ip)-source))-1;
}

/* Verbatim from sys/vfs/hammer2/hammer2_lz4.c:520-525 */
int LZ4_decompress_safe(char* source, char* dest, int inputSize, int maxOutputSize)
{
    return LZ4_decompress_generic(source, dest, inputSize, maxOutputSize,
                        endOnInputSize, noPrefix, full, 0);
}

/* =====================================================================
 * Harness
 * ===================================================================== */

static sigjmp_buf jb;
static volatile sig_atomic_t in_decoder;
static void *fault_addr;

static void
segv_handler(int sig, siginfo_t *si, void *uc)
{
    (void)sig; (void)uc;
    fault_addr = si->si_addr;
    in_decoder = 0;
    siglongjmp(jb, 1);
}

static size_t pagesz;

int
main(int argc, char **argv)
{
    unsigned long fuzz_iters = 1000000;
    if (argc > 1) fuzz_iters = strtoul(argv[1], NULL, 0);

    pagesz = (size_t)sysconf(_SC_PAGESIZE);
    struct sigaction sa;
    memset(&sa, 0, sizeof(sa));
    sa.sa_sigaction = segv_handler;
    sa.sa_flags = SA_SIGINFO;
    sigemptyset(&sa.sa_mask);
    sigaction(SIGSEGV, &sa, NULL);
    sigaction(SIGBUS, &sa, NULL);

    puts("[harness] DF-2664: LZ4_decompress_safe() token read with inputSize==0");
    puts("[harness] decoder = verbatim sys/vfs/hammer2/hammer2_lz4.c (upstream LZ4 r97)");

    /*
     * TEST A — the finding.
     * Map [ RW | GUARD ]; place a 64 KiB output buffer normally, and the
     * SOURCE at the very end of the RW page. inputSize = 0.
     */
    {
        char *region = mmap(NULL, 2 * pagesz, PROT_READ|PROT_WRITE,
                            MAP_PRIVATE|MAP_ANON, -1, 0);
        if (region == MAP_FAILED) { perror("mmap"); return 1; }
        if (mprotect(region + pagesz, pagesz, PROT_NONE) != 0) {
            perror("mprotect"); return 1;
        }
        char *src = region + pagesz;        /* == end of RW page == iend */
        char *dst = calloc(1, 65536);
        int r = -12345;

        puts("[A] calling LZ4_decompress_safe(src=end_of_page, dst, inputSize=0, 65536)");
        in_decoder = 1;
        if (sigsetjmp(jb, 1) == 0) {
            r = LZ4_decompress_safe(src, dst, 0, 65536);
            in_decoder = 0;
            /* FIXED build: the r96/v1.9.4 guard must reject inputSize==0
             * cleanly BEFORE the token fetch. */
            printf("[A] returned %d WITHOUT faulting\n", r);
            if (r < 0) {
                printf("FIX VALIDATED - inputSize==0 cleanly rejected, no OOB read\n");
                free(dst); munmap(region, 2*pagesz);
                goto test_a2;
            } else {
                printf("FIX FAILED - inputSize==0 accepted\n");
                free(dst); munmap(region, 2*pagesz);
                return 1;
            }
        }
        printf("[A] SIGSEGV at %p while inside LZ4_decompress_safe()\n", fault_addr);
        printf("[A]   faulting address == src (== iend): %p ; delta = %ld\n",
               (void *)src, (long)((char *)fault_addr - src));
        puts("[A] -> LZ4_decompress_safe() dereferenced source[0] with inputSize==0:");
        puts("[A]    1-byte OOB read past the declared input buffer.");
        puts("OOB READ CONFIRMED — DF-2664 (hammer2_lz4.c:418)");
        free(dst); munmap(region, 2*pagesz);
    }

    /*
     * TEST A2 — control: the canonical 1-byte null stream works.
     */
test_a2:
    {
        char src[1] = { 0x00 };
        char dst[256];
        memset(dst, 0xA5, sizeof(dst));
        int r = LZ4_decompress_safe(src, dst, 1, sizeof(dst));
        printf("[A2] inputSize=1, token=0x00 -> return %d (expect 0)\n", r);
        if (r != 0) {
            puts("[A2] UNEXPECTED: canonical null stream failed");
            return 1;
        }
        puts("[A2] control OK: with inputSize>=1 the same entry is well-behaved;");
        puts("[A2] only inputSize==0 is broken (guard dropped in upstream r97).");
    }

    /*
     * TEST B — margin-discipline fuzz (negative proof).
     *
     *   src: [ GUARD | RW page(s) ] with the stream placed flush against
     *        the final guard page: any read at iend[0..] faults.
     *   dst: [ GUARD | RW page ] with canary in [oend, page_end):
     *        any write at oend[0..] corrupts the canary; reads/writes
     *        before dest fault on the leading guard page.
     */
    {
        unsigned char *srcpages = mmap(NULL, 2 * pagesz, PROT_READ|PROT_WRITE,
                                       MAP_PRIVATE|MAP_ANON, -1, 0);
        unsigned char *dstpages = mmap(NULL, 2 * pagesz, PROT_READ|PROT_WRITE,
                                       MAP_PRIVATE|MAP_ANON, -1, 0);
        mprotect(srcpages, pagesz, PROT_NONE);          /* guard BEFORE src region */
        mprotect(dstpages, pagesz, PROT_NONE);          /* guard BEFORE dst */
        unsigned char *srcarea = srcpages + pagesz;     /* one RW page */
        unsigned char *dst = dstpages + pagesz;

        srandom(0xDF2664u);
        unsigned long i;
        unsigned long accepted = 0, rejected = 0;
        const size_t canary_off_min = 32;               /* min canary size */
        size_t max_in = pagesz - 8;                      /* stream must fit one page */

        for (i = 0; i < fuzz_iters; i++) {
            size_t in;
            int outSize;

            /* --- generate input --- */
            unsigned int mode = random() % 10;
            if (i < 16) {
                in = 1 + (i % 20);                      /* tiny streams first */
            } else {
                in = 1 + (size_t)(random() % max_in);
            }
            outSize = 1 + (int)(random() % (pagesz - canary_off_min - 1));
            if (i % 7 == 0)
                outSize = 1 + (int)(random() % 16);     /* exercise tiny outputs */

            unsigned char *p = srcarea + (pagesz - in); /* flush to end */
            size_t n;

            if (mode == 0) {                            /* all 0xFF */
                memset(p, 0xFF, in);
            } else if (mode == 1) {                     /* all zero */
                memset(p, 0x00, in);
            } else if (mode <= 5) {                     /* structured */
                n = 0;
                while (n < in) {
                    unsigned litn, matn;
                    unsigned tok;
                    litn = random() % 20;
                    matn = random() % 20;
                    if (random() % 3 == 0) litn = RUN_MASK;
                    if (random() % 3 == 0) matn = ML_MASK;
                    tok = (litn << ML_BITS) | matn;
                    if (n < in) p[n++] = tok;
                    if (litn == RUN_MASK) {
                        int k = random() % 4;
                        while (k-- > 0 && n < in) p[n++] = (random()%5==0) ? random()%255 : 0xFF;
                        if (n < in) p[n++] = random() % 255;
                    }
                    size_t litbytes = random() % 24;
                    while (litbytes-- > 0 && n < in) p[n++] = random() % 255;
                    /* offset */
                    if (n + 1 < in) {
                        unsigned short off;
                        switch (random() % 6) {
                        case 0: off = 0; break;
                        case 1: off = 1; break;
                        case 2: off = 2; break;
                        case 3: off = 7; break;
                        case 4: off = 0xFFFF; break;
                        default: off = (unsigned short)(random() % 512);
                        }
                        memcpy(p + n, &off, 2); n += 2;
                    }
                    if (matn == ML_MASK) {
                        int k = random() % 4;
                        while (k-- > 0 && n < in) p[n++] = 0xFF;
                        if (n < in) p[n++] = random() % 255;
                    }
                }
            } else {                                    /* pure random */
                for (n = 0; n < in; n++)
                    p[n] = (unsigned char)(random() & 0xFF);
            }

            /* --- canary + run --- */
            size_t canlen = pagesz - (size_t)outSize;
            memset(dst + outSize, 0xC3, canlen);        /* canary after oend */
            memset(dst, 0x5A, (size_t)outSize);         /* poison output */

            in_decoder = 1;
            if (sigsetjmp(jb, 1) != 0) {
                printf("[B] FAULT at iter %lu mode %u in=%zu out=%d addr=%p\n",
                       i, mode, in, outSize, fault_addr);
                char path[128];
                snprintf(path, sizeof(path), "/tmp/df2664_fault_input.bin");
                FILE *f = fopen(path, "wb");
                if (f) { fwrite(p, in, 1, f); fclose(f); }
                printf("[B] input dumped to %s\n", path);
                puts("FUZZ FAULT — decoder violated the guard/canary discipline!");
                return 1;
            }
            int r = LZ4_decompress_safe((char *)p, (char *)dst, (int)in, outSize);
            in_decoder = 0;

            /* --- verify --- */
            size_t j;
            for (j = 0; j < canlen; j++) {
                if (dst[outSize + j] != 0xC3) {
                    printf("[B] CANARY CORRUPT at iter %lu: dst[%d]=%02x\n",
                           i, outSize + (int)j, dst[outSize + j]);
                    puts("WRITE PAST OEND — decoder wrote beyond outputSize!");
                    return 1;
                }
            }
            if (r > outSize || r < -(int)(in + 2)) {
                printf("[B] INSANE RETURN at iter %lu: r=%d in=%zu out=%d\n",
                       i, r, in, outSize);
                return 1;
            }
            if (r < 0) rejected++; else accepted++;
        }
        printf("[B] %lu iterations: %lu decoded ok, %lu rejected, "
               "0 faults, 0 canary corruptions\n",
               fuzz_iters, accepted, rejected);
        puts("[B] NEGATIVE PROOF (breadth): with honest (inputSize,outputSize)");
        puts("[B] the r97 decoder never reads past iend and never writes past oend.");

        /*
         * TEST C — depth fuzz: generate *valid-shaped* streams (small
         * literal runs + in-window offsets + short matches, ending with
         * an exact final literal run) so the decoder walks MANY loop
         * iterations deep into match-copy/overlap machinery, then mutate
         * a few bytes (or truncate) to land near-valid inputs exactly on
         * the margin arithmetic (oend-5/-8/-12, iend-6/-8 boundaries).
         */
        {
            unsigned long accepted2 = 0, rejected2 = 0, mutated = 0;
            unsigned char *gen = calloc(1, pagesz);
            for (i = 0; i < fuzz_iters; i++) {
                size_t g = 0;
                size_t outpos = 0;      /* simulated output position */
                size_t maxg = 64 + (size_t)(random() % (max_in - 64));
                int outSize2 = 64 + (int)(random() % (pagesz - canary_off_min - 64));

                while (g + 16 < maxg) {
                    unsigned lit = random() % 30;
                    unsigned mat = random() % 18;
                    unsigned tok = ((lit < RUN_MASK ? lit : RUN_MASK) << ML_BITS) |
                                   (mat < ML_MASK ? mat : ML_MASK);
                    gen[g++] = tok;
                    if (lit >= RUN_MASK) {                    /* ext bytes */
                        unsigned e = random() % 3;
                        while (e-- > 0 && g + 4 < maxg) gen[g++] = 0xFF;
                        if (g + 4 < maxg) gen[g++] = random() % 200;
                        lit += 255 * (random() % 2);
                    }
                    while (lit-- > 0 && g + 4 < maxg) gen[g++] = random() & 0xFF;
                    outpos += (tok >> ML_BITS);
                    /* offset within simulated output window (0 allowed) */
                    size_t offmax = outpos ? outpos : (tok >> ML_BITS);
                    unsigned short off = (unsigned short)(random() % (offmax ? (offmax > 4096 ? 4096 : offmax) : 1));
                    if (random() % 11 == 0) off = 0;
                    if (random() % 9 == 0) off = 1 + random() % 8;   /* overlap d=1..8 */
                    if (g + 2 < maxg) { gen[g++] = off & 0xFF; gen[g++] = off >> 8; }
                    if ((tok & ML_MASK) == ML_MASK) {
                        unsigned e = random() % 3;
                        while (e-- > 0 && g + 4 < maxg) gen[g++] = 0xFF;
                        if (g + 4 < maxg) gen[g++] = random() % 200;
                    }
                    outpos += (tok & ML_MASK);
                }
                /* final literal run consuming the rest exactly */
                {
                    size_t rem = maxg - g;
                    if (rem > 5 && rem < pagesz) {
                        unsigned tokrun = (rem < RUN_MASK ? rem : RUN_MASK);
                        gen[g++] = tokrun << ML_BITS;
                        size_t r2 = rem;
                        if (rem >= RUN_MASK) {
                            r2 -= RUN_MASK;
                            while (r2 >= 255 && g + 300 < pagesz) { gen[g++] = 0xFF; r2 -= 255; }
                            gen[g++] = r2; r2 = 0;
                        }
                        while (r2-- > 0 && g < pagesz) gen[g++] = random() & 0xFF;
                    }
                }
                if (g > max_in) g = max_in;

                /* mutation */
                if (random() % 2) {
                    mutated++;
                    int nm = 1 + random() % 3;
                    while (nm-- > 0 && g > 1) gen[random() % g] = random() & 0xFF;
                    if (random() % 4 == 0 && g > 2) g = 1 + random() % g;   /* truncate */
                }

                size_t in2 = g;
                unsigned char *p2 = srcarea + (pagesz - in2);
                memmove(p2, gen, in2);

                size_t canlen2 = pagesz - (size_t)outSize2;
                memset(dst + outSize2, 0xC3, canlen2);
                memset(dst, 0x5A, (size_t)outSize2);

                in_decoder = 1;
                if (sigsetjmp(jb, 1) != 0) {
                    printf("[C] FAULT at iter %lu in=%zu out=%d addr=%p\n",
                           i, in2, outSize2, fault_addr);
                    FILE *f = fopen("/tmp/df2664_fault_input.bin", "wb");
                    if (f) { fwrite(p2, in2, 1, f); fclose(f); }
                    puts("FUZZ FAULT — decoder violated the guard/canary discipline!");
                    return 1;
                }
                int r = LZ4_decompress_safe((char *)p2, (char *)dst, (int)in2, outSize2);
                in_decoder = 0;

                for (size_t j2 = 0; j2 < canlen2; j2++) {
                    if (dst[outSize2 + j2] != 0xC3) {
                        printf("[C] CANARY CORRUPT at iter %lu dst[%d]=%02x\n",
                               i, outSize2 + (int)j2, dst[outSize2 + j2]);
                        puts("WRITE PAST OEND!");
                        return 1;
                    }
                }
                if (r > outSize2 || r < -(int)(in2 + 2)) {
                    printf("[C] INSANE RETURN iter %lu r=%d in=%zu out=%d\n",
                           i, r, in2, outSize2);
                    return 1;
                }
                if (r < 0) rejected2++; else accepted2++;
            }
            printf("[C] %lu valid-shaped/mutated iterations (%lu mutated): "
                   "%lu decoded ok, %lu rejected, 0 faults, 0 canary corruptions\n",
                   fuzz_iters, mutated, accepted2, rejected2);
            puts("[C] NEGATIVE PROOF (depth): deep-parsing streams also stay in bounds.");
            free(gen);
        }
    }

    puts("DONE");
    return 0;
}
