2 * Copyright (c) 2016-present, Yann Collet, Facebook, Inc.
5 * This source code is licensed under the BSD-style license found in the
6 * LICENSE file in the root directory of this source tree. An additional grant
7 * of patent rights can be found in the PATENTS file in the same directory.
11 /*-************************************
13 **************************************/
14 #ifdef _MSC_VER /* Visual Studio */
15 # define _CRT_SECURE_NO_WARNINGS /* fgets */
16 # pragma warning(disable : 4127) /* disable: C4127: conditional expression is constant */
17 # pragma warning(disable : 4146) /* disable: C4146: minus unsigned expression */
21 /*-************************************
23 **************************************/
24 #include <stdlib.h> /* free */
25 #include <stdio.h> /* fgets, sscanf */
26 #include <time.h> /* clock_t, clock() */
27 #include <string.h> /* strcmp */
29 #define ZSTD_STATIC_LINKING_ONLY /* ZSTD_maxCLevel */
30 #include "zstd.h" /* ZSTD_compressBound */
31 #define ZBUFF_STATIC_LINKING_ONLY /* ZBUFF_createCCtx_advanced */
32 #include "zbuff.h" /* ZBUFF_isError */
33 #include "datagen.h" /* RDG_genBuffer */
34 #define XXH_STATIC_LINKING_ONLY
35 #include "xxhash.h" /* XXH64_* */
38 /*-************************************
40 **************************************/
45 static const U32 nbTestsDefault = 10000;
46 #define COMPRESSIBLE_NOISE_LENGTH (10 MB)
47 #define FUZ_COMPRESSIBILITY_DEFAULT 50
48 static const U32 prime1 = 2654435761U;
49 static const U32 prime2 = 2246822519U;
53 /*-************************************
55 **************************************/
56 #define DISPLAY(...) fprintf(stderr, __VA_ARGS__)
57 #define DISPLAYLEVEL(l, ...) if (g_displayLevel>=l) { DISPLAY(__VA_ARGS__); }
58 static U32 g_displayLevel = 2;
60 #define DISPLAYUPDATE(l, ...) if (g_displayLevel>=l) { \
61 if ((FUZ_GetClockSpan(g_displayClock) > g_refreshRate) || (g_displayLevel>=4)) \
62 { g_displayClock = clock(); DISPLAY(__VA_ARGS__); \
63 if (g_displayLevel>=4) fflush(stdout); } }
64 static const clock_t g_refreshRate = CLOCKS_PER_SEC * 15 / 100;
65 static clock_t g_displayClock = 0;
67 static clock_t g_clockTime = 0;
70 /*-*******************************************************
72 *********************************************************/
73 #define MAX(a,b) ((a)>(b)?(a):(b))
75 static clock_t FUZ_GetClockSpan(clock_t clockStart)
77 return clock() - clockStart; /* works even when overflow. Max span ~ 30 mn */
81 @return : a 27 bits random value, from a 32-bits `seed`.
82 `seed` is also modified */
83 # define FUZ_rotl32(x,r) ((x << r) | (x >> (32 - r)))
84 unsigned int FUZ_rand(unsigned int* seedPtr)
86 U32 rand32 = *seedPtr;
89 rand32 = FUZ_rotl32(rand32, 13);
96 static unsigned FUZ_highbit32(U32 v32)
100 for ( ; v32 ; v32>>=1) nbBits++;
105 static void* ZBUFF_allocFunction(void* opaque, size_t size)
107 void* address = malloc(size);
109 /* DISPLAYLEVEL(4, "alloc %p, %d opaque=%p \n", address, (int)size, opaque); */
113 static void ZBUFF_freeFunction(void* opaque, void* address)
116 /* if (address) DISPLAYLEVEL(4, "free %p opaque=%p \n", address, opaque); */
120 static int basicUnitTests(U32 seed, double compressibility, ZSTD_customMem customMem)
123 size_t CNBufferSize = COMPRESSIBLE_NOISE_LENGTH;
124 void* CNBuffer = malloc(CNBufferSize);
125 size_t const skippableFrameSize = 11;
126 size_t const compressedBufferSize = (8 + skippableFrameSize) + ZSTD_compressBound(COMPRESSIBLE_NOISE_LENGTH);
127 void* compressedBuffer = malloc(compressedBufferSize);
128 size_t const decodedBufferSize = CNBufferSize;
129 void* decodedBuffer = malloc(decodedBufferSize);
130 size_t cSize, readSize, readSkipSize, genSize;
132 ZBUFF_CCtx* zc = ZBUFF_createCCtx_advanced(customMem);
133 ZBUFF_DCtx* zd = ZBUFF_createDCtx_advanced(customMem);
135 /* Create compressible test buffer */
136 if (!CNBuffer || !compressedBuffer || !decodedBuffer || !zc || !zd) {
137 DISPLAY("Not enough memory, aborting\n");
140 RDG_genBuffer(CNBuffer, CNBufferSize, compressibility, 0., seed);
142 /* generate skippable frame */
143 MEM_writeLE32(compressedBuffer, ZSTD_MAGIC_SKIPPABLE_START);
144 MEM_writeLE32(((char*)compressedBuffer)+4, (U32)skippableFrameSize);
145 cSize = skippableFrameSize + 8;
147 /* Basic compression test */
148 DISPLAYLEVEL(4, "test%3i : compress %u bytes : ", testNb++, COMPRESSIBLE_NOISE_LENGTH);
149 ZBUFF_compressInitDictionary(zc, CNBuffer, 128 KB, 1);
150 readSize = CNBufferSize;
151 genSize = compressedBufferSize;
152 { size_t const r = ZBUFF_compressContinue(zc, ((char*)compressedBuffer)+cSize, &genSize, CNBuffer, &readSize);
153 if (ZBUFF_isError(r)) goto _output_error; }
154 if (readSize != CNBufferSize) goto _output_error; /* entire input should be consumed */
156 genSize = compressedBufferSize - cSize;
157 { size_t const r = ZBUFF_compressEnd(zc, ((char*)compressedBuffer)+cSize, &genSize);
158 if (r != 0) goto _output_error; } /* error, or some data not flushed */
160 DISPLAYLEVEL(4, "OK (%u bytes : %.2f%%)\n", (U32)cSize, (double)cSize/COMPRESSIBLE_NOISE_LENGTH*100);
162 /* skippable frame test */
163 DISPLAYLEVEL(4, "test%3i : decompress skippable frame : ", testNb++);
164 ZBUFF_decompressInitDictionary(zd, CNBuffer, 128 KB);
165 readSkipSize = cSize;
166 genSize = CNBufferSize;
167 { size_t const r = ZBUFF_decompressContinue(zd, decodedBuffer, &genSize, compressedBuffer, &readSkipSize);
168 if (r != 0) goto _output_error; }
169 if (genSize != 0) goto _output_error; /* skippable frame len is 0 */
170 DISPLAYLEVEL(4, "OK \n");
172 /* Basic decompression test */
173 DISPLAYLEVEL(4, "test%3i : decompress %u bytes : ", testNb++, COMPRESSIBLE_NOISE_LENGTH);
174 ZBUFF_decompressInitDictionary(zd, CNBuffer, 128 KB);
175 readSize = cSize - readSkipSize;
176 genSize = CNBufferSize;
177 { size_t const r = ZBUFF_decompressContinue(zd, decodedBuffer, &genSize, ((char*)compressedBuffer)+readSkipSize, &readSize);
178 if (r != 0) goto _output_error; } /* should reach end of frame == 0; otherwise, some data left, or an error */
179 if (genSize != CNBufferSize) goto _output_error; /* should regenerate the same amount */
180 if (readSize+readSkipSize != cSize) goto _output_error; /* should have read the entire frame */
181 DISPLAYLEVEL(4, "OK \n");
183 /* check regenerated data is byte exact */
184 DISPLAYLEVEL(4, "test%3i : check decompressed result : ", testNb++);
186 for (i=0; i<CNBufferSize; i++) {
187 if (((BYTE*)decodedBuffer)[i] != ((BYTE*)CNBuffer)[i]) goto _output_error;;
189 DISPLAYLEVEL(4, "OK \n");
191 /* Byte-by-byte decompression test */
192 DISPLAYLEVEL(4, "test%3i : decompress byte-by-byte : ", testNb++);
193 { size_t r, pIn=0, pOut=0;
195 { ZBUFF_decompressInitDictionary(zd, CNBuffer, 128 KB);
200 r = ZBUFF_decompressContinue(zd, ((BYTE*)decodedBuffer)+pOut, &outS, ((BYTE*)compressedBuffer)+pIn, &inS);
206 } while (genSize==0);
208 if (genSize != CNBufferSize) goto _output_error; /* should regenerate the same amount */
209 if (readSize != cSize) goto _output_error; /* should have read the entire frame */
210 DISPLAYLEVEL(4, "OK \n");
212 /* check regenerated data is byte exact */
213 DISPLAYLEVEL(4, "test%3i : check decompressed result : ", testNb++);
215 for (i=0; i<CNBufferSize; i++) {
216 if (((BYTE*)decodedBuffer)[i] != ((BYTE*)CNBuffer)[i]) goto _output_error;;
218 DISPLAYLEVEL(4, "OK \n");
224 free(compressedBuffer);
230 DISPLAY("Error detected in Unit tests ! \n");
235 static size_t findDiff(const void* buf1, const void* buf2, size_t max)
237 const BYTE* b1 = (const BYTE*)buf1;
238 const BYTE* b2 = (const BYTE*)buf2;
240 for (u=0; u<max; u++) {
241 if (b1[u] != b2[u]) break;
246 static size_t FUZ_rLogLength(U32* seed, U32 logLength)
248 size_t const lengthMask = ((size_t)1 << logLength) - 1;
249 return (lengthMask+1) + (FUZ_rand(seed) & lengthMask);
252 static size_t FUZ_randomLength(U32* seed, U32 maxLog)
254 U32 const logLength = FUZ_rand(seed) % maxLog;
255 return FUZ_rLogLength(seed, logLength);
258 #define MIN(a,b) ( (a) < (b) ? (a) : (b) )
260 #define CHECK(cond, ...) if (cond) { DISPLAY("Error => "); DISPLAY(__VA_ARGS__); \
261 DISPLAY(" (seed %u, test nb %u) \n", seed, testNb); goto _output_error; }
263 static int fuzzerTests(U32 seed, U32 nbTests, unsigned startTest, double compressibility)
265 static const U32 maxSrcLog = 24;
266 static const U32 maxSampleLog = 19;
267 BYTE* cNoiseBuffer[5];
268 size_t const srcBufferSize = (size_t)1<<maxSrcLog;
270 size_t const copyBufferSize= srcBufferSize + (1<<maxSampleLog);
272 size_t const cBufferSize = ZSTD_compressBound(srcBufferSize);
274 size_t dstBufferSize = srcBufferSize;
280 clock_t startClock = clock();
283 zc = ZBUFF_createCCtx();
284 zd = ZBUFF_createDCtx();
285 cNoiseBuffer[0] = (BYTE*)malloc (srcBufferSize);
286 cNoiseBuffer[1] = (BYTE*)malloc (srcBufferSize);
287 cNoiseBuffer[2] = (BYTE*)malloc (srcBufferSize);
288 cNoiseBuffer[3] = (BYTE*)malloc (srcBufferSize);
289 cNoiseBuffer[4] = (BYTE*)malloc (srcBufferSize);
290 copyBuffer= (BYTE*)malloc (copyBufferSize);
291 dstBuffer = (BYTE*)malloc (dstBufferSize);
292 cBuffer = (BYTE*)malloc (cBufferSize);
293 CHECK (!cNoiseBuffer[0] || !cNoiseBuffer[1] || !cNoiseBuffer[2] || !cNoiseBuffer[3] || !cNoiseBuffer[4] ||
294 !copyBuffer || !dstBuffer || !cBuffer || !zc || !zd,
295 "Not enough memory, fuzzer tests cancelled");
297 /* Create initial samples */
298 RDG_genBuffer(cNoiseBuffer[0], srcBufferSize, 0.00, 0., coreSeed); /* pure noise */
299 RDG_genBuffer(cNoiseBuffer[1], srcBufferSize, 0.05, 0., coreSeed); /* barely compressible */
300 RDG_genBuffer(cNoiseBuffer[2], srcBufferSize, compressibility, 0., coreSeed);
301 RDG_genBuffer(cNoiseBuffer[3], srcBufferSize, 0.95, 0., coreSeed); /* highly compressible */
302 RDG_genBuffer(cNoiseBuffer[4], srcBufferSize, 1.00, 0., coreSeed); /* sparse content */
303 memset(copyBuffer, 0x65, copyBufferSize); /* make copyBuffer considered initialized */
305 /* catch up testNb */
306 for (testNb=1; testNb < startTest; testNb++)
310 for ( ; (testNb <= nbTests) || (FUZ_GetClockSpan(startClock) < g_clockTime) ; testNb++ ) {
312 const BYTE* srcBuffer;
314 size_t maxTestSize, dictSize;
315 size_t cSize, totalTestSize, totalCSize, totalGenSize;
318 XXH64_state_t xxhState;
322 DISPLAYUPDATE(2, "\r%6u", testNb);
323 if (nbTests >= testNb) DISPLAYUPDATE(2, "/%6u ", nbTests);
325 lseed = coreSeed ^ prime1;
327 /* states full reset (unsynchronized) */
328 /* some issues only happen when reusing states in a specific sequence of parameters */
329 if ((FUZ_rand(&lseed) & 0xFF) == 131) { ZBUFF_freeCCtx(zc); zc = ZBUFF_createCCtx(); }
330 if ((FUZ_rand(&lseed) & 0xFF) == 132) { ZBUFF_freeDCtx(zd); zd = ZBUFF_createDCtx(); }
332 /* srcBuffer selection [0-4] */
333 { U32 buffNb = FUZ_rand(&lseed) & 0x7F;
334 if (buffNb & 7) buffNb=2; /* most common : compressible (P) */
338 const U32 tnb[2] = { 1, 3 }; /* barely/highly compressible */
339 buffNb = tnb[buffNb >> 3];
341 const U32 tnb[2] = { 0, 4 }; /* not compressible / sparse */
342 buffNb = tnb[buffNb >> 3];
344 srcBuffer = cNoiseBuffer[buffNb];
347 /* compression init */
348 { U32 const testLog = FUZ_rand(&lseed) % maxSrcLog;
349 U32 const cLevel = (FUZ_rand(&lseed) % (ZSTD_maxCLevel() - (testLog/3))) + 1;
350 maxTestSize = FUZ_rLogLength(&lseed, testLog);
351 dictSize = (FUZ_rand(&lseed)==1) ? FUZ_randomLength(&lseed, maxSampleLog) : 0;
352 /* random dictionary selection */
353 { size_t const dictStart = FUZ_rand(&lseed) % (srcBufferSize - dictSize);
354 dict = srcBuffer + dictStart;
356 { ZSTD_parameters params = ZSTD_getParams(cLevel, 0, dictSize);
357 params.fParams.checksumFlag = FUZ_rand(&lseed) & 1;
358 params.fParams.noDictIDFlag = FUZ_rand(&lseed) & 1;
359 { size_t const initError = ZBUFF_compressInit_advanced(zc, dict, dictSize, params, 0);
360 CHECK (ZBUFF_isError(initError),"init error : %s", ZBUFF_getErrorName(initError));
363 /* multi-segments compression test */
364 XXH64_reset(&xxhState, 0);
365 nbChunks = (FUZ_rand(&lseed) & 127) + 2;
366 for (n=0, cSize=0, totalTestSize=0 ; (n<nbChunks) && (totalTestSize < maxTestSize) ; n++) {
367 /* compress random chunk into random size dst buffer */
368 { size_t readChunkSize = FUZ_randomLength(&lseed, maxSampleLog);
369 size_t const randomDstSize = FUZ_randomLength(&lseed, maxSampleLog);
370 size_t dstBuffSize = MIN(cBufferSize - cSize, randomDstSize);
371 size_t const srcStart = FUZ_rand(&lseed) % (srcBufferSize - readChunkSize);
373 size_t const compressionError = ZBUFF_compressContinue(zc, cBuffer+cSize, &dstBuffSize, srcBuffer+srcStart, &readChunkSize);
374 CHECK (ZBUFF_isError(compressionError), "compression error : %s", ZBUFF_getErrorName(compressionError));
376 XXH64_update(&xxhState, srcBuffer+srcStart, readChunkSize);
377 memcpy(copyBuffer+totalTestSize, srcBuffer+srcStart, readChunkSize);
378 cSize += dstBuffSize;
379 totalTestSize += readChunkSize;
382 /* random flush operation, to mess around */
383 if ((FUZ_rand(&lseed) & 15) == 0) {
384 size_t const randomDstSize = FUZ_randomLength(&lseed, maxSampleLog);
385 size_t dstBuffSize = MIN(cBufferSize - cSize, randomDstSize);
386 size_t const flushError = ZBUFF_compressFlush(zc, cBuffer+cSize, &dstBuffSize);
387 CHECK (ZBUFF_isError(flushError), "flush error : %s", ZBUFF_getErrorName(flushError));
388 cSize += dstBuffSize;
391 /* final frame epilogue */
392 { size_t remainingToFlush = (size_t)(-1);
393 while (remainingToFlush) {
394 size_t const randomDstSize = FUZ_randomLength(&lseed, maxSampleLog);
395 size_t dstBuffSize = MIN(cBufferSize - cSize, randomDstSize);
396 U32 const enoughDstSize = dstBuffSize >= remainingToFlush;
397 remainingToFlush = ZBUFF_compressEnd(zc, cBuffer+cSize, &dstBuffSize);
398 CHECK (ZBUFF_isError(remainingToFlush), "flush error : %s", ZBUFF_getErrorName(remainingToFlush));
399 CHECK (enoughDstSize && remainingToFlush, "ZBUFF_compressEnd() not fully flushed (%u remaining), but enough space available", (U32)remainingToFlush);
400 cSize += dstBuffSize;
402 crcOrig = XXH64_digest(&xxhState);
404 /* multi - fragments decompression test */
405 ZBUFF_decompressInitDictionary(zd, dict, dictSize);
407 for (totalCSize = 0, totalGenSize = 0 ; errorCode ; ) {
408 size_t readCSrcSize = FUZ_randomLength(&lseed, maxSampleLog);
409 size_t const randomDstSize = FUZ_randomLength(&lseed, maxSampleLog);
410 size_t dstBuffSize = MIN(dstBufferSize - totalGenSize, randomDstSize);
411 errorCode = ZBUFF_decompressContinue(zd, dstBuffer+totalGenSize, &dstBuffSize, cBuffer+totalCSize, &readCSrcSize);
412 CHECK (ZBUFF_isError(errorCode), "decompression error : %s", ZBUFF_getErrorName(errorCode));
413 totalGenSize += dstBuffSize;
414 totalCSize += readCSrcSize;
416 CHECK (errorCode != 0, "frame not fully decoded");
417 CHECK (totalGenSize != totalTestSize, "decompressed data : wrong size")
418 CHECK (totalCSize != cSize, "compressed data should be fully read")
419 { U64 const crcDest = XXH64(dstBuffer, totalTestSize, 0);
420 if (crcDest!=crcOrig) findDiff(copyBuffer, dstBuffer, totalTestSize);
421 CHECK (crcDest!=crcOrig, "decompressed data corrupted"); }
423 /*===== noisy/erroneous src decompression test =====*/
426 { U32 const nbNoiseChunks = (FUZ_rand(&lseed) & 7) + 2;
427 U32 nn; for (nn=0; nn<nbNoiseChunks; nn++) {
428 size_t const randomNoiseSize = FUZ_randomLength(&lseed, maxSampleLog);
429 size_t const noiseSize = MIN((cSize/3) , randomNoiseSize);
430 size_t const noiseStart = FUZ_rand(&lseed) % (srcBufferSize - noiseSize);
431 size_t const cStart = FUZ_rand(&lseed) % (cSize - noiseSize);
432 memcpy(cBuffer+cStart, srcBuffer+noiseStart, noiseSize);
435 /* try decompression on noisy data */
436 ZBUFF_decompressInit(zd);
439 while ( (totalCSize < cSize) && (totalGenSize < dstBufferSize) ) {
440 size_t readCSrcSize = FUZ_randomLength(&lseed, maxSampleLog);
441 size_t const randomDstSize = FUZ_randomLength(&lseed, maxSampleLog);
442 size_t dstBuffSize = MIN(dstBufferSize - totalGenSize, randomDstSize);
443 size_t const decompressError = ZBUFF_decompressContinue(zd, dstBuffer+totalGenSize, &dstBuffSize, cBuffer+totalCSize, &readCSrcSize);
444 if (ZBUFF_isError(decompressError)) break; /* error correctly detected */
445 totalGenSize += dstBuffSize;
446 totalCSize += readCSrcSize;
448 DISPLAY("\r%u fuzzer tests completed \n", testNb);
453 free(cNoiseBuffer[0]);
454 free(cNoiseBuffer[1]);
455 free(cNoiseBuffer[2]);
456 free(cNoiseBuffer[3]);
457 free(cNoiseBuffer[4]);
469 /*-*******************************************************
471 *********************************************************/
472 int FUZ_usage(const char* programName)
474 DISPLAY( "Usage :\n");
475 DISPLAY( " %s [args]\n", programName);
477 DISPLAY( "Arguments :\n");
478 DISPLAY( " -i# : Nb of tests (default:%u) \n", nbTestsDefault);
479 DISPLAY( " -s# : Select seed (default:prompt user)\n");
480 DISPLAY( " -t# : Select starting test number (default:0)\n");
481 DISPLAY( " -P# : Select compressibility in %% (default:%i%%)\n", FUZ_COMPRESSIBILITY_DEFAULT);
482 DISPLAY( " -v : verbose\n");
483 DISPLAY( " -p : pause at the end\n");
484 DISPLAY( " -h : display help and exit\n");
489 int main(int argc, const char** argv)
494 int nbTests = nbTestsDefault;
496 int proba = FUZ_COMPRESSIBILITY_DEFAULT;
499 const char* programName = argv[0];
500 ZSTD_customMem customMem = { ZBUFF_allocFunction, ZBUFF_freeFunction, NULL };
501 ZSTD_customMem customNULL = { NULL, NULL, NULL };
503 /* Check command line */
504 for(argNb=1; argNb<argc; argNb++) {
505 const char* argument = argv[argNb];
506 if(!argument) continue; /* Protection if argument empty */
508 /* Parsing commands. Aggregated commands are allowed */
509 if (argument[0]=='-') {
512 while (*argument!=0) {
516 return FUZ_usage(programName);
525 case 'p': /* pause at the end */
532 nbTests=0; g_clockTime=0;
533 while ((*argument>='0') && (*argument<='9')) {
535 nbTests += *argument - '0';
542 nbTests=0; g_clockTime=0;
543 while ((*argument>='0') && (*argument<='9')) {
545 g_clockTime += *argument - '0';
548 if (*argument=='m') g_clockTime *=60, argument++;
549 if (*argument=='n') argument++;
550 g_clockTime *= CLOCKS_PER_SEC;
557 while ((*argument>='0') && (*argument<='9')) {
559 seed += *argument - '0';
567 while ((*argument>='0') && (*argument<='9')) {
569 testNb += *argument - '0';
574 case 'P': /* compressibility % */
577 while ((*argument>='0') && (*argument<='9')) {
579 proba += *argument - '0';
582 if (proba<0) proba=0;
583 if (proba>100) proba=100;
587 return FUZ_usage(programName);
589 } } } /* for(argNb=1; argNb<argc; argNb++) */
592 DISPLAY("Starting zstd_buffered tester (%i-bits, %s)\n", (int)(sizeof(size_t)*8), ZSTD_VERSION_STRING);
595 time_t const t = time(NULL);
596 U32 const h = XXH32(&t, sizeof(t), 1);
599 DISPLAY("Seed = %u\n", seed);
600 if (proba!=FUZ_COMPRESSIBILITY_DEFAULT) DISPLAY("Compressibility : %i%%\n", proba);
602 if (nbTests<=0) nbTests=1;
605 result = basicUnitTests(0, ((double)proba) / 100, customNULL); /* constant seed for predictability */
607 DISPLAYLEVEL(4, "Unit tests using customMem :\n")
608 result = basicUnitTests(0, ((double)proba) / 100, customMem); /* use custom memory allocation functions */
612 result = fuzzerTests(seed, nbTests, testNb, ((double)proba) / 100);
616 DISPLAY("Press Enter \n");