Coverage Report

Created: 2026-12-01 06:48

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/zxc/tests/fuzz/fuzz_dict.c
Line
Count
Source
1
// SPDX-License-Identifier: BSD-3-Clause
2
/*
3
 * ZXC - High-performance lossless compression
4
 *
5
 * Copyright (c) Bertrand Lebonnois and contributors.
6
 */
7
8
/**
9
 * @file fuzz_dict.c
10
 * @brief Fuzzer for the dictionary API in zxc_dict.c.
11
 *
12
 * Strategy (exercises the .zxd format and the trainer, not just the in-memory
13
 * dict bounce path):
14
 *
15
 *  Phase 0 -- Raw .zxd parser. Feed the untrusted bytes straight to
16
 *             zxc_dict_load() / zxc_dict_read_id(). Must never crash on garbage.
17
 *             A dictionary that loads then round-trips a payload with its own
18
 *             table, so the tree built from untrusted code lengths is decoded.
19
 *  Phase 1 -- Train. Split the input into samples and call zxc_dict_train_content().
20
 *  Phase 2 -- Serialize roundtrip. Save the trained dict to .zxd, load it back,
21
 *             and verify content / dict_id agree across save/load/get_id/id.
22
 *             Also drives the DST_TOO_SMALL path and single-byte corruption.
23
 *  Phase 3 -- Use the trained dict for a real compress -> decompress roundtrip,
24
 *             with its shared literal table when the header asks (levels 6-7).
25
 *
26
 * The control header carries level, sample count, dict capacity, and the
27
 * corruption position/mask, so the same input deterministically reaches the
28
 * deep validation branches that random bytes (which lack the .zxd magic) miss.
29
 */
30
31
#include <assert.h>
32
#include <stddef.h>
33
#include <stdint.h>
34
#include <stdlib.h>
35
#include <string.h>
36
37
#include "../../include/zxc_buffer.h"
38
#include "../../include/zxc_constants.h"
39
#include "../../include/zxc_dict.h"
40
#include "../../include/zxc_error.h"
41
42
14.1k
#define FUZZ_DICT_MAX_INPUT (256 << 10) /* 256 KiB */
43
42.3k
#define FUZZ_DICT_CTRL 8                /* control-header bytes consumed below */
44
14.1k
#define FUZZ_DICT_MAX_SAMPLES 8
45
0
#define FUZZ_DICT_HUF_PAYLOAD 4096 /* bytes round-tripped with a loaded table */
46
47
/* Compresses up to FUZZ_DICT_HUF_PAYLOAD bytes of @p src at level 6 with a
48
 * loaded dictionary and its table, then decodes: a table load accepted must
49
 * compress, and what compresses must decode bit-exact. */
