1 /**
2  * This fuzz target attempts to decompress the fuzzed data with the simple
3  * decompression function to ensure the decompressor never crashes.
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 "fuzz_data_producer.h"
13 #include "lz4.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 dstCapacitySeed = FUZZ_dataProducer_retrieve32(producer);
19     size = FUZZ_dataProducer_remainingBytes(producer);
20 
21     size_t const dstCapacity = FUZZ_getRange_from_uint32(dstCapacitySeed, 0, 4 * size);
22     size_t const smallDictSize = size + 1;
23     size_t const largeDictSize = 64 * 1024 - 1;
24     size_t const dictSize = MAX(smallDictSize, largeDictSize);
25     char* const dst = (char*)malloc(dstCapacity);
26     char* const dict = (char*)malloc(dictSize + size);
27     char* const largeDict = dict;
28     char* const dataAfterDict = dict + dictSize;
29     char* const smallDict = dataAfterDict - smallDictSize;
30 
31     FUZZ_ASSERT(dst);
32     FUZZ_ASSERT(dict);
33 
34     /* Prepare the dictionary. The data doesn't matter for decompression. */
35     memset(dict, 0, dictSize);
36     memcpy(dataAfterDict, data, size);
37 
38     /* Decompress using each possible dictionary configuration. */
39     /* No dictionary. */
40     LZ4_decompress_safe_usingDict((char const*)data, dst, size,
41                                   dstCapacity, NULL, 0);
42     /* Small external dictonary. */
43     LZ4_decompress_safe_usingDict((char const*)data, dst, size,
44                                   dstCapacity, smallDict, smallDictSize);
45     /* Large external dictionary. */
46     LZ4_decompress_safe_usingDict((char const*)data, dst, size,
47                                   dstCapacity, largeDict, largeDictSize);
48     /* Small prefix. */
49     LZ4_decompress_safe_usingDict((char const*)dataAfterDict, dst, size,
50                                   dstCapacity, smallDict, smallDictSize);
51     /* Large prefix. */
52     LZ4_decompress_safe_usingDict((char const*)data, dst, size,
53                                   dstCapacity, largeDict, largeDictSize);
54     /* Partial decompression. */
55     LZ4_decompress_safe_partial((char const*)data, dst, size,
56                                 dstCapacity, dstCapacity);
57     free(dst);
58     free(dict);
59     FUZZ_dataProducer_free(producer);
60 
61     return 0;
62 }
63