Debian Codegraph @

src/fuzz/fuzz-compress.c

raw
1 /* SPDX-License-Identifier: LGPL-2.1-or-later */
2
3 #include "alloc-util.h"
4 #include "compress.h"
5 #include "fuzz.h"
6 #include "tests.h"
7
8 typedef struct header {
9 uint32_t alg:2; /* We have only three compression algorithms so far, but we might add more in the
10 * future. Let's make this a bit wider so our fuzzer cases remain stable in the
11 * future. */
12 uint32_t sw_len;
13 uint32_t sw_alloc;
14 uint32_t reserved[3]; /* Extra space to keep fuzz cases stable in case we need to
15 * add stuff in the future. */
16 uint8_t data[];
17 } header;
18
19 int LLVMFuzzerTestOneInput(const uint8_t *data, size_t size) {
20 _cleanup_free_ void *buf = NULL, *buf2 = NULL;
21 int r;
22
23 if (size < offsetof(header, data) + 1)
24 return 0;
25
26 const header *h = (struct header*) data;
27 const size_t data_len = size - offsetof(header, data);
28
29 int alg = h->alg;
30
31 fuzz_setup_logging();
32
33 log_info("Using compression %s, data size=%zu",
34 compression_to_string(alg),
35 data_len);
36
37 buf = malloc(MAX(size, 128u)); /* Make the buffer a bit larger for very small data */
38 if (!buf) {
39 log_oom();
40 return 0;
41 }
42
43 size_t csize;
44 r = compress_blob(alg, h->data, data_len, buf, size, &csize, /* level= */ -1);
45 if (r < 0) {
46 log_error_errno(r, "Compression failed: %m");
47 return 0;
48 }
49
50 log_debug("Compressed %zu bytes to → %zu bytes", data_len, csize);
51
52 size_t sw_alloc = MAX(h->sw_alloc, 1u);
53 buf2 = malloc(sw_alloc);
54 if (!buf2) {
55 log_oom();
56 return 0;
57 }
58
59 size_t sw_len = MIN(data_len - 1, h->sw_len);
60
61 ASSERT_OK(decompress_startswith(alg, buf, csize, &buf2, h->data, sw_len, h->data[sw_len]));
62 return 0;
63 }