2 * Copyright (c) 2015-present, Yann Collet, Facebook, Inc.
5 * This source code is licensed under both the BSD-style license (found in the
6 * LICENSE file in the root directory of this source tree) and the GPLv2 (found
7 * in the COPYING file in the root directory of this source tree).
8 * You may select, at your option, one of the above-listed licenses.
12 /*-************************************
14 **************************************/
15 #ifdef _MSC_VER /* Visual Studio */
16 # define _CRT_SECURE_NO_WARNINGS /* fgets */
17 # pragma warning(disable : 4127) /* disable: C4127: conditional expression is constant */
18 # pragma warning(disable : 4146) /* disable: C4146: minus unsigned expression */
22 /*-************************************
24 **************************************/
25 #include <stdlib.h> /* free */
26 #include <stdio.h> /* fgets, sscanf */
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_* */
39 /*-************************************
41 **************************************/
46 static const U32 nbTestsDefault = 10000;
47 #define COMPRESSIBLE_NOISE_LENGTH (10 MB)
48 #define FUZ_COMPRESSIBILITY_DEFAULT 50
49 static const U32 prime1 = 2654435761U;
50 static const U32 prime2 = 2246822519U;
54 /*-************************************
56 **************************************/
57 #define DISPLAY(...) fprintf(stderr, __VA_ARGS__)
58 #define DISPLAYLEVEL(l, ...) if (g_displayLevel>=l) { DISPLAY(__VA_ARGS__); }
59 static U32 g_displayLevel = 2;
61 static const U64 g_refreshRate = SEC_TO_MICRO / 6;
62 static UTIL_time_t g_displayClock = UTIL_TIME_INITIALIZER;
64 #define DISPLAYUPDATE(l, ...) if (g_displayLevel>=l) { \
65 if ((UTIL_clockSpanMicro(g_displayClock) > g_refreshRate) || (g_displayLevel>=4)) \
66 { g_displayClock = UTIL_getTime(); DISPLAY(__VA_ARGS__); \
67 if (g_displayLevel>=4) fflush(stderr); } }
69 static U64 g_clockTime = 0;
72 /*-*******************************************************
74 *********************************************************/
77 #define MIN(a,b) ((a)<(b)?(a):(b))
78 #define MAX(a,b) ((a)>(b)?(a):(b))
80 @return : a 27 bits random value, from a 32-bits `seed`.
81 `seed` is also modified */
82 # define FUZ_rotl32(x,r) ((x << r) | (x >> (32 - r)))
83 unsigned int FUZ_rand(unsigned int* seedPtr)
85 U32 rand32 = *seedPtr;
88 rand32 = FUZ_rotl32(rand32, 13);
95 static unsigned FUZ_highbit32(U32 v32)
99 for ( ; v32 ; v32>>=1) nbBits++;
104 static void* ZBUFF_allocFunction(void* opaque, size_t size)
106 void* address = malloc(size);
108 /* DISPLAYLEVEL(4, "alloc %p, %d opaque=%p \n", address, (int)size, opaque); */
112 static void ZBUFF_freeFunction(void* opaque, void* address)
115 /* if (address) DISPLAYLEVEL(4, "free %p opaque=%p \n", address, opaque); */
119 static int basicUnitTests(U32 seed, double compressibility, ZSTD_customMem customMem)
122 size_t CNBufferSize = COMPRESSIBLE_NOISE_LENGTH;
123 void* CNBuffer = malloc(CNBufferSize);
124 size_t const skippableFrameSize = 11;
125 size_t const compressedBufferSize = (8 + skippableFrameSize) + ZSTD_compressBound(COMPRESSIBLE_NOISE_LENGTH);
126 void* compressedBuffer = malloc(compressedBufferSize);
127 size_t const decodedBufferSize = CNBufferSize;
128 void* decodedBuffer = malloc(decodedBufferSize);
129 size_t cSize, readSize, readSkipSize, genSize;
131 ZBUFF_CCtx* zc = ZBUFF_createCCtx_advanced(customMem);
132 ZBUFF_DCtx* zd = ZBUFF_createDCtx_advanced(customMem);
134 /* Create compressible test buffer */
135 if (!CNBuffer || !compressedBuffer || !decodedBuffer || !zc || !zd) {
136 DISPLAY("Not enough memory, aborting\n");
139 RDG_genBuffer(CNBuffer, CNBufferSize, compressibility, 0., seed);
141 /* generate skippable frame */
142 MEM_writeLE32(compressedBuffer, ZSTD_MAGIC_SKIPPABLE_START);
143 MEM_writeLE32(((char*)compressedBuffer)+4, (U32)skippableFrameSize);
144 cSize = skippableFrameSize + 8;
146 /* Basic compression test */
147 DISPLAYLEVEL(4, "test%3i : compress %u bytes : ", testNb++, COMPRESSIBLE_NOISE_LENGTH);
148 ZBUFF_compressInitDictionary(zc, CNBuffer, 128 KB, 1);
149 readSize = CNBufferSize;
150 genSize = compressedBufferSize;
151 { size_t const r = ZBUFF_compressContinue(zc, ((char*)compressedBuffer)+cSize, &genSize, CNBuffer, &readSize);
152 if (ZBUFF_isError(r)) goto _output_error; }
153 if (readSize != CNBufferSize) goto _output_error; /* entire input should be consumed */
155 genSize = compressedBufferSize - cSize;
156 { size_t const r = ZBUFF_compressEnd(zc, ((char*)compressedBuffer)+cSize, &genSize);
157 if (r != 0) goto _output_error; } /* error, or some data not flushed */
159 DISPLAYLEVEL(4, "OK (%u bytes : %.2f%%)\n", (U32)cSize, (double)cSize/COMPRESSIBLE_NOISE_LENGTH*100);
161 /* skippable frame test */
162 DISPLAYLEVEL(4, "test%3i : decompress skippable frame : ", testNb++);
163 ZBUFF_decompressInitDictionary(zd, CNBuffer, 128 KB);
164 readSkipSize = cSize;
165 genSize = CNBufferSize;
166 { size_t const r = ZBUFF_decompressContinue(zd, decodedBuffer, &genSize, compressedBuffer, &readSkipSize);
167 if (r != 0) goto _output_error; }
168 if (genSize != 0) goto _output_error; /* skippable frame len is 0 */
169 DISPLAYLEVEL(4, "OK \n");
171 /* Basic decompression test */
172 DISPLAYLEVEL(4, "test%3i : decompress %u bytes : ", testNb++, COMPRESSIBLE_NOISE_LENGTH);
173 ZBUFF_decompressInitDictionary(zd, CNBuffer, 128 KB);
174 readSize = cSize - readSkipSize;
175 genSize = CNBufferSize;
176 { size_t const r = ZBUFF_decompressContinue(zd, decodedBuffer, &genSize, ((char*)compressedBuffer)+readSkipSize, &readSize);
177 if (r != 0) goto _output_error; } /* should reach end of frame == 0; otherwise, some data left, or an error */
178 if (genSize != CNBufferSize) goto _output_error; /* should regenerate the same amount */
179 if (readSize+readSkipSize != cSize) goto _output_error; /* should have read the entire frame */
180 DISPLAYLEVEL(4, "OK \n");
182 /* check regenerated data is byte exact */
183 DISPLAYLEVEL(4, "test%3i : check decompressed result : ", testNb++);
185 for (i=0; i<CNBufferSize; i++) {
186 if (((BYTE*)decodedBuffer)[i] != ((BYTE*)CNBuffer)[i]) goto _output_error;;
188 DISPLAYLEVEL(4, "OK \n");
190 /* Byte-by-byte decompression test */
191 DISPLAYLEVEL(4, "test%3i : decompress byte-by-byte : ", testNb++);
192 { size_t r, pIn=0, pOut=0;
194 { ZBUFF_decompressInitDictionary(zd, CNBuffer, 128 KB);
199 r = ZBUFF_decompressContinue(zd, ((BYTE*)decodedBuffer)+pOut, &outS, ((BYTE*)compressedBuffer)+pIn, &inS);
205 } while (genSize==0);
207 if (genSize != CNBufferSize) goto _output_error; /* should regenerate the same amount */
208 if (readSize != cSize) goto _output_error; /* should have read the entire frame */
209 DISPLAYLEVEL(4, "OK \n");
211 /* check regenerated data is byte exact */
212 DISPLAYLEVEL(4, "test%3i : check decompressed result : ", testNb++);
214 for (i=0; i<CNBufferSize; i++) {
215 if (((BYTE*)decodedBuffer)[i] != ((BYTE*)CNBuffer)[i]) goto _output_error;;
217 DISPLAYLEVEL(4, "OK \n");
223 free(compressedBuffer);
229 DISPLAY("Error detected in Unit tests ! \n");
234 static size_t findDiff(const void* buf1, const void* buf2, size_t max)
236 const BYTE* b1 = (const BYTE*)buf1;
237 const BYTE* b2 = (const BYTE*)buf2;
239 for (u=0; u<max; u++) {
240 if (b1[u] != b2[u]) break;
245 static size_t FUZ_rLogLength(U32* seed, U32 logLength)
247 size_t const lengthMask = ((size_t)1 << logLength) - 1;
248 return (lengthMask+1) + (FUZ_rand(seed) & lengthMask);
251 static size_t FUZ_randomLength(U32* seed, U32 maxLog)
253 U32 const logLength = FUZ_rand(seed) % maxLog;
254 return FUZ_rLogLength(seed, logLength);
257 #define CHECK(cond, ...) if (cond) { DISPLAY("Error => "); DISPLAY(__VA_ARGS__); \
258 DISPLAY(" (seed %u, test nb %u) \n", seed, testNb); goto _output_error; }
260 static int fuzzerTests(U32 seed, U32 nbTests, unsigned startTest, double compressibility)
262 static const U32 maxSrcLog = 24;
263 static const U32 maxSampleLog = 19;
264 BYTE* cNoiseBuffer[5];
265 size_t const srcBufferSize = (size_t)1<<maxSrcLog;
267 size_t const copyBufferSize= srcBufferSize + (1<<maxSampleLog);
269 size_t const cBufferSize = ZSTD_compressBound(srcBufferSize);
271 size_t dstBufferSize = srcBufferSize;
277 UTIL_time_t startClock = UTIL_getTime();
280 zc = ZBUFF_createCCtx();
281 zd = ZBUFF_createDCtx();
282 cNoiseBuffer[0] = (BYTE*)malloc (srcBufferSize);
283 cNoiseBuffer[1] = (BYTE*)malloc (srcBufferSize);
284 cNoiseBuffer[2] = (BYTE*)malloc (srcBufferSize);
285 cNoiseBuffer[3] = (BYTE*)malloc (srcBufferSize);
286 cNoiseBuffer[4] = (BYTE*)malloc (srcBufferSize);
287 copyBuffer= (BYTE*)malloc (copyBufferSize);
288 dstBuffer = (BYTE*)malloc (dstBufferSize);
289 cBuffer = (BYTE*)malloc (cBufferSize);
290 CHECK (!cNoiseBuffer[0] || !cNoiseBuffer[1] || !cNoiseBuffer[2] || !cNoiseBuffer[3] || !cNoiseBuffer[4] ||
291 !copyBuffer || !dstBuffer || !cBuffer || !zc || !zd,
292 "Not enough memory, fuzzer tests cancelled");
294 /* Create initial samples */
295 RDG_genBuffer(cNoiseBuffer[0], srcBufferSize, 0.00, 0., coreSeed); /* pure noise */
296 RDG_genBuffer(cNoiseBuffer[1], srcBufferSize, 0.05, 0., coreSeed); /* barely compressible */
297 RDG_genBuffer(cNoiseBuffer[2], srcBufferSize, compressibility, 0., coreSeed);
298 RDG_genBuffer(cNoiseBuffer[3], srcBufferSize, 0.95, 0., coreSeed); /* highly compressible */
299 RDG_genBuffer(cNoiseBuffer[4], srcBufferSize, 1.00, 0., coreSeed); /* sparse content */
300 memset(copyBuffer, 0x65, copyBufferSize); /* make copyBuffer considered initialized */
302 /* catch up testNb */
303 for (testNb=1; testNb < startTest; testNb++)
307 for ( ; (testNb <= nbTests) || (UTIL_clockSpanMicro(startClock) < g_clockTime) ; testNb++ ) {
309 const BYTE* srcBuffer;
311 size_t maxTestSize, dictSize;
312 size_t cSize, totalTestSize, totalCSize, totalGenSize;
315 XXH64_state_t xxhState;
319 DISPLAYUPDATE(2, "\r%6u", testNb);
320 if (nbTests >= testNb) DISPLAYUPDATE(2, "/%6u ", nbTests);
322 lseed = coreSeed ^ prime1;
324 /* states full reset (unsynchronized) */
325 /* some issues only happen when reusing states in a specific sequence of parameters */
326 if ((FUZ_rand(&lseed) & 0xFF) == 131) { ZBUFF_freeCCtx(zc); zc = ZBUFF_createCCtx(); }
327 if ((FUZ_rand(&lseed) & 0xFF) == 132) { ZBUFF_freeDCtx(zd); zd = ZBUFF_createDCtx(); }
329 /* srcBuffer selection [0-4] */
330 { U32 buffNb = FUZ_rand(&lseed) & 0x7F;
331 if (buffNb & 7) buffNb=2; /* most common : compressible (P) */
335 const U32 tnb[2] = { 1, 3 }; /* barely/highly compressible */
336 buffNb = tnb[buffNb >> 3];
338 const U32 tnb[2] = { 0, 4 }; /* not compressible / sparse */
339 buffNb = tnb[buffNb >> 3];
341 srcBuffer = cNoiseBuffer[buffNb];
344 /* compression init */
345 { U32 const testLog = FUZ_rand(&lseed) % maxSrcLog;
346 U32 const cLevel = (FUZ_rand(&lseed) % (ZSTD_maxCLevel() - (testLog/3))) + 1;
347 maxTestSize = FUZ_rLogLength(&lseed, testLog);
348 dictSize = (FUZ_rand(&lseed)==1) ? FUZ_randomLength(&lseed, maxSampleLog) : 0;
349 /* random dictionary selection */
350 { size_t const dictStart = FUZ_rand(&lseed) % (srcBufferSize - dictSize);
351 dict = srcBuffer + dictStart;
353 { ZSTD_parameters params = ZSTD_getParams(cLevel, 0, dictSize);
354 params.fParams.checksumFlag = FUZ_rand(&lseed) & 1;
355 params.fParams.noDictIDFlag = FUZ_rand(&lseed) & 1;
356 { size_t const initError = ZBUFF_compressInit_advanced(zc, dict, dictSize, params, ZSTD_CONTENTSIZE_UNKNOWN);
357 CHECK (ZBUFF_isError(initError),"init error : %s", ZBUFF_getErrorName(initError));
360 /* multi-segments compression test */
361 XXH64_reset(&xxhState, 0);
362 nbChunks = (FUZ_rand(&lseed) & 127) + 2;
363 for (n=0, cSize=0, totalTestSize=0 ; (n<nbChunks) && (totalTestSize < maxTestSize) ; n++) {
364 /* compress random chunk into random size dst buffer */
365 { size_t readChunkSize = FUZ_randomLength(&lseed, maxSampleLog);
366 size_t const randomDstSize = FUZ_randomLength(&lseed, maxSampleLog);
367 size_t dstBuffSize = MIN(cBufferSize - cSize, randomDstSize);
368 size_t const srcStart = FUZ_rand(&lseed) % (srcBufferSize - readChunkSize);
370 size_t const compressionError = ZBUFF_compressContinue(zc, cBuffer+cSize, &dstBuffSize, srcBuffer+srcStart, &readChunkSize);
371 CHECK (ZBUFF_isError(compressionError), "compression error : %s", ZBUFF_getErrorName(compressionError));
373 XXH64_update(&xxhState, srcBuffer+srcStart, readChunkSize);
374 memcpy(copyBuffer+totalTestSize, srcBuffer+srcStart, readChunkSize);
375 cSize += dstBuffSize;
376 totalTestSize += readChunkSize;
379 /* random flush operation, to mess around */
380 if ((FUZ_rand(&lseed) & 15) == 0) {
381 size_t const randomDstSize = FUZ_randomLength(&lseed, maxSampleLog);
382 size_t dstBuffSize = MIN(cBufferSize - cSize, randomDstSize);
383 size_t const flushError = ZBUFF_compressFlush(zc, cBuffer+cSize, &dstBuffSize);
384 CHECK (ZBUFF_isError(flushError), "flush error : %s", ZBUFF_getErrorName(flushError));
385 cSize += dstBuffSize;
388 /* final frame epilogue */
389 { size_t remainingToFlush = (size_t)(-1);
390 while (remainingToFlush) {
391 size_t const randomDstSize = FUZ_randomLength(&lseed, maxSampleLog);
392 size_t dstBuffSize = MIN(cBufferSize - cSize, randomDstSize);
393 U32 const enoughDstSize = dstBuffSize >= remainingToFlush;
394 remainingToFlush = ZBUFF_compressEnd(zc, cBuffer+cSize, &dstBuffSize);
395 CHECK (ZBUFF_isError(remainingToFlush), "flush error : %s", ZBUFF_getErrorName(remainingToFlush));
396 CHECK (enoughDstSize && remainingToFlush, "ZBUFF_compressEnd() not fully flushed (%u remaining), but enough space available", (U32)remainingToFlush);
397 cSize += dstBuffSize;
399 crcOrig = XXH64_digest(&xxhState);
401 /* multi - fragments decompression test */
402 ZBUFF_decompressInitDictionary(zd, dict, dictSize);
404 for (totalCSize = 0, totalGenSize = 0 ; errorCode ; ) {
405 size_t readCSrcSize = FUZ_randomLength(&lseed, maxSampleLog);
406 size_t const randomDstSize = FUZ_randomLength(&lseed, maxSampleLog);
407 size_t dstBuffSize = MIN(dstBufferSize - totalGenSize, randomDstSize);
408 errorCode = ZBUFF_decompressContinue(zd, dstBuffer+totalGenSize, &dstBuffSize, cBuffer+totalCSize, &readCSrcSize);
409 CHECK (ZBUFF_isError(errorCode), "decompression error : %s", ZBUFF_getErrorName(errorCode));
410 totalGenSize += dstBuffSize;
411 totalCSize += readCSrcSize;
413 CHECK (errorCode != 0, "frame not fully decoded");
414 CHECK (totalGenSize != totalTestSize, "decompressed data : wrong size")
415 CHECK (totalCSize != cSize, "compressed data should be fully read")
416 { U64 const crcDest = XXH64(dstBuffer, totalTestSize, 0);
417 if (crcDest!=crcOrig) findDiff(copyBuffer, dstBuffer, totalTestSize);
418 CHECK (crcDest!=crcOrig, "decompressed data corrupted"); }
420 /*===== noisy/erroneous src decompression test =====*/
423 { U32 const nbNoiseChunks = (FUZ_rand(&lseed) & 7) + 2;
424 U32 nn; for (nn=0; nn<nbNoiseChunks; nn++) {
425 size_t const randomNoiseSize = FUZ_randomLength(&lseed, maxSampleLog);
426 size_t const noiseSize = MIN((cSize/3) , randomNoiseSize);
427 size_t const noiseStart = FUZ_rand(&lseed) % (srcBufferSize - noiseSize);
428 size_t const cStart = FUZ_rand(&lseed) % (cSize - noiseSize);
429 memcpy(cBuffer+cStart, srcBuffer+noiseStart, noiseSize);
432 /* try decompression on noisy data */
433 ZBUFF_decompressInit(zd);
436 while ( (totalCSize < cSize) && (totalGenSize < dstBufferSize) ) {
437 size_t readCSrcSize = FUZ_randomLength(&lseed, maxSampleLog);
438 size_t const randomDstSize = FUZ_randomLength(&lseed, maxSampleLog);
439 size_t dstBuffSize = MIN(dstBufferSize - totalGenSize, randomDstSize);
440 size_t const decompressError = ZBUFF_decompressContinue(zd, dstBuffer+totalGenSize, &dstBuffSize, cBuffer+totalCSize, &readCSrcSize);
441 if (ZBUFF_isError(decompressError)) break; /* error correctly detected */
442 totalGenSize += dstBuffSize;
443 totalCSize += readCSrcSize;
445 DISPLAY("\r%u fuzzer tests completed \n", testNb);
450 free(cNoiseBuffer[0]);
451 free(cNoiseBuffer[1]);
452 free(cNoiseBuffer[2]);
453 free(cNoiseBuffer[3]);
454 free(cNoiseBuffer[4]);
466 /*-*******************************************************
468 *********************************************************/
469 int FUZ_usage(const char* programName)
471 DISPLAY( "Usage :\n");
472 DISPLAY( " %s [args]\n", programName);
474 DISPLAY( "Arguments :\n");
475 DISPLAY( " -i# : Nb of tests (default:%u) \n", nbTestsDefault);
476 DISPLAY( " -s# : Select seed (default:prompt user)\n");
477 DISPLAY( " -t# : Select starting test number (default:0)\n");
478 DISPLAY( " -P# : Select compressibility in %% (default:%i%%)\n", FUZ_COMPRESSIBILITY_DEFAULT);
479 DISPLAY( " -v : verbose\n");
480 DISPLAY( " -p : pause at the end\n");
481 DISPLAY( " -h : display help and exit\n");
486 int main(int argc, const char** argv)
491 int nbTests = nbTestsDefault;
493 int proba = FUZ_COMPRESSIBILITY_DEFAULT;
496 const char* programName = argv[0];
497 ZSTD_customMem customMem = { ZBUFF_allocFunction, ZBUFF_freeFunction, NULL };
498 ZSTD_customMem customNULL = { NULL, NULL, NULL };
500 /* Check command line */
501 for(argNb=1; argNb<argc; argNb++) {
502 const char* argument = argv[argNb];
503 if(!argument) continue; /* Protection if argument empty */
505 /* Parsing commands. Aggregated commands are allowed */
506 if (argument[0]=='-') {
509 while (*argument!=0) {
513 return FUZ_usage(programName);
522 case 'p': /* pause at the end */
529 nbTests=0; g_clockTime=0;
530 while ((*argument>='0') && (*argument<='9')) {
532 nbTests += *argument - '0';
539 nbTests=0; g_clockTime=0;
540 while ((*argument>='0') && (*argument<='9')) {
542 g_clockTime += *argument - '0';
545 if (*argument=='m') g_clockTime *=60, argument++;
546 if (*argument=='n') argument++;
547 g_clockTime *= SEC_TO_MICRO;
554 while ((*argument>='0') && (*argument<='9')) {
556 seed += *argument - '0';
564 while ((*argument>='0') && (*argument<='9')) {
566 testNb += *argument - '0';
571 case 'P': /* compressibility % */
574 while ((*argument>='0') && (*argument<='9')) {
576 proba += *argument - '0';
579 if (proba<0) proba=0;
580 if (proba>100) proba=100;
584 return FUZ_usage(programName);
586 } } } /* for(argNb=1; argNb<argc; argNb++) */
589 DISPLAY("Starting zstd_buffered tester (%i-bits, %s)\n", (int)(sizeof(size_t)*8), ZSTD_VERSION_STRING);
592 time_t const t = time(NULL);
593 U32 const h = XXH32(&t, sizeof(t), 1);
596 DISPLAY("Seed = %u\n", seed);
597 if (proba!=FUZ_COMPRESSIBILITY_DEFAULT) DISPLAY("Compressibility : %i%%\n", proba);
599 if (nbTests<=0) nbTests=1;
602 result = basicUnitTests(0, ((double)proba) / 100, customNULL); /* constant seed for predictability */
604 DISPLAYLEVEL(4, "Unit tests using customMem :\n")
605 result = basicUnitTests(0, ((double)proba) / 100, customMem); /* use custom memory allocation functions */
609 result = fuzzerTests(seed, nbTests, testNb, ((double)proba) / 100);
613 DISPLAY("Press Enter \n");