• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /**
2  * This fuzz target attempts to compress the fuzzed data with the simple
3  * compression function with an output buffer that may be too small to
4  * ensure that the compressor never crashes.
5  */
6 
7 #include <stddef.h>
8 #include <stdint.h>
9 #include <stdlib.h>
10 #include <string.h>
11 
12 #include "fuzz_helpers.h"
13 #include "fuzz_data_producer.h"
14 #include "lz4.h"
15 #include "lz4hc.h"
16 
LLVMFuzzerTestOneInput(const uint8_t * data,size_t size)17 int LLVMFuzzerTestOneInput(const uint8_t *data, size_t size)
18 {
19     FUZZ_dataProducer_t *producer = FUZZ_dataProducer_create(data, size);
20     size_t const dstCapacitySeed = FUZZ_dataProducer_retrieve32(producer);
21     size_t const levelSeed = FUZZ_dataProducer_retrieve32(producer);
22     size = FUZZ_dataProducer_remainingBytes(producer);
23 
24     size_t const dstCapacity = FUZZ_getRange_from_uint32(dstCapacitySeed, 0, size);
25     int const level = FUZZ_getRange_from_uint32(levelSeed, LZ4HC_CLEVEL_MIN, LZ4HC_CLEVEL_MAX);
26 
27     char* const dst = (char*)malloc(dstCapacity);
28     char* const rt = (char*)malloc(size);
29 
30     FUZZ_ASSERT(dst);
31     FUZZ_ASSERT(rt);
32 
33     /* If compression succeeds it must round trip correctly. */
34     {
35         int const dstSize = LZ4_compress_HC((const char*)data, dst, size,
36                                             dstCapacity, level);
37         if (dstSize > 0) {
38             int const rtSize = LZ4_decompress_safe(dst, rt, dstSize, size);
39             FUZZ_ASSERT_MSG(rtSize == size, "Incorrect regenerated size");
40             FUZZ_ASSERT_MSG(!memcmp(data, rt, size), "Corruption!");
41         }
42     }
43 
44     if (dstCapacity > 0) {
45         /* Compression succeeds and must round trip correctly. */
46         void* state = malloc(LZ4_sizeofStateHC());
47         FUZZ_ASSERT(state);
48         int compressedSize = size;
49         int const dstSize = LZ4_compress_HC_destSize(state, (const char*)data,
50                                                      dst, &compressedSize,
51                                                      dstCapacity, level);
52         FUZZ_ASSERT(dstSize > 0);
53         int const rtSize = LZ4_decompress_safe(dst, rt, dstSize, size);
54         FUZZ_ASSERT_MSG(rtSize == compressedSize, "Incorrect regenerated size");
55         FUZZ_ASSERT_MSG(!memcmp(data, rt, compressedSize), "Corruption!");
56         free(state);
57     }
58 
59     free(dst);
60     free(rt);
61     FUZZ_dataProducer_free(producer);
62 
63     return 0;
64 }
65