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 "lz4.h"
13 
LLVMFuzzerTestOneInput(const uint8_t * data,size_t size)14 int LLVMFuzzerTestOneInput(const uint8_t *data, size_t size)
15 {
16 
17     uint32_t seed = FUZZ_seed(&data, &size);
18     size_t const dstCapacity = FUZZ_rand32(&seed, 0, 4 * size);
19     size_t const smallDictSize = size + 1;
20     size_t const largeDictSize = 64 * 1024 - 1;
21     size_t const dictSize = MAX(smallDictSize, largeDictSize);
22     char* const dst = (char*)malloc(dstCapacity);
23     char* const dict = (char*)malloc(dictSize + size);
24     char* const largeDict = dict;
25     char* const dataAfterDict = dict + dictSize;
26     char* const smallDict = dataAfterDict - smallDictSize;
27 
28     FUZZ_ASSERT(dst);
29     FUZZ_ASSERT(dict);
30 
31     /* Prepare the dictionary. The data doesn't matter for decompression. */
32     memset(dict, 0, dictSize);
33     memcpy(dataAfterDict, data, size);
34 
35     /* Decompress using each possible dictionary configuration. */
36     /* No dictionary. */
37     LZ4_decompress_safe_usingDict((char const*)data, dst, size,
38                                   dstCapacity, NULL, 0);
39     /* Small external dictonary. */
40     LZ4_decompress_safe_usingDict((char const*)data, dst, size,
41                                   dstCapacity, smallDict, smallDictSize);
42     /* Large external dictionary. */
43     LZ4_decompress_safe_usingDict((char const*)data, dst, size,
44                                   dstCapacity, largeDict, largeDictSize);
45     /* Small prefix. */
46     LZ4_decompress_safe_usingDict((char const*)dataAfterDict, dst, size,
47                                   dstCapacity, smallDict, smallDictSize);
48     /* Large prefix. */
49     LZ4_decompress_safe_usingDict((char const*)data, dst, size,
50                                   dstCapacity, largeDict, largeDictSize);
51     /* Partial decompression. */
52     LZ4_decompress_safe_partial((char const*)data, dst, size,
53                                 dstCapacity, dstCapacity);
54     free(dst);
55     free(dict);
56 
57     return 0;
58 }
59