1 /**
2  * This fuzz target performs a lz4 round-trip test (compress & decompress),
3  * compares the result with the original, and calls abort() on corruption.
4  */
5 
6 #include <stddef.h>
7 #include <stdint.h>
8 #include <stdlib.h>
9 #include <string.h>
10 
11 #include "fuzz_helpers.h"
12 #include "lz4.h"
13 #include "fuzz_data_producer.h"
14 
LLVMFuzzerTestOneInput(const uint8_t * data,size_t size)15 int LLVMFuzzerTestOneInput(const uint8_t *data, size_t size)
16 {
17     FUZZ_dataProducer_t *producer = FUZZ_dataProducer_create(data, size);
18     size_t const partialCapacitySeed = FUZZ_dataProducer_retrieve32(producer);
19     size = FUZZ_dataProducer_remainingBytes(producer);
20 
21     size_t const partialCapacity = FUZZ_getRange_from_uint32(partialCapacitySeed, 0, size);
22     size_t const dstCapacity = LZ4_compressBound(size);
23 
24     char* const dst = (char*)malloc(dstCapacity);
25     char* const rt = (char*)malloc(size);
26 
27     FUZZ_ASSERT(dst);
28     FUZZ_ASSERT(rt);
29 
30     /* Compression must succeed and round trip correctly. */
31     int const dstSize = LZ4_compress_default((const char*)data, dst,
32                                              size, dstCapacity);
33     FUZZ_ASSERT(dstSize > 0);
34 
35     int const rtSize = LZ4_decompress_safe(dst, rt, dstSize, size);
36     FUZZ_ASSERT_MSG(rtSize == size, "Incorrect size");
37     FUZZ_ASSERT_MSG(!memcmp(data, rt, size), "Corruption!");
38 
39     /* Partial decompression must succeed. */
40     {
41         char* const partial = (char*)malloc(partialCapacity);
42         FUZZ_ASSERT(partial);
43         int const partialSize = LZ4_decompress_safe_partial(
44                 dst, partial, dstSize, partialCapacity, partialCapacity);
45         FUZZ_ASSERT(partialSize >= 0);
46         FUZZ_ASSERT_MSG(partialSize == partialCapacity, "Incorrect size");
47         FUZZ_ASSERT_MSG(!memcmp(data, partial, partialSize), "Corruption!");
48         free(partial);
49     }
50 
51 
52     free(dst);
53     free(rt);
54     FUZZ_dataProducer_free(producer);
55 
56     return 0;
57 }
58