โฌข DragonFlyBSD Kernel Audit
DF-2664 / lz4_zero_input_fixed.c
โ† back to finding โ†“ download raw
  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
/*
 * 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;
}