1 #include <stdio.h>
2 #include <stddef.h>
3 #include <stdint.h>
4 #include <string.h>
5 #include <assert.h>
6 #include <stdlib.h>
7 #include <inttypes.h>
8
9 #include "zbuild.h"
10 #ifdef ZLIB_COMPAT
11 # include "zlib.h"
12 #else
13 # include "zlib-ng.h"
14 #endif
15
16 static const uint8_t *data;
17 static size_t dataLen;
18
check_compress_level(uint8_t * compr,z_size_t comprLen,uint8_t * uncompr,z_size_t uncomprLen,int level)19 static void check_compress_level(uint8_t *compr, z_size_t comprLen,
20 uint8_t *uncompr, z_size_t uncomprLen,
21 int level) {
22 PREFIX(compress2)(compr, &comprLen, data, dataLen, level);
23 PREFIX(uncompress)(uncompr, &uncomprLen, compr, comprLen);
24
25 /* Make sure compress + uncompress gives back the input data. */
26 assert(dataLen == uncomprLen);
27 assert(0 == memcmp(data, uncompr, dataLen));
28 }
29
30 #define put_byte(s, i, c) {s[i] = (unsigned char)(c);}
31
write_zlib_header(uint8_t * s)32 static void write_zlib_header(uint8_t *s) {
33 unsigned level_flags = 0; /* compression level (0..3) */
34 unsigned w_bits = 8; /* window size log2(w_size) (8..16) */
35 unsigned int header = (Z_DEFLATED + ((w_bits-8)<<4)) << 8;
36 header |= (level_flags << 6);
37
38 header += 31 - (header % 31);
39
40 /* s is guaranteed to be longer than 2 bytes. */
41 put_byte(s, 0, (header >> 8));
42 put_byte(s, 1, (header & 0xff));
43 }
44
check_decompress(uint8_t * compr,size_t comprLen)45 static void check_decompress(uint8_t *compr, size_t comprLen) {
46 /* We need to write a valid zlib header of size two bytes. Copy the input data
47 in a larger buffer. Do not modify the input data to avoid libFuzzer error:
48 fuzz target overwrites its const input. */
49 size_t copyLen = dataLen + 2;
50 uint8_t *copy = (uint8_t *)malloc(copyLen);
51 memcpy(copy + 2, data, dataLen);
52 write_zlib_header(copy);
53
54 PREFIX(uncompress)(compr, &comprLen, copy, copyLen);
55 free(copy);
56 }
57
LLVMFuzzerTestOneInput(const uint8_t * d,size_t size)58 int LLVMFuzzerTestOneInput(const uint8_t *d, size_t size) {
59 /* compressBound does not provide enough space for low compression levels. */
60 z_size_t comprLen = 100 + 2 * PREFIX(compressBound)(size);
61 z_size_t uncomprLen = (z_size_t)size;
62 uint8_t *compr, *uncompr;
63
64 /* Discard inputs larger than 1Mb. */
65 static size_t kMaxSize = 1024 * 1024;
66
67 if (size < 1 || size > kMaxSize)
68 return 0;
69
70 data = d;
71 dataLen = size;
72 compr = (uint8_t *)calloc(1, comprLen);
73 uncompr = (uint8_t *)calloc(1, uncomprLen);
74
75 check_compress_level(compr, comprLen, uncompr, uncomprLen, 1);
76 check_compress_level(compr, comprLen, uncompr, uncomprLen, 3);
77 check_compress_level(compr, comprLen, uncompr, uncomprLen, 6);
78 check_compress_level(compr, comprLen, uncompr, uncomprLen, 7);
79
80 check_decompress(compr, comprLen);
81
82 free(compr);
83 free(uncompr);
84
85 /* This function must return 0. */
86 return 0;
87 }
88