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 : 4204) /* disable: C4204: non-constant aggregate initializer */
21 /*-************************************
23 **************************************/
24 #include <stdlib.h> /* free */
25 #include <stdio.h> /* fgets, sscanf */
26 #include <string.h> /* strcmp */
27 #include <time.h> /* clock_t */
28 #define ZSTD_STATIC_LINKING_ONLY /* ZSTD_compressContinue, ZSTD_compressBlock */
29 #include "zstd.h" /* ZSTD_VERSION_STRING */
30 #include "zstd_errors.h" /* ZSTD_getErrorCode */
31 #include "zstdmt_compress.h"
32 #define ZDICT_STATIC_LINKING_ONLY
33 #include "zdict.h" /* ZDICT_trainFromBuffer */
34 #include "datagen.h" /* RDG_genBuffer */
36 #define XXH_STATIC_LINKING_ONLY
37 #include "xxhash.h" /* XXH64 */
40 /*-************************************
42 **************************************/
47 static const U32 FUZ_compressibility_default = 50;
48 static const U32 nbTestsDefault = 30000;
51 /*-************************************
53 **************************************/
54 #define DISPLAY(...) fprintf(stderr, __VA_ARGS__)
55 #define DISPLAYLEVEL(l, ...) if (g_displayLevel>=l) { DISPLAY(__VA_ARGS__); }
56 static U32 g_displayLevel = 2;
58 #define DISPLAYUPDATE(l, ...) if (g_displayLevel>=l) { \
59 if ((FUZ_clockSpan(g_displayClock) > g_refreshRate) || (g_displayLevel>=4)) \
60 { g_displayClock = clock(); DISPLAY(__VA_ARGS__); \
61 if (g_displayLevel>=4) fflush(stderr); } }
62 static const clock_t g_refreshRate = CLOCKS_PER_SEC / 6;
63 static clock_t g_displayClock = 0;
66 /*-*******************************************************
68 *********************************************************/
69 #define MIN(a,b) ((a)<(b)?(a):(b))
70 #define MAX(a,b) ((a)>(b)?(a):(b))
72 static clock_t FUZ_clockSpan(clock_t cStart)
74 return clock() - cStart; /* works even when overflow; max span ~ 30mn */
77 #define FUZ_rotl32(x,r) ((x << r) | (x >> (32 - r)))
78 static unsigned FUZ_rand(unsigned* src)
80 static const U32 prime1 = 2654435761U;
81 static const U32 prime2 = 2246822519U;
85 rand32 = FUZ_rotl32(rand32, 13);
90 static unsigned FUZ_highbit32(U32 v32)
94 while (v32) v32 >>= 1, nbBits++;
99 /*=============================================
101 =============================================*/
103 #define CHECK_V(var, fn) size_t const var = fn; if (ZSTD_isError(var)) goto _output_error
104 #define CHECK(fn) { CHECK_V(err, fn); }
105 #define CHECKPLUS(var, fn, more) { CHECK_V(var, fn); more; }
107 static int basicUnitTests(U32 seed, double compressibility)
109 size_t const CNBuffSize = 5 MB;
110 void* const CNBuffer = malloc(CNBuffSize);
111 void* const compressedBuffer = malloc(ZSTD_compressBound(CNBuffSize));
112 void* const decodedBuffer = malloc(CNBuffSize);
113 ZSTD_DCtx* dctx = ZSTD_createDCtx();
118 /* Create compressible noise */
119 if (!CNBuffer || !compressedBuffer || !decodedBuffer) {
120 DISPLAY("Not enough memory, aborting\n");
124 RDG_genBuffer(CNBuffer, CNBuffSize, compressibility, 0., seed);
127 DISPLAYLEVEL(4, "test%3i : ZSTD_getErrorName : ", testNb++);
128 { const char* errorString = ZSTD_getErrorName(0);
129 DISPLAYLEVEL(4, "OK : %s \n", errorString);
132 DISPLAYLEVEL(4, "test%3i : ZSTD_getErrorName with wrong value : ", testNb++);
133 { const char* errorString = ZSTD_getErrorName(499);
134 DISPLAYLEVEL(4, "OK : %s \n", errorString);
138 DISPLAYLEVEL(4, "test%3i : compress %u bytes : ", testNb++, (U32)CNBuffSize);
139 CHECKPLUS(r, ZSTD_compress(compressedBuffer, ZSTD_compressBound(CNBuffSize),
140 CNBuffer, CNBuffSize, 1),
142 DISPLAYLEVEL(4, "OK (%u bytes : %.2f%%)\n", (U32)cSize, (double)cSize/CNBuffSize*100);
145 DISPLAYLEVEL(4, "test%3i : ZSTD_getFrameContentSize test : ", testNb++);
146 { unsigned long long const rSize = ZSTD_getFrameContentSize(compressedBuffer, cSize);
147 if (rSize != CNBuffSize) goto _output_error;
149 DISPLAYLEVEL(4, "OK \n");
151 DISPLAYLEVEL(4, "test%3i : ZSTD_findDecompressedSize test : ", testNb++);
152 { unsigned long long const rSize = ZSTD_findDecompressedSize(compressedBuffer, cSize);
153 if (rSize != CNBuffSize) goto _output_error;
155 DISPLAYLEVEL(4, "OK \n");
157 DISPLAYLEVEL(4, "test%3i : decompress %u bytes : ", testNb++, (U32)CNBuffSize);
158 { size_t const r = ZSTD_decompress(decodedBuffer, CNBuffSize, compressedBuffer, cSize);
159 if (r != CNBuffSize) goto _output_error; }
160 DISPLAYLEVEL(4, "OK \n");
162 DISPLAYLEVEL(4, "test%3i : check decompressed result : ", testNb++);
164 for (u=0; u<CNBuffSize; u++) {
165 if (((BYTE*)decodedBuffer)[u] != ((BYTE*)CNBuffer)[u]) goto _output_error;;
167 DISPLAYLEVEL(4, "OK \n");
170 DISPLAYLEVEL(4, "test%3i : decompress with null dict : ", testNb++);
171 { size_t const r = ZSTD_decompress_usingDict(dctx, decodedBuffer, CNBuffSize, compressedBuffer, cSize, NULL, 0);
172 if (r != CNBuffSize) goto _output_error; }
173 DISPLAYLEVEL(4, "OK \n");
175 DISPLAYLEVEL(4, "test%3i : decompress with null DDict : ", testNb++);
176 { size_t const r = ZSTD_decompress_usingDDict(dctx, decodedBuffer, CNBuffSize, compressedBuffer, cSize, NULL);
177 if (r != CNBuffSize) goto _output_error; }
178 DISPLAYLEVEL(4, "OK \n");
180 DISPLAYLEVEL(4, "test%3i : decompress with 1 missing byte : ", testNb++);
181 { size_t const r = ZSTD_decompress(decodedBuffer, CNBuffSize, compressedBuffer, cSize-1);
182 if (!ZSTD_isError(r)) goto _output_error;
183 if (ZSTD_getErrorCode((size_t)r) != ZSTD_error_srcSize_wrong) goto _output_error; }
184 DISPLAYLEVEL(4, "OK \n");
186 DISPLAYLEVEL(4, "test%3i : decompress with 1 too much byte : ", testNb++);
187 { size_t const r = ZSTD_decompress(decodedBuffer, CNBuffSize, compressedBuffer, cSize+1);
188 if (!ZSTD_isError(r)) goto _output_error;
189 if (ZSTD_getErrorCode(r) != ZSTD_error_srcSize_wrong) goto _output_error; }
190 DISPLAYLEVEL(4, "OK \n");
193 /* Static CCtx tests */
194 #define STATIC_CCTX_LEVEL 3
195 DISPLAYLEVEL(4, "test%3i : create static CCtx for level %u :", testNb++, STATIC_CCTX_LEVEL);
196 { size_t const staticCCtxSize = ZSTD_estimateCStreamSize(STATIC_CCTX_LEVEL);
197 void* const staticCCtxBuffer = malloc(staticCCtxSize);
198 size_t const staticDCtxSize = ZSTD_estimateDCtxSize();
199 void* const staticDCtxBuffer = malloc(staticDCtxSize);
200 if (staticCCtxBuffer==NULL || staticDCtxBuffer==NULL) {
201 free(staticCCtxBuffer);
202 free(staticDCtxBuffer);
203 DISPLAY("Not enough memory, aborting\n");
207 { ZSTD_CCtx* staticCCtx = ZSTD_initStaticCCtx(staticCCtxBuffer, staticCCtxSize);
208 ZSTD_DCtx* staticDCtx = ZSTD_initStaticDCtx(staticDCtxBuffer, staticDCtxSize);
209 if ((staticCCtx==NULL) || (staticDCtx==NULL)) goto _output_error;
210 DISPLAYLEVEL(4, "OK \n");
212 DISPLAYLEVEL(4, "test%3i : init CCtx for level %u : ", testNb++, STATIC_CCTX_LEVEL);
213 { size_t const r = ZSTD_compressBegin(staticCCtx, STATIC_CCTX_LEVEL);
214 if (ZSTD_isError(r)) goto _output_error; }
215 DISPLAYLEVEL(4, "OK \n");
217 DISPLAYLEVEL(4, "test%3i : simple compression test with static CCtx : ", testNb++);
218 CHECKPLUS(r, ZSTD_compressCCtx(staticCCtx,
219 compressedBuffer, ZSTD_compressBound(CNBuffSize),
220 CNBuffer, CNBuffSize, STATIC_CCTX_LEVEL),
222 DISPLAYLEVEL(4, "OK (%u bytes : %.2f%%)\n",
223 (U32)cSize, (double)cSize/CNBuffSize*100);
225 DISPLAYLEVEL(4, "test%3i : simple decompression test with static DCtx : ", testNb++);
226 { size_t const r = ZSTD_decompressDCtx(staticDCtx,
227 decodedBuffer, CNBuffSize,
228 compressedBuffer, cSize);
229 if (r != CNBuffSize) goto _output_error; }
230 DISPLAYLEVEL(4, "OK \n");
232 DISPLAYLEVEL(4, "test%3i : check decompressed result : ", testNb++);
234 for (u=0; u<CNBuffSize; u++) {
235 if (((BYTE*)decodedBuffer)[u] != ((BYTE*)CNBuffer)[u])
238 DISPLAYLEVEL(4, "OK \n");
240 DISPLAYLEVEL(4, "test%3i : init CCtx for too large level (must fail) : ", testNb++);
241 { size_t const r = ZSTD_compressBegin(staticCCtx, ZSTD_maxCLevel());
242 if (!ZSTD_isError(r)) goto _output_error; }
243 DISPLAYLEVEL(4, "OK \n");
245 DISPLAYLEVEL(4, "test%3i : init CCtx for small level %u (should work again) : ", testNb++, 1);
246 { size_t const r = ZSTD_compressBegin(staticCCtx, 1);
247 if (ZSTD_isError(r)) goto _output_error; }
248 DISPLAYLEVEL(4, "OK \n");
250 DISPLAYLEVEL(4, "test%3i : init CStream for small level %u : ", testNb++, 1);
251 { size_t const r = ZSTD_initCStream(staticCCtx, 1);
252 if (ZSTD_isError(r)) goto _output_error; }
253 DISPLAYLEVEL(4, "OK \n");
255 DISPLAYLEVEL(4, "test%3i : init CStream with dictionary (should fail) : ", testNb++);
256 { size_t const r = ZSTD_initCStream_usingDict(staticCCtx, CNBuffer, 64 KB, 1);
257 if (!ZSTD_isError(r)) goto _output_error; }
258 DISPLAYLEVEL(4, "OK \n");
260 DISPLAYLEVEL(4, "test%3i : init DStream (should fail) : ", testNb++);
261 { size_t const r = ZSTD_initDStream(staticDCtx);
262 if (ZSTD_isError(r)) goto _output_error; }
263 { ZSTD_outBuffer output = { decodedBuffer, CNBuffSize, 0 };
264 ZSTD_inBuffer input = { compressedBuffer, ZSTD_FRAMEHEADERSIZE_MAX+1, 0 };
265 size_t const r = ZSTD_decompressStream(staticDCtx, &output, &input);
266 if (!ZSTD_isError(r)) goto _output_error;
268 DISPLAYLEVEL(4, "OK \n");
270 free(staticCCtxBuffer);
271 free(staticDCtxBuffer);
276 /* ZSTDMT simple MT compression test */
277 DISPLAYLEVEL(4, "test%3i : create ZSTDMT CCtx : ", testNb++);
278 { ZSTDMT_CCtx* mtctx = ZSTDMT_createCCtx(2);
280 DISPLAY("mtctx : mot enough memory, aborting \n");
284 DISPLAYLEVEL(4, "OK \n");
286 DISPLAYLEVEL(4, "test%3i : compress %u bytes with 2 threads : ", testNb++, (U32)CNBuffSize);
287 CHECKPLUS(r, ZSTDMT_compressCCtx(mtctx,
288 compressedBuffer, ZSTD_compressBound(CNBuffSize),
289 CNBuffer, CNBuffSize,
292 DISPLAYLEVEL(4, "OK (%u bytes : %.2f%%)\n", (U32)cSize, (double)cSize/CNBuffSize*100);
294 DISPLAYLEVEL(4, "test%3i : decompressed size test : ", testNb++);
295 { unsigned long long const rSize = ZSTD_getFrameContentSize(compressedBuffer, cSize);
296 if (rSize != CNBuffSize) {
297 DISPLAY("ZSTD_getFrameContentSize incorrect : %u != %u \n", (U32)rSize, (U32)CNBuffSize);
300 DISPLAYLEVEL(4, "OK \n");
302 DISPLAYLEVEL(4, "test%3i : decompress %u bytes : ", testNb++, (U32)CNBuffSize);
303 { size_t const r = ZSTD_decompress(decodedBuffer, CNBuffSize, compressedBuffer, cSize);
304 if (r != CNBuffSize) goto _output_error; }
305 DISPLAYLEVEL(4, "OK \n");
307 DISPLAYLEVEL(4, "test%3i : check decompressed result : ", testNb++);
309 for (u=0; u<CNBuffSize; u++) {
310 if (((BYTE*)decodedBuffer)[u] != ((BYTE*)CNBuffer)[u]) goto _output_error;;
312 DISPLAYLEVEL(4, "OK \n");
314 ZSTDMT_freeCCtx(mtctx);
318 /* Simple API multiframe test */
319 DISPLAYLEVEL(4, "test%3i : compress multiple frames : ", testNb++);
323 /* only use the first half so we don't push against size limit of compressedBuffer */
324 size_t const segSize = (CNBuffSize / 2) / segs;
325 for (i = 0; i < segs; i++) {
328 (BYTE *)compressedBuffer + off, CNBuffSize - off,
329 (BYTE *)CNBuffer + segSize * i,
333 /* insert skippable frame */
334 const U32 skipLen = 128 KB;
335 MEM_writeLE32((BYTE*)compressedBuffer + off, ZSTD_MAGIC_SKIPPABLE_START);
336 MEM_writeLE32((BYTE*)compressedBuffer + off + 4, skipLen);
337 off += skipLen + ZSTD_skippableHeaderSize;
342 DISPLAYLEVEL(4, "OK \n");
344 DISPLAYLEVEL(4, "test%3i : get decompressed size of multiple frames : ", testNb++);
345 { unsigned long long const r = ZSTD_findDecompressedSize(compressedBuffer, cSize);
346 if (r != CNBuffSize / 2) goto _output_error; }
347 DISPLAYLEVEL(4, "OK \n");
349 DISPLAYLEVEL(4, "test%3i : decompress multiple frames : ", testNb++);
350 { CHECK_V(r, ZSTD_decompress(decodedBuffer, CNBuffSize, compressedBuffer, cSize));
351 if (r != CNBuffSize / 2) goto _output_error; }
352 DISPLAYLEVEL(4, "OK \n");
354 DISPLAYLEVEL(4, "test%3i : check decompressed result : ", testNb++);
355 if (memcmp(decodedBuffer, CNBuffer, CNBuffSize / 2) != 0) goto _output_error;
356 DISPLAYLEVEL(4, "OK \n");
358 /* Dictionary and CCtx Duplication tests */
359 { ZSTD_CCtx* const ctxOrig = ZSTD_createCCtx();
360 ZSTD_CCtx* const ctxDuplicated = ZSTD_createCCtx();
361 static const size_t dictSize = 551;
363 DISPLAYLEVEL(4, "test%3i : copy context too soon : ", testNb++);
364 { size_t const copyResult = ZSTD_copyCCtx(ctxDuplicated, ctxOrig, 0);
365 if (!ZSTD_isError(copyResult)) goto _output_error; } /* error must be detected */
366 DISPLAYLEVEL(4, "OK \n");
368 DISPLAYLEVEL(4, "test%3i : load dictionary into context : ", testNb++);
369 CHECK( ZSTD_compressBegin_usingDict(ctxOrig, CNBuffer, dictSize, 2) );
370 CHECK( ZSTD_copyCCtx(ctxDuplicated, ctxOrig, 0) ); /* Begin_usingDict implies unknown srcSize, so match that */
371 DISPLAYLEVEL(4, "OK \n");
373 DISPLAYLEVEL(4, "test%3i : compress with flat dictionary : ", testNb++);
375 CHECKPLUS(r, ZSTD_compressEnd(ctxOrig, compressedBuffer, ZSTD_compressBound(CNBuffSize),
376 (const char*)CNBuffer + dictSize, CNBuffSize - dictSize),
378 DISPLAYLEVEL(4, "OK (%u bytes : %.2f%%)\n", (U32)cSize, (double)cSize/CNBuffSize*100);
380 DISPLAYLEVEL(4, "test%3i : frame built with flat dictionary should be decompressible : ", testNb++);
381 CHECKPLUS(r, ZSTD_decompress_usingDict(dctx,
382 decodedBuffer, CNBuffSize,
383 compressedBuffer, cSize,
385 if (r != CNBuffSize - dictSize) goto _output_error);
386 DISPLAYLEVEL(4, "OK \n");
388 DISPLAYLEVEL(4, "test%3i : compress with duplicated context : ", testNb++);
389 { size_t const cSizeOrig = cSize;
391 CHECKPLUS(r, ZSTD_compressEnd(ctxDuplicated, compressedBuffer, ZSTD_compressBound(CNBuffSize),
392 (const char*)CNBuffer + dictSize, CNBuffSize - dictSize),
394 if (cSize != cSizeOrig) goto _output_error; /* should be identical ==> same size */
396 DISPLAYLEVEL(4, "OK (%u bytes : %.2f%%)\n", (U32)cSize, (double)cSize/CNBuffSize*100);
398 DISPLAYLEVEL(4, "test%3i : frame built with duplicated context should be decompressible : ", testNb++);
399 CHECKPLUS(r, ZSTD_decompress_usingDict(dctx,
400 decodedBuffer, CNBuffSize,
401 compressedBuffer, cSize,
403 if (r != CNBuffSize - dictSize) goto _output_error);
404 DISPLAYLEVEL(4, "OK \n");
406 DISPLAYLEVEL(4, "test%3i : decompress with DDict : ", testNb++);
407 { ZSTD_DDict* const ddict = ZSTD_createDDict(CNBuffer, dictSize);
408 size_t const r = ZSTD_decompress_usingDDict(dctx, decodedBuffer, CNBuffSize, compressedBuffer, cSize, ddict);
409 if (r != CNBuffSize - dictSize) goto _output_error;
410 DISPLAYLEVEL(4, "OK (size of DDict : %u) \n", (U32)ZSTD_sizeof_DDict(ddict));
411 ZSTD_freeDDict(ddict);
414 DISPLAYLEVEL(4, "test%3i : decompress with static DDict : ", testNb++);
415 { size_t const ddictBufferSize = ZSTD_estimateDDictSize(dictSize, 0);
416 void* ddictBuffer = malloc(ddictBufferSize);
417 if (ddictBuffer == NULL) goto _output_error;
418 { ZSTD_DDict* const ddict = ZSTD_initStaticDDict(ddictBuffer, ddictBufferSize, CNBuffer, dictSize, 0);
419 size_t const r = ZSTD_decompress_usingDDict(dctx, decodedBuffer, CNBuffSize, compressedBuffer, cSize, ddict);
420 if (r != CNBuffSize - dictSize) goto _output_error;
423 DISPLAYLEVEL(4, "OK (size of static DDict : %u) \n", (U32)ddictBufferSize);
426 DISPLAYLEVEL(4, "test%3i : check content size on duplicated context : ", testNb++);
427 { size_t const testSize = CNBuffSize / 3;
428 { ZSTD_parameters p = ZSTD_getParams(2, testSize, dictSize);
429 p.fParams.contentSizeFlag = 1;
430 CHECK( ZSTD_compressBegin_advanced(ctxOrig, CNBuffer, dictSize, p, testSize-1) );
432 CHECK( ZSTD_copyCCtx(ctxDuplicated, ctxOrig, testSize) );
434 CHECKPLUS(r, ZSTD_compressEnd(ctxDuplicated, compressedBuffer, ZSTD_compressBound(testSize),
435 (const char*)CNBuffer + dictSize, testSize),
437 { ZSTD_frameHeader fp;
438 if (ZSTD_getFrameHeader(&fp, compressedBuffer, cSize)) goto _output_error;
439 if ((fp.frameContentSize != testSize) && (fp.frameContentSize != 0)) goto _output_error;
441 DISPLAYLEVEL(4, "OK \n");
443 ZSTD_freeCCtx(ctxOrig);
444 ZSTD_freeCCtx(ctxDuplicated);
447 /* Dictionary and dictBuilder tests */
448 { ZSTD_CCtx* const cctx = ZSTD_createCCtx();
449 size_t dictSize = 16 KB;
450 void* dictBuffer = malloc(dictSize);
451 size_t const totalSampleSize = 1 MB;
452 size_t const sampleUnitSize = 8 KB;
453 U32 const nbSamples = (U32)(totalSampleSize / sampleUnitSize);
454 size_t* const samplesSizes = (size_t*) malloc(nbSamples * sizeof(size_t));
457 if (dictBuffer==NULL || samplesSizes==NULL) {
463 DISPLAYLEVEL(4, "test%3i : dictBuilder : ", testNb++);
464 { U32 u; for (u=0; u<nbSamples; u++) samplesSizes[u] = sampleUnitSize; }
465 dictSize = ZDICT_trainFromBuffer(dictBuffer, dictSize,
466 CNBuffer, samplesSizes, nbSamples);
467 if (ZDICT_isError(dictSize)) goto _output_error;
468 DISPLAYLEVEL(4, "OK, created dictionary of size %u \n", (U32)dictSize);
470 DISPLAYLEVEL(4, "test%3i : check dictID : ", testNb++);
471 dictID = ZDICT_getDictID(dictBuffer, dictSize);
472 if (dictID==0) goto _output_error;
473 DISPLAYLEVEL(4, "OK : %u \n", dictID);
475 DISPLAYLEVEL(4, "test%3i : compress with dictionary : ", testNb++);
476 cSize = ZSTD_compress_usingDict(cctx, compressedBuffer, ZSTD_compressBound(CNBuffSize),
477 CNBuffer, CNBuffSize,
478 dictBuffer, dictSize, 4);
479 if (ZSTD_isError(cSize)) goto _output_error;
480 DISPLAYLEVEL(4, "OK (%u bytes : %.2f%%)\n", (U32)cSize, (double)cSize/CNBuffSize*100);
482 DISPLAYLEVEL(4, "test%3i : retrieve dictID from dictionary : ", testNb++);
483 { U32 const did = ZSTD_getDictID_fromDict(dictBuffer, dictSize);
484 if (did != dictID) goto _output_error; /* non-conformant (content-only) dictionary */
486 DISPLAYLEVEL(4, "OK \n");
488 DISPLAYLEVEL(4, "test%3i : retrieve dictID from frame : ", testNb++);
489 { U32 const did = ZSTD_getDictID_fromFrame(compressedBuffer, cSize);
490 if (did != dictID) goto _output_error; /* non-conformant (content-only) dictionary */
492 DISPLAYLEVEL(4, "OK \n");
494 DISPLAYLEVEL(4, "test%3i : frame built with dictionary should be decompressible : ", testNb++);
495 CHECKPLUS(r, ZSTD_decompress_usingDict(dctx,
496 decodedBuffer, CNBuffSize,
497 compressedBuffer, cSize,
498 dictBuffer, dictSize),
499 if (r != CNBuffSize) goto _output_error);
500 DISPLAYLEVEL(4, "OK \n");
502 DISPLAYLEVEL(4, "test%3i : estimate CDict size : ", testNb++);
503 { ZSTD_compressionParameters const cParams = ZSTD_getCParams(1, CNBuffSize, dictSize);
504 size_t const estimatedSize = ZSTD_estimateCDictSize_advanced(dictSize, cParams, 1 /*byReference*/);
505 DISPLAYLEVEL(4, "OK : %u \n", (U32)estimatedSize);
508 DISPLAYLEVEL(4, "test%3i : compress with CDict ", testNb++);
509 { ZSTD_compressionParameters const cParams = ZSTD_getCParams(1, CNBuffSize, dictSize);
510 ZSTD_CDict* const cdict = ZSTD_createCDict_advanced(dictBuffer, dictSize,
511 1 /* byReference */, ZSTD_dm_auto,
512 cParams, ZSTD_defaultCMem);
513 DISPLAYLEVEL(4, "(size : %u) : ", (U32)ZSTD_sizeof_CDict(cdict));
514 cSize = ZSTD_compress_usingCDict(cctx, compressedBuffer, ZSTD_compressBound(CNBuffSize),
515 CNBuffer, CNBuffSize, cdict);
516 ZSTD_freeCDict(cdict);
517 if (ZSTD_isError(cSize)) goto _output_error;
519 DISPLAYLEVEL(4, "OK (%u bytes : %.2f%%)\n", (U32)cSize, (double)cSize/CNBuffSize*100);
521 DISPLAYLEVEL(4, "test%3i : retrieve dictID from frame : ", testNb++);
522 { U32 const did = ZSTD_getDictID_fromFrame(compressedBuffer, cSize);
523 if (did != dictID) goto _output_error; /* non-conformant (content-only) dictionary */
525 DISPLAYLEVEL(4, "OK \n");
527 DISPLAYLEVEL(4, "test%3i : frame built with dictionary should be decompressible : ", testNb++);
528 CHECKPLUS(r, ZSTD_decompress_usingDict(dctx,
529 decodedBuffer, CNBuffSize,
530 compressedBuffer, cSize,
531 dictBuffer, dictSize),
532 if (r != CNBuffSize) goto _output_error);
533 DISPLAYLEVEL(4, "OK \n");
535 DISPLAYLEVEL(4, "test%3i : compress with static CDict : ", testNb++);
536 { ZSTD_compressionParameters const cParams = ZSTD_getCParams(1, CNBuffSize, dictSize);
537 size_t const cdictSize = ZSTD_estimateCDictSize_advanced(dictSize, cParams, 0);
538 void* const cdictBuffer = malloc(cdictSize);
539 if (cdictBuffer==NULL) goto _output_error;
540 { ZSTD_CDict* const cdict = ZSTD_initStaticCDict(cdictBuffer, cdictSize,
541 dictBuffer, dictSize,
542 0 /* by Reference */, ZSTD_dm_auto,
545 DISPLAY("ZSTD_initStaticCDict failed ");
548 cSize = ZSTD_compress_usingCDict(cctx,
549 compressedBuffer, ZSTD_compressBound(CNBuffSize),
550 CNBuffer, CNBuffSize, cdict);
551 if (ZSTD_isError(cSize)) {
552 DISPLAY("ZSTD_compress_usingCDict failed ");
557 DISPLAYLEVEL(4, "OK (%u bytes : %.2f%%)\n", (U32)cSize, (double)cSize/CNBuffSize*100);
559 DISPLAYLEVEL(4, "test%3i : ZSTD_compress_usingCDict_advanced, no contentSize, no dictID : ", testNb++);
560 { ZSTD_frameParameters const fParams = { 0 /* frameSize */, 1 /* checksum */, 1 /* noDictID*/ };
561 ZSTD_compressionParameters const cParams = ZSTD_getCParams(1, CNBuffSize, dictSize);
562 ZSTD_CDict* const cdict = ZSTD_createCDict_advanced(dictBuffer, dictSize, 1 /*byRef*/, ZSTD_dm_auto, cParams, ZSTD_defaultCMem);
563 cSize = ZSTD_compress_usingCDict_advanced(cctx, compressedBuffer, ZSTD_compressBound(CNBuffSize),
564 CNBuffer, CNBuffSize, cdict, fParams);
565 ZSTD_freeCDict(cdict);
566 if (ZSTD_isError(cSize)) goto _output_error;
568 DISPLAYLEVEL(4, "OK (%u bytes : %.2f%%)\n", (U32)cSize, (double)cSize/CNBuffSize*100);
570 DISPLAYLEVEL(4, "test%3i : try retrieving contentSize from frame : ", testNb++);
571 { U64 const contentSize = ZSTD_getFrameContentSize(compressedBuffer, cSize);
572 if (contentSize != ZSTD_CONTENTSIZE_UNKNOWN) goto _output_error;
574 DISPLAYLEVEL(4, "OK (unknown)\n");
576 DISPLAYLEVEL(4, "test%3i : frame built without dictID should be decompressible : ", testNb++);
577 CHECKPLUS(r, ZSTD_decompress_usingDict(dctx,
578 decodedBuffer, CNBuffSize,
579 compressedBuffer, cSize,
580 dictBuffer, dictSize),
581 if (r != CNBuffSize) goto _output_error);
582 DISPLAYLEVEL(4, "OK \n");
584 DISPLAYLEVEL(4, "test%3i : ZSTD_compress_advanced, no dictID : ", testNb++);
585 { ZSTD_parameters p = ZSTD_getParams(3, CNBuffSize, dictSize);
586 p.fParams.noDictIDFlag = 1;
587 cSize = ZSTD_compress_advanced(cctx, compressedBuffer, ZSTD_compressBound(CNBuffSize),
588 CNBuffer, CNBuffSize,
589 dictBuffer, dictSize, p);
590 if (ZSTD_isError(cSize)) goto _output_error;
592 DISPLAYLEVEL(4, "OK (%u bytes : %.2f%%)\n", (U32)cSize, (double)cSize/CNBuffSize*100);
594 DISPLAYLEVEL(4, "test%3i : frame built without dictID should be decompressible : ", testNb++);
595 CHECKPLUS(r, ZSTD_decompress_usingDict(dctx,
596 decodedBuffer, CNBuffSize,
597 compressedBuffer, cSize,
598 dictBuffer, dictSize),
599 if (r != CNBuffSize) goto _output_error);
600 DISPLAYLEVEL(4, "OK \n");
602 DISPLAYLEVEL(4, "test%3i : dictionary containing only header should return error : ", testNb++);
604 const size_t ret = ZSTD_decompress_usingDict(
605 dctx, decodedBuffer, CNBuffSize, compressedBuffer, cSize,
606 "\x37\xa4\x30\xec\x11\x22\x33\x44", 8);
607 if (ZSTD_getErrorCode(ret) != ZSTD_error_dictionary_corrupted) goto _output_error;
609 DISPLAYLEVEL(4, "OK \n");
611 DISPLAYLEVEL(4, "test%3i : Building cdict w/ ZSTD_dm_fullDict on a good dictionary : ", testNb++);
612 { ZSTD_compressionParameters const cParams = ZSTD_getCParams(1, CNBuffSize, dictSize);
613 ZSTD_CDict* const cdict = ZSTD_createCDict_advanced(dictBuffer, dictSize, 1 /*byRef*/, ZSTD_dm_fullDict, cParams, ZSTD_defaultCMem);
614 if (cdict==NULL) goto _output_error;
615 ZSTD_freeCDict(cdict);
617 DISPLAYLEVEL(4, "OK \n");
619 DISPLAYLEVEL(4, "test%3i : Building cdict w/ ZSTD_dm_fullDict on a rawContent (must fail) : ", testNb++);
620 { ZSTD_compressionParameters const cParams = ZSTD_getCParams(1, CNBuffSize, dictSize);
621 ZSTD_CDict* const cdict = ZSTD_createCDict_advanced((const char*)dictBuffer+1, dictSize-1, 1 /*byRef*/, ZSTD_dm_fullDict, cParams, ZSTD_defaultCMem);
622 if (cdict!=NULL) goto _output_error;
623 ZSTD_freeCDict(cdict);
625 DISPLAYLEVEL(4, "OK \n");
632 /* COVER dictionary builder tests */
633 { ZSTD_CCtx* const cctx = ZSTD_createCCtx();
634 size_t dictSize = 16 KB;
635 size_t optDictSize = dictSize;
636 void* dictBuffer = malloc(dictSize);
637 size_t const totalSampleSize = 1 MB;
638 size_t const sampleUnitSize = 8 KB;
639 U32 const nbSamples = (U32)(totalSampleSize / sampleUnitSize);
640 size_t* const samplesSizes = (size_t*) malloc(nbSamples * sizeof(size_t));
641 ZDICT_cover_params_t params;
644 if (dictBuffer==NULL || samplesSizes==NULL) {
650 DISPLAYLEVEL(4, "test%3i : ZDICT_trainFromBuffer_cover : ", testNb++);
651 { U32 u; for (u=0; u<nbSamples; u++) samplesSizes[u] = sampleUnitSize; }
652 memset(¶ms, 0, sizeof(params));
653 params.d = 1 + (FUZ_rand(&seed) % 16);
654 params.k = params.d + (FUZ_rand(&seed) % 256);
655 dictSize = ZDICT_trainFromBuffer_cover(dictBuffer, dictSize,
656 CNBuffer, samplesSizes, nbSamples,
658 if (ZDICT_isError(dictSize)) goto _output_error;
659 DISPLAYLEVEL(4, "OK, created dictionary of size %u \n", (U32)dictSize);
661 DISPLAYLEVEL(4, "test%3i : check dictID : ", testNb++);
662 dictID = ZDICT_getDictID(dictBuffer, dictSize);
663 if (dictID==0) goto _output_error;
664 DISPLAYLEVEL(4, "OK : %u \n", dictID);
666 DISPLAYLEVEL(4, "test%3i : ZDICT_optimizeTrainFromBuffer_cover : ", testNb++);
667 memset(¶ms, 0, sizeof(params));
669 optDictSize = ZDICT_optimizeTrainFromBuffer_cover(dictBuffer, optDictSize,
670 CNBuffer, samplesSizes,
671 nbSamples / 4, ¶ms);
672 if (ZDICT_isError(optDictSize)) goto _output_error;
673 DISPLAYLEVEL(4, "OK, created dictionary of size %u \n", (U32)optDictSize);
675 DISPLAYLEVEL(4, "test%3i : check dictID : ", testNb++);
676 dictID = ZDICT_getDictID(dictBuffer, optDictSize);
677 if (dictID==0) goto _output_error;
678 DISPLAYLEVEL(4, "OK : %u \n", dictID);
685 /* Decompression defense tests */
686 DISPLAYLEVEL(4, "test%3i : Check input length for magic number : ", testNb++);
687 { size_t const r = ZSTD_decompress(decodedBuffer, CNBuffSize, CNBuffer, 3); /* too small input */
688 if (!ZSTD_isError(r)) goto _output_error;
689 if (ZSTD_getErrorCode(r) != ZSTD_error_srcSize_wrong) goto _output_error; }
690 DISPLAYLEVEL(4, "OK \n");
692 DISPLAYLEVEL(4, "test%3i : Check magic Number : ", testNb++);
693 ((char*)(CNBuffer))[0] = 1;
694 { size_t const r = ZSTD_decompress(decodedBuffer, CNBuffSize, CNBuffer, 4);
695 if (!ZSTD_isError(r)) goto _output_error; }
696 DISPLAYLEVEL(4, "OK \n");
698 /* content size verification test */
699 DISPLAYLEVEL(4, "test%3i : Content size verification : ", testNb++);
700 { ZSTD_CCtx* const cctx = ZSTD_createCCtx();
701 size_t const srcSize = 5000;
702 size_t const wrongSrcSize = (srcSize + 1000);
703 ZSTD_parameters params = ZSTD_getParams(1, wrongSrcSize, 0);
704 params.fParams.contentSizeFlag = 1;
705 CHECK( ZSTD_compressBegin_advanced(cctx, NULL, 0, params, wrongSrcSize) );
706 { size_t const result = ZSTD_compressEnd(cctx, decodedBuffer, CNBuffSize, CNBuffer, srcSize);
707 if (!ZSTD_isError(result)) goto _output_error;
708 if (ZSTD_getErrorCode(result) != ZSTD_error_srcSize_wrong) goto _output_error;
709 DISPLAYLEVEL(4, "OK : %s \n", ZSTD_getErrorName(result));
714 /* block API tests */
715 { ZSTD_CCtx* const cctx = ZSTD_createCCtx();
716 static const size_t dictSize = 65 KB;
717 static const size_t blockSize = 100 KB; /* won't cause pb with small dict size */
720 /* basic block compression */
721 DISPLAYLEVEL(4, "test%3i : Block compression test : ", testNb++);
722 CHECK( ZSTD_compressBegin(cctx, 5) );
723 CHECK( ZSTD_getBlockSize(cctx) >= blockSize);
724 cSize = ZSTD_compressBlock(cctx, compressedBuffer, ZSTD_compressBound(blockSize), CNBuffer, blockSize);
725 if (ZSTD_isError(cSize)) goto _output_error;
726 DISPLAYLEVEL(4, "OK \n");
728 DISPLAYLEVEL(4, "test%3i : Block decompression test : ", testNb++);
729 CHECK( ZSTD_decompressBegin(dctx) );
730 { CHECK_V(r, ZSTD_decompressBlock(dctx, decodedBuffer, CNBuffSize, compressedBuffer, cSize) );
731 if (r != blockSize) goto _output_error; }
732 DISPLAYLEVEL(4, "OK \n");
734 /* dictionary block compression */
735 DISPLAYLEVEL(4, "test%3i : Dictionary Block compression test : ", testNb++);
736 CHECK( ZSTD_compressBegin_usingDict(cctx, CNBuffer, dictSize, 5) );
737 cSize = ZSTD_compressBlock(cctx, compressedBuffer, ZSTD_compressBound(blockSize), (char*)CNBuffer+dictSize, blockSize);
738 if (ZSTD_isError(cSize)) goto _output_error;
739 cSize2 = ZSTD_compressBlock(cctx, (char*)compressedBuffer+cSize, ZSTD_compressBound(blockSize), (char*)CNBuffer+dictSize+blockSize, blockSize);
740 if (ZSTD_isError(cSize2)) goto _output_error;
741 memcpy((char*)compressedBuffer+cSize, (char*)CNBuffer+dictSize+blockSize, blockSize); /* fake non-compressed block */
742 cSize2 = ZSTD_compressBlock(cctx, (char*)compressedBuffer+cSize+blockSize, ZSTD_compressBound(blockSize),
743 (char*)CNBuffer+dictSize+2*blockSize, blockSize);
744 if (ZSTD_isError(cSize2)) goto _output_error;
745 DISPLAYLEVEL(4, "OK \n");
747 DISPLAYLEVEL(4, "test%3i : Dictionary Block decompression test : ", testNb++);
748 CHECK( ZSTD_decompressBegin_usingDict(dctx, CNBuffer, dictSize) );
749 { CHECK_V( r, ZSTD_decompressBlock(dctx, decodedBuffer, CNBuffSize, compressedBuffer, cSize) );
750 if (r != blockSize) goto _output_error; }
751 ZSTD_insertBlock(dctx, (char*)decodedBuffer+blockSize, blockSize); /* insert non-compressed block into dctx history */
752 { CHECK_V( r, ZSTD_decompressBlock(dctx, (char*)decodedBuffer+2*blockSize, CNBuffSize, (char*)compressedBuffer+cSize+blockSize, cSize2) );
753 if (r != blockSize) goto _output_error; }
754 DISPLAYLEVEL(4, "OK \n");
761 { size_t sampleSize = 0;
762 DISPLAYLEVEL(4, "test%3i : Long RLE test : ", testNb++);
763 RDG_genBuffer(CNBuffer, sampleSize, compressibility, 0., seed+1);
764 memset((char*)CNBuffer+sampleSize, 'B', 256 KB - 1);
765 sampleSize += 256 KB - 1;
766 RDG_genBuffer((char*)CNBuffer+sampleSize, 96 KB, compressibility, 0., seed+2);
768 cSize = ZSTD_compress(compressedBuffer, ZSTD_compressBound(sampleSize), CNBuffer, sampleSize, 1);
769 if (ZSTD_isError(cSize)) goto _output_error;
770 { CHECK_V(regenSize, ZSTD_decompress(decodedBuffer, sampleSize, compressedBuffer, cSize));
771 if (regenSize!=sampleSize) goto _output_error; }
772 DISPLAYLEVEL(4, "OK \n");
775 /* All zeroes test (test bug #137) */
776 #define ZEROESLENGTH 100
777 DISPLAYLEVEL(4, "test%3i : compress %u zeroes : ", testNb++, ZEROESLENGTH);
778 memset(CNBuffer, 0, ZEROESLENGTH);
779 { CHECK_V(r, ZSTD_compress(compressedBuffer, ZSTD_compressBound(ZEROESLENGTH), CNBuffer, ZEROESLENGTH, 1) );
781 DISPLAYLEVEL(4, "OK (%u bytes : %.2f%%)\n", (U32)cSize, (double)cSize/ZEROESLENGTH*100);
783 DISPLAYLEVEL(4, "test%3i : decompress %u zeroes : ", testNb++, ZEROESLENGTH);
784 { CHECK_V(r, ZSTD_decompress(decodedBuffer, ZEROESLENGTH, compressedBuffer, cSize) );
785 if (r != ZEROESLENGTH) goto _output_error; }
786 DISPLAYLEVEL(4, "OK \n");
788 /* nbSeq limit test */
789 #define _3BYTESTESTLENGTH 131000
790 #define NB3BYTESSEQLOG 9
791 #define NB3BYTESSEQ (1 << NB3BYTESSEQLOG)
792 #define NB3BYTESSEQMASK (NB3BYTESSEQ-1)
793 /* creates a buffer full of 3-bytes sequences */
794 { BYTE _3BytesSeqs[NB3BYTESSEQ][3];
797 /* create batch of 3-bytes sequences */
799 for (i=0; i < NB3BYTESSEQ; i++) {
800 _3BytesSeqs[i][0] = (BYTE)(FUZ_rand(&rSeed) & 255);
801 _3BytesSeqs[i][1] = (BYTE)(FUZ_rand(&rSeed) & 255);
802 _3BytesSeqs[i][2] = (BYTE)(FUZ_rand(&rSeed) & 255);
805 /* randomly fills CNBuffer with prepared 3-bytes sequences */
807 for (i=0; i < _3BYTESTESTLENGTH; i += 3) { /* note : CNBuffer size > _3BYTESTESTLENGTH+3 */
808 U32 const id = FUZ_rand(&rSeed) & NB3BYTESSEQMASK;
809 ((BYTE*)CNBuffer)[i+0] = _3BytesSeqs[id][0];
810 ((BYTE*)CNBuffer)[i+1] = _3BytesSeqs[id][1];
811 ((BYTE*)CNBuffer)[i+2] = _3BytesSeqs[id][2];
813 DISPLAYLEVEL(4, "test%3i : compress lots 3-bytes sequences : ", testNb++);
814 { CHECK_V(r, ZSTD_compress(compressedBuffer, ZSTD_compressBound(_3BYTESTESTLENGTH),
815 CNBuffer, _3BYTESTESTLENGTH, 19) );
817 DISPLAYLEVEL(4, "OK (%u bytes : %.2f%%)\n", (U32)cSize, (double)cSize/_3BYTESTESTLENGTH*100);
819 DISPLAYLEVEL(4, "test%3i : decompress lots 3-bytes sequence : ", testNb++);
820 { CHECK_V(r, ZSTD_decompress(decodedBuffer, _3BYTESTESTLENGTH, compressedBuffer, cSize) );
821 if (r != _3BYTESTESTLENGTH) goto _output_error; }
822 DISPLAYLEVEL(4, "OK \n");
824 /* findFrameCompressedSize on skippable frames */
825 DISPLAYLEVEL(4, "test%3i : frame compressed size of skippable frame : ", testNb++);
826 { const char* frame = "\x50\x2a\x4d\x18\x05\x0\x0\0abcde";
827 size_t const frameSrcSize = 13;
828 if (ZSTD_findFrameCompressedSize(frame, frameSrcSize) != frameSrcSize) goto _output_error; }
829 DISPLAYLEVEL(4, "OK \n");
831 /* error string tests */
832 DISPLAYLEVEL(4, "test%3i : testing ZSTD error code strings : ", testNb++);
833 if (strcmp("No error detected", ZSTD_getErrorName((ZSTD_ErrorCode)(0-ZSTD_error_no_error))) != 0) goto _output_error;
834 if (strcmp("No error detected", ZSTD_getErrorString(ZSTD_error_no_error)) != 0) goto _output_error;
835 if (strcmp("Unspecified error code", ZSTD_getErrorString((ZSTD_ErrorCode)(0-ZSTD_error_GENERIC))) != 0) goto _output_error;
836 if (strcmp("Error (generic)", ZSTD_getErrorName((size_t)0-ZSTD_error_GENERIC)) != 0) goto _output_error;
837 if (strcmp("Error (generic)", ZSTD_getErrorString(ZSTD_error_GENERIC)) != 0) goto _output_error;
838 if (strcmp("No error detected", ZSTD_getErrorName(ZSTD_error_GENERIC)) != 0) goto _output_error;
839 DISPLAYLEVEL(4, "OK \n");
843 free(compressedBuffer);
849 DISPLAY("Error detected in Unit tests ! \n");
854 static size_t findDiff(const void* buf1, const void* buf2, size_t max)
856 const BYTE* b1 = (const BYTE*)buf1;
857 const BYTE* b2 = (const BYTE*)buf2;
859 for (u=0; u<max; u++) {
860 if (b1[u] != b2[u]) break;
866 static ZSTD_parameters FUZ_makeParams(ZSTD_compressionParameters cParams, ZSTD_frameParameters fParams)
868 ZSTD_parameters params;
869 params.cParams = cParams;
870 params.fParams = fParams;
874 static size_t FUZ_rLogLength(U32* seed, U32 logLength)
876 size_t const lengthMask = ((size_t)1 << logLength) - 1;
877 return (lengthMask+1) + (FUZ_rand(seed) & lengthMask);
880 static size_t FUZ_randomLength(U32* seed, U32 maxLog)
882 U32 const logLength = FUZ_rand(seed) % maxLog;
883 return FUZ_rLogLength(seed, logLength);
887 #define CHECK(cond, ...) { \
889 DISPLAY("Error => "); \
890 DISPLAY(__VA_ARGS__); \
891 DISPLAY(" (seed %u, test nb %u) \n", seed, testNb); \
892 goto _output_error; \
895 #define CHECK_Z(f) { \
896 size_t const err = f; \
897 if (ZSTD_isError(err)) { \
898 DISPLAY("Error => %s : %s ", \
899 #f, ZSTD_getErrorName(err)); \
900 DISPLAY(" (seed %u, test nb %u) \n", seed, testNb); \
901 goto _output_error; \
905 static int fuzzerTests(U32 seed, U32 nbTests, unsigned startTest, U32 const maxDurationS, double compressibility, int bigTests)
907 static const U32 maxSrcLog = 23;
908 static const U32 maxSampleLog = 22;
909 size_t const srcBufferSize = (size_t)1<<maxSrcLog;
910 size_t const dstBufferSize = (size_t)1<<maxSampleLog;
911 size_t const cBufferSize = ZSTD_compressBound(dstBufferSize);
912 BYTE* cNoiseBuffer[5];
913 BYTE* srcBuffer; /* jumping pointer */
914 BYTE* const cBuffer = (BYTE*) malloc (cBufferSize);
915 BYTE* const dstBuffer = (BYTE*) malloc (dstBufferSize);
916 BYTE* const mirrorBuffer = (BYTE*) malloc (dstBufferSize);
917 ZSTD_CCtx* const refCtx = ZSTD_createCCtx();
918 ZSTD_CCtx* const ctx = ZSTD_createCCtx();
919 ZSTD_DCtx* const dctx = ZSTD_createDCtx();
922 U32 coreSeed = seed, lseed = 0;
923 clock_t const startClock = clock();
924 clock_t const maxClockSpan = maxDurationS * CLOCKS_PER_SEC;
925 int const cLevelLimiter = bigTests ? 3 : 2;
928 cNoiseBuffer[0] = (BYTE*)malloc (srcBufferSize);
929 cNoiseBuffer[1] = (BYTE*)malloc (srcBufferSize);
930 cNoiseBuffer[2] = (BYTE*)malloc (srcBufferSize);
931 cNoiseBuffer[3] = (BYTE*)malloc (srcBufferSize);
932 cNoiseBuffer[4] = (BYTE*)malloc (srcBufferSize);
933 CHECK (!cNoiseBuffer[0] || !cNoiseBuffer[1] || !cNoiseBuffer[2] || !cNoiseBuffer[3] || !cNoiseBuffer[4]
934 || !dstBuffer || !mirrorBuffer || !cBuffer || !refCtx || !ctx || !dctx,
935 "Not enough memory, fuzzer tests cancelled");
937 /* Create initial samples */
938 RDG_genBuffer(cNoiseBuffer[0], srcBufferSize, 0.00, 0., coreSeed); /* pure noise */
939 RDG_genBuffer(cNoiseBuffer[1], srcBufferSize, 0.05, 0., coreSeed); /* barely compressible */
940 RDG_genBuffer(cNoiseBuffer[2], srcBufferSize, compressibility, 0., coreSeed);
941 RDG_genBuffer(cNoiseBuffer[3], srcBufferSize, 0.95, 0., coreSeed); /* highly compressible */
942 RDG_genBuffer(cNoiseBuffer[4], srcBufferSize, 1.00, 0., coreSeed); /* sparse content */
943 srcBuffer = cNoiseBuffer[2];
945 /* catch up testNb */
946 for (testNb=1; testNb < startTest; testNb++) FUZ_rand(&coreSeed);
949 for ( ; (testNb <= nbTests) || (FUZ_clockSpan(startClock) < maxClockSpan); testNb++ ) {
950 size_t sampleSize, maxTestSize, totalTestSize;
951 size_t cSize, totalCSize, totalGenSize;
958 if (nbTests >= testNb) { DISPLAYUPDATE(2, "\r%6u/%6u ", testNb, nbTests); }
959 else { DISPLAYUPDATE(2, "\r%6u ", testNb); }
962 { U32 const prime1 = 2654435761U; lseed = coreSeed ^ prime1; }
964 /* srcBuffer selection [0-4] */
965 { U32 buffNb = FUZ_rand(&lseed) & 0x7F;
966 if (buffNb & 7) buffNb=2; /* most common : compressible (P) */
970 const U32 tnb[2] = { 1, 3 }; /* barely/highly compressible */
971 buffNb = tnb[buffNb >> 3];
973 const U32 tnb[2] = { 0, 4 }; /* not compressible / sparse */
974 buffNb = tnb[buffNb >> 3];
976 srcBuffer = cNoiseBuffer[buffNb];
979 /* select src segment */
980 sampleSize = FUZ_randomLength(&lseed, maxSampleLog);
982 /* create sample buffer (to catch read error with valgrind & sanitizers) */
983 sampleBuffer = (BYTE*)malloc(sampleSize);
984 CHECK(sampleBuffer==NULL, "not enough memory for sample buffer");
985 { size_t const sampleStart = FUZ_rand(&lseed) % (srcBufferSize - sampleSize);
986 memcpy(sampleBuffer, srcBuffer + sampleStart, sampleSize); }
987 crcOrig = XXH64(sampleBuffer, sampleSize, 0);
989 /* compression tests */
990 { unsigned const cLevel =
992 (ZSTD_maxCLevel() - (FUZ_highbit32((U32)sampleSize) / cLevelLimiter)) )
994 cSize = ZSTD_compressCCtx(ctx, cBuffer, cBufferSize, sampleBuffer, sampleSize, cLevel);
995 CHECK(ZSTD_isError(cSize), "ZSTD_compressCCtx failed : %s", ZSTD_getErrorName(cSize));
997 /* compression failure test : too small dest buffer */
999 const size_t missing = (FUZ_rand(&lseed) % (cSize-2)) + 1; /* no problem, as cSize > 4 (frameHeaderSizer) */
1000 const size_t tooSmallSize = cSize - missing;
1001 const U32 endMark = 0x4DC2B1A9;
1002 memcpy(dstBuffer+tooSmallSize, &endMark, 4);
1003 { size_t const errorCode = ZSTD_compressCCtx(ctx, dstBuffer, tooSmallSize, sampleBuffer, sampleSize, cLevel);
1004 CHECK(!ZSTD_isError(errorCode), "ZSTD_compressCCtx should have failed ! (buffer too small : %u < %u)", (U32)tooSmallSize, (U32)cSize); }
1005 { U32 endCheck; memcpy(&endCheck, dstBuffer+tooSmallSize, 4);
1006 CHECK(endCheck != endMark, "ZSTD_compressCCtx : dst buffer overflow"); }
1009 /* Decompressed size test */
1010 { unsigned long long const rSize = ZSTD_findDecompressedSize(cBuffer, cSize);
1011 CHECK(rSize != sampleSize, "decompressed size incorrect");
1014 /* frame header decompression test */
1015 { ZSTD_frameHeader dParams;
1016 CHECK_Z( ZSTD_getFrameHeader(&dParams, cBuffer, cSize) );
1017 CHECK(dParams.frameContentSize != sampleSize, "Frame content size incorrect");
1020 /* successful decompression test */
1021 { size_t const margin = (FUZ_rand(&lseed) & 1) ? 0 : (FUZ_rand(&lseed) & 31) + 1;
1022 size_t const dSize = ZSTD_decompress(dstBuffer, sampleSize + margin, cBuffer, cSize);
1023 CHECK(dSize != sampleSize, "ZSTD_decompress failed (%s) (srcSize : %u ; cSize : %u)", ZSTD_getErrorName(dSize), (U32)sampleSize, (U32)cSize);
1024 { U64 const crcDest = XXH64(dstBuffer, sampleSize, 0);
1025 CHECK(crcOrig != crcDest, "decompression result corrupted (pos %u / %u)", (U32)findDiff(sampleBuffer, dstBuffer, sampleSize), (U32)sampleSize);
1028 free(sampleBuffer); /* no longer useful after this point */
1030 /* truncated src decompression test */
1031 { size_t const missing = (FUZ_rand(&lseed) % (cSize-2)) + 1; /* no problem, as cSize > 4 (frameHeaderSizer) */
1032 size_t const tooSmallSize = cSize - missing;
1033 void* cBufferTooSmall = malloc(tooSmallSize); /* valgrind will catch read overflows */
1034 CHECK(cBufferTooSmall == NULL, "not enough memory !");
1035 memcpy(cBufferTooSmall, cBuffer, tooSmallSize);
1036 { size_t const errorCode = ZSTD_decompress(dstBuffer, dstBufferSize, cBufferTooSmall, tooSmallSize);
1037 CHECK(!ZSTD_isError(errorCode), "ZSTD_decompress should have failed ! (truncated src buffer)"); }
1038 free(cBufferTooSmall);
1041 /* too small dst decompression test */
1042 if (sampleSize > 3) {
1043 size_t const missing = (FUZ_rand(&lseed) % (sampleSize-2)) + 1; /* no problem, as cSize > 4 (frameHeaderSizer) */
1044 size_t const tooSmallSize = sampleSize - missing;
1045 static const BYTE token = 0xA9;
1046 dstBuffer[tooSmallSize] = token;
1047 { size_t const errorCode = ZSTD_decompress(dstBuffer, tooSmallSize, cBuffer, cSize);
1048 CHECK(!ZSTD_isError(errorCode), "ZSTD_decompress should have failed : %u > %u (dst buffer too small)", (U32)errorCode, (U32)tooSmallSize); }
1049 CHECK(dstBuffer[tooSmallSize] != token, "ZSTD_decompress : dst buffer overflow");
1052 /* noisy src decompression test */
1054 /* insert noise into src */
1055 { U32 const maxNbBits = FUZ_highbit32((U32)(cSize-4));
1056 size_t pos = 4; /* preserve magic number (too easy to detect) */
1058 /* keep some original src */
1059 { U32 const nbBits = FUZ_rand(&lseed) % maxNbBits;
1060 size_t const mask = (1<<nbBits) - 1;
1061 size_t const skipLength = FUZ_rand(&lseed) & mask;
1064 if (pos <= cSize) break;
1066 { U32 const nbBitsCodes = FUZ_rand(&lseed) % maxNbBits;
1067 U32 const nbBits = nbBitsCodes ? nbBitsCodes-1 : 0;
1068 size_t const mask = (1<<nbBits) - 1;
1069 size_t const rNoiseLength = (FUZ_rand(&lseed) & mask) + 1;
1070 size_t const noiseLength = MIN(rNoiseLength, cSize-pos);
1071 size_t const noiseStart = FUZ_rand(&lseed) % (srcBufferSize - noiseLength);
1072 memcpy(cBuffer + pos, srcBuffer + noiseStart, noiseLength);
1076 /* decompress noisy source */
1077 { U32 const endMark = 0xA9B1C3D6;
1078 memcpy(dstBuffer+sampleSize, &endMark, 4);
1079 { size_t const decompressResult = ZSTD_decompress(dstBuffer, sampleSize, cBuffer, cSize);
1080 /* result *may* be an unlikely success, but even then, it must strictly respect dst buffer boundaries */
1081 CHECK((!ZSTD_isError(decompressResult)) && (decompressResult>sampleSize),
1082 "ZSTD_decompress on noisy src : result is too large : %u > %u (dst buffer)", (U32)decompressResult, (U32)sampleSize);
1084 { U32 endCheck; memcpy(&endCheck, dstBuffer+sampleSize, 4);
1085 CHECK(endMark!=endCheck, "ZSTD_decompress on noisy src : dst buffer overflow");
1086 } } } /* noisy src decompression test */
1088 /*===== Streaming compression test, scattered segments and dictionary =====*/
1090 { U32 const testLog = FUZ_rand(&lseed) % maxSrcLog;
1091 U32 const dictLog = FUZ_rand(&lseed) % maxSrcLog;
1092 int const cLevel = (FUZ_rand(&lseed) %
1094 (MAX(testLog, dictLog) / cLevelLimiter))) +
1096 maxTestSize = FUZ_rLogLength(&lseed, testLog);
1097 if (maxTestSize >= dstBufferSize) maxTestSize = dstBufferSize-1;
1099 dictSize = FUZ_rLogLength(&lseed, dictLog); /* needed also for decompression */
1100 dict = srcBuffer + (FUZ_rand(&lseed) % (srcBufferSize - dictSize));
1102 if (FUZ_rand(&lseed) & 0xF) {
1103 CHECK_Z ( ZSTD_compressBegin_usingDict(refCtx, dict, dictSize, cLevel) );
1105 ZSTD_compressionParameters const cPar = ZSTD_getCParams(cLevel, 0, dictSize);
1106 ZSTD_frameParameters const fPar = { FUZ_rand(&lseed)&1 /* contentSizeFlag */,
1107 !(FUZ_rand(&lseed)&3) /* contentChecksumFlag*/,
1108 0 /*NodictID*/ }; /* note : since dictionary is fake, dictIDflag has no impact */
1109 ZSTD_parameters const p = FUZ_makeParams(cPar, fPar);
1110 CHECK_Z ( ZSTD_compressBegin_advanced(refCtx, dict, dictSize, p, 0) );
1112 CHECK_Z( ZSTD_copyCCtx(ctx, refCtx, 0) );
1114 ZSTD_setCCtxParameter(ctx, ZSTD_p_forceWindow, FUZ_rand(&lseed) & 1);
1116 { U32 const nbChunks = (FUZ_rand(&lseed) & 127) + 2;
1118 XXH64_state_t xxhState;
1119 XXH64_reset(&xxhState, 0);
1120 for (totalTestSize=0, cSize=0, n=0 ; n<nbChunks ; n++) {
1121 size_t const segmentSize = FUZ_randomLength(&lseed, maxSampleLog);
1122 size_t const segmentStart = FUZ_rand(&lseed) % (srcBufferSize - segmentSize);
1124 if (cBufferSize-cSize < ZSTD_compressBound(segmentSize)) break; /* avoid invalid dstBufferTooSmall */
1125 if (totalTestSize+segmentSize > maxTestSize) break;
1127 { size_t const compressResult = ZSTD_compressContinue(ctx, cBuffer+cSize, cBufferSize-cSize, srcBuffer+segmentStart, segmentSize);
1128 CHECK (ZSTD_isError(compressResult), "multi-segments compression error : %s", ZSTD_getErrorName(compressResult));
1129 cSize += compressResult;
1131 XXH64_update(&xxhState, srcBuffer+segmentStart, segmentSize);
1132 memcpy(mirrorBuffer + totalTestSize, srcBuffer+segmentStart, segmentSize);
1133 totalTestSize += segmentSize;
1136 { size_t const flushResult = ZSTD_compressEnd(ctx, cBuffer+cSize, cBufferSize-cSize, NULL, 0);
1137 CHECK (ZSTD_isError(flushResult), "multi-segments epilogue error : %s", ZSTD_getErrorName(flushResult));
1138 cSize += flushResult;
1140 crcOrig = XXH64_digest(&xxhState);
1143 /* streaming decompression test */
1144 if (dictSize<8) dictSize=0, dict=NULL; /* disable dictionary */
1145 CHECK_Z( ZSTD_decompressBegin_usingDict(dctx, dict, dictSize) );
1148 while (totalCSize < cSize) {
1149 size_t const inSize = ZSTD_nextSrcSizeToDecompress(dctx);
1150 size_t const genSize = ZSTD_decompressContinue(dctx, dstBuffer+totalGenSize, dstBufferSize-totalGenSize, cBuffer+totalCSize, inSize);
1151 CHECK (ZSTD_isError(genSize), "ZSTD_decompressContinue error : %s", ZSTD_getErrorName(genSize));
1152 totalGenSize += genSize;
1153 totalCSize += inSize;
1155 CHECK (ZSTD_nextSrcSizeToDecompress(dctx) != 0, "frame not fully decoded");
1156 CHECK (totalGenSize != totalTestSize, "streaming decompressed data : wrong size")
1157 CHECK (totalCSize != cSize, "compressed data should be fully read")
1158 { U64 const crcDest = XXH64(dstBuffer, totalTestSize, 0);
1159 if (crcDest!=crcOrig) {
1160 size_t const errorPos = findDiff(mirrorBuffer, dstBuffer, totalTestSize);
1161 CHECK (1, "streaming decompressed data corrupted : byte %u / %u (%02X!=%02X)",
1162 (U32)errorPos, (U32)totalTestSize, dstBuffer[errorPos], mirrorBuffer[errorPos]);
1164 } /* for ( ; (testNb <= nbTests) */
1165 DISPLAY("\r%u fuzzer tests completed \n", testNb-1);
1168 ZSTD_freeCCtx(refCtx);
1170 ZSTD_freeDCtx(dctx);
1171 free(cNoiseBuffer[0]);
1172 free(cNoiseBuffer[1]);
1173 free(cNoiseBuffer[2]);
1174 free(cNoiseBuffer[3]);
1175 free(cNoiseBuffer[4]);
1187 /*_*******************************************************
1189 *********************************************************/
1190 static int FUZ_usage(const char* programName)
1192 DISPLAY( "Usage :\n");
1193 DISPLAY( " %s [args]\n", programName);
1195 DISPLAY( "Arguments :\n");
1196 DISPLAY( " -i# : Nb of tests (default:%u) \n", nbTestsDefault);
1197 DISPLAY( " -s# : Select seed (default:prompt user)\n");
1198 DISPLAY( " -t# : Select starting test number (default:0)\n");
1199 DISPLAY( " -P# : Select compressibility in %% (default:%u%%)\n", FUZ_compressibility_default);
1200 DISPLAY( " -v : verbose\n");
1201 DISPLAY( " -p : pause at the end\n");
1202 DISPLAY( " -h : display help and exit\n");
1206 /*! readU32FromChar() :
1207 @return : unsigned integer value read from input in `char` format
1208 allows and interprets K, KB, KiB, M, MB and MiB suffix.
1209 Will also modify `*stringPtr`, advancing it to position where it stopped reading.
1210 Note : function result can overflow if digit string > MAX_UINT */
1211 static unsigned readU32FromChar(const char** stringPtr)
1213 unsigned result = 0;
1214 while ((**stringPtr >='0') && (**stringPtr <='9'))
1215 result *= 10, result += **stringPtr - '0', (*stringPtr)++ ;
1216 if ((**stringPtr=='K') || (**stringPtr=='M')) {
1218 if (**stringPtr=='M') result <<= 10;
1220 if (**stringPtr=='i') (*stringPtr)++;
1221 if (**stringPtr=='B') (*stringPtr)++;
1226 int main(int argc, const char** argv)
1231 int nbTests = nbTestsDefault;
1233 U32 proba = FUZ_compressibility_default;
1236 U32 maxDuration = 0;
1238 const char* const programName = argv[0];
1240 /* Check command line */
1241 for (argNb=1; argNb<argc; argNb++) {
1242 const char* argument = argv[argNb];
1243 if(!argument) continue; /* Protection if argument empty */
1245 /* Handle commands. Aggregated commands are allowed */
1246 if (argument[0]=='-') {
1248 if (!strcmp(argument, "--no-big-tests")) { bigTests=0; continue; }
1251 while (*argument!=0) {
1255 return FUZ_usage(programName);
1267 case 'p': /* pause at the end */
1273 argument++; maxDuration = 0;
1274 nbTests = readU32FromChar(&argument);
1280 maxDuration = readU32FromChar(&argument);
1281 if (*argument=='s') argument++; /* seconds */
1282 if (*argument=='m') maxDuration *= 60, argument++; /* minutes */
1283 if (*argument=='n') argument++;
1289 seed = readU32FromChar(&argument);
1294 testNb = readU32FromChar(&argument);
1297 case 'P': /* compressibility % */
1299 proba = readU32FromChar(&argument);
1300 if (proba>100) proba = 100;
1304 return (FUZ_usage(programName), 1);
1305 } } } } /* for (argNb=1; argNb<argc; argNb++) */
1308 DISPLAY("Starting zstd tester (%i-bits, %s)\n", (int)(sizeof(size_t)*8), ZSTD_VERSION_STRING);
1311 time_t const t = time(NULL);
1312 U32 const h = XXH32(&t, sizeof(t), 1);
1316 DISPLAY("Seed = %u\n", seed);
1317 if (proba!=FUZ_compressibility_default) DISPLAY("Compressibility : %u%%\n", proba);
1319 if (nbTests < testNb) nbTests = testNb;
1322 result = basicUnitTests(0, ((double)proba) / 100); /* constant seed for predictability */
1324 result = fuzzerTests(seed, nbTests, testNb, maxDuration, ((double)proba) / 100, bigTests);
1327 DISPLAY("Press Enter \n");