1 /*
2 fuzzer.c - Fuzzer test tool for LZ4
3 Copyright (C) Yann Collet 2012-2020
4
5 GPL v2 License
6
7 This program is free software; you can redistribute it and/or modify
8 it under the terms of the GNU General Public License as published by
9 the Free Software Foundation; either version 2 of the License, or
10 (at your option) any later version.
11
12 This program is distributed in the hope that it will be useful,
13 but WITHOUT ANY WARRANTY; without even the implied warranty of
14 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 GNU General Public License for more details.
16
17 You should have received a copy of the GNU General Public License along
18 with this program; if not, write to the Free Software Foundation, Inc.,
19 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
20
21 You can contact the author at :
22 - LZ4 homepage : http://www.lz4.org
23 - LZ4 source repo : https://github.com/lz4/lz4
24 */
25
26 /*-************************************
27 * Compiler options
28 **************************************/
29 #ifdef _MSC_VER /* Visual Studio */
30 # pragma warning(disable : 4127) /* disable: C4127: conditional expression is constant */
31 # pragma warning(disable : 4146) /* disable: C4146: minus unsigned expression */
32 # pragma warning(disable : 4310) /* disable: C4310: constant char value > 127 */
33 # pragma warning(disable : 26451) /* disable: C26451: Arithmetic overflow */
34 #endif
35
36
37 /*-************************************
38 * Dependencies
39 **************************************/
40 #if defined(__unix__) && !defined(_AIX) /* must be included before platform.h for MAP_ANONYMOUS */
41 # undef _GNU_SOURCE /* in case it's already defined */
42 # define _GNU_SOURCE /* MAP_ANONYMOUS even in -std=c99 mode */
43 # include <sys/mman.h> /* mmap */
44 #endif
45 #include "platform.h" /* _CRT_SECURE_NO_WARNINGS */
46 #include "util.h" /* U32 */
47 #include <stdlib.h>
48 #include <stdio.h> /* fgets, sscanf */
49 #include <string.h> /* strcmp */
50 #include <time.h> /* clock_t, clock, CLOCKS_PER_SEC */
51 #include <assert.h>
52 #include <limits.h> /* INT_MAX */
53
54 #if defined(_AIX)
55 # include <sys/mman.h> /* mmap */
56 #endif
57
58 #define LZ4_DISABLE_DEPRECATE_WARNINGS /* LZ4_decompress_fast */
59 #define LZ4_STATIC_LINKING_ONLY
60 #include "lz4.h"
61 #define LZ4_HC_STATIC_LINKING_ONLY
62 #include "lz4hc.h"
63 #define XXH_STATIC_LINKING_ONLY
64 #include "xxhash.h"
65
66
67 /*-************************************
68 * Basic Types
69 **************************************/
70 #if !defined(__cplusplus) && !(defined (__STDC_VERSION__) && (__STDC_VERSION__ >= 199901L) /* C99 */)
71 typedef size_t uintptr_t; /* true on most systems, except OpenVMS-64 (which doesn't need address overflow test) */
72 #endif
73
74
75 /*-************************************
76 * Constants
77 **************************************/
78 #define NB_ATTEMPTS (1<<16)
79 #define COMPRESSIBLE_NOISE_LENGTH (1 << 21)
80 #define FUZ_MAX_BLOCK_SIZE (1 << 17)
81 #define FUZ_MAX_DICT_SIZE (1 << 15)
82 #define FUZ_COMPRESSIBILITY_DEFAULT 60
83 #define PRIME1 2654435761U
84 #define PRIME2 2246822519U
85 #define PRIME3 3266489917U
86
87 #define KB *(1U<<10)
88 #define MB *(1U<<20)
89 #define GB *(1U<<30)
90
91
92 /*-***************************************
93 * Macros
94 *****************************************/
95 #define DISPLAY(...) fprintf(stdout, __VA_ARGS__)
96 #define DISPLAYLEVEL(l, ...) if (g_displayLevel>=l) { DISPLAY(__VA_ARGS__); }
97 static int g_displayLevel = 2;
98
99 #define MIN(a,b) ( (a) < (b) ? (a) : (b) )
100
101
102 /*-*******************************************************
103 * Fuzzer functions
104 *********************************************************/
FUZ_GetClockSpan(clock_t clockStart)105 static clock_t FUZ_GetClockSpan(clock_t clockStart)
106 {
107 return clock() - clockStart; /* works even if overflow; max span ~ 30mn */
108 }
109
FUZ_displayUpdate(unsigned testNb)110 static void FUZ_displayUpdate(unsigned testNb)
111 {
112 static clock_t g_time = 0;
113 static const clock_t g_refreshRate = CLOCKS_PER_SEC / 5;
114 if ((FUZ_GetClockSpan(g_time) > g_refreshRate) || (g_displayLevel>=4)) {
115 g_time = clock();
116 DISPLAY("\r%5u ", testNb);
117 fflush(stdout);
118 }
119 }
120
FUZ_rotl32(U32 u32,U32 nbBits)121 static U32 FUZ_rotl32(U32 u32, U32 nbBits)
122 {
123 return ((u32 << nbBits) | (u32 >> (32 - nbBits)));
124 }
125
FUZ_highbit32(U32 v32)126 static U32 FUZ_highbit32(U32 v32)
127 {
128 unsigned nbBits = 0;
129 if (v32==0) return 0;
130 while (v32) { v32 >>= 1; nbBits++; }
131 return nbBits;
132 }
133
FUZ_rand(U32 * src)134 static U32 FUZ_rand(U32* src)
135 {
136 U32 rand32 = *src;
137 rand32 *= PRIME1;
138 rand32 ^= PRIME2;
139 rand32 = FUZ_rotl32(rand32, 13);
140 *src = rand32;
141 return rand32;
142 }
143
144
145 #define FUZ_RAND15BITS ((FUZ_rand(seed) >> 3) & 32767)
146 #define FUZ_RANDLENGTH ( ((FUZ_rand(seed) >> 7) & 3) ? (FUZ_rand(seed) % 15) : (FUZ_rand(seed) % 510) + 15)
FUZ_fillCompressibleNoiseBuffer(void * buffer,size_t bufferSize,double proba,U32 * seed)147 static void FUZ_fillCompressibleNoiseBuffer(void* buffer, size_t bufferSize, double proba, U32* seed)
148 {
149 BYTE* const BBuffer = (BYTE*)buffer;
150 size_t pos = 0;
151 U32 const P32 = (U32)(32768 * proba);
152
153 /* First Bytes */
154 while (pos < 20)
155 BBuffer[pos++] = (BYTE)(FUZ_rand(seed));
156
157 while (pos < bufferSize) {
158 /* Select : Literal (noise) or copy (within 64K) */
159 if (FUZ_RAND15BITS < P32) {
160 /* Copy (within 64K) */
161 size_t const length = (size_t)FUZ_RANDLENGTH + 4;
162 size_t const d = MIN(pos+length, bufferSize);
163 size_t match;
164 size_t offset = (size_t)FUZ_RAND15BITS + 1;
165 while (offset > pos) offset >>= 1;
166 match = pos - offset;
167 while (pos < d) BBuffer[pos++] = BBuffer[match++];
168 } else {
169 /* Literal (noise) */
170 size_t const length = FUZ_RANDLENGTH;
171 size_t const d = MIN(pos+length, bufferSize);
172 while (pos < d) BBuffer[pos++] = (BYTE)(FUZ_rand(seed) >> 5);
173 }
174 }
175 }
176
177
178 #define MAX_NB_BUFF_I134 150
179 #define BLOCKSIZE_I134 (32 MB)
180 /*! FUZ_AddressOverflow() :
181 * Aggressively pushes memory allocation limits,
182 * and generates patterns which create address space overflow.
183 * only possible in 32-bits mode */
FUZ_AddressOverflow(void)184 static int FUZ_AddressOverflow(void)
185 {
186 char* buffers[MAX_NB_BUFF_I134+1];
187 int nbBuff=0;
188 int highAddress = 0;
189
190 DISPLAY("Overflow tests : ");
191
192 /* Only possible in 32-bits */
193 if (sizeof(void*)==8) {
194 DISPLAY("64 bits mode : no overflow \n");
195 fflush(stdout);
196 return 0;
197 }
198
199 buffers[0] = (char*)malloc(BLOCKSIZE_I134);
200 buffers[1] = (char*)malloc(BLOCKSIZE_I134);
201 if ((!buffers[0]) || (!buffers[1])) {
202 free(buffers[0]); free(buffers[1]);
203 DISPLAY("not enough memory for tests \n");
204 return 0;
205 }
206
207 for (nbBuff=2; nbBuff < MAX_NB_BUFF_I134; nbBuff++) {
208 DISPLAY("%3i \b\b\b\b", nbBuff); fflush(stdout);
209 buffers[nbBuff] = (char*)malloc(BLOCKSIZE_I134);
210 if (buffers[nbBuff]==NULL) goto _endOfTests;
211
212 if (((uintptr_t)buffers[nbBuff] > (uintptr_t)0x80000000) && (!highAddress)) {
213 DISPLAY("high address detected : ");
214 fflush(stdout);
215 highAddress=1;
216 }
217
218 { size_t const sizeToGenerateOverflow = (size_t)(- ((uintptr_t)buffers[nbBuff-1]) + 512);
219 int const nbOf255 = (int)((sizeToGenerateOverflow / 255) + 1);
220 char* const input = buffers[nbBuff-1];
221 char* output = buffers[nbBuff];
222 int r;
223 input[0] = (char)0xF0; /* Literal length overflow */
224 input[1] = (char)0xFF;
225 input[2] = (char)0xFF;
226 input[3] = (char)0xFF;
227 { int u; for(u = 4; u <= nbOf255+4; u++) input[u] = (char)0xff; }
228 r = LZ4_decompress_safe(input, output, nbOf255+64, BLOCKSIZE_I134);
229 if (r>0) { DISPLAY("LZ4_decompress_safe = %i \n", r); goto _overflowError; }
230 input[0] = (char)0x1F; /* Match length overflow */
231 input[1] = (char)0x01;
232 input[2] = (char)0x01;
233 input[3] = (char)0x00;
234 r = LZ4_decompress_safe(input, output, nbOf255+64, BLOCKSIZE_I134);
235 if (r>0) { DISPLAY("LZ4_decompress_safe = %i \n", r); goto _overflowError; }
236
237 output = buffers[nbBuff-2]; /* Reverse in/out pointer order */
238 input[0] = (char)0xF0; /* Literal length overflow */
239 input[1] = (char)0xFF;
240 input[2] = (char)0xFF;
241 input[3] = (char)0xFF;
242 r = LZ4_decompress_safe(input, output, nbOf255+64, BLOCKSIZE_I134);
243 if (r>0) goto _overflowError;
244 input[0] = (char)0x1F; /* Match length overflow */
245 input[1] = (char)0x01;
246 input[2] = (char)0x01;
247 input[3] = (char)0x00;
248 r = LZ4_decompress_safe(input, output, nbOf255+64, BLOCKSIZE_I134);
249 if (r>0) goto _overflowError;
250 }
251 }
252
253 nbBuff++;
254 _endOfTests:
255 { int i; for (i=0 ; i<nbBuff; i++) free(buffers[i]); }
256 if (!highAddress) DISPLAY("high address not possible \n");
257 else DISPLAY("all overflows correctly detected \n");
258 return 0;
259
260 _overflowError:
261 DISPLAY("Address space overflow error !! \n");
262 exit(1);
263 }
264
265
266 #ifdef __unix__ /* is expected to be triggered on linux+gcc */
267
FUZ_createLowAddr(size_t size)268 static void* FUZ_createLowAddr(size_t size)
269 {
270 void* const lowBuff = mmap((void*)(0x1000), size,
271 PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS,
272 -1, 0);
273 DISPLAYLEVEL(2, "generating low buffer at address %p \n", lowBuff);
274 return lowBuff;
275 }
276
FUZ_freeLowAddr(void * buffer,size_t size)277 static void FUZ_freeLowAddr(void* buffer, size_t size)
278 {
279 if (munmap(buffer, size)) {
280 perror("fuzzer: freeing low address buffer");
281 abort();
282 }
283 }
284
285 #else
286
FUZ_createLowAddr(size_t size)287 static void* FUZ_createLowAddr(size_t size)
288 {
289 return malloc(size);
290 }
291
FUZ_freeLowAddr(void * buffer,size_t size)292 static void FUZ_freeLowAddr(void* buffer, size_t size)
293 {
294 (void)size;
295 free(buffer);
296 }
297
298 #endif
299
300
301 /*! FUZ_findDiff() :
302 * find the first different byte between buff1 and buff2.
303 * presumes buff1 != buff2.
304 * presumes a difference exists before end of either buffer.
305 * Typically invoked after a checksum mismatch.
306 */
FUZ_findDiff(const void * buff1,const void * buff2)307 static void FUZ_findDiff(const void* buff1, const void* buff2)
308 {
309 const BYTE* const b1 = (const BYTE*)buff1;
310 const BYTE* const b2 = (const BYTE*)buff2;
311 size_t u = 0;
312 while (b1[u]==b2[u]) u++;
313 DISPLAY("\nWrong Byte at position %u \n", (unsigned)u);
314 }
315
316
FUZ_test(U32 seed,U32 nbCycles,const U32 startCycle,const double compressibility,U32 duration_s)317 static int FUZ_test(U32 seed, U32 nbCycles, const U32 startCycle, const double compressibility, U32 duration_s)
318 {
319 unsigned long long bytes = 0;
320 unsigned long long cbytes = 0;
321 unsigned long long hcbytes = 0;
322 unsigned long long ccbytes = 0;
323 void* const CNBuffer = malloc(COMPRESSIBLE_NOISE_LENGTH);
324 size_t const compressedBufferSize = (size_t)LZ4_compressBound(FUZ_MAX_BLOCK_SIZE);
325 char* const compressedBuffer = (char*)malloc(compressedBufferSize);
326 char* const decodedBuffer = (char*)malloc(FUZ_MAX_DICT_SIZE + FUZ_MAX_BLOCK_SIZE);
327 size_t const labSize = 96 KB;
328 void* const lowAddrBuffer = FUZ_createLowAddr(labSize);
329 void* const stateLZ4 = malloc((size_t)LZ4_sizeofState());
330 void* const stateLZ4HC = malloc((size_t)LZ4_sizeofStateHC());
331 LZ4_stream_t LZ4dictBody;
332 LZ4_streamHC_t* LZ4dictHC = LZ4_createStreamHC();
333 U32 coreRandState = seed;
334 clock_t const clockStart = clock();
335 clock_t const clockDuration = (clock_t)duration_s * CLOCKS_PER_SEC;
336 int result = 0;
337 unsigned cycleNb;
338
339 # define EXIT_MSG(...) { \
340 printf("Test %u : ", testNb); printf(__VA_ARGS__); \
341 printf(" (seed %u, cycle %u) \n", seed, cycleNb); \
342 exit(1); \
343 }
344
345 # define FUZ_CHECKTEST(cond, ...) if (cond) { EXIT_MSG(__VA_ARGS__) }
346
347 # define FUZ_DISPLAYTEST(...) { \
348 testNb++; \
349 if (g_displayLevel>=4) { \
350 printf("\r%4u - %2u :", cycleNb, testNb); \
351 printf(" " __VA_ARGS__); \
352 printf(" "); \
353 fflush(stdout); \
354 } }
355
356
357 /* init */
358 if(!CNBuffer || !compressedBuffer || !decodedBuffer || !LZ4dictHC) {
359 DISPLAY("Not enough memory to start fuzzer tests");
360 exit(1);
361 }
362 if ( LZ4_initStream(&LZ4dictBody, sizeof(LZ4dictBody)) == NULL) abort();
363 { U32 randState = coreRandState ^ PRIME3;
364 FUZ_fillCompressibleNoiseBuffer(CNBuffer, COMPRESSIBLE_NOISE_LENGTH, compressibility, &randState);
365 }
366
367 /* move to startCycle */
368 for (cycleNb = 0; cycleNb < startCycle; cycleNb++)
369 (void) FUZ_rand(&coreRandState); /* sync coreRandState */
370
371 /* Main test loop */
372 for (cycleNb = startCycle;
373 (cycleNb < nbCycles) || (FUZ_GetClockSpan(clockStart) < clockDuration);
374 cycleNb++) {
375 U32 testNb = 0;
376 U32 randState = FUZ_rand(&coreRandState) ^ PRIME3;
377 int const blockSize = (FUZ_rand(&randState) % (FUZ_MAX_BLOCK_SIZE-1)) + 1;
378 int const blockStart = (int)(FUZ_rand(&randState) % (U32)(COMPRESSIBLE_NOISE_LENGTH - blockSize - 1)) + 1;
379 int const dictSizeRand = FUZ_rand(&randState) % FUZ_MAX_DICT_SIZE;
380 int const dictSize = MIN(dictSizeRand, blockStart - 1);
381 int const compressionLevel = FUZ_rand(&randState) % (LZ4HC_CLEVEL_MAX+1);
382 const char* block = ((char*)CNBuffer) + blockStart;
383 const char* dict = block - dictSize;
384 int compressedSize, HCcompressedSize;
385 int blockContinueCompressedSize;
386 U32 const crcOrig = XXH32(block, (size_t)blockSize, 0);
387 int ret;
388
389 FUZ_displayUpdate(cycleNb);
390
391 /* Compression tests */
392 if ( ((FUZ_rand(&randState) & 63) == 2)
393 && ((size_t)blockSize < labSize) ) {
394 memcpy(lowAddrBuffer, block, blockSize);
395 block = (const char*)lowAddrBuffer;
396 }
397
398 /* Test compression destSize */
399 FUZ_DISPLAYTEST("test LZ4_compress_destSize()");
400 { int cSize, srcSize = blockSize;
401 int const targetSize = srcSize * (int)((FUZ_rand(&randState) & 127)+1) >> 7;
402 char const endCheck = (char)(FUZ_rand(&randState) & 255);
403 compressedBuffer[targetSize] = endCheck;
404 cSize = LZ4_compress_destSize(block, compressedBuffer, &srcSize, targetSize);
405 FUZ_CHECKTEST(cSize > targetSize, "LZ4_compress_destSize() result larger than dst buffer !");
406 FUZ_CHECKTEST(compressedBuffer[targetSize] != endCheck, "LZ4_compress_destSize() overwrite dst buffer !");
407 FUZ_CHECKTEST(srcSize > blockSize, "LZ4_compress_destSize() read more than src buffer !");
408 DISPLAYLEVEL(5, "destSize : %7i/%7i; content%7i/%7i ", cSize, targetSize, srcSize, blockSize);
409 if (targetSize>0) {
410 /* check correctness */
411 U32 const crcBase = XXH32(block, (size_t)srcSize, 0);
412 char const canary = (char)(FUZ_rand(&randState) & 255);
413 FUZ_CHECKTEST((cSize==0), "LZ4_compress_destSize() compression failed");
414 FUZ_DISPLAYTEST();
415 decodedBuffer[srcSize] = canary;
416 { int const dSize = LZ4_decompress_safe(compressedBuffer, decodedBuffer, cSize, srcSize);
417 FUZ_CHECKTEST(dSize<0, "LZ4_decompress_safe() failed on data compressed by LZ4_compress_destSize");
418 FUZ_CHECKTEST(dSize!=srcSize, "LZ4_decompress_safe() failed : did not fully decompressed data");
419 }
420 FUZ_CHECKTEST(decodedBuffer[srcSize] != canary, "LZ4_decompress_safe() overwrite dst buffer !");
421 { U32 const crcDec = XXH32(decodedBuffer, (size_t)srcSize, 0);
422 FUZ_CHECKTEST(crcDec!=crcBase, "LZ4_decompress_safe() corrupted decoded data");
423 } }
424 DISPLAYLEVEL(5, " OK \n");
425 }
426
427 /* Test compression HC destSize */
428 FUZ_DISPLAYTEST("test LZ4_compress_HC_destSize()");
429 { int cSize, srcSize = blockSize;
430 int const targetSize = srcSize * (int)((FUZ_rand(&randState) & 127)+1) >> 7;
431 char const endCheck = (char)(FUZ_rand(&randState) & 255);
432 void* const ctx = LZ4_createHC(block);
433 FUZ_CHECKTEST(ctx==NULL, "LZ4_createHC() allocation failed");
434 compressedBuffer[targetSize] = endCheck;
435 cSize = LZ4_compress_HC_destSize(ctx, block, compressedBuffer, &srcSize, targetSize, compressionLevel);
436 DISPLAYLEVEL(5, "LZ4_compress_HC_destSize(%i): destSize : %7i/%7i; content%7i/%7i ",
437 compressionLevel, cSize, targetSize, srcSize, blockSize);
438 LZ4_freeHC(ctx);
439 FUZ_CHECKTEST(cSize > targetSize, "LZ4_compress_HC_destSize() result larger than dst buffer !");
440 FUZ_CHECKTEST(compressedBuffer[targetSize] != endCheck, "LZ4_compress_HC_destSize() overwrite dst buffer !");
441 FUZ_CHECKTEST(srcSize > blockSize, "LZ4_compress_HC_destSize() fed more than src buffer !");
442 if (targetSize>0) {
443 /* check correctness */
444 U32 const crcBase = XXH32(block, (size_t)srcSize, 0);
445 char const canary = (char)(FUZ_rand(&randState) & 255);
446 FUZ_CHECKTEST((cSize==0), "LZ4_compress_HC_destSize() compression failed");
447 FUZ_DISPLAYTEST();
448 decodedBuffer[srcSize] = canary;
449 { int const dSize = LZ4_decompress_safe(compressedBuffer, decodedBuffer, cSize, srcSize);
450 FUZ_CHECKTEST(dSize<0, "LZ4_decompress_safe failed (%i) on data compressed by LZ4_compressHC_destSize", dSize);
451 FUZ_CHECKTEST(dSize!=srcSize, "LZ4_decompress_safe failed : decompressed %i bytes, was supposed to decompress %i bytes", dSize, srcSize);
452 }
453 FUZ_CHECKTEST(decodedBuffer[srcSize] != canary, "LZ4_decompress_safe overwrite dst buffer !");
454 { U32 const crcDec = XXH32(decodedBuffer, (size_t)srcSize, 0);
455 FUZ_CHECKTEST(crcDec!=crcBase, "LZ4_decompress_safe() corrupted decoded data");
456 } }
457 DISPLAYLEVEL(5, " OK \n");
458 }
459
460 /* Test compression HC */
461 FUZ_DISPLAYTEST("test LZ4_compress_HC()");
462 HCcompressedSize = LZ4_compress_HC(block, compressedBuffer, blockSize, (int)compressedBufferSize, compressionLevel);
463 FUZ_CHECKTEST(HCcompressedSize==0, "LZ4_compress_HC() failed");
464
465 /* Test compression HC using external state */
466 FUZ_DISPLAYTEST("test LZ4_compress_HC_extStateHC()");
467 { int const r = LZ4_compress_HC_extStateHC(stateLZ4HC, block, compressedBuffer, blockSize, (int)compressedBufferSize, compressionLevel);
468 FUZ_CHECKTEST(r==0, "LZ4_compress_HC_extStateHC() failed")
469 }
470
471 /* Test compression HC using fast reset external state */
472 FUZ_DISPLAYTEST("test LZ4_compress_HC_extStateHC_fastReset()");
473 { int const r = LZ4_compress_HC_extStateHC_fastReset(stateLZ4HC, block, compressedBuffer, blockSize, (int)compressedBufferSize, compressionLevel);
474 FUZ_CHECKTEST(r==0, "LZ4_compress_HC_extStateHC_fastReset() failed");
475 }
476
477 /* Test compression using external state */
478 FUZ_DISPLAYTEST("test LZ4_compress_fast_extState()");
479 { int const r = LZ4_compress_fast_extState(stateLZ4, block, compressedBuffer, blockSize, (int)compressedBufferSize, 8);
480 FUZ_CHECKTEST(r==0, "LZ4_compress_fast_extState() failed"); }
481
482 /* Test compression using fast reset external state*/
483 FUZ_DISPLAYTEST();
484 { int const r = LZ4_compress_fast_extState_fastReset(stateLZ4, block, compressedBuffer, blockSize, (int)compressedBufferSize, 8);
485 FUZ_CHECKTEST(r==0, "LZ4_compress_fast_extState_fastReset() failed"); }
486
487 /* Test compression */
488 FUZ_DISPLAYTEST("test LZ4_compress_default()");
489 compressedSize = LZ4_compress_default(block, compressedBuffer, blockSize, (int)compressedBufferSize);
490 FUZ_CHECKTEST(compressedSize<=0, "LZ4_compress_default() failed");
491
492 /* Decompression tests */
493
494 /* Test decompress_fast() with input buffer size exactly correct => must not read out of bound */
495 { char* const cBuffer_exact = (char*)malloc((size_t)compressedSize);
496 assert(cBuffer_exact != NULL);
497 assert(compressedSize <= (int)compressedBufferSize);
498 #if defined(_MSC_VER) && (_MSC_VER <= 1933) /* MSVC 2022 ver 17.3 or earlier */
499 # pragma warning(push)
500 # pragma warning(disable : 6385) /* lz4\tests\fuzzer.c(497): warning C6385: Reading invalid data from 'compressedBuffer'. */
501 #endif
502 memcpy(cBuffer_exact, compressedBuffer, compressedSize);
503 #if defined(_MSC_VER) && (_MSC_VER <= 1933) /* MSVC 2022 ver 17.3 or earlier */
504 # pragma warning(pop)
505 #endif
506
507 /* Test decoding with output size exactly correct => must work */
508 FUZ_DISPLAYTEST("LZ4_decompress_fast() with exact output buffer");
509 { int const r = LZ4_decompress_fast(cBuffer_exact, decodedBuffer, blockSize);
510 FUZ_CHECKTEST(r<0, "LZ4_decompress_fast failed despite correct space");
511 FUZ_CHECKTEST(r!=compressedSize, "LZ4_decompress_fast failed : did not fully read compressed data");
512 }
513 { U32 const crcCheck = XXH32(decodedBuffer, (size_t)blockSize, 0);
514 FUZ_CHECKTEST(crcCheck!=crcOrig, "LZ4_decompress_fast corrupted decoded data");
515 }
516
517 /* Test decoding with one byte missing => must fail */
518 FUZ_DISPLAYTEST("LZ4_decompress_fast() with output buffer 1-byte too short");
519 decodedBuffer[blockSize-1] = 0;
520 { int const r = LZ4_decompress_fast(cBuffer_exact, decodedBuffer, blockSize-1);
521 FUZ_CHECKTEST(r>=0, "LZ4_decompress_fast should have failed, due to Output Size being too small");
522 }
523 FUZ_CHECKTEST(decodedBuffer[blockSize-1]!=0, "LZ4_decompress_fast overrun specified output buffer");
524
525 /* Test decoding with one byte too much => must fail */
526 FUZ_DISPLAYTEST();
527 { int const r = LZ4_decompress_fast(cBuffer_exact, decodedBuffer, blockSize+1);
528 FUZ_CHECKTEST(r>=0, "LZ4_decompress_fast should have failed, due to Output Size being too large");
529 }
530
531 /* Test decoding with output size exactly what's necessary => must work */
532 FUZ_DISPLAYTEST();
533 decodedBuffer[blockSize] = 0;
534 { int const r = LZ4_decompress_safe(cBuffer_exact, decodedBuffer, compressedSize, blockSize);
535 FUZ_CHECKTEST(r<0, "LZ4_decompress_safe failed despite sufficient space");
536 FUZ_CHECKTEST(r!=blockSize, "LZ4_decompress_safe did not regenerate original data");
537 }
538 FUZ_CHECKTEST(decodedBuffer[blockSize], "LZ4_decompress_safe overrun specified output buffer size");
539 { U32 const crcCheck = XXH32(decodedBuffer, (size_t)blockSize, 0);
540 FUZ_CHECKTEST(crcCheck!=crcOrig, "LZ4_decompress_safe corrupted decoded data");
541 }
542
543 /* Test decoding with more than enough output size => must work */
544 FUZ_DISPLAYTEST();
545 decodedBuffer[blockSize] = 0;
546 decodedBuffer[blockSize+1] = 0;
547 { int const r = LZ4_decompress_safe(cBuffer_exact, decodedBuffer, compressedSize, blockSize+1);
548 FUZ_CHECKTEST(r<0, "LZ4_decompress_safe failed despite amply sufficient space");
549 FUZ_CHECKTEST(r!=blockSize, "LZ4_decompress_safe did not regenerate original data");
550 }
551 FUZ_CHECKTEST(decodedBuffer[blockSize+1], "LZ4_decompress_safe overrun specified output buffer size");
552 { U32 const crcCheck = XXH32(decodedBuffer, (size_t)blockSize, 0);
553 FUZ_CHECKTEST(crcCheck!=crcOrig, "LZ4_decompress_safe corrupted decoded data");
554 }
555
556 /* Test decoding with output size being one byte too short => must fail */
557 FUZ_DISPLAYTEST();
558 decodedBuffer[blockSize-1] = 0;
559 { int const r = LZ4_decompress_safe(cBuffer_exact, decodedBuffer, compressedSize, blockSize-1);
560 FUZ_CHECKTEST(r>=0, "LZ4_decompress_safe should have failed, due to Output Size being one byte too short");
561 }
562 FUZ_CHECKTEST(decodedBuffer[blockSize-1], "LZ4_decompress_safe overrun specified output buffer size");
563
564 /* Test decoding with output size being 10 bytes too short => must fail */
565 FUZ_DISPLAYTEST();
566 if (blockSize>10) {
567 decodedBuffer[blockSize-10] = 0;
568 { int const r = LZ4_decompress_safe(cBuffer_exact, decodedBuffer, compressedSize, blockSize-10);
569 FUZ_CHECKTEST(r>=0, "LZ4_decompress_safe should have failed, due to Output Size being 10 bytes too short");
570 }
571 FUZ_CHECKTEST(decodedBuffer[blockSize-10], "LZ4_decompress_safe overrun specified output buffer size");
572 }
573
574 /* noisy src decompression test */
575
576 /* insert noise into src */
577 { U32 const maxNbBits = FUZ_highbit32((U32)compressedSize);
578 size_t pos = 0;
579 for (;;) {
580 /* keep some original src */
581 { U32 const nbBits = FUZ_rand(&randState) % maxNbBits;
582 size_t const mask = (1ULL <<nbBits) - 1;
583 size_t const skipLength = FUZ_rand(&randState) & mask;
584 pos += skipLength;
585 }
586 if (pos >= (size_t)compressedSize) break;
587 /* add noise */
588 { U32 const nbBitsCodes = FUZ_rand(&randState) % maxNbBits;
589 U32 const nbBits = nbBitsCodes ? nbBitsCodes-1 : 0;
590 size_t const mask = (1ULL <<nbBits) - 1;
591 size_t const rNoiseLength = (FUZ_rand(&randState) & mask) + 1;
592 size_t const noiseLength = MIN(rNoiseLength, (size_t)compressedSize-pos);
593 size_t const noiseStart = FUZ_rand(&randState) % (COMPRESSIBLE_NOISE_LENGTH - noiseLength);
594 memcpy(cBuffer_exact + pos, (const char*)CNBuffer + noiseStart, noiseLength);
595 pos += noiseLength;
596 } } }
597
598 /* decompress noisy source */
599 FUZ_DISPLAYTEST("decompress noisy source ");
600 { U32 const endMark = 0xA9B1C3D6;
601 memcpy(decodedBuffer+blockSize, &endMark, sizeof(endMark));
602 { int const decompressResult = LZ4_decompress_safe(cBuffer_exact, decodedBuffer, compressedSize, blockSize);
603 /* result *may* be an unlikely success, but even then, it must strictly respect dst buffer boundaries */
604 FUZ_CHECKTEST(decompressResult > blockSize, "LZ4_decompress_safe on noisy src : result is too large : %u > %u (dst buffer)", (unsigned)decompressResult, (unsigned)blockSize);
605 }
606 { U32 endCheck; memcpy(&endCheck, decodedBuffer+blockSize, sizeof(endCheck));
607 FUZ_CHECKTEST(endMark!=endCheck, "LZ4_decompress_safe on noisy src : dst buffer overflow");
608 } } /* noisy src decompression test */
609
610 free(cBuffer_exact);
611 }
612
613 /* Test decoding with input size being one byte too short => must fail */
614 FUZ_DISPLAYTEST();
615 { int const r = LZ4_decompress_safe(compressedBuffer, decodedBuffer, compressedSize-1, blockSize);
616 FUZ_CHECKTEST(r>=0, "LZ4_decompress_safe should have failed, due to input size being one byte too short (blockSize=%i, result=%i, compressedSize=%i)", blockSize, r, compressedSize);
617 }
618
619 /* Test decoding with input size being one byte too large => must fail */
620 FUZ_DISPLAYTEST();
621 decodedBuffer[blockSize] = 0;
622 { int const r = LZ4_decompress_safe(compressedBuffer, decodedBuffer, compressedSize+1, blockSize);
623 FUZ_CHECKTEST(r>=0, "LZ4_decompress_safe should have failed, due to input size being too large");
624 }
625 FUZ_CHECKTEST(decodedBuffer[blockSize], "LZ4_decompress_safe overrun specified output buffer size");
626
627 /* Test partial decoding => must work */
628 FUZ_DISPLAYTEST("test LZ4_decompress_safe_partial");
629 { size_t const missingOutBytes = FUZ_rand(&randState) % (unsigned)blockSize;
630 int const targetSize = (int)((size_t)blockSize - missingOutBytes);
631 size_t const extraneousInBytes = FUZ_rand(&randState) % 2;
632 int const inCSize = (int)((size_t)compressedSize + extraneousInBytes);
633 char const sentinel = decodedBuffer[targetSize] = block[targetSize] ^ 0x5A;
634 int const decResult = LZ4_decompress_safe_partial(compressedBuffer, decodedBuffer, inCSize, targetSize, blockSize);
635 FUZ_CHECKTEST(decResult<0, "LZ4_decompress_safe_partial failed despite valid input data (error:%i)", decResult);
636 FUZ_CHECKTEST(decResult != targetSize, "LZ4_decompress_safe_partial did not regenerated required amount of data (%i < %i <= %i)", decResult, targetSize, blockSize);
637 FUZ_CHECKTEST(decodedBuffer[targetSize] != sentinel, "LZ4_decompress_safe_partial overwrite beyond requested size (though %i <= %i <= %i)", decResult, targetSize, blockSize);
638 FUZ_CHECKTEST(memcmp(block, decodedBuffer, (size_t)targetSize), "LZ4_decompress_safe_partial: corruption detected in regenerated data");
639 }
640
641 /* Partial decompression using dictionary. */
642 FUZ_DISPLAYTEST("test LZ4_decompress_safe_partial_usingDict using no dict");
643 { size_t const missingOutBytes = FUZ_rand(&randState) % (unsigned)blockSize;
644 int const targetSize = (int)((size_t)blockSize - missingOutBytes);
645 size_t const extraneousInBytes = FUZ_rand(&randState) % 2;
646 int const inCSize = (int)((size_t)compressedSize + extraneousInBytes);
647 char const sentinel = decodedBuffer[targetSize] = block[targetSize] ^ 0x5A;
648 int const decResult = LZ4_decompress_safe_partial_usingDict(compressedBuffer, decodedBuffer, inCSize, targetSize, blockSize, NULL, 0);
649 FUZ_CHECKTEST(decResult<0, "LZ4_decompress_safe_partial_usingDict failed despite valid input data (error:%i)", decResult);
650 FUZ_CHECKTEST(decResult != targetSize, "LZ4_decompress_safe_partial_usingDict did not regenerated required amount of data (%i < %i <= %i)", decResult, targetSize, blockSize);
651 FUZ_CHECKTEST(decodedBuffer[targetSize] != sentinel, "LZ4_decompress_safe_partial_usingDict overwrite beyond requested size (though %i <= %i <= %i)", decResult, targetSize, blockSize);
652 FUZ_CHECKTEST(memcmp(block, decodedBuffer, (size_t)targetSize), "LZ4_decompress_safe_partial_usingDict: corruption detected in regenerated data");
653 }
654
655 FUZ_DISPLAYTEST("test LZ4_decompress_safe_partial_usingDict() using prefix as dict");
656 { size_t const missingOutBytes = FUZ_rand(&randState) % (unsigned)blockSize;
657 int const targetSize = (int)((size_t)blockSize - missingOutBytes);
658 size_t const extraneousInBytes = FUZ_rand(&randState) % 2;
659 int const inCSize = (int)((size_t)compressedSize + extraneousInBytes);
660 char const sentinel = decodedBuffer[targetSize] = block[targetSize] ^ 0x5A;
661 int const decResult = LZ4_decompress_safe_partial_usingDict(compressedBuffer, decodedBuffer, inCSize, targetSize, blockSize, decodedBuffer, dictSize);
662 FUZ_CHECKTEST(decResult<0, "LZ4_decompress_safe_partial_usingDict failed despite valid input data (error:%i)", decResult);
663 FUZ_CHECKTEST(decResult != targetSize, "LZ4_decompress_safe_partial_usingDict did not regenerated required amount of data (%i < %i <= %i)", decResult, targetSize, blockSize);
664 FUZ_CHECKTEST(decodedBuffer[targetSize] != sentinel, "LZ4_decompress_safe_partial_usingDict overwrite beyond requested size (though %i <= %i <= %i)", decResult, targetSize, blockSize);
665 FUZ_CHECKTEST(memcmp(block, decodedBuffer, (size_t)targetSize), "LZ4_decompress_safe_partial_usingDict: corruption detected in regenerated data");
666 }
667
668 FUZ_DISPLAYTEST("test LZ4_decompress_safe_partial_usingDict() using external dict");
669 { size_t const missingOutBytes = FUZ_rand(&randState) % (unsigned)blockSize;
670 int const targetSize = (int)((size_t)blockSize - missingOutBytes);
671 size_t const extraneousInBytes = FUZ_rand(&randState) % 2;
672 int const inCSize = (int)((size_t)compressedSize + extraneousInBytes);
673 char const sentinel = decodedBuffer[targetSize] = block[targetSize] ^ 0x5A;
674 int const decResult = LZ4_decompress_safe_partial_usingDict(compressedBuffer, decodedBuffer, inCSize, targetSize, blockSize, dict, dictSize);
675 FUZ_CHECKTEST(decResult<0, "LZ4_decompress_safe_partial_usingDict failed despite valid input data (error:%i)", decResult);
676 FUZ_CHECKTEST(decResult != targetSize, "LZ4_decompress_safe_partial_usingDict did not regenerated required amount of data (%i < %i <= %i)", decResult, targetSize, blockSize);
677 FUZ_CHECKTEST(decodedBuffer[targetSize] != sentinel, "LZ4_decompress_safe_partial_usingDict overwrite beyond requested size (though %i <= %i <= %i)", decResult, targetSize, blockSize);
678 FUZ_CHECKTEST(memcmp(block, decodedBuffer, (size_t)targetSize), "LZ4_decompress_safe_partial_usingDict: corruption detected in regenerated data");
679 }
680
681 /* Test Compression with limited output size */
682
683 /* Test compression with output size being exactly what's necessary (should work) */
684 FUZ_DISPLAYTEST("test LZ4_compress_default() with output buffer just the right size");
685 ret = LZ4_compress_default(block, compressedBuffer, blockSize, compressedSize);
686 FUZ_CHECKTEST(ret==0, "LZ4_compress_default() failed despite sufficient space");
687
688 /* Test compression with output size being exactly what's necessary and external state (should work) */
689 FUZ_DISPLAYTEST("test LZ4_compress_fast_extState() with output buffer just the right size");
690 ret = LZ4_compress_fast_extState(stateLZ4, block, compressedBuffer, blockSize, compressedSize, 1);
691 FUZ_CHECKTEST(ret==0, "LZ4_compress_fast_extState() failed despite sufficient space");
692
693 /* Test HC compression with output size being exactly what's necessary (should work) */
694 FUZ_DISPLAYTEST("test LZ4_compress_HC() with output buffer just the right size");
695 ret = LZ4_compress_HC(block, compressedBuffer, blockSize, HCcompressedSize, compressionLevel);
696 FUZ_CHECKTEST(ret==0, "LZ4_compress_HC() failed despite sufficient space");
697
698 /* Test HC compression with output size being exactly what's necessary (should work) */
699 FUZ_DISPLAYTEST("test LZ4_compress_HC_extStateHC() with output buffer just the right size");
700 ret = LZ4_compress_HC_extStateHC(stateLZ4HC, block, compressedBuffer, blockSize, HCcompressedSize, compressionLevel);
701 FUZ_CHECKTEST(ret==0, "LZ4_compress_HC_extStateHC() failed despite sufficient space");
702
703 /* Test compression with missing bytes into output buffer => must fail */
704 FUZ_DISPLAYTEST("test LZ4_compress_default() with output buffer a bit too short");
705 { int missingBytes = (FUZ_rand(&randState) % 0x3F) + 1;
706 if (missingBytes >= compressedSize) missingBytes = compressedSize-1;
707 missingBytes += !missingBytes; /* avoid special case missingBytes==0 */
708 compressedBuffer[compressedSize-missingBytes] = 0;
709 { int const cSize = LZ4_compress_default(block, compressedBuffer, blockSize, compressedSize-missingBytes);
710 FUZ_CHECKTEST(cSize, "LZ4_compress_default should have failed (output buffer too small by %i byte)", missingBytes);
711 }
712 FUZ_CHECKTEST(compressedBuffer[compressedSize-missingBytes], "LZ4_compress_default overran output buffer ! (%i missingBytes)", missingBytes)
713 }
714
715 /* Test HC compression with missing bytes into output buffer => must fail */
716 FUZ_DISPLAYTEST("test LZ4_compress_HC() with output buffer a bit too short");
717 { int missingBytes = (FUZ_rand(&randState) % 0x3F) + 1;
718 if (missingBytes >= HCcompressedSize) missingBytes = HCcompressedSize-1;
719 missingBytes += !missingBytes; /* avoid special case missingBytes==0 */
720 compressedBuffer[HCcompressedSize-missingBytes] = 0;
721 { int const hcSize = LZ4_compress_HC(block, compressedBuffer, blockSize, HCcompressedSize-missingBytes, compressionLevel);
722 FUZ_CHECKTEST(hcSize, "LZ4_compress_HC should have failed (output buffer too small by %i byte)", missingBytes);
723 }
724 FUZ_CHECKTEST(compressedBuffer[HCcompressedSize-missingBytes], "LZ4_compress_HC overran output buffer ! (%i missingBytes)", missingBytes)
725 }
726
727
728 /*-******************/
729 /* Dictionary tests */
730 /*-******************/
731
732 /* Compress using dictionary */
733 FUZ_DISPLAYTEST("test LZ4_compress_fast_continue() with dictionary of size %i", dictSize);
734 { LZ4_stream_t LZ4_stream;
735 LZ4_initStream(&LZ4_stream, sizeof(LZ4_stream));
736 LZ4_compress_fast_continue (&LZ4_stream, dict, compressedBuffer, dictSize, (int)compressedBufferSize, 1); /* Just to fill hash tables */
737 blockContinueCompressedSize = LZ4_compress_fast_continue (&LZ4_stream, block, compressedBuffer, blockSize, (int)compressedBufferSize, 1);
738 FUZ_CHECKTEST(blockContinueCompressedSize==0, "LZ4_compress_fast_continue failed");
739 }
740
741 /* Decompress with dictionary as prefix */
742 FUZ_DISPLAYTEST("test LZ4_decompress_fast_usingDict() with dictionary as prefix");
743 memcpy(decodedBuffer, dict, dictSize);
744 ret = LZ4_decompress_fast_usingDict(compressedBuffer, decodedBuffer+dictSize, blockSize, decodedBuffer, dictSize);
745 FUZ_CHECKTEST(ret!=blockContinueCompressedSize, "LZ4_decompress_fast_usingDict did not read all compressed block input");
746 { U32 const crcCheck = XXH32(decodedBuffer+dictSize, (size_t)blockSize, 0);
747 if (crcCheck!=crcOrig) {
748 FUZ_findDiff(block, decodedBuffer);
749 EXIT_MSG("LZ4_decompress_fast_usingDict corrupted decoded data (dict %i)", dictSize);
750 } }
751
752 FUZ_DISPLAYTEST("test LZ4_decompress_safe_usingDict()");
753 ret = LZ4_decompress_safe_usingDict(compressedBuffer, decodedBuffer+dictSize, blockContinueCompressedSize, blockSize, decodedBuffer, dictSize);
754 FUZ_CHECKTEST(ret!=blockSize, "LZ4_decompress_safe_usingDict did not regenerate original data");
755 { U32 const crcCheck = XXH32(decodedBuffer+dictSize, (size_t)blockSize, 0);
756 FUZ_CHECKTEST(crcCheck!=crcOrig, "LZ4_decompress_safe_usingDict corrupted decoded data");
757 }
758
759 /* Compress using External dictionary */
760 FUZ_DISPLAYTEST("test LZ4_compress_fast_continue(), with non-contiguous dictionary");
761 dict -= (size_t)(FUZ_rand(&randState) & 0xF) + 1; /* create space, so now dictionary is an ExtDict */
762 if (dict < (char*)CNBuffer) dict = (char*)CNBuffer;
763 LZ4_loadDict(&LZ4dictBody, dict, dictSize);
764 blockContinueCompressedSize = LZ4_compress_fast_continue(&LZ4dictBody, block, compressedBuffer, blockSize, (int)compressedBufferSize, 1);
765 FUZ_CHECKTEST(blockContinueCompressedSize==0, "LZ4_compress_fast_continue failed");
766
767 FUZ_DISPLAYTEST("LZ4_compress_fast_continue() with dictionary and output buffer too short by one byte");
768 LZ4_loadDict(&LZ4dictBody, dict, dictSize);
769 ret = LZ4_compress_fast_continue(&LZ4dictBody, block, compressedBuffer, blockSize, blockContinueCompressedSize-1, 1);
770 FUZ_CHECKTEST(ret>0, "LZ4_compress_fast_continue using ExtDict should fail : one missing byte for output buffer : %i written, %i buffer", ret, blockContinueCompressedSize);
771
772 FUZ_DISPLAYTEST("test LZ4_compress_fast_continue() with dictionary loaded with LZ4_loadDict()");
773 DISPLAYLEVEL(5, " compress %i bytes from buffer(%p) into dst(%p) using dict(%p) of size %i \n",
774 blockSize, (const void *)block, (void *)decodedBuffer, (const void *)dict, dictSize);
775 LZ4_loadDict(&LZ4dictBody, dict, dictSize);
776 ret = LZ4_compress_fast_continue(&LZ4dictBody, block, compressedBuffer, blockSize, blockContinueCompressedSize, 1);
777 FUZ_CHECKTEST(ret!=blockContinueCompressedSize, "LZ4_compress_limitedOutput_compressed size is different (%i != %i)", ret, blockContinueCompressedSize);
778 FUZ_CHECKTEST(ret<=0, "LZ4_compress_fast_continue should work : enough size available within output buffer");
779
780 /* Decompress with dictionary as external */
781 FUZ_DISPLAYTEST("test LZ4_decompress_fast_usingDict() with dictionary as extDict");
782 DISPLAYLEVEL(5, " decoding %i bytes from buffer(%p) using dict(%p) of size %i \n",
783 blockSize, (void *)decodedBuffer, (const void *)dict, dictSize);
784 decodedBuffer[blockSize] = 0;
785 ret = LZ4_decompress_fast_usingDict(compressedBuffer, decodedBuffer, blockSize, dict, dictSize);
786 FUZ_CHECKTEST(ret!=blockContinueCompressedSize, "LZ4_decompress_fast_usingDict did not read all compressed block input");
787 FUZ_CHECKTEST(decodedBuffer[blockSize], "LZ4_decompress_fast_usingDict overrun specified output buffer size");
788 { U32 const crcCheck = XXH32(decodedBuffer, (size_t)blockSize, 0);
789 if (crcCheck!=crcOrig) {
790 FUZ_findDiff(block, decodedBuffer);
791 EXIT_MSG("LZ4_decompress_fast_usingDict corrupted decoded data (dict %i)", dictSize);
792 } }
793
794 FUZ_DISPLAYTEST();
795 decodedBuffer[blockSize] = 0;
796 ret = LZ4_decompress_safe_usingDict(compressedBuffer, decodedBuffer, blockContinueCompressedSize, blockSize, dict, dictSize);
797 FUZ_CHECKTEST(ret!=blockSize, "LZ4_decompress_safe_usingDict did not regenerate original data");
798 FUZ_CHECKTEST(decodedBuffer[blockSize], "LZ4_decompress_safe_usingDict overrun specified output buffer size");
799 { U32 const crcCheck = XXH32(decodedBuffer, (size_t)blockSize, 0);
800 FUZ_CHECKTEST(crcCheck!=crcOrig, "LZ4_decompress_safe_usingDict corrupted decoded data");
801 }
802
803 FUZ_DISPLAYTEST();
804 decodedBuffer[blockSize-1] = 0;
805 ret = LZ4_decompress_fast_usingDict(compressedBuffer, decodedBuffer, blockSize-1, dict, dictSize);
806 FUZ_CHECKTEST(ret>=0, "LZ4_decompress_fast_usingDict should have failed : wrong original size (-1 byte)");
807 FUZ_CHECKTEST(decodedBuffer[blockSize-1], "LZ4_decompress_fast_usingDict overrun specified output buffer size");
808
809 FUZ_DISPLAYTEST();
810 decodedBuffer[blockSize-1] = 0;
811 ret = LZ4_decompress_safe_usingDict(compressedBuffer, decodedBuffer, blockContinueCompressedSize, blockSize-1, dict, dictSize);
812 FUZ_CHECKTEST(ret>=0, "LZ4_decompress_safe_usingDict should have failed : not enough output size (-1 byte)");
813 FUZ_CHECKTEST(decodedBuffer[blockSize-1], "LZ4_decompress_safe_usingDict overrun specified output buffer size");
814
815 FUZ_DISPLAYTEST();
816 { int const missingBytes = (FUZ_rand(&randState) & 0xF) + 2;
817 if (blockSize > missingBytes) {
818 decodedBuffer[blockSize-missingBytes] = 0;
819 ret = LZ4_decompress_safe_usingDict(compressedBuffer, decodedBuffer, blockContinueCompressedSize, blockSize-missingBytes, dict, dictSize);
820 FUZ_CHECKTEST(ret>=0, "LZ4_decompress_safe_usingDict should have failed : output buffer too small (-%i byte)", missingBytes);
821 FUZ_CHECKTEST(decodedBuffer[blockSize-missingBytes], "LZ4_decompress_safe_usingDict overrun specified output buffer size (-%i byte) (blockSize=%i)", missingBytes, blockSize);
822 } }
823
824 /* Compress using external dictionary stream */
825 { LZ4_stream_t LZ4_stream;
826 int expectedSize;
827 U32 expectedCrc;
828
829 FUZ_DISPLAYTEST("LZ4_compress_fast_continue() after LZ4_loadDict()");
830 LZ4_loadDict(&LZ4dictBody, dict, dictSize);
831 expectedSize = LZ4_compress_fast_continue(&LZ4dictBody, block, compressedBuffer, blockSize, (int)compressedBufferSize, 1);
832 FUZ_CHECKTEST(expectedSize<=0, "LZ4_compress_fast_continue reference compression for extDictCtx should have succeeded");
833 expectedCrc = XXH32(compressedBuffer, (size_t)expectedSize, 0);
834
835 FUZ_DISPLAYTEST("LZ4_compress_fast_continue() after LZ4_attach_dictionary()");
836 LZ4_loadDict(&LZ4dictBody, dict, dictSize);
837 LZ4_initStream(&LZ4_stream, sizeof(LZ4_stream));
838 LZ4_attach_dictionary(&LZ4_stream, &LZ4dictBody);
839 blockContinueCompressedSize = LZ4_compress_fast_continue(&LZ4_stream, block, compressedBuffer, blockSize, (int)compressedBufferSize, 1);
840 FUZ_CHECKTEST(blockContinueCompressedSize==0, "LZ4_compress_fast_continue using extDictCtx failed");
841
842 /* In the future, it might be desirable to let extDictCtx mode's
843 * output diverge from the output generated by regular extDict mode.
844 * Until that time, this comparison serves as a good regression
845 * test.
846 */
847 FUZ_CHECKTEST(blockContinueCompressedSize != expectedSize, "LZ4_compress_fast_continue using extDictCtx produced different-sized output (%d expected vs %d actual)", expectedSize, blockContinueCompressedSize);
848 FUZ_CHECKTEST(XXH32(compressedBuffer, (size_t)blockContinueCompressedSize, 0) != expectedCrc, "LZ4_compress_fast_continue using extDictCtx produced different output");
849
850 FUZ_DISPLAYTEST("LZ4_compress_fast_continue() after LZ4_attach_dictionary(), but output buffer is 1 byte too short");
851 LZ4_resetStream_fast(&LZ4_stream);
852 LZ4_attach_dictionary(&LZ4_stream, &LZ4dictBody);
853 ret = LZ4_compress_fast_continue(&LZ4_stream, block, compressedBuffer, blockSize, blockContinueCompressedSize-1, 1);
854 FUZ_CHECKTEST(ret>0, "LZ4_compress_fast_continue using extDictCtx should fail : one missing byte for output buffer : %i written, %i buffer", ret, blockContinueCompressedSize);
855 /* note : context is no longer dirty after a failed compressed block */
856
857 FUZ_DISPLAYTEST();
858 LZ4_resetStream_fast(&LZ4_stream);
859 LZ4_attach_dictionary(&LZ4_stream, &LZ4dictBody);
860 ret = LZ4_compress_fast_continue(&LZ4_stream, block, compressedBuffer, blockSize, blockContinueCompressedSize, 1);
861 FUZ_CHECKTEST(ret!=blockContinueCompressedSize, "LZ4_compress_limitedOutput_compressed size is different (%i != %i)", ret, blockContinueCompressedSize);
862 FUZ_CHECKTEST(ret<=0, "LZ4_compress_fast_continue using extDictCtx should work : enough size available within output buffer");
863 FUZ_CHECKTEST(ret != expectedSize, "LZ4_compress_fast_continue using extDictCtx produced different-sized output");
864 FUZ_CHECKTEST(XXH32(compressedBuffer, (size_t)ret, 0) != expectedCrc, "LZ4_compress_fast_continue using extDictCtx produced different output");
865
866 FUZ_DISPLAYTEST();
867 LZ4_resetStream_fast(&LZ4_stream);
868 LZ4_attach_dictionary(&LZ4_stream, &LZ4dictBody);
869 ret = LZ4_compress_fast_continue(&LZ4_stream, block, compressedBuffer, blockSize, blockContinueCompressedSize, 1);
870 FUZ_CHECKTEST(ret!=blockContinueCompressedSize, "LZ4_compress_limitedOutput_compressed size is different (%i != %i)", ret, blockContinueCompressedSize);
871 FUZ_CHECKTEST(ret<=0, "LZ4_compress_fast_continue using extDictCtx with re-used context should work : enough size available within output buffer");
872 FUZ_CHECKTEST(ret != expectedSize, "LZ4_compress_fast_continue using extDictCtx produced different-sized output");
873 FUZ_CHECKTEST(XXH32(compressedBuffer, (size_t)ret, 0) != expectedCrc, "LZ4_compress_fast_continue using extDictCtx produced different output");
874 }
875
876 /* Decompress with dictionary as external */
877 FUZ_DISPLAYTEST();
878 decodedBuffer[blockSize] = 0;
879 ret = LZ4_decompress_fast_usingDict(compressedBuffer, decodedBuffer, blockSize, dict, dictSize);
880 FUZ_CHECKTEST(ret!=blockContinueCompressedSize, "LZ4_decompress_fast_usingDict did not read all compressed block input");
881 FUZ_CHECKTEST(decodedBuffer[blockSize], "LZ4_decompress_fast_usingDict overrun specified output buffer size");
882 { U32 const crcCheck = XXH32(decodedBuffer, (size_t)blockSize, 0);
883 if (crcCheck!=crcOrig) {
884 FUZ_findDiff(block, decodedBuffer);
885 EXIT_MSG("LZ4_decompress_fast_usingDict corrupted decoded data (dict %i)", dictSize);
886 } }
887
888 FUZ_DISPLAYTEST();
889 decodedBuffer[blockSize] = 0;
890 ret = LZ4_decompress_safe_usingDict(compressedBuffer, decodedBuffer, blockContinueCompressedSize, blockSize, dict, dictSize);
891 FUZ_CHECKTEST(ret!=blockSize, "LZ4_decompress_safe_usingDict did not regenerate original data");
892 FUZ_CHECKTEST(decodedBuffer[blockSize], "LZ4_decompress_safe_usingDict overrun specified output buffer size");
893 { U32 const crcCheck = XXH32(decodedBuffer, (size_t)blockSize, 0);
894 FUZ_CHECKTEST(crcCheck!=crcOrig, "LZ4_decompress_safe_usingDict corrupted decoded data");
895 }
896
897 FUZ_DISPLAYTEST();
898 decodedBuffer[blockSize-1] = 0;
899 ret = LZ4_decompress_fast_usingDict(compressedBuffer, decodedBuffer, blockSize-1, dict, dictSize);
900 FUZ_CHECKTEST(ret>=0, "LZ4_decompress_fast_usingDict should have failed : wrong original size (-1 byte)");
901 FUZ_CHECKTEST(decodedBuffer[blockSize-1], "LZ4_decompress_fast_usingDict overrun specified output buffer size");
902
903 FUZ_DISPLAYTEST();
904 decodedBuffer[blockSize-1] = 0;
905 ret = LZ4_decompress_safe_usingDict(compressedBuffer, decodedBuffer, blockContinueCompressedSize, blockSize-1, dict, dictSize);
906 FUZ_CHECKTEST(ret>=0, "LZ4_decompress_safe_usingDict should have failed : not enough output size (-1 byte)");
907 FUZ_CHECKTEST(decodedBuffer[blockSize-1], "LZ4_decompress_safe_usingDict overrun specified output buffer size");
908
909 FUZ_DISPLAYTEST("LZ4_decompress_safe_usingDict with a too small output buffer");
910 { int const missingBytes = (FUZ_rand(&randState) & 0xF) + 2;
911 if (blockSize > missingBytes) {
912 decodedBuffer[blockSize-missingBytes] = 0;
913 ret = LZ4_decompress_safe_usingDict(compressedBuffer, decodedBuffer, blockContinueCompressedSize, blockSize-missingBytes, dict, dictSize);
914 FUZ_CHECKTEST(ret>=0, "LZ4_decompress_safe_usingDict should have failed : output buffer too small (-%i byte)", missingBytes);
915 FUZ_CHECKTEST(decodedBuffer[blockSize-missingBytes], "LZ4_decompress_safe_usingDict overrun specified output buffer size (-%i byte) (blockSize=%i)", missingBytes, blockSize);
916 } }
917
918 /* Compress HC using External dictionary */
919 FUZ_DISPLAYTEST("LZ4_compress_HC_continue with an external dictionary");
920 dict -= (FUZ_rand(&randState) & 7); /* even bigger separation */
921 if (dict < (char*)CNBuffer) dict = (char*)CNBuffer;
922 LZ4_loadDictHC(LZ4dictHC, dict, dictSize);
923 LZ4_setCompressionLevel (LZ4dictHC, compressionLevel);
924 blockContinueCompressedSize = LZ4_compress_HC_continue(LZ4dictHC, block, compressedBuffer, blockSize, (int)compressedBufferSize);
925 FUZ_CHECKTEST(blockContinueCompressedSize==0, "LZ4_compress_HC_continue failed");
926 FUZ_CHECKTEST(LZ4dictHC->internal_donotuse.dirty, "Context should be clean");
927
928 FUZ_DISPLAYTEST("LZ4_compress_HC_continue with same external dictionary, but output buffer 1 byte too short");
929 LZ4_loadDictHC(LZ4dictHC, dict, dictSize);
930 ret = LZ4_compress_HC_continue(LZ4dictHC, block, compressedBuffer, blockSize, blockContinueCompressedSize-1);
931 FUZ_CHECKTEST(ret>0, "LZ4_compress_HC_continue using ExtDict should fail : one missing byte for output buffer (expected %i, but result=%i)", blockContinueCompressedSize, ret);
932 /* note : context is no longer dirty after a failed compressed block */
933
934 FUZ_DISPLAYTEST("LZ4_compress_HC_continue with same external dictionary, and output buffer exactly the right size");
935 LZ4_loadDictHC(LZ4dictHC, dict, dictSize);
936 ret = LZ4_compress_HC_continue(LZ4dictHC, block, compressedBuffer, blockSize, blockContinueCompressedSize);
937 FUZ_CHECKTEST(ret!=blockContinueCompressedSize, "LZ4_compress_HC_continue size is different : ret(%i) != expected(%i)", ret, blockContinueCompressedSize);
938 FUZ_CHECKTEST(ret<=0, "LZ4_compress_HC_continue should work : enough size available within output buffer");
939 FUZ_CHECKTEST(LZ4dictHC->internal_donotuse.dirty, "Context should be clean");
940
941 FUZ_DISPLAYTEST();
942 decodedBuffer[blockSize] = 0;
943 ret = LZ4_decompress_safe_usingDict(compressedBuffer, decodedBuffer, blockContinueCompressedSize, blockSize, dict, dictSize);
944 FUZ_CHECKTEST(ret!=blockSize, "LZ4_decompress_safe_usingDict did not regenerate original data");
945 FUZ_CHECKTEST(decodedBuffer[blockSize], "LZ4_decompress_safe_usingDict overrun specified output buffer size");
946 { U32 const crcCheck = XXH32(decodedBuffer, (size_t)blockSize, 0);
947 if (crcCheck!=crcOrig) {
948 FUZ_findDiff(block, decodedBuffer);
949 EXIT_MSG("LZ4_decompress_safe_usingDict corrupted decoded data");
950 } }
951
952 /* Compress HC using external dictionary stream */
953 FUZ_DISPLAYTEST();
954 { LZ4_streamHC_t* const LZ4_streamHC = LZ4_createStreamHC();
955
956 LZ4_loadDictHC(LZ4dictHC, dict, dictSize);
957 LZ4_attach_HC_dictionary(LZ4_streamHC, LZ4dictHC);
958 LZ4_setCompressionLevel (LZ4_streamHC, compressionLevel);
959 blockContinueCompressedSize = LZ4_compress_HC_continue(LZ4_streamHC, block, compressedBuffer, blockSize, (int)compressedBufferSize);
960 FUZ_CHECKTEST(blockContinueCompressedSize==0, "LZ4_compress_HC_continue with ExtDictCtx failed");
961 FUZ_CHECKTEST(LZ4_streamHC->internal_donotuse.dirty, "Context should be clean");
962
963 FUZ_DISPLAYTEST();
964 LZ4_resetStreamHC_fast (LZ4_streamHC, compressionLevel);
965 LZ4_attach_HC_dictionary(LZ4_streamHC, LZ4dictHC);
966 ret = LZ4_compress_HC_continue(LZ4_streamHC, block, compressedBuffer, blockSize, blockContinueCompressedSize-1);
967 FUZ_CHECKTEST(ret>0, "LZ4_compress_HC_continue using ExtDictCtx should fail : one missing byte for output buffer (%i != %i)", ret, blockContinueCompressedSize);
968 /* note : context is no longer dirty after a failed compressed block */
969
970 FUZ_DISPLAYTEST();
971 LZ4_resetStreamHC_fast (LZ4_streamHC, compressionLevel);
972 LZ4_attach_HC_dictionary(LZ4_streamHC, LZ4dictHC);
973 ret = LZ4_compress_HC_continue(LZ4_streamHC, block, compressedBuffer, blockSize, blockContinueCompressedSize);
974 FUZ_CHECKTEST(ret!=blockContinueCompressedSize, "LZ4_compress_HC_continue using ExtDictCtx size is different (%i != %i)", ret, blockContinueCompressedSize);
975 FUZ_CHECKTEST(ret<=0, "LZ4_compress_HC_continue using ExtDictCtx should work : enough size available within output buffer");
976 FUZ_CHECKTEST(LZ4_streamHC->internal_donotuse.dirty, "Context should be clean");
977
978 FUZ_DISPLAYTEST();
979 LZ4_resetStreamHC_fast (LZ4_streamHC, compressionLevel);
980 LZ4_attach_HC_dictionary(LZ4_streamHC, LZ4dictHC);
981 ret = LZ4_compress_HC_continue(LZ4_streamHC, block, compressedBuffer, blockSize, blockContinueCompressedSize);
982 FUZ_CHECKTEST(ret!=blockContinueCompressedSize, "LZ4_compress_HC_continue using ExtDictCtx and fast reset size is different (%i != %i)",
983 ret, blockContinueCompressedSize);
984 FUZ_CHECKTEST(ret<=0, "LZ4_compress_HC_continue using ExtDictCtx and fast reset should work : enough size available within output buffer");
985 FUZ_CHECKTEST(LZ4_streamHC->internal_donotuse.dirty, "Context should be clean");
986
987 LZ4_freeStreamHC(LZ4_streamHC);
988 }
989
990 FUZ_DISPLAYTEST();
991 decodedBuffer[blockSize] = 0;
992 ret = LZ4_decompress_safe_usingDict(compressedBuffer, decodedBuffer, blockContinueCompressedSize, blockSize, dict, dictSize);
993 FUZ_CHECKTEST(ret!=blockSize, "LZ4_decompress_safe_usingDict did not regenerate original data");
994 FUZ_CHECKTEST(decodedBuffer[blockSize], "LZ4_decompress_safe_usingDict overrun specified output buffer size");
995 { U32 const crcCheck = XXH32(decodedBuffer, (size_t)blockSize, 0);
996 if (crcCheck!=crcOrig) {
997 FUZ_findDiff(block, decodedBuffer);
998 EXIT_MSG("LZ4_decompress_safe_usingDict corrupted decoded data");
999 } }
1000
1001 /* Compress HC continue destSize */
1002 FUZ_DISPLAYTEST();
1003 { int const availableSpace = (int)(FUZ_rand(&randState) % (U32)blockSize) + 5;
1004 int consumedSize = blockSize;
1005 FUZ_DISPLAYTEST();
1006 LZ4_loadDictHC(LZ4dictHC, dict, dictSize);
1007 LZ4_setCompressionLevel(LZ4dictHC, compressionLevel);
1008 blockContinueCompressedSize = LZ4_compress_HC_continue_destSize(LZ4dictHC, block, compressedBuffer, &consumedSize, availableSpace);
1009 DISPLAYLEVEL(5, " LZ4_compress_HC_continue_destSize : compressed %6i/%6i into %6i/%6i at cLevel=%i \n",
1010 consumedSize, blockSize, blockContinueCompressedSize, availableSpace, compressionLevel);
1011 FUZ_CHECKTEST(blockContinueCompressedSize==0, "LZ4_compress_HC_continue_destSize failed");
1012 FUZ_CHECKTEST(blockContinueCompressedSize > availableSpace, "LZ4_compress_HC_continue_destSize write overflow");
1013 FUZ_CHECKTEST(consumedSize > blockSize, "LZ4_compress_HC_continue_destSize read overflow");
1014
1015 FUZ_DISPLAYTEST();
1016 decodedBuffer[consumedSize] = 0;
1017 ret = LZ4_decompress_safe_usingDict(compressedBuffer, decodedBuffer, blockContinueCompressedSize, consumedSize, dict, dictSize);
1018 FUZ_CHECKTEST(ret != consumedSize, "LZ4_decompress_safe_usingDict regenerated %i bytes (%i expected)", ret, consumedSize);
1019 FUZ_CHECKTEST(decodedBuffer[consumedSize], "LZ4_decompress_safe_usingDict overrun specified output buffer size")
1020 { U32 const crcSrc = XXH32(block, (size_t)consumedSize, 0);
1021 U32 const crcDst = XXH32(decodedBuffer, (size_t)consumedSize, 0);
1022 if (crcSrc!=crcDst) {
1023 FUZ_findDiff(block, decodedBuffer);
1024 EXIT_MSG("LZ4_decompress_safe_usingDict corrupted decoded data");
1025 } }
1026 }
1027
1028 /* ***** End of tests *** */
1029 /* Fill stats */
1030 assert(blockSize >= 0);
1031 bytes += (unsigned)blockSize;
1032 assert(compressedSize >= 0);
1033 cbytes += (unsigned)compressedSize;
1034 assert(HCcompressedSize >= 0);
1035 hcbytes += (unsigned)HCcompressedSize;
1036 assert(blockContinueCompressedSize >= 0);
1037 ccbytes += (unsigned)blockContinueCompressedSize;
1038 }
1039
1040 if (nbCycles<=1) nbCycles = cycleNb; /* end by time */
1041 bytes += !bytes; /* avoid division by 0 */
1042 printf("\r%7u /%7u - ", cycleNb, nbCycles);
1043 printf("all tests completed successfully \n");
1044 printf("compression ratio: %0.3f%%\n", (double)cbytes/bytes*100);
1045 printf("HC compression ratio: %0.3f%%\n", (double)hcbytes/bytes*100);
1046 printf("ratio with dict: %0.3f%%\n", (double)ccbytes/bytes*100);
1047
1048 /* release memory */
1049 free(CNBuffer);
1050 free(compressedBuffer);
1051 free(decodedBuffer);
1052 FUZ_freeLowAddr(lowAddrBuffer, labSize);
1053 LZ4_freeStreamHC(LZ4dictHC);
1054 free(stateLZ4);
1055 free(stateLZ4HC);
1056 return result;
1057 }
1058
1059
1060 #define testInputSize (196 KB)
1061 #define testCompressedSize (130 KB)
1062 #define ringBufferSize (8 KB)
1063
FUZ_unitTests(int compressionLevel)1064 static void FUZ_unitTests(int compressionLevel)
1065 {
1066 const unsigned testNb = 0;
1067 const unsigned seed = 0;
1068 const unsigned cycleNb= 0;
1069 char* testInput = (char*)malloc(testInputSize);
1070 char* testCompressed = (char*)malloc(testCompressedSize);
1071 char* testVerify = (char*)malloc(testInputSize);
1072 char ringBuffer[ringBufferSize] = {0};
1073 U32 randState = 1;
1074
1075 /* Init */
1076 if (!testInput || !testCompressed || !testVerify) {
1077 EXIT_MSG("not enough memory for FUZ_unitTests");
1078 }
1079 FUZ_fillCompressibleNoiseBuffer(testInput, testInputSize, 0.50, &randState);
1080
1081 /* 32-bits address space overflow test */
1082 FUZ_AddressOverflow();
1083
1084 /* Test decoding with empty input */
1085 DISPLAYLEVEL(3, "LZ4_decompress_safe() with empty input \n");
1086 LZ4_decompress_safe(testCompressed, testVerify, 0, testInputSize);
1087
1088 /* Test decoding with a one byte input */
1089 DISPLAYLEVEL(3, "LZ4_decompress_safe() with one byte input \n");
1090 { char const tmp = (char)0xFF;
1091 LZ4_decompress_safe(&tmp, testVerify, 1, testInputSize);
1092 }
1093
1094 /* Test decoding shortcut edge case */
1095 DISPLAYLEVEL(3, "LZ4_decompress_safe() with shortcut edge case \n");
1096 { char tmp[17];
1097 /* 14 bytes of literals, followed by a 14 byte match.
1098 * Should not read beyond the end of the buffer.
1099 * See https://github.com/lz4/lz4/issues/508. */
1100 *tmp = (char)0xEE;
1101 memset(tmp + 1, 0, 14);
1102 tmp[15] = 14;
1103 tmp[16] = 0;
1104 { int const r = LZ4_decompress_safe(tmp, testVerify, sizeof(tmp), testInputSize);
1105 FUZ_CHECKTEST(r >= 0, "LZ4_decompress_safe() should fail");
1106 } }
1107
1108
1109 /* to be tested with undefined sanitizer */
1110 DISPLAYLEVEL(3, "LZ4_compress_default() with NULL input:");
1111 { int const maxCSize = LZ4_compressBound(0);
1112 int const cSize = LZ4_compress_default(NULL, testCompressed, 0, maxCSize);
1113 FUZ_CHECKTEST(!(cSize==1 && testCompressed[0]==0),
1114 "compressing empty should give byte 0"
1115 " (maxCSize == %i) (cSize == %i) (byte == 0x%02X)",
1116 maxCSize, cSize, testCompressed[0]);
1117 }
1118 DISPLAYLEVEL(3, " OK \n");
1119
1120 DISPLAYLEVEL(3, "LZ4_compress_default() with both NULL input and output:");
1121 { int const cSize = LZ4_compress_default(NULL, NULL, 0, 0);
1122 FUZ_CHECKTEST(cSize != 0,
1123 "compressing into NULL must fail"
1124 " (cSize == %i != 0)", cSize);
1125 }
1126 DISPLAYLEVEL(3, " OK \n");
1127
1128 /* in-place compression test */
1129 DISPLAYLEVEL(3, "in-place compression using LZ4_compress_default() :");
1130 { int const sampleSize = 65 KB;
1131 int const maxCSize = LZ4_COMPRESSBOUND(sampleSize);
1132 int const outSize = LZ4_COMPRESS_INPLACE_BUFFER_SIZE(maxCSize);
1133 int const startInputIndex = outSize - sampleSize;
1134 char* const startInput = testCompressed + startInputIndex;
1135 XXH32_hash_t const crcOrig = XXH32(testInput, sampleSize, 0);
1136 int cSize;
1137 assert(outSize < (int)testCompressedSize);
1138 memcpy(startInput, testInput, sampleSize); /* copy at end of buffer */
1139 /* compress in-place */
1140 cSize = LZ4_compress_default(startInput, testCompressed, sampleSize, maxCSize);
1141 assert(cSize != 0); /* ensure compression is successful */
1142 assert(maxCSize < INT_MAX);
1143 assert(cSize <= maxCSize);
1144 /* decompress and verify */
1145 { int const dSize = LZ4_decompress_safe(testCompressed, testVerify, cSize, testInputSize);
1146 assert(dSize == sampleSize); /* correct size */
1147 { XXH32_hash_t const crcCheck = XXH32(testVerify, (size_t)dSize, 0);
1148 FUZ_CHECKTEST(crcCheck != crcOrig, "LZ4_decompress_safe decompression corruption");
1149 } } }
1150 DISPLAYLEVEL(3, " OK \n");
1151
1152 /* in-place decompression test */
1153 DISPLAYLEVEL(3, "in-place decompression, limit case:");
1154 { int const sampleSize = 65 KB;
1155
1156 FUZ_fillCompressibleNoiseBuffer(testInput, sampleSize, 0.0, &randState);
1157 memset(testInput, 0, 267); /* calculated exactly so that compressedSize == originalSize-1 */
1158
1159 { XXH64_hash_t const crcOrig = XXH64(testInput, sampleSize, 0);
1160 int const cSize = LZ4_compress_default(testInput, testCompressed, sampleSize, testCompressedSize);
1161 assert(cSize == sampleSize - 1); /* worst case for in-place decompression */
1162
1163 { int const bufferSize = LZ4_DECOMPRESS_INPLACE_BUFFER_SIZE(sampleSize);
1164 int const startInputIndex = bufferSize - cSize;
1165 char* const startInput = testVerify + startInputIndex;
1166 memcpy(startInput, testCompressed, cSize);
1167
1168 /* decompress and verify */
1169 { int const dSize = LZ4_decompress_safe(startInput, testVerify, cSize, sampleSize);
1170 assert(dSize == sampleSize); /* correct size */
1171 { XXH64_hash_t const crcCheck = XXH64(testVerify, (size_t)dSize, 0);
1172 FUZ_CHECKTEST(crcCheck != crcOrig, "LZ4_decompress_safe decompression corruption");
1173 } } } } }
1174 DISPLAYLEVEL(3, " OK \n");
1175
1176 DISPLAYLEVEL(3, "LZ4_initStream with multiple valid alignments : ");
1177 { typedef struct {
1178 LZ4_stream_t state1;
1179 LZ4_stream_t state2;
1180 char c;
1181 LZ4_stream_t state3;
1182 } shct;
1183 shct* const shc = (shct*)malloc(sizeof(*shc));
1184 assert(shc != NULL);
1185 memset(shc, 0, sizeof(*shc));
1186 DISPLAYLEVEL(4, "state1(%p) state2(%p) state3(%p) LZ4_stream_t size(0x%x): ",
1187 (void*)&(shc->state1), (void*)&(shc->state2), (void*)&(shc->state3), (unsigned)sizeof(LZ4_stream_t));
1188 FUZ_CHECKTEST( LZ4_initStream(&(shc->state1), sizeof(shc->state1)) == NULL, "state1 (%p) failed init", (void*)&(shc->state1) );
1189 FUZ_CHECKTEST( LZ4_initStream(&(shc->state2), sizeof(shc->state2)) == NULL, "state2 (%p) failed init", (void*)&(shc->state2) );
1190 FUZ_CHECKTEST( LZ4_initStream(&(shc->state3), sizeof(shc->state3)) == NULL, "state3 (%p) failed init", (void*)&(shc->state3) );
1191 FUZ_CHECKTEST( LZ4_initStream((char*)&(shc->state1) + 1, sizeof(shc->state1)) != NULL,
1192 "hc1+1 (%p) init must fail, due to bad alignment", (void*)((char*)&(shc->state1) + 1) );
1193 free(shc);
1194 }
1195 DISPLAYLEVEL(3, "all inits OK \n");
1196
1197 /* Allocation test */
1198 { LZ4_stream_t* const statePtr = LZ4_createStream();
1199 FUZ_CHECKTEST(statePtr==NULL, "LZ4_createStream() allocation failed");
1200 LZ4_freeStream(statePtr);
1201 }
1202
1203 /* LZ4 streaming tests */
1204 { LZ4_stream_t streamingState;
1205
1206 /* simple compression test */
1207 LZ4_initStream(&streamingState, sizeof(streamingState));
1208 { int const cs = LZ4_compress_fast_continue(&streamingState, testInput, testCompressed, testCompressedSize, testCompressedSize-1, 1);
1209 FUZ_CHECKTEST(cs==0, "LZ4_compress_fast_continue() compression failed!");
1210 { int const r = LZ4_decompress_safe(testCompressed, testVerify, cs, testCompressedSize);
1211 FUZ_CHECKTEST(r!=(int)testCompressedSize, "LZ4_decompress_safe() decompression failed");
1212 } }
1213 { U64 const crcOrig = XXH64(testInput, testCompressedSize, 0);
1214 U64 const crcNew = XXH64(testVerify, testCompressedSize, 0);
1215 FUZ_CHECKTEST(crcOrig!=crcNew, "LZ4_decompress_safe() decompression corruption");
1216 }
1217
1218 /* early saveDict */
1219 DISPLAYLEVEL(3, "saveDict (right after init) : ");
1220 { LZ4_stream_t* const ctx = LZ4_initStream(&streamingState, sizeof(streamingState));
1221 assert(ctx != NULL); /* ensure init is successful */
1222
1223 /* Check access violation with asan */
1224 FUZ_CHECKTEST( LZ4_saveDict(ctx, NULL, 0) != 0,
1225 "LZ4_saveDict() can't save anything into (NULL,0)");
1226
1227 /* Check access violation with asan */
1228 { char tmp_buffer[240] = { 0 };
1229 FUZ_CHECKTEST( LZ4_saveDict(ctx, tmp_buffer, sizeof(tmp_buffer)) != 0,
1230 "LZ4_saveDict() can't save anything since compression hasn't started");
1231 } }
1232 DISPLAYLEVEL(3, "OK \n");
1233
1234 /* ring buffer test */
1235 { XXH64_state_t xxhOrig;
1236 XXH64_state_t xxhNewSafe, xxhNewFast;
1237 LZ4_streamDecode_t decodeStateSafe, decodeStateFast;
1238 const U32 maxMessageSizeLog = 10;
1239 const U32 maxMessageSizeMask = (1<<maxMessageSizeLog) - 1;
1240 U32 messageSize = (FUZ_rand(&randState) & maxMessageSizeMask) + 1;
1241 U32 iNext = 0;
1242 U32 rNext = 0;
1243 U32 dNext = 0;
1244 const U32 dBufferSize = ringBufferSize + maxMessageSizeMask;
1245
1246 XXH64_reset(&xxhOrig, 0);
1247 XXH64_reset(&xxhNewSafe, 0);
1248 XXH64_reset(&xxhNewFast, 0);
1249 LZ4_resetStream_fast(&streamingState);
1250 LZ4_setStreamDecode(&decodeStateSafe, NULL, 0);
1251 LZ4_setStreamDecode(&decodeStateFast, NULL, 0);
1252
1253 while (iNext + messageSize < testCompressedSize) {
1254 int compressedSize; U64 crcOrig;
1255 XXH64_update(&xxhOrig, testInput + iNext, messageSize);
1256 crcOrig = XXH64_digest(&xxhOrig);
1257
1258 memcpy (ringBuffer + rNext, testInput + iNext, messageSize);
1259 compressedSize = LZ4_compress_fast_continue(&streamingState, ringBuffer + rNext, testCompressed, (int)messageSize, testCompressedSize-ringBufferSize, 1);
1260 FUZ_CHECKTEST(compressedSize==0, "LZ4_compress_fast_continue() compression failed");
1261
1262 { int const r = LZ4_decompress_safe_continue(&decodeStateSafe, testCompressed, testVerify + dNext, compressedSize, (int)messageSize);
1263 FUZ_CHECKTEST(r!=(int)messageSize, "ringBuffer : LZ4_decompress_safe_continue() test failed"); }
1264
1265 XXH64_update(&xxhNewSafe, testVerify + dNext, messageSize);
1266 { U64 const crcNew = XXH64_digest(&xxhNewSafe);
1267 FUZ_CHECKTEST(crcOrig!=crcNew, "LZ4_decompress_safe_continue() decompression corruption"); }
1268
1269 { int const r = LZ4_decompress_fast_continue(&decodeStateFast, testCompressed, testVerify + dNext, (int)messageSize);
1270 FUZ_CHECKTEST(r!=compressedSize, "ringBuffer : LZ4_decompress_fast_continue() test failed"); }
1271
1272 XXH64_update(&xxhNewFast, testVerify + dNext, messageSize);
1273 { U64 const crcNew = XXH64_digest(&xxhNewFast);
1274 FUZ_CHECKTEST(crcOrig!=crcNew, "LZ4_decompress_fast_continue() decompression corruption"); }
1275
1276 /* prepare next message */
1277 iNext += messageSize;
1278 rNext += messageSize;
1279 dNext += messageSize;
1280 messageSize = (FUZ_rand(&randState) & maxMessageSizeMask) + 1;
1281 if (rNext + messageSize > ringBufferSize) rNext = 0;
1282 if (dNext + messageSize > dBufferSize) dNext = 0;
1283 } }
1284 }
1285
1286 DISPLAYLEVEL(3, "LZ4_initStreamHC with multiple valid alignments : ");
1287 { typedef struct {
1288 LZ4_streamHC_t hc1;
1289 LZ4_streamHC_t hc2;
1290 char c;
1291 LZ4_streamHC_t hc3;
1292 } shct;
1293 shct* const shc = (shct*)malloc(sizeof(*shc));
1294 assert(shc != NULL);
1295 memset(shc, 0, sizeof(*shc));
1296 DISPLAYLEVEL(4, "hc1(%p) hc2(%p) hc3(%p) size(0x%x): ",
1297 (void*)&(shc->hc1), (void*)&(shc->hc2), (void*)&(shc->hc3),
1298 (unsigned)sizeof(LZ4_streamHC_t));
1299 FUZ_CHECKTEST( LZ4_initStreamHC(&(shc->hc1), sizeof(shc->hc1)) == NULL, "hc1 (%p) failed init", (void*)&(shc->hc1) );
1300 FUZ_CHECKTEST( LZ4_initStreamHC(&(shc->hc2), sizeof(shc->hc2)) == NULL, "hc2 (%p) failed init", (void*)&(shc->hc2) );
1301 FUZ_CHECKTEST( LZ4_initStreamHC(&(shc->hc3), sizeof(shc->hc3)) == NULL, "hc3 (%p) failed init", (void*)&(shc->hc3) );
1302 FUZ_CHECKTEST( LZ4_initStreamHC((char*)&(shc->hc1) + 1, sizeof(shc->hc1)) != NULL,
1303 "hc1+1 (%p) init must fail, due to bad alignment", (void*)((char*)&(shc->hc1) + 1) );
1304 free(shc);
1305 }
1306 DISPLAYLEVEL(3, "all inits OK \n");
1307
1308 /* LZ4 HC streaming tests */
1309 { LZ4_streamHC_t sHC; /* statically allocated */
1310 int result;
1311 LZ4_initStreamHC(&sHC, sizeof(sHC));
1312
1313 /* Allocation test */
1314 DISPLAYLEVEL(3, "Basic HC allocation : ");
1315 { LZ4_streamHC_t* const sp = LZ4_createStreamHC();
1316 FUZ_CHECKTEST(sp==NULL, "LZ4_createStreamHC() allocation failed");
1317 LZ4_freeStreamHC(sp);
1318 }
1319 DISPLAYLEVEL(3, "OK \n");
1320
1321 /* simple HC compression test */
1322 DISPLAYLEVEL(3, "Simple HC round-trip : ");
1323 { U64 const crc64 = XXH64(testInput, testCompressedSize, 0);
1324 LZ4_setCompressionLevel(&sHC, compressionLevel);
1325 result = LZ4_compress_HC_continue(&sHC, testInput, testCompressed, testCompressedSize, testCompressedSize-1);
1326 FUZ_CHECKTEST(result==0, "LZ4_compressHC_limitedOutput_continue() compression failed");
1327 FUZ_CHECKTEST(sHC.internal_donotuse.dirty, "Context should be clean");
1328
1329 result = LZ4_decompress_safe(testCompressed, testVerify, result, testCompressedSize);
1330 FUZ_CHECKTEST(result!=(int)testCompressedSize, "LZ4_decompress_safe() decompression failed");
1331 { U64 const crcNew = XXH64(testVerify, testCompressedSize, 0);
1332 FUZ_CHECKTEST(crc64!=crcNew, "LZ4_decompress_safe() decompression corruption");
1333 } }
1334 DISPLAYLEVEL(3, "OK \n");
1335
1336 /* saveDictHC test #926 */
1337 DISPLAYLEVEL(3, "saveDictHC test #926 : ");
1338 { LZ4_streamHC_t* const ctx = LZ4_initStreamHC(&sHC, sizeof(sHC));
1339 assert(ctx != NULL); /* ensure init is successful */
1340
1341 /* Check access violation with asan */
1342 FUZ_CHECKTEST( LZ4_saveDictHC(ctx, NULL, 0) != 0,
1343 "LZ4_saveDictHC() can't save anything into (NULL,0)");
1344
1345 /* Check access violation with asan */
1346 { char tmp_buffer[240] = { 0 };
1347 FUZ_CHECKTEST( LZ4_saveDictHC(ctx, tmp_buffer, sizeof(tmp_buffer)) != 0,
1348 "LZ4_saveDictHC() can't save anything since compression hasn't started");
1349 } }
1350 DISPLAYLEVEL(3, "OK \n");
1351
1352 /* long sequence test */
1353 DISPLAYLEVEL(3, "Long sequence HC_destSize test : ");
1354 { size_t const blockSize = 1 MB;
1355 size_t const targetSize = 4116; /* size carefully selected to trigger an overflow */
1356 void* const block = malloc(blockSize);
1357 void* const dstBlock = malloc(targetSize+1);
1358 BYTE const sentinel = 101;
1359 int srcSize;
1360
1361 assert(block != NULL); assert(dstBlock != NULL);
1362 memset(block, 0, blockSize);
1363 ((char*)dstBlock)[targetSize] = sentinel;
1364
1365 LZ4_resetStreamHC_fast(&sHC, 3);
1366 assert(blockSize < INT_MAX);
1367 srcSize = (int)blockSize;
1368 assert(targetSize < INT_MAX);
1369 result = LZ4_compress_HC_destSize(&sHC, (const char*)block, (char*)dstBlock, &srcSize, (int)targetSize, 3);
1370 DISPLAYLEVEL(4, "cSize=%i; readSize=%i; ", result, srcSize);
1371 FUZ_CHECKTEST(result != 4116, "LZ4_compress_HC_destSize() : "
1372 "compression (%i->%i) must fill dstBuffer (%i) exactly",
1373 srcSize, result, (int)targetSize);
1374 FUZ_CHECKTEST(((char*)dstBlock)[targetSize] != sentinel,
1375 "LZ4_compress_HC_destSize() overwrites dst buffer");
1376 FUZ_CHECKTEST(srcSize < 1045000, "LZ4_compress_HC_destSize() doesn't compress enough"
1377 " (%i -> %i , expected > %i)", srcSize, result, 1045000);
1378
1379 LZ4_resetStreamHC_fast(&sHC, 3); /* make sure the context is clean after the test */
1380 free(block);
1381 free(dstBlock);
1382 }
1383 DISPLAYLEVEL(3, " OK \n");
1384
1385 /* simple dictionary HC compression test */
1386 DISPLAYLEVEL(3, "HC dictionary compression test : ");
1387 { U64 const crc64 = XXH64(testInput + 64 KB, testCompressedSize, 0);
1388 LZ4_resetStreamHC_fast(&sHC, compressionLevel);
1389 LZ4_loadDictHC(&sHC, testInput, 64 KB);
1390 { int const cSize = LZ4_compress_HC_continue(&sHC, testInput + 64 KB, testCompressed, testCompressedSize, testCompressedSize-1);
1391 FUZ_CHECKTEST(cSize==0, "LZ4_compressHC_limitedOutput_continue() dictionary compression failed : @return = %i", cSize);
1392 FUZ_CHECKTEST(sHC.internal_donotuse.dirty, "Context should be clean");
1393 { int const dSize = LZ4_decompress_safe_usingDict(testCompressed, testVerify, cSize, testCompressedSize, testInput, 64 KB);
1394 FUZ_CHECKTEST(dSize!=(int)testCompressedSize, "LZ4_decompress_safe() simple dictionary decompression test failed");
1395 } }
1396 { U64 const crcNew = XXH64(testVerify, testCompressedSize, 0);
1397 FUZ_CHECKTEST(crc64!=crcNew, "LZ4_decompress_safe() simple dictionary decompression test : corruption");
1398 } }
1399 DISPLAYLEVEL(3, " OK \n");
1400
1401 /* multiple HC compression test with dictionary */
1402 { int result1, result2;
1403 int segSize = testCompressedSize / 2;
1404 XXH64_hash_t const crc64 = ( (void)assert((unsigned)segSize + testCompressedSize < testInputSize) ,
1405 XXH64(testInput + segSize, testCompressedSize, 0) );
1406 LZ4_resetStreamHC_fast(&sHC, compressionLevel);
1407 LZ4_loadDictHC(&sHC, testInput, segSize);
1408 result1 = LZ4_compress_HC_continue(&sHC, testInput + segSize, testCompressed, segSize, segSize -1);
1409 FUZ_CHECKTEST(result1==0, "LZ4_compressHC_limitedOutput_continue() dictionary compression failed : result = %i", result1);
1410 FUZ_CHECKTEST(sHC.internal_donotuse.dirty, "Context should be clean");
1411 result2 = LZ4_compress_HC_continue(&sHC, testInput + 2*(size_t)segSize, testCompressed+result1, segSize, segSize-1);
1412 FUZ_CHECKTEST(result2==0, "LZ4_compressHC_limitedOutput_continue() dictionary compression failed : result = %i", result2);
1413 FUZ_CHECKTEST(sHC.internal_donotuse.dirty, "Context should be clean");
1414
1415 result = LZ4_decompress_safe_usingDict(testCompressed, testVerify, result1, segSize, testInput, segSize);
1416 FUZ_CHECKTEST(result!=segSize, "LZ4_decompress_safe() dictionary decompression part 1 failed");
1417 result = LZ4_decompress_safe_usingDict(testCompressed+result1, testVerify+segSize, result2, segSize, testInput, 2*segSize);
1418 FUZ_CHECKTEST(result!=segSize, "LZ4_decompress_safe() dictionary decompression part 2 failed");
1419 { XXH64_hash_t const crcNew = XXH64(testVerify, testCompressedSize, 0);
1420 FUZ_CHECKTEST(crc64!=crcNew, "LZ4_decompress_safe() dictionary decompression corruption");
1421 } }
1422
1423 /* remote dictionary HC compression test */
1424 { U64 const crc64 = XXH64(testInput + 64 KB, testCompressedSize, 0);
1425 LZ4_resetStreamHC_fast(&sHC, compressionLevel);
1426 LZ4_loadDictHC(&sHC, testInput, 32 KB);
1427 result = LZ4_compress_HC_continue(&sHC, testInput + 64 KB, testCompressed, testCompressedSize, testCompressedSize-1);
1428 FUZ_CHECKTEST(result==0, "LZ4_compressHC_limitedOutput_continue() remote dictionary failed : result = %i", result);
1429 FUZ_CHECKTEST(sHC.internal_donotuse.dirty, "Context should be clean");
1430
1431 result = LZ4_decompress_safe_usingDict(testCompressed, testVerify, result, testCompressedSize, testInput, 32 KB);
1432 FUZ_CHECKTEST(result!=(int)testCompressedSize, "LZ4_decompress_safe_usingDict() decompression failed following remote dictionary HC compression test");
1433 { U64 const crcNew = XXH64(testVerify, testCompressedSize, 0);
1434 FUZ_CHECKTEST(crc64!=crcNew, "LZ4_decompress_safe_usingDict() decompression corruption");
1435 } }
1436
1437 /* multiple HC compression with ext. dictionary */
1438 { XXH64_state_t crcOrigState;
1439 XXH64_state_t crcNewState;
1440 const char* dict = testInput + 3;
1441 size_t dictSize = (FUZ_rand(&randState) & 8191);
1442 char* dst = testVerify;
1443
1444 size_t segStart = dictSize + 7;
1445 size_t segSize = (FUZ_rand(&randState) & 8191);
1446 int segNb = 1;
1447
1448 LZ4_resetStreamHC_fast(&sHC, compressionLevel);
1449 LZ4_loadDictHC(&sHC, dict, (int)dictSize);
1450
1451 XXH64_reset(&crcOrigState, 0);
1452 XXH64_reset(&crcNewState, 0);
1453
1454 while (segStart + segSize < testInputSize) {
1455 XXH64_hash_t crcOrig;
1456 XXH64_update(&crcOrigState, testInput + segStart, segSize);
1457 crcOrig = XXH64_digest(&crcOrigState);
1458 assert(segSize <= INT_MAX);
1459 result = LZ4_compress_HC_continue(&sHC, testInput + segStart, testCompressed, (int)segSize, LZ4_compressBound((int)segSize));
1460 FUZ_CHECKTEST(result==0, "LZ4_compressHC_limitedOutput_continue() dictionary compression failed : result = %i", result);
1461 FUZ_CHECKTEST(sHC.internal_donotuse.dirty, "Context should be clean");
1462
1463 result = LZ4_decompress_safe_usingDict(testCompressed, dst, result, (int)segSize, dict, (int)dictSize);
1464 FUZ_CHECKTEST(result!=(int)segSize, "LZ4_decompress_safe_usingDict() dictionary decompression part %i failed", (int)segNb);
1465 XXH64_update(&crcNewState, dst, segSize);
1466 { U64 const crcNew = XXH64_digest(&crcNewState);
1467 if (crcOrig != crcNew) FUZ_findDiff(dst, testInput+segStart);
1468 FUZ_CHECKTEST(crcOrig!=crcNew, "LZ4_decompress_safe_usingDict() part %i corruption", segNb);
1469 }
1470
1471 dict = dst;
1472 dictSize = segSize;
1473
1474 dst += segSize + 1;
1475 segNb ++;
1476
1477 segStart += segSize + (FUZ_rand(&randState) & 0xF) + 1;
1478 segSize = (FUZ_rand(&randState) & 8191);
1479 } }
1480
1481 /* ring buffer test */
1482 { XXH64_state_t xxhOrig;
1483 XXH64_state_t xxhNewSafe, xxhNewFast;
1484 LZ4_streamDecode_t decodeStateSafe, decodeStateFast;
1485 const U32 maxMessageSizeLog = 10;
1486 const U32 maxMessageSizeMask = (1<<maxMessageSizeLog) - 1;
1487 U32 messageSize = (FUZ_rand(&randState) & maxMessageSizeMask) + 1;
1488 U32 iNext = 0;
1489 U32 rNext = 0;
1490 U32 dNext = 0;
1491 const U32 dBufferSize = ringBufferSize + maxMessageSizeMask;
1492
1493 XXH64_reset(&xxhOrig, 0);
1494 XXH64_reset(&xxhNewSafe, 0);
1495 XXH64_reset(&xxhNewFast, 0);
1496 LZ4_resetStreamHC_fast(&sHC, compressionLevel);
1497 LZ4_setStreamDecode(&decodeStateSafe, NULL, 0);
1498 LZ4_setStreamDecode(&decodeStateFast, NULL, 0);
1499
1500 while (iNext + messageSize < testCompressedSize) {
1501 int compressedSize;
1502 XXH64_hash_t crcOrig;
1503 XXH64_update(&xxhOrig, testInput + iNext, messageSize);
1504 crcOrig = XXH64_digest(&xxhOrig);
1505
1506 memcpy (ringBuffer + rNext, testInput + iNext, messageSize);
1507 assert(messageSize < INT_MAX);
1508 compressedSize = LZ4_compress_HC_continue(&sHC, ringBuffer + rNext, testCompressed, (int)messageSize, testCompressedSize-ringBufferSize);
1509 FUZ_CHECKTEST(compressedSize==0, "LZ4_compress_HC_continue() compression failed");
1510 FUZ_CHECKTEST(sHC.internal_donotuse.dirty, "Context should be clean");
1511
1512 assert(messageSize < INT_MAX);
1513 result = LZ4_decompress_safe_continue(&decodeStateSafe, testCompressed, testVerify + dNext, compressedSize, (int)messageSize);
1514 FUZ_CHECKTEST(result!=(int)messageSize, "ringBuffer : LZ4_decompress_safe_continue() test failed");
1515
1516 XXH64_update(&xxhNewSafe, testVerify + dNext, messageSize);
1517 { XXH64_hash_t const crcNew = XXH64_digest(&xxhNewSafe);
1518 FUZ_CHECKTEST(crcOrig!=crcNew, "LZ4_decompress_safe_continue() decompression corruption"); }
1519
1520 assert(messageSize < INT_MAX);
1521 result = LZ4_decompress_fast_continue(&decodeStateFast, testCompressed, testVerify + dNext, (int)messageSize);
1522 FUZ_CHECKTEST(result!=compressedSize, "ringBuffer : LZ4_decompress_fast_continue() test failed");
1523
1524 XXH64_update(&xxhNewFast, testVerify + dNext, messageSize);
1525 { XXH64_hash_t const crcNew = XXH64_digest(&xxhNewFast);
1526 FUZ_CHECKTEST(crcOrig!=crcNew, "LZ4_decompress_fast_continue() decompression corruption"); }
1527
1528 /* prepare next message */
1529 iNext += messageSize;
1530 rNext += messageSize;
1531 dNext += messageSize;
1532 messageSize = (FUZ_rand(&randState) & maxMessageSizeMask) + 1;
1533 if (rNext + messageSize > ringBufferSize) rNext = 0;
1534 if (dNext + messageSize > dBufferSize) dNext = 0;
1535 }
1536 }
1537
1538 /* Ring buffer test : Non synchronized decoder */
1539 /* This test uses minimum amount of memory required to setup a decoding ring buffer
1540 * while being unsynchronized with encoder
1541 * (no assumption done on how the data is encoded, it just follows LZ4 format specification).
1542 * This size is documented in lz4.h, and is LZ4_decoderRingBufferSize(maxBlockSize).
1543 */
1544 { XXH64_state_t xxhOrig;
1545 XXH64_state_t xxhNewSafe, xxhNewFast;
1546 XXH64_hash_t crcOrig;
1547 LZ4_streamDecode_t decodeStateSafe, decodeStateFast;
1548 const int maxMessageSizeLog = 12;
1549 const int maxMessageSize = 1 << maxMessageSizeLog;
1550 const int maxMessageSizeMask = maxMessageSize - 1;
1551 int messageSize;
1552 U32 totalMessageSize = 0;
1553 const int dBufferSize = LZ4_decoderRingBufferSize(maxMessageSize);
1554 char* const ringBufferSafe = testVerify;
1555 char* const ringBufferFast = testVerify + dBufferSize + 1; /* used by LZ4_decompress_fast_continue */
1556 int iNext = 0;
1557 int dNext = 0;
1558 int compressedSize;
1559
1560 assert((size_t)dBufferSize * 2 + 1 < testInputSize); /* space used by ringBufferSafe and ringBufferFast */
1561 XXH64_reset(&xxhOrig, 0);
1562 XXH64_reset(&xxhNewSafe, 0);
1563 XXH64_reset(&xxhNewFast, 0);
1564 LZ4_resetStreamHC_fast(&sHC, compressionLevel);
1565 LZ4_setStreamDecode(&decodeStateSafe, NULL, 0);
1566 LZ4_setStreamDecode(&decodeStateFast, NULL, 0);
1567
1568 #define BSIZE1 (dBufferSize - (maxMessageSize-1))
1569
1570 /* first block */
1571 messageSize = BSIZE1; /* note : we cheat a bit here, in theory no message should be > maxMessageSize. We just want to fill the decoding ring buffer once. */
1572 XXH64_update(&xxhOrig, testInput + iNext, (size_t)messageSize);
1573 crcOrig = XXH64_digest(&xxhOrig);
1574
1575 compressedSize = LZ4_compress_HC_continue(&sHC, testInput + iNext, testCompressed, messageSize, testCompressedSize-ringBufferSize);
1576 FUZ_CHECKTEST(compressedSize==0, "LZ4_compress_HC_continue() compression failed");
1577 FUZ_CHECKTEST(sHC.internal_donotuse.dirty, "Context should be clean");
1578
1579 result = LZ4_decompress_safe_continue(&decodeStateSafe, testCompressed, ringBufferSafe + dNext, compressedSize, messageSize);
1580 FUZ_CHECKTEST(result!=messageSize, "64K D.ringBuffer : LZ4_decompress_safe_continue() test failed");
1581
1582 XXH64_update(&xxhNewSafe, ringBufferSafe + dNext, (size_t)messageSize);
1583 { U64 const crcNew = XXH64_digest(&xxhNewSafe);
1584 FUZ_CHECKTEST(crcOrig!=crcNew, "LZ4_decompress_safe_continue() decompression corruption"); }
1585
1586 result = LZ4_decompress_fast_continue(&decodeStateFast, testCompressed, ringBufferFast + dNext, messageSize);
1587 FUZ_CHECKTEST(result!=compressedSize, "64K D.ringBuffer : LZ4_decompress_fast_continue() test failed");
1588
1589 XXH64_update(&xxhNewFast, ringBufferFast + dNext, (size_t)messageSize);
1590 { U64 const crcNew = XXH64_digest(&xxhNewFast);
1591 FUZ_CHECKTEST(crcOrig!=crcNew, "LZ4_decompress_fast_continue() decompression corruption"); }
1592
1593 /* prepare second message */
1594 dNext += messageSize;
1595 assert(messageSize >= 0);
1596 totalMessageSize += (unsigned)messageSize;
1597 messageSize = maxMessageSize;
1598 iNext = BSIZE1+1;
1599 assert(BSIZE1 >= 65535);
1600 memcpy(testInput + iNext, testInput + (BSIZE1-65535), messageSize); /* will generate a match at max distance == 65535 */
1601 FUZ_CHECKTEST(dNext+messageSize <= dBufferSize, "Ring buffer test : second message should require restarting from beginning");
1602 dNext = 0;
1603
1604 while (totalMessageSize < 9 MB) {
1605 XXH64_update(&xxhOrig, testInput + iNext, (size_t)messageSize);
1606 crcOrig = XXH64_digest(&xxhOrig);
1607
1608 compressedSize = LZ4_compress_HC_continue(&sHC, testInput + iNext, testCompressed, messageSize, testCompressedSize-ringBufferSize);
1609 FUZ_CHECKTEST(compressedSize==0, "LZ4_compress_HC_continue() compression failed");
1610 FUZ_CHECKTEST(sHC.internal_donotuse.dirty, "Context should be clean");
1611 DISPLAYLEVEL(5, "compressed %i bytes to %i bytes \n", messageSize, compressedSize);
1612
1613 /* test LZ4_decompress_safe_continue */
1614 assert(dNext < dBufferSize);
1615 assert(dBufferSize - dNext >= maxMessageSize);
1616 result = LZ4_decompress_safe_continue(&decodeStateSafe,
1617 testCompressed, ringBufferSafe + dNext,
1618 compressedSize, dBufferSize - dNext); /* works without knowing messageSize, under assumption that messageSize <= maxMessageSize */
1619 FUZ_CHECKTEST(result!=messageSize, "D.ringBuffer : LZ4_decompress_safe_continue() test failed");
1620 XXH64_update(&xxhNewSafe, ringBufferSafe + dNext, (size_t)messageSize);
1621 { U64 const crcNew = XXH64_digest(&xxhNewSafe);
1622 if (crcOrig != crcNew) FUZ_findDiff(testInput + iNext, ringBufferSafe + dNext);
1623 FUZ_CHECKTEST(crcOrig!=crcNew, "LZ4_decompress_safe_continue() decompression corruption during D.ringBuffer test");
1624 }
1625
1626 /* test LZ4_decompress_fast_continue in its own buffer ringBufferFast */
1627 result = LZ4_decompress_fast_continue(&decodeStateFast, testCompressed, ringBufferFast + dNext, messageSize);
1628 FUZ_CHECKTEST(result!=compressedSize, "D.ringBuffer : LZ4_decompress_fast_continue() test failed");
1629 XXH64_update(&xxhNewFast, ringBufferFast + dNext, (size_t)messageSize);
1630 { U64 const crcNew = XXH64_digest(&xxhNewFast);
1631 if (crcOrig != crcNew) FUZ_findDiff(testInput + iNext, ringBufferFast + dNext);
1632 FUZ_CHECKTEST(crcOrig!=crcNew, "LZ4_decompress_fast_continue() decompression corruption during D.ringBuffer test");
1633 }
1634
1635 /* prepare next message */
1636 dNext += messageSize;
1637 assert(messageSize >= 0);
1638 totalMessageSize += (unsigned)messageSize;
1639 messageSize = (FUZ_rand(&randState) & maxMessageSizeMask) + 1;
1640 iNext = (FUZ_rand(&randState) & 65535);
1641 if (dNext + maxMessageSize > dBufferSize) dNext = 0;
1642 }
1643 } /* Ring buffer test : Non synchronized decoder */
1644 }
1645
1646 DISPLAYLEVEL(3, "LZ4_compress_HC_destSize : ");
1647 /* encode congenerical sequence test for HC compressors */
1648 { LZ4_streamHC_t* const sHC = LZ4_createStreamHC();
1649 int const src_buf_size = 3 MB;
1650 int const dst_buf_size = 6 KB;
1651 int const payload = 0;
1652 int const dst_step = 43;
1653 int const dst_min_len = 33 + (FUZ_rand(&randState) % dst_step);
1654 int const dst_max_len = 5000;
1655 int slen, dlen;
1656 char* sbuf1 = (char*)malloc(src_buf_size + 1);
1657 char* sbuf2 = (char*)malloc(src_buf_size + 1);
1658 char* dbuf1 = (char*)malloc(dst_buf_size + 1);
1659 char* dbuf2 = (char*)malloc(dst_buf_size + 1);
1660
1661 assert(sHC != NULL);
1662 assert(dst_buf_size > dst_max_len);
1663 if (!sbuf1 || !sbuf2 || !dbuf1 || !dbuf2) {
1664 EXIT_MSG("not enough memory for FUZ_unitTests (destSize)");
1665 }
1666 for (dlen = dst_min_len; dlen <= dst_max_len; dlen += dst_step) {
1667 int src_len = (dlen - 10)*255 + 24;
1668 if (src_len + 10 >= src_buf_size) break; /* END of check */
1669 for (slen = src_len - 3; slen <= src_len + 3; slen++) {
1670 int srcsz1, srcsz2;
1671 int dsz1, dsz2;
1672 int res1, res2;
1673 char const endchk = (char)0x88;
1674 DISPLAYLEVEL(5, "slen = %i, ", slen);
1675
1676 srcsz1 = slen;
1677 memset(sbuf1, payload, slen);
1678 memset(dbuf1, 0, dlen);
1679 dbuf1[dlen] = endchk;
1680 dsz1 = LZ4_compress_destSize(sbuf1, dbuf1, &srcsz1, dlen);
1681 DISPLAYLEVEL(5, "LZ4_compress_destSize: %i bytes compressed into %i bytes, ", srcsz1, dsz1);
1682 DISPLAYLEVEL(5, "last token : 0x%0X, ", dbuf1[dsz1 - 6]);
1683 DISPLAYLEVEL(5, "last ML extra lenbyte : 0x%0X, \n", dbuf1[dsz1 - 7]);
1684 FUZ_CHECKTEST(dbuf1[dlen] != endchk, "LZ4_compress_destSize() overwrite dst buffer !");
1685 FUZ_CHECKTEST(dsz1 <= 0, "LZ4_compress_destSize() compression failed");
1686 FUZ_CHECKTEST(dsz1 > dlen, "LZ4_compress_destSize() result larger than dst buffer !");
1687 FUZ_CHECKTEST(srcsz1 > slen, "LZ4_compress_destSize() read more than src buffer !");
1688
1689 res1 = LZ4_decompress_safe(dbuf1, sbuf1, dsz1, src_buf_size);
1690 FUZ_CHECKTEST(res1 != srcsz1, "LZ4_compress_destSize() decompression failed!");
1691
1692 srcsz2 = slen;
1693 memset(sbuf2, payload, slen);
1694 memset(dbuf2, 0, dlen);
1695 dbuf2[dlen] = endchk;
1696 LZ4_resetStreamHC(sHC, compressionLevel);
1697 dsz2 = LZ4_compress_HC_destSize(sHC, sbuf2, dbuf2, &srcsz2, dlen, compressionLevel);
1698 DISPLAYLEVEL(5, "LZ4_compress_HC_destSize: %i bytes compressed into %i bytes, ", srcsz2, dsz2);
1699 DISPLAYLEVEL(5, "last token : 0x%0X, ", dbuf2[dsz2 - 6]);
1700 DISPLAYLEVEL(5, "last ML extra lenbyte : 0x%0X, \n", dbuf2[dsz2 - 7]);
1701 FUZ_CHECKTEST(dbuf2[dlen] != endchk, "LZ4_compress_HC_destSize() overwrite dst buffer !");
1702 FUZ_CHECKTEST(dsz2 <= 0, "LZ4_compress_HC_destSize() compression failed");
1703 FUZ_CHECKTEST(dsz2 > dlen, "LZ4_compress_HC_destSize() result larger than dst buffer !");
1704 FUZ_CHECKTEST(srcsz2 > slen, "LZ4_compress_HC_destSize() read more than src buffer !");
1705 FUZ_CHECKTEST(dsz2 != dsz1, "LZ4_compress_HC_destSize() return incorrect result !");
1706 FUZ_CHECKTEST(srcsz2 != srcsz1, "LZ4_compress_HC_destSize() return incorrect src buffer size "
1707 ": srcsz2(%i) != srcsz1(%i)", srcsz2, srcsz1);
1708 FUZ_CHECKTEST(memcmp(dbuf2, dbuf1, (size_t)dsz2), "LZ4_compress_HC_destSize() return incorrect data into dst buffer !");
1709
1710 res2 = LZ4_decompress_safe(dbuf2, sbuf1, dsz2, src_buf_size);
1711 FUZ_CHECKTEST(res2 != srcsz1, "LZ4_compress_HC_destSize() decompression failed!");
1712
1713 FUZ_CHECKTEST(memcmp(sbuf1, sbuf2, (size_t)res2), "LZ4_compress_HC_destSize() decompression corruption!");
1714 }
1715 }
1716 LZ4_freeStreamHC(sHC);
1717 free(sbuf1);
1718 free(sbuf2);
1719 free(dbuf1);
1720 free(dbuf2);
1721 }
1722 DISPLAYLEVEL(3, " OK \n");
1723
1724
1725 /* clean up */
1726 free(testInput);
1727 free(testCompressed);
1728 free(testVerify);
1729
1730 printf("All unit tests completed successfully compressionLevel=%d \n", compressionLevel);
1731 return;
1732 }
1733
1734
1735
1736 /* =======================================
1737 * CLI
1738 * ======================================= */
1739
FUZ_usage(const char * programName)1740 static int FUZ_usage(const char* programName)
1741 {
1742 DISPLAY( "Usage :\n");
1743 DISPLAY( " %s [args]\n", programName);
1744 DISPLAY( "\n");
1745 DISPLAY( "Arguments :\n");
1746 DISPLAY( " -i# : Nb of tests (default:%i) \n", NB_ATTEMPTS);
1747 DISPLAY( " -T# : Duration of tests, in seconds (default: use Nb of tests) \n");
1748 DISPLAY( " -s# : Select seed (default:prompt user)\n");
1749 DISPLAY( " -t# : Select starting test number (default:0)\n");
1750 DISPLAY( " -P# : Select compressibility in %% (default:%i%%)\n", FUZ_COMPRESSIBILITY_DEFAULT);
1751 DISPLAY( " -v : verbose\n");
1752 DISPLAY( " -p : pause at the end\n");
1753 DISPLAY( " -h : display help and exit\n");
1754 return 0;
1755 }
1756
1757
main(int argc,const char ** argv)1758 int main(int argc, const char** argv)
1759 {
1760 U32 seed = 0;
1761 int seedset = 0;
1762 int argNb;
1763 unsigned nbTests = NB_ATTEMPTS;
1764 unsigned testNb = 0;
1765 int proba = FUZ_COMPRESSIBILITY_DEFAULT;
1766 int use_pause = 0;
1767 const char* programName = argv[0];
1768 U32 duration = 0;
1769
1770 /* Check command line */
1771 for(argNb=1; argNb<argc; argNb++) {
1772 const char* argument = argv[argNb];
1773
1774 if(!argument) continue; // Protection if argument empty
1775
1776 // Decode command (note : aggregated commands are allowed)
1777 if (argument[0]=='-') {
1778 if (!strcmp(argument, "--no-prompt")) { use_pause=0; seedset=1; g_displayLevel=1; continue; }
1779 argument++;
1780
1781 while (*argument!=0) {
1782 switch(*argument)
1783 {
1784 case 'h': /* display help */
1785 return FUZ_usage(programName);
1786
1787 case 'v': /* verbose mode */
1788 g_displayLevel++;
1789 argument++;
1790 break;
1791
1792 case 'p': /* pause at the end */
1793 use_pause=1;
1794 argument++;
1795 break;
1796
1797 case 'i':
1798 argument++;
1799 nbTests = 0; duration = 0;
1800 while ((*argument>='0') && (*argument<='9')) {
1801 nbTests *= 10;
1802 nbTests += (unsigned)(*argument - '0');
1803 argument++;
1804 }
1805 break;
1806
1807 case 'T':
1808 argument++;
1809 nbTests = 0; duration = 0;
1810 for (;;) {
1811 switch(*argument)
1812 {
1813 case 'm': duration *= 60; argument++; continue;
1814 case 's':
1815 case 'n': argument++; continue;
1816 case '0':
1817 case '1':
1818 case '2':
1819 case '3':
1820 case '4':
1821 case '5':
1822 case '6':
1823 case '7':
1824 case '8':
1825 case '9': duration *= 10; duration += (U32)(*argument++ - '0'); continue;
1826 }
1827 break;
1828 }
1829 break;
1830
1831 case 's':
1832 argument++;
1833 seed=0; seedset=1;
1834 while ((*argument>='0') && (*argument<='9')) {
1835 seed *= 10;
1836 seed += (U32)(*argument - '0');
1837 argument++;
1838 }
1839 break;
1840
1841 case 't': /* select starting test nb */
1842 argument++;
1843 testNb=0;
1844 while ((*argument>='0') && (*argument<='9')) {
1845 testNb *= 10;
1846 testNb += (unsigned)(*argument - '0');
1847 argument++;
1848 }
1849 break;
1850
1851 case 'P': /* change probability */
1852 argument++;
1853 proba=0;
1854 while ((*argument>='0') && (*argument<='9')) {
1855 proba *= 10;
1856 proba += *argument - '0';
1857 argument++;
1858 }
1859 if (proba<0) proba=0;
1860 if (proba>100) proba=100;
1861 break;
1862 default: ;
1863 }
1864 }
1865 }
1866 }
1867
1868 printf("Starting LZ4 fuzzer (%i-bits, v%s)\n", (int)(sizeof(size_t)*8), LZ4_versionString());
1869
1870 if (!seedset) {
1871 time_t const t = time(NULL);
1872 U32 const h = XXH32(&t, sizeof(t), 1);
1873 seed = h % 10000;
1874 }
1875 printf("Seed = %u\n", seed);
1876
1877 if (proba!=FUZ_COMPRESSIBILITY_DEFAULT) printf("Compressibility : %i%%\n", proba);
1878
1879 if ((seedset==0) && (testNb==0)) { FUZ_unitTests(LZ4HC_CLEVEL_DEFAULT); FUZ_unitTests(LZ4HC_CLEVEL_OPT_MIN); }
1880
1881 nbTests += (nbTests==0); /* avoid zero */
1882
1883 { int const result = FUZ_test(seed, nbTests, testNb, ((double)proba) / 100, duration);
1884 if (use_pause) {
1885 DISPLAY("press enter ... \n");
1886 (void)getchar();
1887 }
1888 return result;
1889 }
1890 }
1891