50
static void dict_huf_roundtrip(const void* dict, const size_t dict_size, const void* huf,
51
0
                               const uint8_t* src, size_t n) {
52
0
    static uint8_t comp[FUZZ_DICT_HUF_PAYLOAD * 2 + 1024];
53
0
    if (n > FUZZ_DICT_HUF_PAYLOAD) n = FUZZ_DICT_HUF_PAYLOAD;
54
0
    if (n == 0 || zxc_compress_bound(n) > sizeof(comp)) return;
55
0
    static zxc_cctx* cctx = NULL;
56
0
    static zxc_dctx* dctx = NULL;
57
0
    if (!cctx) cctx = zxc_create_cctx();
58
0
    if (!dctx) dctx = zxc_create_dctx();
59
0
    if (!cctx || !dctx) return;
60
0
    const int ready = zxc_cctx_set_param(cctx, ZXC_C_LEVEL, 6) == ZXC_OK &&
61
0
                      zxc_cctx_set_dict(cctx, dict, dict_size, huf) == ZXC_OK &&
62
0
                      zxc_dctx_set_dict(dctx, dict, dict_size, huf) == ZXC_OK;
63
0
    uint8_t* const out = ready ? (uint8_t*)malloc(n) : NULL;
64
0
    if (out) {
65
0
        const int64_t c = zxc_compress_cctx(cctx, src, n, comp, sizeof(comp));
66
0
        assert(c > 0);
67
0
        const int64_t d = zxc_decompress_dctx(dctx, comp, (size_t)c, out, n);
68
0
        assert(d == (int64_t)n && memcmp(out, src, n) == 0);
69
0
        (void)c;
70
0
        (void)d;
71
0
    }
72
0
    free(out);
73
0
}
74
75
/* Configures a compression context for phase 3; ZXC_OK, or the setter's error. */
76
static int configure_cctx(zxc_cctx* c, const int level, const int checksum, const void* dict,
77
28.1k
                          const size_t dict_size, const void* huf) {
78
28.1k
    int rc = zxc_cctx_set_param(c, ZXC_C_LEVEL, level);
79
28.1k
    if (rc == ZXC_OK) rc = zxc_cctx_set_param(c, ZXC_C_CHECKSUM, checksum);
80
28.1k
    if (rc == ZXC_OK) rc = zxc_cctx_set_dict(c, dict, dict_size, huf);
81
28.1k
    return rc;
82
28.1k
}
83
84
/* Same for a decompression context. */
85
static int configure_dctx(zxc_dctx* d, const int checksum, const void* dict, const size_t dict_size,
86
28.1k
                          const void* huf) {
87
28.1k
    int rc = zxc_dctx_set_param(d, ZXC_D_CHECKSUM, checksum);
88
28.1k
    if (rc == ZXC_OK) rc = zxc_dctx_set_dict(d, dict, dict_size, huf);
89
28.1k
    return rc;
90
28.1k
}
91
92
/* Phase 3. */
93
static void dict_roundtrip(const uint8_t* data, const size_t size, const int level,
94
                           const int use_checksum, const void* dict, const size_t dict_size,
95
                           const void* dict_huf, uint8_t* comp_buf, uint8_t* comp2_buf,
96
14.0k
                           const size_t bound, uint8_t* decomp_buf) {
97
    /* Reference: a fresh context, used once. */
98
14.0k
    zxc_cctx* const fresh = zxc_create_cctx();
99
14.0k
    if (!fresh) return;
100
14.0k
    if (configure_cctx(fresh, level, use_checksum, dict, dict_size, dict_huf) != ZXC_OK) {
101
0
        zxc_free_cctx(fresh);
102
0
        return;
103
0
    }
104
14.0k
    const int64_t csize = zxc_compress_cctx(fresh, data, size, comp_buf, bound);
105
14.0k
    zxc_free_cctx(fresh);
106
14.0k
    if (csize < 0) return;
107
108
    /* The context reused across runs must produce the very same archive. */
109
14.0k
    static zxc_cctx* cctx = NULL;
110
14.0k
    if (!cctx) cctx = zxc_create_cctx();
111
14.0k
    if (cctx && configure_cctx(cctx, level, use_checksum, dict, dict_size, dict_huf) == ZXC_OK) {
112
14.0k
        const int64_t c2 = zxc_compress_cctx(cctx, data, size, comp2_buf, bound);
113
14.0k
        assert(c2 == csize);
114
14.0k
        assert(memcmp(comp_buf, comp2_buf, (size_t)csize) == 0);
115
14.0k
    }
116
117
    /* Reference decode: a fresh context, used once. */
118
14.0k
    zxc_dctx* const fresh_d = zxc_create_dctx();
119
14.0k
    if (!fresh_d) return;
120
14.0k
    if (configure_dctx(fresh_d, use_checksum, dict, dict_size, dict_huf) != ZXC_OK) {
121
0
        zxc_free_dctx(fresh_d);
122
0
        return;
123
0
    }
124
14.0k
    const int64_t dsize = zxc_decompress_dctx(fresh_d, comp_buf, (size_t)csize, decomp_buf, size);
125
14.0k
    zxc_free_dctx(fresh_d);
126
127
14.0k
    if (dsize >= 0) {
128
14.0k
        assert((size_t)dsize == size);
129
14.0k
        assert(memcmp(data, decomp_buf, size) == 0);
130
14.0k
    }
131
132
    /* Same archive through the context reused across runs: must agree. */
133
14.0k
    static zxc_dctx* dctx = NULL;
134
14.0k
    if (!dctx) dctx = zxc_create_dctx();
135
14.0k
    if (dctx && configure_dctx(dctx, use_checksum, dict, dict_size, dict_huf) == ZXC_OK) {
136
14.0k
        const int64_t d2 = zxc_decompress_dctx(dctx, comp_buf, (size_t)csize, decomp_buf, size);
137
14.0k
        assert(d2 == dsize);
138
14.0k
        if (d2 >= 0) assert(memcmp(data, decomp_buf, size) == 0);
139
14.0k
    }
140
14.0k
}
141
142
14.1k
int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size) {
143
14.1k
    static uint8_t* dict_buf = NULL; /* trained dict content (<= ZXC_DICT_SIZE_MAX) */
144
14.1k
    static uint8_t* zxd_buf = NULL;  /* serialized .zxd (header + content)          */
145
146
14.1k
    if (size > FUZZ_DICT_MAX_INPUT) return 0;
147
148
    /* ------------------------------------------------------------------ */
149
    /* Phase 0: raw .zxd parser on untrusted bytes (must not crash).      */
150
    /* zxc_dict_load tolerates buf_size < header, so any size is safe.    */
151
    /* ------------------------------------------------------------------ */
152
14.1k
    {
153
14.1k
        const void* content = NULL;
154
14.1k
        size_t content_size = 0;
155
14.1k
        const void* huf = NULL;
156
14.1k
        uint32_t id = 0;
157
14.1k
        const int rc = zxc_dict_load(data, size, &content, &content_size, &huf, &id);
158
14.1k
        if (rc == ZXC_OK) {
159
0
            assert(content);
160
0
            assert(content_size > 0 && content_size <= ZXC_DICT_SIZE_MAX);
161
            /* A validated header round-trips through both ID accessors; the
162
             * stored id binds the (content, table) pair. */
163
0
            assert(zxc_dict_read_id(data, size) == id);
164
0
            assert(zxc_dict_compute_id(content, content_size, huf) == id);
165
0
            dict_huf_roundtrip(content, content_size, huf, data, size);
166
0
        }
167
14.1k
        (void)zxc_dict_read_id(data, size);
168
14.1k
    }
169
170
    /* ------------------------------------------------------------------ */
171
    /* Parse the control header.                                          */
172
    /* ------------------------------------------------------------------ */
173
14.1k
    if (size < FUZZ_DICT_CTRL) return 0;
174
175
    // With the shared table, levels 6-7: the only ones that use it.
176
14.1k
    const int use_huf = (data[7] >> 1) & 1;
177
14.1k
    const int level = use_huf ? 6 + (data[0] & 1) : (int)(data[0] % (unsigned)zxc_max_level()) + 1;
178
14.1k
    const size_t n_samples = (size_t)(data[1] % FUZZ_DICT_MAX_SAMPLES) + 1;
179
14.1k
    size_t dict_cap = (size_t)(data[2] | (data[3] << 8));
180
14.1k
    const size_t corrupt_pos = (size_t)(data[4] | (data[5] << 8));
181
14.1k
    const uint8_t corrupt_mask = data[6];
182
14.1k
    const int use_checksum = data[7] & 1;
183
14.1k
    data += FUZZ_DICT_CTRL;
184
14.1k
    size -= FUZZ_DICT_CTRL;
185
186
14.1k
    if (size == 0) return 0;
187
188
14.1k
    if (dict_cap == 0) dict_cap = 1;
189
14.1k
    if (dict_cap > ZXC_DICT_SIZE_MAX) dict_cap = ZXC_DICT_SIZE_MAX;
190
191
    /* ------------------------------------------------------------------ */
192
    /* Phase 1: split input into samples and train.                       */
193
    /* ------------------------------------------------------------------ */
194
14.1k
    const void* samples[FUZZ_DICT_MAX_SAMPLES];
195
14.1k
    size_t sample_sizes[FUZZ_DICT_MAX_SAMPLES];
196
14.1k
    const size_t chunk = size / n_samples;
197
63.1k
    for (size_t i = 0; i < n_samples; i++) {
198
49.0k
        samples[i] = data + chunk * i;
199
49.0k
        sample_sizes[i] = (i + 1 < n_samples) ? chunk : (size - chunk * (n_samples - 1));
200
49.0k
    }
201
202
14.1k
    if (!dict_buf) {
203
1
        dict_buf = (uint8_t*)malloc(ZXC_DICT_SIZE_MAX);
204
1
        if (!dict_buf) return 0;
205
1
    }
206
207
14.1k
    const int64_t dict_sz =
208
14.1k
        zxc_dict_train_content(samples, sample_sizes, n_samples, dict_buf, dict_cap);
209
14.1k
    if (dict_sz <= 0) return 0; /* corpus too small / no patterns: nothing to serialize */
210
14.1k
    assert((size_t)dict_sz <= dict_cap);
211
212
    /* The .zxd format requires the shared literal table; train it on the same
213
     * samples (it needs the trained content for the post-LZ literal stats). */
214
14.0k
    uint8_t huf[ZXC_HUF_TABLE_SIZE];
215
14.0k
    if (zxc_dict_train_huf(samples, sample_sizes, n_samples, dict_buf, (size_t)dict_sz, huf) !=
216
14.0k
        ZXC_OK)
217
0
        return 0;
218
219
    /* ------------------------------------------------------------------ */
220
    /* Phase 2: .zxd save / load roundtrip + corruption.                  */
221
    /* ------------------------------------------------------------------ */
222
14.0k
    const size_t zxd_bound = zxc_dict_save_bound((size_t)dict_sz);
223
14.0k
    if (!zxd_buf) {
224
1
        zxd_buf = (uint8_t*)malloc(ZXC_DICT_HEADER_SIZE + ZXC_DICT_SIZE_MAX + ZXC_HUF_TABLE_SIZE);
225
1
        if (!zxd_buf) return 0;
226
1
    }
227
228
14.0k
    const int64_t zxd_sz = zxc_dict_save(dict_buf, (size_t)dict_sz, huf, zxd_buf, zxd_bound);
229
14.0k
    assert(zxd_sz == (int64_t)zxd_bound);
230
231
14.0k
    {
232
14.0k
        const void* lc = NULL;
233
14.0k
        size_t lcs = 0;
234
14.0k
        const void* lh = NULL;
235
14.0k
        uint32_t lid = 0;
236
14.0k
        const int rc = zxc_dict_load(zxd_buf, (size_t)zxd_sz, &lc, &lcs, &lh, &lid);
237
14.0k
        assert(rc == ZXC_OK);
238
14.0k
        (void)rc;
239
14.0k
        assert(lcs == (size_t)dict_sz);
240
14.0k
        assert(memcmp(lc, dict_buf, (size_t)dict_sz) == 0);
241
14.0k
        assert(lh && memcmp(lh, huf, ZXC_HUF_TABLE_SIZE) == 0);
242
        /* The stored id binds the (content, table) pair, not the content alone. */
243
14.0k
        assert(zxc_dict_read_id(zxd_buf, (size_t)zxd_sz) == lid);
244
14.0k
    }
245
246
    /* DST_TOO_SMALL: any capacity below the full file must be rejected. */
247
14.0k
    {
248
14.0k
        const size_t small_cap = corrupt_pos % (size_t)zxd_sz; /* in [0, zxd_sz) */
249
14.0k
        const int64_t r = zxc_dict_save(dict_buf, (size_t)dict_sz, huf, zxd_buf, small_cap);
250
14.0k
        assert(r < 0);
251
14.0k
        (void)r;
252
14.0k
    }
253
254
    /* Re-save (the DST_TOO_SMALL attempt left zxd_buf untouched, but be safe). */
255
14.0k
    assert(zxc_dict_save(dict_buf, (size_t)dict_sz, huf, zxd_buf, zxd_bound) == (int64_t)zxd_sz);
256
257
    /* Flip one byte and re-load: must not crash. A header flip that survives
258
     * (reserved or flags byte) leaves the content intact; a payload flip that
259
     * survives is a dict_id collision, which a fuzzer can forge, so there the
260
     * only invariant is load's contract: OK means the id binds (content, table). */
261
14.0k
    {
262
14.0k
        const size_t pos = corrupt_pos % (size_t)zxd_sz;
263
14.0k
        const uint8_t saved = zxd_buf[pos];
264
14.0k
        zxd_buf[pos] ^= (uint8_t)(corrupt_mask | 1U); /* guaranteed to differ */
265
266
14.0k
        const void* cc = NULL;
267
14.0k
        const void* ch = NULL;
268
14.0k
        size_t ccs = 0;
269
14.0k
        uint32_t cid = 0;
270
14.0k
        const int rc = zxc_dict_load(zxd_buf, (size_t)zxd_sz, &cc, &ccs, &ch, &cid);
271
14.0k
        if (rc == ZXC_OK) {
272
2
            assert(ccs == (size_t)dict_sz);
273
2
            assert(zxc_dict_compute_id(cc, ccs, ch) == cid);
274
2
            if (pos < ZXC_DICT_HEADER_SIZE) assert(memcmp(cc, dict_buf, (size_t)dict_sz) == 0);
275
2
        }
276
14.0k
        zxd_buf[pos] = saved;
277
14.0k
    }
278
279
    /* ------------------------------------------------------------------ */
280
    /* Phase 3: real compress -> decompress roundtrip with the trained    */
281
    /* dict (also keeps the in-memory dict bounce path covered).          */
282
    /* ------------------------------------------------------------------ */
283
14.0k
    const size_t bound = zxc_compress_bound(size);
284
14.0k
    if (bound == 0) return 0;
285
    /* Exact sizes: ASan sees overruns. */
286
14.0k
    uint8_t* const comp_buf = (uint8_t*)malloc(bound);
287
14.0k
    uint8_t* const comp2_buf = (uint8_t*)malloc(bound);
288
14.0k
    uint8_t* const decomp_buf = (uint8_t*)malloc(size);
289
14.0k
    if (comp_buf && comp2_buf && decomp_buf)
290
14.0k
        dict_roundtrip(data, size, level, use_checksum, dict_buf, (size_t)dict_sz,
291
14.0k
                       use_huf ? huf : NULL, comp_buf, comp2_buf, bound, decomp_buf);
292
14.0k
    free(comp_buf);
293
14.0k
    free(comp2_buf);
294
14.0k
    free(decomp_buf);
295
296
14.0k
    return 0;
297
14.0k
}