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 : 4204) /* disable: C4204: non-constant aggregate initializer */
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_compressContinue, ZSTD_compressBlock */
31 #include "zstd.h" /* ZSTD_VERSION_STRING */
32 #include "zstd_errors.h" /* ZSTD_getErrorCode */
33 #include "zstdmt_compress.h"
34 #define ZDICT_STATIC_LINKING_ONLY
35 #include "zdict.h" /* ZDICT_trainFromBuffer */
36 #include "datagen.h" /* RDG_genBuffer */
38 #define XXH_STATIC_LINKING_ONLY /* XXH64_state_t */
39 #include "xxhash.h" /* XXH64 */
43 /*-************************************
45 **************************************/
50 static const U32 FUZ_compressibility_default = 50;
51 static const U32 nbTestsDefault = 30000;
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); } }
70 /*-*******************************************************
72 *********************************************************/
75 /* Declaring the function is it isn't unused */
76 void FUZ_bug976(void);
78 { /* these constants shall not depend on MIN() macro */
79 assert(ZSTD_HASHLOG_MAX < 31);
80 assert(ZSTD_CHAINLOG_MAX < 31);
84 /*-*******************************************************
86 *********************************************************/
87 #define MIN(a,b) ((a)<(b)?(a):(b))
88 #define MAX(a,b) ((a)>(b)?(a):(b))
90 #define FUZ_rotl32(x,r) ((x << r) | (x >> (32 - r)))
91 static unsigned FUZ_rand(unsigned* src)
93 static const U32 prime1 = 2654435761U;
94 static const U32 prime2 = 2246822519U;
98 rand32 = FUZ_rotl32(rand32, 13);
103 static unsigned FUZ_highbit32(U32 v32)
106 if (v32==0) return 0;
107 while (v32) v32 >>= 1, nbBits++;
112 /*=============================================
114 =============================================*/
115 #define CHECK_Z(f) { \
116 size_t const err = f; \
117 if (ZSTD_isError(err)) { \
118 DISPLAY("Error => %s : %s ", \
119 #f, ZSTD_getErrorName(err)); \
123 #define CHECK_V(var, fn) size_t const var = fn; if (ZSTD_isError(var)) goto _output_error
124 #define CHECK(fn) { CHECK_V(err, fn); }
125 #define CHECKPLUS(var, fn, more) { CHECK_V(var, fn); more; }
127 #define CHECK_EQ(lhs, rhs) { \
128 if ((lhs) != (rhs)) { \
129 DISPLAY("Error L%u => %s != %s ", __LINE__, #lhs, #rhs); \
130 goto _output_error; \
135 /*=============================================
137 =============================================*/
138 #if defined(__APPLE__) && defined(__MACH__)
140 #include <malloc/malloc.h> /* malloc_size */
143 unsigned long long totalMalloc;
144 size_t currentMalloc;
150 static const mallocCounter_t INIT_MALLOC_COUNTER = { 0, 0, 0, 0, 0 };
152 static void* FUZ_mallocDebug(void* counter, size_t size)
154 mallocCounter_t* const mcPtr = (mallocCounter_t*)counter;
155 void* const ptr = malloc(size);
156 if (ptr==NULL) return NULL;
157 DISPLAYLEVEL(4, "allocating %u KB => effectively %u KB \n",
158 (U32)(size >> 10), (U32)(malloc_size(ptr) >> 10)); /* OS-X specific */
159 mcPtr->totalMalloc += size;
160 mcPtr->currentMalloc += size;
161 if (mcPtr->currentMalloc > mcPtr->peakMalloc)
162 mcPtr->peakMalloc = mcPtr->currentMalloc;
163 mcPtr->nbMalloc += 1;
167 static void FUZ_freeDebug(void* counter, void* address)
169 mallocCounter_t* const mcPtr = (mallocCounter_t*)counter;
170 DISPLAYLEVEL(4, "freeing %u KB \n", (U32)(malloc_size(address) >> 10));
172 mcPtr->currentMalloc -= malloc_size(address); /* OS-X specific */
176 static void FUZ_displayMallocStats(mallocCounter_t count)
178 DISPLAYLEVEL(3, "peak:%6u KB, nbMallocs:%2u, total:%6u KB \n",
179 (U32)(count.peakMalloc >> 10),
181 (U32)(count.totalMalloc >> 10));
184 static int FUZ_mallocTests_internal(unsigned seed, double compressibility, unsigned part,
185 void* inBuffer, size_t inSize, void* outBuffer, size_t outSize)
187 /* test only played in verbose mode, as they are long */
188 if (g_displayLevel<3) return 0;
190 /* Create compressible noise */
191 if (!inBuffer || !outBuffer) {
192 DISPLAY("Not enough memory, aborting\n");
195 RDG_genBuffer(inBuffer, inSize, compressibility, 0. /*auto*/, seed);
197 /* simple compression tests */
199 { int compressionLevel;
200 for (compressionLevel=1; compressionLevel<=6; compressionLevel++) {
201 mallocCounter_t malcount = INIT_MALLOC_COUNTER;
202 ZSTD_customMem const cMem = { FUZ_mallocDebug, FUZ_freeDebug, &malcount };
203 ZSTD_CCtx* const cctx = ZSTD_createCCtx_advanced(cMem);
204 CHECK_Z( ZSTD_compressCCtx(cctx, outBuffer, outSize, inBuffer, inSize, compressionLevel) );
206 DISPLAYLEVEL(3, "compressCCtx level %i : ", compressionLevel);
207 FUZ_displayMallocStats(malcount);
210 /* streaming compression tests */
212 { int compressionLevel;
213 for (compressionLevel=1; compressionLevel<=6; compressionLevel++) {
214 mallocCounter_t malcount = INIT_MALLOC_COUNTER;
215 ZSTD_customMem const cMem = { FUZ_mallocDebug, FUZ_freeDebug, &malcount };
216 ZSTD_CCtx* const cstream = ZSTD_createCStream_advanced(cMem);
217 ZSTD_outBuffer out = { outBuffer, outSize, 0 };
218 ZSTD_inBuffer in = { inBuffer, inSize, 0 };
219 CHECK_Z( ZSTD_initCStream(cstream, compressionLevel) );
220 CHECK_Z( ZSTD_compressStream(cstream, &out, &in) );
221 CHECK_Z( ZSTD_endStream(cstream, &out) );
222 ZSTD_freeCStream(cstream);
223 DISPLAYLEVEL(3, "compressStream level %i : ", compressionLevel);
224 FUZ_displayMallocStats(malcount);
227 /* advanced MT API test */
230 for (nbThreads=1; nbThreads<=4; nbThreads++) {
231 int compressionLevel;
232 for (compressionLevel=1; compressionLevel<=6; compressionLevel++) {
233 mallocCounter_t malcount = INIT_MALLOC_COUNTER;
234 ZSTD_customMem const cMem = { FUZ_mallocDebug, FUZ_freeDebug, &malcount };
235 ZSTD_CCtx* const cctx = ZSTD_createCCtx_advanced(cMem);
236 ZSTD_outBuffer out = { outBuffer, outSize, 0 };
237 ZSTD_inBuffer in = { inBuffer, inSize, 0 };
238 CHECK_Z( ZSTD_CCtx_setParameter(cctx, ZSTD_p_compressionLevel, (U32)compressionLevel) );
239 CHECK_Z( ZSTD_CCtx_setParameter(cctx, ZSTD_p_nbWorkers, nbThreads) );
240 while ( ZSTD_compress_generic(cctx, &out, &in, ZSTD_e_end) ) {}
242 DISPLAYLEVEL(3, "compress_generic,-T%u,end level %i : ",
243 nbThreads, compressionLevel);
244 FUZ_displayMallocStats(malcount);
247 /* advanced MT streaming API test */
250 for (nbThreads=1; nbThreads<=4; nbThreads++) {
251 int compressionLevel;
252 for (compressionLevel=1; compressionLevel<=6; compressionLevel++) {
253 mallocCounter_t malcount = INIT_MALLOC_COUNTER;
254 ZSTD_customMem const cMem = { FUZ_mallocDebug, FUZ_freeDebug, &malcount };
255 ZSTD_CCtx* const cctx = ZSTD_createCCtx_advanced(cMem);
256 ZSTD_outBuffer out = { outBuffer, outSize, 0 };
257 ZSTD_inBuffer in = { inBuffer, inSize, 0 };
258 CHECK_Z( ZSTD_CCtx_setParameter(cctx, ZSTD_p_compressionLevel, (U32)compressionLevel) );
259 CHECK_Z( ZSTD_CCtx_setParameter(cctx, ZSTD_p_nbWorkers, nbThreads) );
260 CHECK_Z( ZSTD_compress_generic(cctx, &out, &in, ZSTD_e_continue) );
261 while ( ZSTD_compress_generic(cctx, &out, &in, ZSTD_e_end) ) {}
263 DISPLAYLEVEL(3, "compress_generic,-T%u,continue level %i : ",
264 nbThreads, compressionLevel);
265 FUZ_displayMallocStats(malcount);
271 static int FUZ_mallocTests(unsigned seed, double compressibility, unsigned part)
273 size_t const inSize = 64 MB + 16 MB + 4 MB + 1 MB + 256 KB + 64 KB; /* 85.3 MB */
274 size_t const outSize = ZSTD_compressBound(inSize);
275 void* const inBuffer = malloc(inSize);
276 void* const outBuffer = malloc(outSize);
279 /* Create compressible noise */
280 if (!inBuffer || !outBuffer) {
281 DISPLAY("Not enough memory, aborting \n");
285 result = FUZ_mallocTests_internal(seed, compressibility, part,
286 inBuffer, inSize, outBuffer, outSize);
295 static int FUZ_mallocTests(unsigned seed, double compressibility, unsigned part)
297 (void)seed; (void)compressibility; (void)part;
303 /*=============================================
305 =============================================*/
307 static int basicUnitTests(U32 seed, double compressibility)
309 size_t const CNBuffSize = 5 MB;
310 void* const CNBuffer = malloc(CNBuffSize);
311 size_t const compressedBufferSize = ZSTD_compressBound(CNBuffSize);
312 void* const compressedBuffer = malloc(compressedBufferSize);
313 void* const decodedBuffer = malloc(CNBuffSize);
314 ZSTD_DCtx* dctx = ZSTD_createDCtx();
319 /* Create compressible noise */
320 if (!CNBuffer || !compressedBuffer || !decodedBuffer) {
321 DISPLAY("Not enough memory, aborting\n");
325 RDG_genBuffer(CNBuffer, CNBuffSize, compressibility, 0., seed);
328 DISPLAYLEVEL(3, "test%3i : ZSTD_getErrorName : ", testNb++);
329 { const char* errorString = ZSTD_getErrorName(0);
330 DISPLAYLEVEL(3, "OK : %s \n", errorString);
333 DISPLAYLEVEL(3, "test%3i : ZSTD_getErrorName with wrong value : ", testNb++);
334 { const char* errorString = ZSTD_getErrorName(499);
335 DISPLAYLEVEL(3, "OK : %s \n", errorString);
338 DISPLAYLEVEL(3, "test%3i : min compression level : ", testNb++);
339 { int const mcl = ZSTD_minCLevel();
340 DISPLAYLEVEL(3, "%i (OK) \n", mcl);
343 DISPLAYLEVEL(3, "test%3i : compress %u bytes : ", testNb++, (U32)CNBuffSize);
344 { ZSTD_CCtx* const cctx = ZSTD_createCCtx();
345 if (cctx==NULL) goto _output_error;
346 CHECKPLUS(r, ZSTD_compressCCtx(cctx,
347 compressedBuffer, compressedBufferSize,
348 CNBuffer, CNBuffSize, 1),
350 DISPLAYLEVEL(3, "OK (%u bytes : %.2f%%)\n", (U32)cSize, (double)cSize/CNBuffSize*100);
352 DISPLAYLEVEL(3, "test%3i : size of cctx for level 1 : ", testNb++);
353 { size_t const cctxSize = ZSTD_sizeof_CCtx(cctx);
354 DISPLAYLEVEL(3, "%u bytes \n", (U32)cctxSize);
360 DISPLAYLEVEL(3, "test%3i : ZSTD_getFrameContentSize test : ", testNb++);
361 { unsigned long long const rSize = ZSTD_getFrameContentSize(compressedBuffer, cSize);
362 if (rSize != CNBuffSize) goto _output_error;
364 DISPLAYLEVEL(3, "OK \n");
366 DISPLAYLEVEL(3, "test%3i : ZSTD_findDecompressedSize test : ", testNb++);
367 { unsigned long long const rSize = ZSTD_findDecompressedSize(compressedBuffer, cSize);
368 if (rSize != CNBuffSize) goto _output_error;
370 DISPLAYLEVEL(3, "OK \n");
372 DISPLAYLEVEL(3, "test%3i : decompress %u bytes : ", testNb++, (U32)CNBuffSize);
373 { size_t const r = ZSTD_decompress(decodedBuffer, CNBuffSize, compressedBuffer, cSize);
374 if (r != CNBuffSize) goto _output_error; }
375 DISPLAYLEVEL(3, "OK \n");
377 DISPLAYLEVEL(3, "test%3i : check decompressed result : ", testNb++);
379 for (u=0; u<CNBuffSize; u++) {
380 if (((BYTE*)decodedBuffer)[u] != ((BYTE*)CNBuffer)[u]) goto _output_error;;
382 DISPLAYLEVEL(3, "OK \n");
385 DISPLAYLEVEL(3, "test%3i : decompress with null dict : ", testNb++);
386 { size_t const r = ZSTD_decompress_usingDict(dctx, decodedBuffer, CNBuffSize, compressedBuffer, cSize, NULL, 0);
387 if (r != CNBuffSize) goto _output_error; }
388 DISPLAYLEVEL(3, "OK \n");
390 DISPLAYLEVEL(3, "test%3i : decompress with null DDict : ", testNb++);
391 { size_t const r = ZSTD_decompress_usingDDict(dctx, decodedBuffer, CNBuffSize, compressedBuffer, cSize, NULL);
392 if (r != CNBuffSize) goto _output_error; }
393 DISPLAYLEVEL(3, "OK \n");
395 DISPLAYLEVEL(3, "test%3i : decompress with 1 missing byte : ", testNb++);
396 { size_t const r = ZSTD_decompress(decodedBuffer, CNBuffSize, compressedBuffer, cSize-1);
397 if (!ZSTD_isError(r)) goto _output_error;
398 if (ZSTD_getErrorCode((size_t)r) != ZSTD_error_srcSize_wrong) goto _output_error; }
399 DISPLAYLEVEL(3, "OK \n");
401 DISPLAYLEVEL(3, "test%3i : decompress with 1 too much byte : ", testNb++);
402 { size_t const r = ZSTD_decompress(decodedBuffer, CNBuffSize, compressedBuffer, cSize+1);
403 if (!ZSTD_isError(r)) goto _output_error;
404 if (ZSTD_getErrorCode(r) != ZSTD_error_srcSize_wrong) goto _output_error; }
405 DISPLAYLEVEL(3, "OK \n");
407 DISPLAYLEVEL(3, "test%3i : decompress too large input : ", testNb++);
408 { size_t const r = ZSTD_decompress(decodedBuffer, CNBuffSize, compressedBuffer, compressedBufferSize);
409 if (!ZSTD_isError(r)) goto _output_error;
410 if (ZSTD_getErrorCode(r) != ZSTD_error_srcSize_wrong) goto _output_error; }
411 DISPLAYLEVEL(3, "OK \n");
413 DISPLAYLEVEL(3, "test%3d : check CCtx size after compressing empty input : ", testNb++);
414 { ZSTD_CCtx* cctx = ZSTD_createCCtx();
415 size_t const r = ZSTD_compressCCtx(cctx, compressedBuffer, compressedBufferSize, NULL, 0, 19);
416 if (ZSTD_isError(r)) goto _output_error;
417 if (ZSTD_sizeof_CCtx(cctx) > (1U << 20)) goto _output_error;
420 DISPLAYLEVEL(3, "OK \n");
422 DISPLAYLEVEL(3, "test%3d : re-use CCtx with expanding block size : ", testNb++);
423 { ZSTD_CCtx* const cctx = ZSTD_createCCtx();
424 ZSTD_parameters const params = ZSTD_getParams(1, ZSTD_CONTENTSIZE_UNKNOWN, 0);
425 assert(params.fParams.contentSizeFlag == 1); /* block size will be adapted if pledgedSrcSize is enabled */
426 CHECK_Z( ZSTD_compressBegin_advanced(cctx, NULL, 0, params, 1 /*pledgedSrcSize*/) );
427 CHECK_Z( ZSTD_compressEnd(cctx, compressedBuffer, compressedBufferSize, CNBuffer, 1) ); /* creates a block size of 1 */
429 CHECK_Z( ZSTD_compressBegin_advanced(cctx, NULL, 0, params, ZSTD_CONTENTSIZE_UNKNOWN) ); /* re-use same parameters */
430 { size_t const inSize = 2* 128 KB;
431 size_t const outSize = ZSTD_compressBound(inSize);
432 CHECK_Z( ZSTD_compressEnd(cctx, compressedBuffer, outSize, CNBuffer, inSize) );
433 /* will fail if blockSize is not resized */
437 DISPLAYLEVEL(3, "OK \n");
439 DISPLAYLEVEL(3, "test%3d : re-using a CCtx should compress the same : ", testNb++);
442 ((char*)CNBuffer)[i] = (char)i; /* ensure no match during initial section */
443 memcpy((char*)CNBuffer + 20, CNBuffer, 10); /* create one match, starting from beginning of sample, which is the difficult case (see #1241) */
444 for (i=1; i<=19; i++) {
445 ZSTD_CCtx* const cctx = ZSTD_createCCtx();
447 DISPLAYLEVEL(5, "l%i ", i);
448 size1 = ZSTD_compressCCtx(cctx, compressedBuffer, compressedBufferSize, CNBuffer, 30, i);
450 size2 = ZSTD_compressCCtx(cctx, compressedBuffer, compressedBufferSize, CNBuffer, 30, i);
452 CHECK_EQ(size1, size2);
457 DISPLAYLEVEL(3, "OK \n");
459 DISPLAYLEVEL(3, "test%3d : ZSTD_CCtx_getParameter() : ", testNb++);
460 { ZSTD_CCtx* const cctx = ZSTD_createCCtx();
461 ZSTD_outBuffer out = {NULL, 0, 0};
462 ZSTD_inBuffer in = {NULL, 0, 0};
465 CHECK_Z(ZSTD_CCtx_getParameter(cctx, ZSTD_p_compressionLevel, &value));
467 CHECK_Z(ZSTD_CCtx_getParameter(cctx, ZSTD_p_hashLog, &value));
469 CHECK_Z(ZSTD_CCtx_setParameter(cctx, ZSTD_p_hashLog, ZSTD_HASHLOG_MIN));
470 CHECK_Z(ZSTD_CCtx_getParameter(cctx, ZSTD_p_compressionLevel, &value));
472 CHECK_Z(ZSTD_CCtx_getParameter(cctx, ZSTD_p_hashLog, &value));
473 CHECK_EQ(value, ZSTD_HASHLOG_MIN);
474 CHECK_Z(ZSTD_CCtx_setParameter(cctx, ZSTD_p_compressionLevel, 7));
475 CHECK_Z(ZSTD_CCtx_getParameter(cctx, ZSTD_p_compressionLevel, &value));
477 CHECK_Z(ZSTD_CCtx_getParameter(cctx, ZSTD_p_hashLog, &value));
478 CHECK_EQ(value, ZSTD_HASHLOG_MIN);
479 /* Start a compression job */
480 ZSTD_compress_generic(cctx, &out, &in, ZSTD_e_continue);
481 CHECK_Z(ZSTD_CCtx_getParameter(cctx, ZSTD_p_compressionLevel, &value));
483 CHECK_Z(ZSTD_CCtx_getParameter(cctx, ZSTD_p_hashLog, &value));
484 CHECK_EQ(value, ZSTD_HASHLOG_MIN);
486 ZSTD_CCtx_reset(cctx);
487 CHECK_Z(ZSTD_CCtx_getParameter(cctx, ZSTD_p_compressionLevel, &value));
489 CHECK_Z(ZSTD_CCtx_getParameter(cctx, ZSTD_p_hashLog, &value));
490 CHECK_EQ(value, ZSTD_HASHLOG_MIN);
491 /* Reset the parameters */
492 ZSTD_CCtx_resetParameters(cctx);
493 CHECK_Z(ZSTD_CCtx_getParameter(cctx, ZSTD_p_compressionLevel, &value));
495 CHECK_Z(ZSTD_CCtx_getParameter(cctx, ZSTD_p_hashLog, &value));
500 DISPLAYLEVEL(3, "OK \n");
502 /* this test is really too long, and should be made faster */
503 DISPLAYLEVEL(3, "test%3d : overflow protection with large windowLog : ", testNb++);
504 { ZSTD_CCtx* const cctx = ZSTD_createCCtx();
505 ZSTD_parameters params = ZSTD_getParams(-9, ZSTD_CONTENTSIZE_UNKNOWN, 0);
506 size_t const nbCompressions = ((1U << 31) / CNBuffSize) + 1; /* ensure U32 overflow protection is triggered */
508 assert(cctx != NULL);
509 params.fParams.contentSizeFlag = 0;
510 params.cParams.windowLog = ZSTD_WINDOWLOG_MAX;
511 for (cnb = 0; cnb < nbCompressions; ++cnb) {
512 DISPLAYLEVEL(6, "run %zu / %zu \n", cnb, nbCompressions);
513 CHECK_Z( ZSTD_compressBegin_advanced(cctx, NULL, 0, params, ZSTD_CONTENTSIZE_UNKNOWN) ); /* re-use same parameters */
514 CHECK_Z( ZSTD_compressEnd(cctx, compressedBuffer, compressedBufferSize, CNBuffer, CNBuffSize) );
518 DISPLAYLEVEL(3, "OK \n");
520 DISPLAYLEVEL(3, "test%3d : size down context : ", testNb++);
521 { ZSTD_CCtx* const largeCCtx = ZSTD_createCCtx();
522 assert(largeCCtx != NULL);
523 CHECK_Z( ZSTD_compressBegin(largeCCtx, 19) ); /* streaming implies ZSTD_CONTENTSIZE_UNKNOWN, which maximizes memory usage */
524 CHECK_Z( ZSTD_compressEnd(largeCCtx, compressedBuffer, compressedBufferSize, CNBuffer, 1) );
525 { size_t const largeCCtxSize = ZSTD_sizeof_CCtx(largeCCtx); /* size of context must be measured after compression */
526 { ZSTD_CCtx* const smallCCtx = ZSTD_createCCtx();
527 assert(smallCCtx != NULL);
528 CHECK_Z(ZSTD_compressCCtx(smallCCtx, compressedBuffer, compressedBufferSize, CNBuffer, 1, 1));
529 { size_t const smallCCtxSize = ZSTD_sizeof_CCtx(smallCCtx);
530 DISPLAYLEVEL(5, "(large) %zuKB > 32*%zuKB (small) : ",
531 largeCCtxSize>>10, smallCCtxSize>>10);
532 assert(largeCCtxSize > 32* smallCCtxSize); /* note : "too large" definition is handled within zstd_compress.c .
533 * make this test case extreme, so that it doesn't depend on a possibly fluctuating definition */
535 ZSTD_freeCCtx(smallCCtx);
537 { U32 const maxNbAttempts = 1100; /* nb of usages before triggering size down is handled within zstd_compress.c.
538 * currently defined as 128x, but could be adjusted in the future.
539 * make this test long enough so that it's not too much tied to the current definition within zstd_compress.c */
541 for (u=0; u<maxNbAttempts; u++) {
542 CHECK_Z(ZSTD_compressCCtx(largeCCtx, compressedBuffer, compressedBufferSize, CNBuffer, 1, 1));
543 if (ZSTD_sizeof_CCtx(largeCCtx) < largeCCtxSize) break; /* sized down */
545 DISPLAYLEVEL(5, "size down after %u attempts : ", u);
546 if (u==maxNbAttempts) goto _output_error; /* no sizedown happened */
549 ZSTD_freeCCtx(largeCCtx);
551 DISPLAYLEVEL(3, "OK \n");
553 /* Static CCtx tests */
554 #define STATIC_CCTX_LEVEL 3
555 DISPLAYLEVEL(3, "test%3i : create static CCtx for level %u :", testNb++, STATIC_CCTX_LEVEL);
556 { size_t const staticCCtxSize = ZSTD_estimateCStreamSize(STATIC_CCTX_LEVEL);
557 void* const staticCCtxBuffer = malloc(staticCCtxSize);
558 size_t const staticDCtxSize = ZSTD_estimateDCtxSize();
559 void* const staticDCtxBuffer = malloc(staticDCtxSize);
560 if (staticCCtxBuffer==NULL || staticDCtxBuffer==NULL) {
561 free(staticCCtxBuffer);
562 free(staticDCtxBuffer);
563 DISPLAY("Not enough memory, aborting\n");
567 { ZSTD_CCtx* staticCCtx = ZSTD_initStaticCCtx(staticCCtxBuffer, staticCCtxSize);
568 ZSTD_DCtx* staticDCtx = ZSTD_initStaticDCtx(staticDCtxBuffer, staticDCtxSize);
569 if ((staticCCtx==NULL) || (staticDCtx==NULL)) goto _output_error;
570 DISPLAYLEVEL(3, "OK \n");
572 DISPLAYLEVEL(3, "test%3i : init CCtx for level %u : ", testNb++, STATIC_CCTX_LEVEL);
573 { size_t const r = ZSTD_compressBegin(staticCCtx, STATIC_CCTX_LEVEL);
574 if (ZSTD_isError(r)) goto _output_error; }
575 DISPLAYLEVEL(3, "OK \n");
577 DISPLAYLEVEL(3, "test%3i : simple compression test with static CCtx : ", testNb++);
578 CHECKPLUS(r, ZSTD_compressCCtx(staticCCtx,
579 compressedBuffer, compressedBufferSize,
580 CNBuffer, CNBuffSize, STATIC_CCTX_LEVEL),
582 DISPLAYLEVEL(3, "OK (%u bytes : %.2f%%)\n",
583 (U32)cSize, (double)cSize/CNBuffSize*100);
585 DISPLAYLEVEL(3, "test%3i : simple decompression test with static DCtx : ", testNb++);
586 { size_t const r = ZSTD_decompressDCtx(staticDCtx,
587 decodedBuffer, CNBuffSize,
588 compressedBuffer, cSize);
589 if (r != CNBuffSize) goto _output_error; }
590 DISPLAYLEVEL(3, "OK \n");
592 DISPLAYLEVEL(3, "test%3i : check decompressed result : ", testNb++);
594 for (u=0; u<CNBuffSize; u++) {
595 if (((BYTE*)decodedBuffer)[u] != ((BYTE*)CNBuffer)[u])
598 DISPLAYLEVEL(3, "OK \n");
600 DISPLAYLEVEL(3, "test%3i : init CCtx for too large level (must fail) : ", testNb++);
601 { size_t const r = ZSTD_compressBegin(staticCCtx, ZSTD_maxCLevel());
602 if (!ZSTD_isError(r)) goto _output_error; }
603 DISPLAYLEVEL(3, "OK \n");
605 DISPLAYLEVEL(3, "test%3i : init CCtx for small level %u (should work again) : ", testNb++, 1);
606 { size_t const r = ZSTD_compressBegin(staticCCtx, 1);
607 if (ZSTD_isError(r)) goto _output_error; }
608 DISPLAYLEVEL(3, "OK \n");
610 DISPLAYLEVEL(3, "test%3i : init CStream for small level %u : ", testNb++, 1);
611 { size_t const r = ZSTD_initCStream(staticCCtx, 1);
612 if (ZSTD_isError(r)) goto _output_error; }
613 DISPLAYLEVEL(3, "OK \n");
615 DISPLAYLEVEL(3, "test%3i : init CStream with dictionary (should fail) : ", testNb++);
616 { size_t const r = ZSTD_initCStream_usingDict(staticCCtx, CNBuffer, 64 KB, 1);
617 if (!ZSTD_isError(r)) goto _output_error; }
618 DISPLAYLEVEL(3, "OK \n");
620 DISPLAYLEVEL(3, "test%3i : init DStream (should fail) : ", testNb++);
621 { size_t const r = ZSTD_initDStream(staticDCtx);
622 if (ZSTD_isError(r)) goto _output_error; }
623 { ZSTD_outBuffer output = { decodedBuffer, CNBuffSize, 0 };
624 ZSTD_inBuffer input = { compressedBuffer, ZSTD_FRAMEHEADERSIZE_MAX+1, 0 };
625 size_t const r = ZSTD_decompressStream(staticDCtx, &output, &input);
626 if (!ZSTD_isError(r)) goto _output_error;
628 DISPLAYLEVEL(3, "OK \n");
630 free(staticCCtxBuffer);
631 free(staticDCtxBuffer);
635 /* ZSTDMT simple MT compression test */
636 DISPLAYLEVEL(3, "test%3i : create ZSTDMT CCtx : ", testNb++);
637 { ZSTDMT_CCtx* mtctx = ZSTDMT_createCCtx(2);
639 DISPLAY("mtctx : mot enough memory, aborting \n");
643 DISPLAYLEVEL(3, "OK \n");
645 DISPLAYLEVEL(3, "test%3i : compress %u bytes with 2 threads : ", testNb++, (U32)CNBuffSize);
646 CHECKPLUS(r, ZSTDMT_compressCCtx(mtctx,
647 compressedBuffer, compressedBufferSize,
648 CNBuffer, CNBuffSize,
651 DISPLAYLEVEL(3, "OK (%u bytes : %.2f%%)\n", (U32)cSize, (double)cSize/CNBuffSize*100);
653 DISPLAYLEVEL(3, "test%3i : decompressed size test : ", testNb++);
654 { unsigned long long const rSize = ZSTD_getFrameContentSize(compressedBuffer, cSize);
655 if (rSize != CNBuffSize) {
656 DISPLAY("ZSTD_getFrameContentSize incorrect : %u != %u \n", (U32)rSize, (U32)CNBuffSize);
659 DISPLAYLEVEL(3, "OK \n");
661 DISPLAYLEVEL(3, "test%3i : decompress %u bytes : ", testNb++, (U32)CNBuffSize);
662 { size_t const r = ZSTD_decompress(decodedBuffer, CNBuffSize, compressedBuffer, cSize);
663 if (r != CNBuffSize) goto _output_error; }
664 DISPLAYLEVEL(3, "OK \n");
666 DISPLAYLEVEL(3, "test%3i : check decompressed result : ", testNb++);
668 for (u=0; u<CNBuffSize; u++) {
669 if (((BYTE*)decodedBuffer)[u] != ((BYTE*)CNBuffer)[u]) goto _output_error;;
671 DISPLAYLEVEL(3, "OK \n");
673 DISPLAYLEVEL(3, "test%3i : compress -T2 with checksum : ", testNb++);
674 { ZSTD_parameters params = ZSTD_getParams(1, CNBuffSize, 0);
675 params.fParams.checksumFlag = 1;
676 params.fParams.contentSizeFlag = 1;
677 CHECKPLUS(r, ZSTDMT_compress_advanced(mtctx,
678 compressedBuffer, compressedBufferSize,
679 CNBuffer, CNBuffSize,
680 NULL, params, 3 /*overlapRLog*/),
683 DISPLAYLEVEL(3, "OK (%u bytes : %.2f%%)\n", (U32)cSize, (double)cSize/CNBuffSize*100);
685 DISPLAYLEVEL(3, "test%3i : decompress %u bytes : ", testNb++, (U32)CNBuffSize);
686 { size_t const r = ZSTD_decompress(decodedBuffer, CNBuffSize, compressedBuffer, cSize);
687 if (r != CNBuffSize) goto _output_error; }
688 DISPLAYLEVEL(3, "OK \n");
690 ZSTDMT_freeCCtx(mtctx);
694 /* Simple API multiframe test */
695 DISPLAYLEVEL(3, "test%3i : compress multiple frames : ", testNb++);
699 /* only use the first half so we don't push against size limit of compressedBuffer */
700 size_t const segSize = (CNBuffSize / 2) / segs;
701 for (i = 0; i < segs; i++) {
702 CHECK_V(r, ZSTD_compress(
703 (BYTE *)compressedBuffer + off, CNBuffSize - off,
704 (BYTE *)CNBuffer + segSize * i,
708 /* insert skippable frame */
709 const U32 skipLen = 129 KB;
710 MEM_writeLE32((BYTE*)compressedBuffer + off, ZSTD_MAGIC_SKIPPABLE_START);
711 MEM_writeLE32((BYTE*)compressedBuffer + off + 4, skipLen);
712 off += skipLen + ZSTD_skippableHeaderSize;
717 DISPLAYLEVEL(3, "OK \n");
719 DISPLAYLEVEL(3, "test%3i : get decompressed size of multiple frames : ", testNb++);
720 { unsigned long long const r = ZSTD_findDecompressedSize(compressedBuffer, cSize);
721 if (r != CNBuffSize / 2) goto _output_error; }
722 DISPLAYLEVEL(3, "OK \n");
724 DISPLAYLEVEL(3, "test%3i : decompress multiple frames : ", testNb++);
725 { CHECK_V(r, ZSTD_decompress(decodedBuffer, CNBuffSize, compressedBuffer, cSize));
726 if (r != CNBuffSize / 2) goto _output_error; }
727 DISPLAYLEVEL(3, "OK \n");
729 DISPLAYLEVEL(3, "test%3i : check decompressed result : ", testNb++);
730 if (memcmp(decodedBuffer, CNBuffer, CNBuffSize / 2) != 0) goto _output_error;
731 DISPLAYLEVEL(3, "OK \n");
733 /* Dictionary and CCtx Duplication tests */
734 { ZSTD_CCtx* const ctxOrig = ZSTD_createCCtx();
735 ZSTD_CCtx* const ctxDuplicated = ZSTD_createCCtx();
736 static const size_t dictSize = 551;
738 DISPLAYLEVEL(3, "test%3i : copy context too soon : ", testNb++);
739 { size_t const copyResult = ZSTD_copyCCtx(ctxDuplicated, ctxOrig, 0);
740 if (!ZSTD_isError(copyResult)) goto _output_error; } /* error must be detected */
741 DISPLAYLEVEL(3, "OK \n");
743 DISPLAYLEVEL(3, "test%3i : load dictionary into context : ", testNb++);
744 CHECK( ZSTD_compressBegin_usingDict(ctxOrig, CNBuffer, dictSize, 2) );
745 CHECK( ZSTD_copyCCtx(ctxDuplicated, ctxOrig, 0) ); /* Begin_usingDict implies unknown srcSize, so match that */
746 DISPLAYLEVEL(3, "OK \n");
748 DISPLAYLEVEL(3, "test%3i : compress with flat dictionary : ", testNb++);
750 CHECKPLUS(r, ZSTD_compressEnd(ctxOrig, compressedBuffer, compressedBufferSize,
751 (const char*)CNBuffer + dictSize, CNBuffSize - dictSize),
753 DISPLAYLEVEL(3, "OK (%u bytes : %.2f%%)\n", (U32)cSize, (double)cSize/CNBuffSize*100);
755 DISPLAYLEVEL(3, "test%3i : frame built with flat dictionary should be decompressible : ", testNb++);
756 CHECKPLUS(r, ZSTD_decompress_usingDict(dctx,
757 decodedBuffer, CNBuffSize,
758 compressedBuffer, cSize,
760 if (r != CNBuffSize - dictSize) goto _output_error);
761 DISPLAYLEVEL(3, "OK \n");
763 DISPLAYLEVEL(3, "test%3i : compress with duplicated context : ", testNb++);
764 { size_t const cSizeOrig = cSize;
766 CHECKPLUS(r, ZSTD_compressEnd(ctxDuplicated, compressedBuffer, compressedBufferSize,
767 (const char*)CNBuffer + dictSize, CNBuffSize - dictSize),
769 if (cSize != cSizeOrig) goto _output_error; /* should be identical ==> same size */
771 DISPLAYLEVEL(3, "OK (%u bytes : %.2f%%)\n", (U32)cSize, (double)cSize/CNBuffSize*100);
773 DISPLAYLEVEL(3, "test%3i : frame built with duplicated context should be decompressible : ", testNb++);
774 CHECKPLUS(r, ZSTD_decompress_usingDict(dctx,
775 decodedBuffer, CNBuffSize,
776 compressedBuffer, cSize,
778 if (r != CNBuffSize - dictSize) goto _output_error);
779 DISPLAYLEVEL(3, "OK \n");
781 DISPLAYLEVEL(3, "test%3i : decompress with DDict : ", testNb++);
782 { ZSTD_DDict* const ddict = ZSTD_createDDict(CNBuffer, dictSize);
783 size_t const r = ZSTD_decompress_usingDDict(dctx, decodedBuffer, CNBuffSize, compressedBuffer, cSize, ddict);
784 if (r != CNBuffSize - dictSize) goto _output_error;
785 DISPLAYLEVEL(3, "OK (size of DDict : %u) \n", (U32)ZSTD_sizeof_DDict(ddict));
786 ZSTD_freeDDict(ddict);
789 DISPLAYLEVEL(3, "test%3i : decompress with static DDict : ", testNb++);
790 { size_t const ddictBufferSize = ZSTD_estimateDDictSize(dictSize, ZSTD_dlm_byCopy);
791 void* ddictBuffer = malloc(ddictBufferSize);
792 if (ddictBuffer == NULL) goto _output_error;
793 { const ZSTD_DDict* const ddict = ZSTD_initStaticDDict(ddictBuffer, ddictBufferSize, CNBuffer, dictSize, ZSTD_dlm_byCopy, ZSTD_dct_auto);
794 size_t const r = ZSTD_decompress_usingDDict(dctx, decodedBuffer, CNBuffSize, compressedBuffer, cSize, ddict);
795 if (r != CNBuffSize - dictSize) goto _output_error;
798 DISPLAYLEVEL(3, "OK (size of static DDict : %u) \n", (U32)ddictBufferSize);
801 DISPLAYLEVEL(3, "test%3i : check content size on duplicated context : ", testNb++);
802 { size_t const testSize = CNBuffSize / 3;
803 { ZSTD_parameters p = ZSTD_getParams(2, testSize, dictSize);
804 p.fParams.contentSizeFlag = 1;
805 CHECK( ZSTD_compressBegin_advanced(ctxOrig, CNBuffer, dictSize, p, testSize-1) );
807 CHECK( ZSTD_copyCCtx(ctxDuplicated, ctxOrig, testSize) );
809 CHECKPLUS(r, ZSTD_compressEnd(ctxDuplicated, compressedBuffer, ZSTD_compressBound(testSize),
810 (const char*)CNBuffer + dictSize, testSize),
812 { ZSTD_frameHeader zfh;
813 if (ZSTD_getFrameHeader(&zfh, compressedBuffer, cSize)) goto _output_error;
814 if ((zfh.frameContentSize != testSize) && (zfh.frameContentSize != 0)) goto _output_error;
816 DISPLAYLEVEL(3, "OK \n");
818 ZSTD_freeCCtx(ctxOrig);
819 ZSTD_freeCCtx(ctxDuplicated);
822 /* Dictionary and dictBuilder tests */
823 { ZSTD_CCtx* const cctx = ZSTD_createCCtx();
824 size_t const dictBufferCapacity = 16 KB;
825 void* dictBuffer = malloc(dictBufferCapacity);
826 size_t const totalSampleSize = 1 MB;
827 size_t const sampleUnitSize = 8 KB;
828 U32 const nbSamples = (U32)(totalSampleSize / sampleUnitSize);
829 size_t* const samplesSizes = (size_t*) malloc(nbSamples * sizeof(size_t));
833 if (dictBuffer==NULL || samplesSizes==NULL) {
839 DISPLAYLEVEL(3, "test%3i : dictBuilder on cyclic data : ", testNb++);
840 assert(compressedBufferSize >= totalSampleSize);
841 { U32 u; for (u=0; u<totalSampleSize; u++) ((BYTE*)decodedBuffer)[u] = (BYTE)u; }
842 { U32 u; for (u=0; u<nbSamples; u++) samplesSizes[u] = sampleUnitSize; }
843 { size_t const sDictSize = ZDICT_trainFromBuffer(dictBuffer, dictBufferCapacity,
844 decodedBuffer, samplesSizes, nbSamples);
845 if (ZDICT_isError(sDictSize)) goto _output_error;
846 DISPLAYLEVEL(3, "OK, created dictionary of size %u \n", (U32)sDictSize);
849 DISPLAYLEVEL(3, "test%3i : dictBuilder : ", testNb++);
850 { U32 u; for (u=0; u<nbSamples; u++) samplesSizes[u] = sampleUnitSize; }
851 dictSize = ZDICT_trainFromBuffer(dictBuffer, dictBufferCapacity,
852 CNBuffer, samplesSizes, nbSamples);
853 if (ZDICT_isError(dictSize)) goto _output_error;
854 DISPLAYLEVEL(3, "OK, created dictionary of size %u \n", (U32)dictSize);
856 DISPLAYLEVEL(3, "test%3i : check dictID : ", testNb++);
857 dictID = ZDICT_getDictID(dictBuffer, dictSize);
858 if (dictID==0) goto _output_error;
859 DISPLAYLEVEL(3, "OK : %u \n", dictID);
861 DISPLAYLEVEL(3, "test%3i : compress with dictionary : ", testNb++);
862 cSize = ZSTD_compress_usingDict(cctx, compressedBuffer, compressedBufferSize,
863 CNBuffer, CNBuffSize,
864 dictBuffer, dictSize, 4);
865 if (ZSTD_isError(cSize)) goto _output_error;
866 DISPLAYLEVEL(3, "OK (%u bytes : %.2f%%)\n", (U32)cSize, (double)cSize/CNBuffSize*100);
868 DISPLAYLEVEL(3, "test%3i : retrieve dictID from dictionary : ", testNb++);
869 { U32 const did = ZSTD_getDictID_fromDict(dictBuffer, dictSize);
870 if (did != dictID) goto _output_error; /* non-conformant (content-only) dictionary */
872 DISPLAYLEVEL(3, "OK \n");
874 DISPLAYLEVEL(3, "test%3i : retrieve dictID from frame : ", testNb++);
875 { U32 const did = ZSTD_getDictID_fromFrame(compressedBuffer, cSize);
876 if (did != dictID) goto _output_error; /* non-conformant (content-only) dictionary */
878 DISPLAYLEVEL(3, "OK \n");
880 DISPLAYLEVEL(3, "test%3i : frame built with dictionary should be decompressible : ", testNb++);
881 CHECKPLUS(r, ZSTD_decompress_usingDict(dctx,
882 decodedBuffer, CNBuffSize,
883 compressedBuffer, cSize,
884 dictBuffer, dictSize),
885 if (r != CNBuffSize) goto _output_error);
886 DISPLAYLEVEL(3, "OK \n");
888 DISPLAYLEVEL(3, "test%3i : estimate CDict size : ", testNb++);
889 { ZSTD_compressionParameters const cParams = ZSTD_getCParams(1, CNBuffSize, dictSize);
890 size_t const estimatedSize = ZSTD_estimateCDictSize_advanced(dictSize, cParams, ZSTD_dlm_byRef);
891 DISPLAYLEVEL(3, "OK : %u \n", (U32)estimatedSize);
894 DISPLAYLEVEL(3, "test%3i : compress with CDict ", testNb++);
895 { ZSTD_compressionParameters const cParams = ZSTD_getCParams(1, CNBuffSize, dictSize);
896 ZSTD_CDict* const cdict = ZSTD_createCDict_advanced(dictBuffer, dictSize,
897 ZSTD_dlm_byRef, ZSTD_dct_auto,
898 cParams, ZSTD_defaultCMem);
899 DISPLAYLEVEL(3, "(size : %u) : ", (U32)ZSTD_sizeof_CDict(cdict));
900 cSize = ZSTD_compress_usingCDict(cctx, compressedBuffer, compressedBufferSize,
901 CNBuffer, CNBuffSize, cdict);
902 ZSTD_freeCDict(cdict);
903 if (ZSTD_isError(cSize)) goto _output_error;
905 DISPLAYLEVEL(3, "OK (%u bytes : %.2f%%)\n", (U32)cSize, (double)cSize/CNBuffSize*100);
907 DISPLAYLEVEL(3, "test%3i : retrieve dictID from frame : ", testNb++);
908 { U32 const did = ZSTD_getDictID_fromFrame(compressedBuffer, cSize);
909 if (did != dictID) goto _output_error; /* non-conformant (content-only) dictionary */
911 DISPLAYLEVEL(3, "OK \n");
913 DISPLAYLEVEL(3, "test%3i : frame built with dictionary should be decompressible : ", testNb++);
914 CHECKPLUS(r, ZSTD_decompress_usingDict(dctx,
915 decodedBuffer, CNBuffSize,
916 compressedBuffer, cSize,
917 dictBuffer, dictSize),
918 if (r != CNBuffSize) goto _output_error);
919 DISPLAYLEVEL(3, "OK \n");
921 DISPLAYLEVEL(3, "test%3i : compress with static CDict : ", testNb++);
922 { int const maxLevel = ZSTD_maxCLevel();
924 for (level = 1; level <= maxLevel; ++level) {
925 ZSTD_compressionParameters const cParams = ZSTD_getCParams(level, CNBuffSize, dictSize);
926 size_t const cdictSize = ZSTD_estimateCDictSize_advanced(dictSize, cParams, ZSTD_dlm_byCopy);
927 void* const cdictBuffer = malloc(cdictSize);
928 if (cdictBuffer==NULL) goto _output_error;
929 { const ZSTD_CDict* const cdict = ZSTD_initStaticCDict(
930 cdictBuffer, cdictSize,
931 dictBuffer, dictSize,
932 ZSTD_dlm_byCopy, ZSTD_dct_auto,
935 DISPLAY("ZSTD_initStaticCDict failed ");
938 cSize = ZSTD_compress_usingCDict(cctx,
939 compressedBuffer, compressedBufferSize,
940 CNBuffer, MIN(10 KB, CNBuffSize), cdict);
941 if (ZSTD_isError(cSize)) {
942 DISPLAY("ZSTD_compress_usingCDict failed ");
947 DISPLAYLEVEL(3, "OK (%u bytes : %.2f%%)\n", (U32)cSize, (double)cSize/CNBuffSize*100);
949 DISPLAYLEVEL(3, "test%3i : ZSTD_compress_usingCDict_advanced, no contentSize, no dictID : ", testNb++);
950 { ZSTD_frameParameters const fParams = { 0 /* frameSize */, 1 /* checksum */, 1 /* noDictID*/ };
951 ZSTD_compressionParameters const cParams = ZSTD_getCParams(1, CNBuffSize, dictSize);
952 ZSTD_CDict* const cdict = ZSTD_createCDict_advanced(dictBuffer, dictSize, ZSTD_dlm_byRef, ZSTD_dct_auto, cParams, ZSTD_defaultCMem);
953 cSize = ZSTD_compress_usingCDict_advanced(cctx, compressedBuffer, compressedBufferSize,
954 CNBuffer, CNBuffSize, cdict, fParams);
955 ZSTD_freeCDict(cdict);
956 if (ZSTD_isError(cSize)) goto _output_error;
958 DISPLAYLEVEL(3, "OK (%u bytes : %.2f%%)\n", (U32)cSize, (double)cSize/CNBuffSize*100);
960 DISPLAYLEVEL(3, "test%3i : try retrieving contentSize from frame : ", testNb++);
961 { U64 const contentSize = ZSTD_getFrameContentSize(compressedBuffer, cSize);
962 if (contentSize != ZSTD_CONTENTSIZE_UNKNOWN) goto _output_error;
964 DISPLAYLEVEL(3, "OK (unknown)\n");
966 DISPLAYLEVEL(3, "test%3i : frame built without dictID should be decompressible : ", testNb++);
967 CHECKPLUS(r, ZSTD_decompress_usingDict(dctx,
968 decodedBuffer, CNBuffSize,
969 compressedBuffer, cSize,
970 dictBuffer, dictSize),
971 if (r != CNBuffSize) goto _output_error);
972 DISPLAYLEVEL(3, "OK \n");
974 DISPLAYLEVEL(3, "test%3i : ZSTD_compress_advanced, no dictID : ", testNb++);
975 { ZSTD_parameters p = ZSTD_getParams(3, CNBuffSize, dictSize);
976 p.fParams.noDictIDFlag = 1;
977 cSize = ZSTD_compress_advanced(cctx, compressedBuffer, compressedBufferSize,
978 CNBuffer, CNBuffSize,
979 dictBuffer, dictSize, p);
980 if (ZSTD_isError(cSize)) goto _output_error;
982 DISPLAYLEVEL(3, "OK (%u bytes : %.2f%%)\n", (U32)cSize, (double)cSize/CNBuffSize*100);
984 DISPLAYLEVEL(3, "test%3i : frame built without dictID should be decompressible : ", testNb++);
985 CHECKPLUS(r, ZSTD_decompress_usingDict(dctx,
986 decodedBuffer, CNBuffSize,
987 compressedBuffer, cSize,
988 dictBuffer, dictSize),
989 if (r != CNBuffSize) goto _output_error);
990 DISPLAYLEVEL(3, "OK \n");
992 DISPLAYLEVEL(3, "test%3i : dictionary containing only header should return error : ", testNb++);
994 const size_t ret = ZSTD_decompress_usingDict(
995 dctx, decodedBuffer, CNBuffSize, compressedBuffer, cSize,
996 "\x37\xa4\x30\xec\x11\x22\x33\x44", 8);
997 if (ZSTD_getErrorCode(ret) != ZSTD_error_dictionary_corrupted) goto _output_error;
999 DISPLAYLEVEL(3, "OK \n");
1001 DISPLAYLEVEL(3, "test%3i : Building cdict w/ ZSTD_dm_fullDict on a good dictionary : ", testNb++);
1002 { ZSTD_compressionParameters const cParams = ZSTD_getCParams(1, CNBuffSize, dictSize);
1003 ZSTD_CDict* const cdict = ZSTD_createCDict_advanced(dictBuffer, dictSize, ZSTD_dlm_byRef, ZSTD_dct_fullDict, cParams, ZSTD_defaultCMem);
1004 if (cdict==NULL) goto _output_error;
1005 ZSTD_freeCDict(cdict);
1007 DISPLAYLEVEL(3, "OK \n");
1009 DISPLAYLEVEL(3, "test%3i : Building cdict w/ ZSTD_dm_fullDict on a rawContent (must fail) : ", testNb++);
1010 { ZSTD_compressionParameters const cParams = ZSTD_getCParams(1, CNBuffSize, dictSize);
1011 ZSTD_CDict* const cdict = ZSTD_createCDict_advanced((const char*)dictBuffer+1, dictSize-1, ZSTD_dlm_byRef, ZSTD_dct_fullDict, cParams, ZSTD_defaultCMem);
1012 if (cdict!=NULL) goto _output_error;
1013 ZSTD_freeCDict(cdict);
1015 DISPLAYLEVEL(3, "OK \n");
1017 DISPLAYLEVEL(3, "test%3i : Loading rawContent starting with dict header w/ ZSTD_dm_auto should fail : ", testNb++);
1020 MEM_writeLE32((char*)dictBuffer+2, ZSTD_MAGIC_DICTIONARY);
1021 ret = ZSTD_CCtx_loadDictionary_advanced(
1022 cctx, (const char*)dictBuffer+2, dictSize-2, ZSTD_dlm_byRef, ZSTD_dct_auto);
1023 if (!ZSTD_isError(ret)) goto _output_error;
1025 DISPLAYLEVEL(3, "OK \n");
1027 DISPLAYLEVEL(3, "test%3i : Loading rawContent starting with dict header w/ ZSTD_dm_rawContent should pass : ", testNb++);
1030 MEM_writeLE32((char*)dictBuffer+2, ZSTD_MAGIC_DICTIONARY);
1031 ret = ZSTD_CCtx_loadDictionary_advanced(
1032 cctx, (const char*)dictBuffer+2, dictSize-2, ZSTD_dlm_byRef, ZSTD_dct_rawContent);
1033 if (ZSTD_isError(ret)) goto _output_error;
1035 DISPLAYLEVEL(3, "OK \n");
1037 DISPLAYLEVEL(3, "test%3i : Dictionary with non-default repcodes : ", testNb++);
1038 { U32 u; for (u=0; u<nbSamples; u++) samplesSizes[u] = sampleUnitSize; }
1039 dictSize = ZDICT_trainFromBuffer(dictBuffer, dictSize,
1040 CNBuffer, samplesSizes, nbSamples);
1041 if (ZDICT_isError(dictSize)) goto _output_error;
1042 /* Set all the repcodes to non-default */
1044 BYTE* dictPtr = (BYTE*)dictBuffer;
1045 BYTE* dictLimit = dictPtr + dictSize - 12;
1046 /* Find the repcodes */
1047 while (dictPtr < dictLimit &&
1048 (MEM_readLE32(dictPtr) != 1 || MEM_readLE32(dictPtr + 4) != 4 ||
1049 MEM_readLE32(dictPtr + 8) != 8)) {
1052 if (dictPtr >= dictLimit) goto _output_error;
1053 MEM_writeLE32(dictPtr + 0, 10);
1054 MEM_writeLE32(dictPtr + 4, 10);
1055 MEM_writeLE32(dictPtr + 8, 10);
1056 /* Set the last 8 bytes to 'x' */
1057 memset((BYTE*)dictBuffer + dictSize - 8, 'x', 8);
1059 /* The optimal parser checks all the repcodes.
1060 * Make sure at least one is a match >= targetLength so that it is
1061 * immediately chosen. This will make sure that the compressor and
1062 * decompressor agree on at least one of the repcodes.
1066 ZSTD_compressionParameters const cParams = ZSTD_getCParams(19, CNBuffSize, dictSize);
1067 ZSTD_CDict* const cdict = ZSTD_createCDict_advanced(dictBuffer, dictSize,
1068 ZSTD_dlm_byRef, ZSTD_dct_auto,
1069 cParams, ZSTD_defaultCMem);
1070 memset(data, 'x', sizeof(data));
1071 cSize = ZSTD_compress_usingCDict(cctx, compressedBuffer, compressedBufferSize,
1072 data, sizeof(data), cdict);
1073 ZSTD_freeCDict(cdict);
1074 if (ZSTD_isError(cSize)) { DISPLAYLEVEL(5, "Compression error %s : ", ZSTD_getErrorName(cSize)); goto _output_error; }
1075 dSize = ZSTD_decompress_usingDict(dctx, decodedBuffer, sizeof(data), compressedBuffer, cSize, dictBuffer, dictSize);
1076 if (ZSTD_isError(dSize)) { DISPLAYLEVEL(5, "Decompression error %s : ", ZSTD_getErrorName(dSize)); goto _output_error; }
1077 if (memcmp(data, decodedBuffer, sizeof(data))) { DISPLAYLEVEL(5, "Data corruption : "); goto _output_error; }
1079 DISPLAYLEVEL(3, "OK \n");
1081 ZSTD_freeCCtx(cctx);
1086 /* COVER dictionary builder tests */
1087 { ZSTD_CCtx* const cctx = ZSTD_createCCtx();
1088 size_t dictSize = 16 KB;
1089 size_t optDictSize = dictSize;
1090 void* dictBuffer = malloc(dictSize);
1091 size_t const totalSampleSize = 1 MB;
1092 size_t const sampleUnitSize = 8 KB;
1093 U32 const nbSamples = (U32)(totalSampleSize / sampleUnitSize);
1094 size_t* const samplesSizes = (size_t*) malloc(nbSamples * sizeof(size_t));
1095 ZDICT_cover_params_t params;
1098 if (dictBuffer==NULL || samplesSizes==NULL) {
1104 DISPLAYLEVEL(3, "test%3i : ZDICT_trainFromBuffer_cover : ", testNb++);
1105 { U32 u; for (u=0; u<nbSamples; u++) samplesSizes[u] = sampleUnitSize; }
1106 memset(¶ms, 0, sizeof(params));
1107 params.d = 1 + (FUZ_rand(&seed) % 16);
1108 params.k = params.d + (FUZ_rand(&seed) % 256);
1109 dictSize = ZDICT_trainFromBuffer_cover(dictBuffer, dictSize,
1110 CNBuffer, samplesSizes, nbSamples,
1112 if (ZDICT_isError(dictSize)) goto _output_error;
1113 DISPLAYLEVEL(3, "OK, created dictionary of size %u \n", (U32)dictSize);
1115 DISPLAYLEVEL(3, "test%3i : check dictID : ", testNb++);
1116 dictID = ZDICT_getDictID(dictBuffer, dictSize);
1117 if (dictID==0) goto _output_error;
1118 DISPLAYLEVEL(3, "OK : %u \n", dictID);
1120 DISPLAYLEVEL(3, "test%3i : ZDICT_optimizeTrainFromBuffer_cover : ", testNb++);
1121 memset(¶ms, 0, sizeof(params));
1123 optDictSize = ZDICT_optimizeTrainFromBuffer_cover(dictBuffer, optDictSize,
1124 CNBuffer, samplesSizes,
1125 nbSamples / 4, ¶ms);
1126 if (ZDICT_isError(optDictSize)) goto _output_error;
1127 DISPLAYLEVEL(3, "OK, created dictionary of size %u \n", (U32)optDictSize);
1129 DISPLAYLEVEL(3, "test%3i : check dictID : ", testNb++);
1130 dictID = ZDICT_getDictID(dictBuffer, optDictSize);
1131 if (dictID==0) goto _output_error;
1132 DISPLAYLEVEL(3, "OK : %u \n", dictID);
1134 ZSTD_freeCCtx(cctx);
1139 /* Decompression defense tests */
1140 DISPLAYLEVEL(3, "test%3i : Check input length for magic number : ", testNb++);
1141 { size_t const r = ZSTD_decompress(decodedBuffer, CNBuffSize, CNBuffer, 3); /* too small input */
1142 if (!ZSTD_isError(r)) goto _output_error;
1143 if (ZSTD_getErrorCode(r) != ZSTD_error_srcSize_wrong) goto _output_error; }
1144 DISPLAYLEVEL(3, "OK \n");
1146 DISPLAYLEVEL(3, "test%3i : Check magic Number : ", testNb++);
1147 ((char*)(CNBuffer))[0] = 1;
1148 { size_t const r = ZSTD_decompress(decodedBuffer, CNBuffSize, CNBuffer, 4);
1149 if (!ZSTD_isError(r)) goto _output_error; }
1150 DISPLAYLEVEL(3, "OK \n");
1152 /* content size verification test */
1153 DISPLAYLEVEL(3, "test%3i : Content size verification : ", testNb++);
1154 { ZSTD_CCtx* const cctx = ZSTD_createCCtx();
1155 size_t const srcSize = 5000;
1156 size_t const wrongSrcSize = (srcSize + 1000);
1157 ZSTD_parameters params = ZSTD_getParams(1, wrongSrcSize, 0);
1158 params.fParams.contentSizeFlag = 1;
1159 CHECK( ZSTD_compressBegin_advanced(cctx, NULL, 0, params, wrongSrcSize) );
1160 { size_t const result = ZSTD_compressEnd(cctx, decodedBuffer, CNBuffSize, CNBuffer, srcSize);
1161 if (!ZSTD_isError(result)) goto _output_error;
1162 if (ZSTD_getErrorCode(result) != ZSTD_error_srcSize_wrong) goto _output_error;
1163 DISPLAYLEVEL(3, "OK : %s \n", ZSTD_getErrorName(result));
1165 ZSTD_freeCCtx(cctx);
1168 /* negative compression level test : ensure simple API and advanced API produce same result */
1169 DISPLAYLEVEL(3, "test%3i : negative compression level : ", testNb++);
1170 { ZSTD_CCtx* const cctx = ZSTD_createCCtx();
1171 size_t const srcSize = CNBuffSize / 5;
1172 int const compressionLevel = -1;
1174 assert(cctx != NULL);
1175 { ZSTD_parameters const params = ZSTD_getParams(compressionLevel, srcSize, 0);
1176 size_t const cSize_1pass = ZSTD_compress_advanced(cctx,
1177 compressedBuffer, compressedBufferSize,
1181 if (ZSTD_isError(cSize_1pass)) goto _output_error;
1183 CHECK( ZSTD_CCtx_setParameter(cctx, ZSTD_p_compressionLevel, (unsigned)compressionLevel) );
1184 { ZSTD_inBuffer in = { CNBuffer, srcSize, 0 };
1185 ZSTD_outBuffer out = { compressedBuffer, compressedBufferSize, 0 };
1186 size_t const compressionResult = ZSTD_compress_generic(cctx, &out, &in, ZSTD_e_end);
1187 DISPLAYLEVEL(5, "simple=%zu vs %zu=advanced : ", cSize_1pass, out.pos);
1188 if (ZSTD_isError(compressionResult)) goto _output_error;
1189 if (out.pos != cSize_1pass) goto _output_error;
1191 ZSTD_freeCCtx(cctx);
1193 DISPLAYLEVEL(3, "OK \n");
1195 /* parameters order test */
1196 { size_t const inputSize = CNBuffSize / 2;
1199 { ZSTD_CCtx* const cctx = ZSTD_createCCtx();
1200 DISPLAYLEVEL(3, "test%3i : parameters in order : ", testNb++);
1201 assert(cctx != NULL);
1202 CHECK( ZSTD_CCtx_setParameter(cctx, ZSTD_p_compressionLevel, 2) );
1203 CHECK( ZSTD_CCtx_setParameter(cctx, ZSTD_p_enableLongDistanceMatching, 1) );
1204 CHECK( ZSTD_CCtx_setParameter(cctx, ZSTD_p_windowLog, 18) );
1205 { ZSTD_inBuffer in = { CNBuffer, inputSize, 0 };
1206 ZSTD_outBuffer out = { compressedBuffer, ZSTD_compressBound(inputSize), 0 };
1207 size_t const result = ZSTD_compress_generic(cctx, &out, &in, ZSTD_e_end);
1208 if (result != 0) goto _output_error;
1209 if (in.pos != in.size) goto _output_error;
1211 xxh64 = XXH64(out.dst, out.pos, 0);
1213 DISPLAYLEVEL(3, "OK (compress : %u -> %u bytes)\n", (U32)inputSize, (U32)cSize);
1214 ZSTD_freeCCtx(cctx);
1217 { ZSTD_CCtx* cctx = ZSTD_createCCtx();
1218 DISPLAYLEVEL(3, "test%3i : parameters disordered : ", testNb++);
1219 CHECK( ZSTD_CCtx_setParameter(cctx, ZSTD_p_windowLog, 18) );
1220 CHECK( ZSTD_CCtx_setParameter(cctx, ZSTD_p_enableLongDistanceMatching, 1) );
1221 CHECK( ZSTD_CCtx_setParameter(cctx, ZSTD_p_compressionLevel, 2) );
1222 { ZSTD_inBuffer in = { CNBuffer, inputSize, 0 };
1223 ZSTD_outBuffer out = { compressedBuffer, ZSTD_compressBound(inputSize), 0 };
1224 size_t const result = ZSTD_compress_generic(cctx, &out, &in, ZSTD_e_end);
1225 if (result != 0) goto _output_error;
1226 if (in.pos != in.size) goto _output_error;
1227 if (out.pos != cSize) goto _output_error; /* must result in same compressed result, hence same size */
1228 if (XXH64(out.dst, out.pos, 0) != xxh64) goto _output_error; /* must result in exactly same content, hence same hash */
1229 DISPLAYLEVEL(3, "OK (compress : %u -> %u bytes)\n", (U32)inputSize, (U32)out.pos);
1231 ZSTD_freeCCtx(cctx);
1235 /* custom formats tests */
1236 { ZSTD_CCtx* const cctx = ZSTD_createCCtx();
1237 size_t const inputSize = CNBuffSize / 2; /* won't cause pb with small dict size */
1239 /* basic block compression */
1240 DISPLAYLEVEL(3, "test%3i : magic-less format test : ", testNb++);
1241 CHECK( ZSTD_CCtx_setParameter(cctx, ZSTD_p_format, ZSTD_f_zstd1_magicless) );
1242 { ZSTD_inBuffer in = { CNBuffer, inputSize, 0 };
1243 ZSTD_outBuffer out = { compressedBuffer, ZSTD_compressBound(inputSize), 0 };
1244 size_t const result = ZSTD_compress_generic(cctx, &out, &in, ZSTD_e_end);
1245 if (result != 0) goto _output_error;
1246 if (in.pos != in.size) goto _output_error;
1249 DISPLAYLEVEL(3, "OK (compress : %u -> %u bytes)\n", (U32)inputSize, (U32)cSize);
1251 DISPLAYLEVEL(3, "test%3i : decompress normally (should fail) : ", testNb++);
1252 { size_t const decodeResult = ZSTD_decompressDCtx(dctx, decodedBuffer, CNBuffSize, compressedBuffer, cSize);
1253 if (ZSTD_getErrorCode(decodeResult) != ZSTD_error_prefix_unknown) goto _output_error;
1254 DISPLAYLEVEL(3, "OK : %s \n", ZSTD_getErrorName(decodeResult));
1257 DISPLAYLEVEL(3, "test%3i : decompress of magic-less frame : ", testNb++);
1258 ZSTD_DCtx_reset(dctx);
1259 CHECK( ZSTD_DCtx_setFormat(dctx, ZSTD_f_zstd1_magicless) );
1260 { ZSTD_frameHeader zfh;
1261 size_t const zfhrt = ZSTD_getFrameHeader_advanced(&zfh, compressedBuffer, cSize, ZSTD_f_zstd1_magicless);
1262 if (zfhrt != 0) goto _output_error;
1264 { ZSTD_inBuffer in = { compressedBuffer, cSize, 0 };
1265 ZSTD_outBuffer out = { decodedBuffer, CNBuffSize, 0 };
1266 size_t const result = ZSTD_decompress_generic(dctx, &out, &in);
1267 if (result != 0) goto _output_error;
1268 if (in.pos != in.size) goto _output_error;
1269 if (out.pos != inputSize) goto _output_error;
1270 DISPLAYLEVEL(3, "OK : regenerated %u bytes \n", (U32)out.pos);
1273 ZSTD_freeCCtx(cctx);
1276 /* block API tests */
1277 { ZSTD_CCtx* const cctx = ZSTD_createCCtx();
1278 static const size_t dictSize = 65 KB;
1279 static const size_t blockSize = 100 KB; /* won't cause pb with small dict size */
1282 /* basic block compression */
1283 DISPLAYLEVEL(3, "test%3i : Block compression test : ", testNb++);
1284 CHECK( ZSTD_compressBegin(cctx, 5) );
1285 CHECK( ZSTD_getBlockSize(cctx) >= blockSize);
1286 cSize = ZSTD_compressBlock(cctx, compressedBuffer, ZSTD_compressBound(blockSize), CNBuffer, blockSize);
1287 if (ZSTD_isError(cSize)) goto _output_error;
1288 DISPLAYLEVEL(3, "OK \n");
1290 DISPLAYLEVEL(3, "test%3i : Block decompression test : ", testNb++);
1291 CHECK( ZSTD_decompressBegin(dctx) );
1292 { CHECK_V(r, ZSTD_decompressBlock(dctx, decodedBuffer, CNBuffSize, compressedBuffer, cSize) );
1293 if (r != blockSize) goto _output_error; }
1294 DISPLAYLEVEL(3, "OK \n");
1296 /* very long stream of block compression */
1297 DISPLAYLEVEL(3, "test%3i : Huge block streaming compression test : ", testNb++);
1298 CHECK( ZSTD_compressBegin(cctx, -99) ); /* we just want to quickly overflow internal U32 index */
1299 CHECK( ZSTD_getBlockSize(cctx) >= blockSize);
1300 { U64 const toCompress = 5000000000ULL; /* > 4 GB */
1302 while (compressed < toCompress) {
1303 size_t const blockCSize = ZSTD_compressBlock(cctx, compressedBuffer, ZSTD_compressBound(blockSize), CNBuffer, blockSize);
1304 if (ZSTD_isError(cSize)) goto _output_error;
1305 compressed += blockCSize;
1308 DISPLAYLEVEL(3, "OK \n");
1310 /* dictionary block compression */
1311 DISPLAYLEVEL(3, "test%3i : Dictionary Block compression test : ", testNb++);
1312 CHECK( ZSTD_compressBegin_usingDict(cctx, CNBuffer, dictSize, 5) );
1313 cSize = ZSTD_compressBlock(cctx, compressedBuffer, ZSTD_compressBound(blockSize), (char*)CNBuffer+dictSize, blockSize);
1314 if (ZSTD_isError(cSize)) goto _output_error;
1315 cSize2 = ZSTD_compressBlock(cctx, (char*)compressedBuffer+cSize, ZSTD_compressBound(blockSize), (char*)CNBuffer+dictSize+blockSize, blockSize);
1316 if (ZSTD_isError(cSize2)) goto _output_error;
1317 memcpy((char*)compressedBuffer+cSize, (char*)CNBuffer+dictSize+blockSize, blockSize); /* fake non-compressed block */
1318 cSize2 = ZSTD_compressBlock(cctx, (char*)compressedBuffer+cSize+blockSize, ZSTD_compressBound(blockSize),
1319 (char*)CNBuffer+dictSize+2*blockSize, blockSize);
1320 if (ZSTD_isError(cSize2)) goto _output_error;
1321 DISPLAYLEVEL(3, "OK \n");
1323 DISPLAYLEVEL(3, "test%3i : Dictionary Block decompression test : ", testNb++);
1324 CHECK( ZSTD_decompressBegin_usingDict(dctx, CNBuffer, dictSize) );
1325 { CHECK_V( r, ZSTD_decompressBlock(dctx, decodedBuffer, CNBuffSize, compressedBuffer, cSize) );
1326 if (r != blockSize) goto _output_error; }
1327 ZSTD_insertBlock(dctx, (char*)decodedBuffer+blockSize, blockSize); /* insert non-compressed block into dctx history */
1328 { CHECK_V( r, ZSTD_decompressBlock(dctx, (char*)decodedBuffer+2*blockSize, CNBuffSize, (char*)compressedBuffer+cSize+blockSize, cSize2) );
1329 if (r != blockSize) goto _output_error; }
1330 DISPLAYLEVEL(3, "OK \n");
1332 DISPLAYLEVEL(3, "test%3i : Block compression with CDict : ", testNb++);
1333 { ZSTD_CDict* const cdict = ZSTD_createCDict(CNBuffer, dictSize, 3);
1334 if (cdict==NULL) goto _output_error;
1335 CHECK( ZSTD_compressBegin_usingCDict(cctx, cdict) );
1336 CHECK( ZSTD_compressBlock(cctx, compressedBuffer, ZSTD_compressBound(blockSize), (char*)CNBuffer+dictSize, blockSize) );
1337 ZSTD_freeCDict(cdict);
1339 DISPLAYLEVEL(3, "OK \n");
1341 ZSTD_freeCCtx(cctx);
1343 ZSTD_freeDCtx(dctx);
1346 { size_t sampleSize = 0;
1347 DISPLAYLEVEL(3, "test%3i : Long RLE test : ", testNb++);
1348 RDG_genBuffer(CNBuffer, sampleSize, compressibility, 0., seed+1);
1349 memset((char*)CNBuffer+sampleSize, 'B', 256 KB - 1);
1350 sampleSize += 256 KB - 1;
1351 RDG_genBuffer((char*)CNBuffer+sampleSize, 96 KB, compressibility, 0., seed+2);
1352 sampleSize += 96 KB;
1353 cSize = ZSTD_compress(compressedBuffer, ZSTD_compressBound(sampleSize), CNBuffer, sampleSize, 1);
1354 if (ZSTD_isError(cSize)) goto _output_error;
1355 { CHECK_V(regenSize, ZSTD_decompress(decodedBuffer, sampleSize, compressedBuffer, cSize));
1356 if (regenSize!=sampleSize) goto _output_error; }
1357 DISPLAYLEVEL(3, "OK \n");
1360 /* All zeroes test (test bug #137) */
1361 #define ZEROESLENGTH 100
1362 DISPLAYLEVEL(3, "test%3i : compress %u zeroes : ", testNb++, ZEROESLENGTH);
1363 memset(CNBuffer, 0, ZEROESLENGTH);
1364 { CHECK_V(r, ZSTD_compress(compressedBuffer, ZSTD_compressBound(ZEROESLENGTH), CNBuffer, ZEROESLENGTH, 1) );
1366 DISPLAYLEVEL(3, "OK (%u bytes : %.2f%%)\n", (U32)cSize, (double)cSize/ZEROESLENGTH*100);
1368 DISPLAYLEVEL(3, "test%3i : decompress %u zeroes : ", testNb++, ZEROESLENGTH);
1369 { CHECK_V(r, ZSTD_decompress(decodedBuffer, ZEROESLENGTH, compressedBuffer, cSize) );
1370 if (r != ZEROESLENGTH) goto _output_error; }
1371 DISPLAYLEVEL(3, "OK \n");
1373 /* nbSeq limit test */
1374 #define _3BYTESTESTLENGTH 131000
1375 #define NB3BYTESSEQLOG 9
1376 #define NB3BYTESSEQ (1 << NB3BYTESSEQLOG)
1377 #define NB3BYTESSEQMASK (NB3BYTESSEQ-1)
1378 /* creates a buffer full of 3-bytes sequences */
1379 { BYTE _3BytesSeqs[NB3BYTESSEQ][3];
1382 /* create batch of 3-bytes sequences */
1384 for (i=0; i < NB3BYTESSEQ; i++) {
1385 _3BytesSeqs[i][0] = (BYTE)(FUZ_rand(&rSeed) & 255);
1386 _3BytesSeqs[i][1] = (BYTE)(FUZ_rand(&rSeed) & 255);
1387 _3BytesSeqs[i][2] = (BYTE)(FUZ_rand(&rSeed) & 255);
1390 /* randomly fills CNBuffer with prepared 3-bytes sequences */
1392 for (i=0; i < _3BYTESTESTLENGTH; i += 3) { /* note : CNBuffer size > _3BYTESTESTLENGTH+3 */
1393 U32 const id = FUZ_rand(&rSeed) & NB3BYTESSEQMASK;
1394 ((BYTE*)CNBuffer)[i+0] = _3BytesSeqs[id][0];
1395 ((BYTE*)CNBuffer)[i+1] = _3BytesSeqs[id][1];
1396 ((BYTE*)CNBuffer)[i+2] = _3BytesSeqs[id][2];
1398 DISPLAYLEVEL(3, "test%3i : growing nbSeq : ", testNb++);
1399 { ZSTD_CCtx* const cctx = ZSTD_createCCtx();
1400 size_t const maxNbSeq = _3BYTESTESTLENGTH / 3;
1401 size_t const bound = ZSTD_compressBound(_3BYTESTESTLENGTH);
1403 while (nbSeq <= maxNbSeq) {
1404 CHECK(ZSTD_compressCCtx(cctx, compressedBuffer, bound, CNBuffer, nbSeq * 3, 19));
1405 /* Check every sequence for the first 100, then skip more rapidly. */
1409 nbSeq += (nbSeq >> 2);
1412 ZSTD_freeCCtx(cctx);
1414 DISPLAYLEVEL(3, "OK \n");
1416 DISPLAYLEVEL(3, "test%3i : compress lots 3-bytes sequences : ", testNb++);
1417 { CHECK_V(r, ZSTD_compress(compressedBuffer, ZSTD_compressBound(_3BYTESTESTLENGTH),
1418 CNBuffer, _3BYTESTESTLENGTH, 19) );
1420 DISPLAYLEVEL(3, "OK (%u bytes : %.2f%%)\n", (U32)cSize, (double)cSize/_3BYTESTESTLENGTH*100);
1422 DISPLAYLEVEL(3, "test%3i : decompress lots 3-bytes sequence : ", testNb++);
1423 { CHECK_V(r, ZSTD_decompress(decodedBuffer, _3BYTESTESTLENGTH, compressedBuffer, cSize) );
1424 if (r != _3BYTESTESTLENGTH) goto _output_error; }
1425 DISPLAYLEVEL(3, "OK \n");
1428 DISPLAYLEVEL(3, "test%3i : growing literals buffer : ", testNb++);
1429 RDG_genBuffer(CNBuffer, CNBuffSize, 0.0, 0.1, seed);
1430 { ZSTD_CCtx* const cctx = ZSTD_createCCtx();
1431 size_t const bound = ZSTD_compressBound(CNBuffSize);
1433 while (size <= CNBuffSize) {
1434 CHECK(ZSTD_compressCCtx(cctx, compressedBuffer, bound, CNBuffer, size, 3));
1435 /* Check every size for the first 100, then skip more rapidly. */
1439 size += (size >> 2);
1442 ZSTD_freeCCtx(cctx);
1444 DISPLAYLEVEL(3, "OK \n");
1446 DISPLAYLEVEL(3, "test%3i : incompressible data and ill suited dictionary : ", testNb++);
1447 { /* Train a dictionary on low characters */
1448 size_t dictSize = 16 KB;
1449 void* const dictBuffer = malloc(dictSize);
1450 size_t const totalSampleSize = 1 MB;
1451 size_t const sampleUnitSize = 8 KB;
1452 U32 const nbSamples = (U32)(totalSampleSize / sampleUnitSize);
1453 size_t* const samplesSizes = (size_t*) malloc(nbSamples * sizeof(size_t));
1454 if (!dictBuffer || !samplesSizes) goto _output_error;
1455 { U32 u; for (u=0; u<nbSamples; u++) samplesSizes[u] = sampleUnitSize; }
1456 dictSize = ZDICT_trainFromBuffer(dictBuffer, dictSize, CNBuffer, samplesSizes, nbSamples);
1457 if (ZDICT_isError(dictSize)) goto _output_error;
1458 /* Reverse the characters to make the dictionary ill suited */
1460 for (u = 0; u < CNBuffSize; ++u) {
1461 ((BYTE*)CNBuffer)[u] = 255 - ((BYTE*)CNBuffer)[u];
1464 { /* Compress the data */
1465 size_t const inputSize = 500;
1466 size_t const outputSize = ZSTD_compressBound(inputSize);
1467 void* const outputBuffer = malloc(outputSize);
1468 ZSTD_CCtx* const cctx = ZSTD_createCCtx();
1469 if (!outputBuffer || !cctx) goto _output_error;
1470 CHECK(ZSTD_compress_usingDict(cctx, outputBuffer, outputSize, CNBuffer, inputSize, dictBuffer, dictSize, 1));
1472 ZSTD_freeCCtx(cctx);
1478 DISPLAYLEVEL(3, "OK \n");
1481 /* findFrameCompressedSize on skippable frames */
1482 DISPLAYLEVEL(3, "test%3i : frame compressed size of skippable frame : ", testNb++);
1483 { const char* frame = "\x50\x2a\x4d\x18\x05\x0\x0\0abcde";
1484 size_t const frameSrcSize = 13;
1485 if (ZSTD_findFrameCompressedSize(frame, frameSrcSize) != frameSrcSize) goto _output_error; }
1486 DISPLAYLEVEL(3, "OK \n");
1488 /* error string tests */
1489 DISPLAYLEVEL(3, "test%3i : testing ZSTD error code strings : ", testNb++);
1490 if (strcmp("No error detected", ZSTD_getErrorName((ZSTD_ErrorCode)(0-ZSTD_error_no_error))) != 0) goto _output_error;
1491 if (strcmp("No error detected", ZSTD_getErrorString(ZSTD_error_no_error)) != 0) goto _output_error;
1492 if (strcmp("Unspecified error code", ZSTD_getErrorString((ZSTD_ErrorCode)(0-ZSTD_error_GENERIC))) != 0) goto _output_error;
1493 if (strcmp("Error (generic)", ZSTD_getErrorName((size_t)0-ZSTD_error_GENERIC)) != 0) goto _output_error;
1494 if (strcmp("Error (generic)", ZSTD_getErrorString(ZSTD_error_GENERIC)) != 0) goto _output_error;
1495 if (strcmp("No error detected", ZSTD_getErrorName(ZSTD_error_GENERIC)) != 0) goto _output_error;
1496 DISPLAYLEVEL(3, "OK \n");
1498 DISPLAYLEVEL(3, "test%3i : testing ZSTD dictionary sizes : ", testNb++);
1499 RDG_genBuffer(CNBuffer, CNBuffSize, compressibility, 0., seed);
1501 size_t const size = MIN(128 KB, CNBuffSize);
1502 ZSTD_CCtx* const cctx = ZSTD_createCCtx();
1503 ZSTD_CDict* const lgCDict = ZSTD_createCDict(CNBuffer, size, 1);
1504 ZSTD_CDict* const smCDict = ZSTD_createCDict(CNBuffer, 1 KB, 1);
1505 ZSTD_frameHeader lgHeader;
1506 ZSTD_frameHeader smHeader;
1508 CHECK_Z(ZSTD_compress_usingCDict(cctx, compressedBuffer, compressedBufferSize, CNBuffer, size, lgCDict));
1509 CHECK_Z(ZSTD_getFrameHeader(&lgHeader, compressedBuffer, compressedBufferSize));
1510 CHECK_Z(ZSTD_compress_usingCDict(cctx, compressedBuffer, compressedBufferSize, CNBuffer, size, smCDict));
1511 CHECK_Z(ZSTD_getFrameHeader(&smHeader, compressedBuffer, compressedBufferSize));
1513 if (lgHeader.windowSize != smHeader.windowSize) goto _output_error;
1515 ZSTD_freeCDict(smCDict);
1516 ZSTD_freeCDict(lgCDict);
1517 ZSTD_freeCCtx(cctx);
1519 DISPLAYLEVEL(3, "OK \n");
1521 DISPLAYLEVEL(3, "test%3i : testing FSE_normalizeCount() PR#1255: ", testNb++);
1525 unsigned const tableLog = 5;
1526 size_t const nbSeq = 32;
1527 unsigned const maxSymbolValue = 31;
1530 for (i = 0; i < 32; ++i)
1532 /* Calling FSE_normalizeCount() on a uniform distribution should not
1533 * cause a division by zero.
1535 FSE_normalizeCount(norm, tableLog, count, nbSeq, maxSymbolValue);
1537 DISPLAYLEVEL(3, "OK \n");
1541 free(compressedBuffer);
1542 free(decodedBuffer);
1547 DISPLAY("Error detected in Unit tests ! \n");
1552 static size_t findDiff(const void* buf1, const void* buf2, size_t max)
1554 const BYTE* b1 = (const BYTE*)buf1;
1555 const BYTE* b2 = (const BYTE*)buf2;
1557 for (u=0; u<max; u++) {
1558 if (b1[u] != b2[u]) break;
1564 static ZSTD_parameters FUZ_makeParams(ZSTD_compressionParameters cParams, ZSTD_frameParameters fParams)
1566 ZSTD_parameters params;
1567 params.cParams = cParams;
1568 params.fParams = fParams;
1572 static size_t FUZ_rLogLength(U32* seed, U32 logLength)
1574 size_t const lengthMask = ((size_t)1 << logLength) - 1;
1575 return (lengthMask+1) + (FUZ_rand(seed) & lengthMask);
1578 static size_t FUZ_randomLength(U32* seed, U32 maxLog)
1580 U32 const logLength = FUZ_rand(seed) % maxLog;
1581 return FUZ_rLogLength(seed, logLength);
1585 #define CHECK(cond, ...) { \
1587 DISPLAY("Error => "); \
1588 DISPLAY(__VA_ARGS__); \
1589 DISPLAY(" (seed %u, test nb %u) \n", seed, testNb); \
1590 goto _output_error; \
1594 #define CHECK_Z(f) { \
1595 size_t const err = f; \
1596 if (ZSTD_isError(err)) { \
1597 DISPLAY("Error => %s : %s ", \
1598 #f, ZSTD_getErrorName(err)); \
1599 DISPLAY(" (seed %u, test nb %u) \n", seed, testNb); \
1600 goto _output_error; \
1604 static int fuzzerTests(U32 seed, U32 nbTests, unsigned startTest, U32 const maxDurationS, double compressibility, int bigTests)
1606 static const U32 maxSrcLog = 23;
1607 static const U32 maxSampleLog = 22;
1608 size_t const srcBufferSize = (size_t)1<<maxSrcLog;
1609 size_t const dstBufferSize = (size_t)1<<maxSampleLog;
1610 size_t const cBufferSize = ZSTD_compressBound(dstBufferSize);
1611 BYTE* cNoiseBuffer[5];
1612 BYTE* const cBuffer = (BYTE*) malloc (cBufferSize);
1613 BYTE* const dstBuffer = (BYTE*) malloc (dstBufferSize);
1614 BYTE* const mirrorBuffer = (BYTE*) malloc (dstBufferSize);
1615 ZSTD_CCtx* const refCtx = ZSTD_createCCtx();
1616 ZSTD_CCtx* const ctx = ZSTD_createCCtx();
1617 ZSTD_DCtx* const dctx = ZSTD_createDCtx();
1620 U32 coreSeed = seed;
1621 UTIL_time_t const startClock = UTIL_getTime();
1622 U64 const maxClockSpan = maxDurationS * SEC_TO_MICRO;
1623 int const cLevelLimiter = bigTests ? 3 : 2;
1626 cNoiseBuffer[0] = (BYTE*)malloc (srcBufferSize);
1627 cNoiseBuffer[1] = (BYTE*)malloc (srcBufferSize);
1628 cNoiseBuffer[2] = (BYTE*)malloc (srcBufferSize);
1629 cNoiseBuffer[3] = (BYTE*)malloc (srcBufferSize);
1630 cNoiseBuffer[4] = (BYTE*)malloc (srcBufferSize);
1631 CHECK (!cNoiseBuffer[0] || !cNoiseBuffer[1] || !cNoiseBuffer[2] || !cNoiseBuffer[3] || !cNoiseBuffer[4]
1632 || !dstBuffer || !mirrorBuffer || !cBuffer || !refCtx || !ctx || !dctx,
1633 "Not enough memory, fuzzer tests cancelled");
1635 /* Create initial samples */
1636 RDG_genBuffer(cNoiseBuffer[0], srcBufferSize, 0.00, 0., coreSeed); /* pure noise */
1637 RDG_genBuffer(cNoiseBuffer[1], srcBufferSize, 0.05, 0., coreSeed); /* barely compressible */
1638 RDG_genBuffer(cNoiseBuffer[2], srcBufferSize, compressibility, 0., coreSeed);
1639 RDG_genBuffer(cNoiseBuffer[3], srcBufferSize, 0.95, 0., coreSeed); /* highly compressible */
1640 RDG_genBuffer(cNoiseBuffer[4], srcBufferSize, 1.00, 0., coreSeed); /* sparse content */
1642 /* catch up testNb */
1643 for (testNb=1; testNb < startTest; testNb++) FUZ_rand(&coreSeed);
1645 /* main test loop */
1646 for ( ; (testNb <= nbTests) || (UTIL_clockSpanMicro(startClock) < maxClockSpan); testNb++ ) {
1647 BYTE* srcBuffer; /* jumping pointer */
1649 size_t sampleSize, maxTestSize, totalTestSize;
1650 size_t cSize, totalCSize, totalGenSize;
1657 if (nbTests >= testNb) { DISPLAYUPDATE(2, "\r%6u/%6u ", testNb, nbTests); }
1658 else { DISPLAYUPDATE(2, "\r%6u ", testNb); }
1660 FUZ_rand(&coreSeed);
1661 { U32 const prime1 = 2654435761U; lseed = coreSeed ^ prime1; }
1663 /* srcBuffer selection [0-4] */
1664 { U32 buffNb = FUZ_rand(&lseed) & 0x7F;
1665 if (buffNb & 7) buffNb=2; /* most common : compressible (P) */
1669 const U32 tnb[2] = { 1, 3 }; /* barely/highly compressible */
1670 buffNb = tnb[buffNb >> 3];
1672 const U32 tnb[2] = { 0, 4 }; /* not compressible / sparse */
1673 buffNb = tnb[buffNb >> 3];
1675 srcBuffer = cNoiseBuffer[buffNb];
1678 /* select src segment */
1679 sampleSize = FUZ_randomLength(&lseed, maxSampleLog);
1681 /* create sample buffer (to catch read error with valgrind & sanitizers) */
1682 sampleBuffer = (BYTE*)malloc(sampleSize);
1683 CHECK(sampleBuffer==NULL, "not enough memory for sample buffer");
1684 { size_t const sampleStart = FUZ_rand(&lseed) % (srcBufferSize - sampleSize);
1685 memcpy(sampleBuffer, srcBuffer + sampleStart, sampleSize); }
1686 crcOrig = XXH64(sampleBuffer, sampleSize, 0);
1688 /* compression tests */
1689 { int const cLevelPositive =
1690 ( FUZ_rand(&lseed) %
1691 (ZSTD_maxCLevel() - (FUZ_highbit32((U32)sampleSize) / cLevelLimiter)) )
1693 int const cLevel = ((FUZ_rand(&lseed) & 15) == 3) ?
1694 - (int)((FUZ_rand(&lseed) & 7) + 1) : /* test negative cLevel */
1696 DISPLAYLEVEL(5, "fuzzer t%u: Simple compression test (level %i) \n", testNb, cLevel);
1697 cSize = ZSTD_compressCCtx(ctx, cBuffer, cBufferSize, sampleBuffer, sampleSize, cLevel);
1698 CHECK(ZSTD_isError(cSize), "ZSTD_compressCCtx failed : %s", ZSTD_getErrorName(cSize));
1700 /* compression failure test : too small dest buffer */
1702 const size_t missing = (FUZ_rand(&lseed) % (cSize-2)) + 1; /* no problem, as cSize > 4 (frameHeaderSizer) */
1703 const size_t tooSmallSize = cSize - missing;
1704 const U32 endMark = 0x4DC2B1A9;
1705 memcpy(dstBuffer+tooSmallSize, &endMark, 4);
1706 { size_t const errorCode = ZSTD_compressCCtx(ctx, dstBuffer, tooSmallSize, sampleBuffer, sampleSize, cLevel);
1707 CHECK(!ZSTD_isError(errorCode), "ZSTD_compressCCtx should have failed ! (buffer too small : %u < %u)", (U32)tooSmallSize, (U32)cSize); }
1708 { U32 endCheck; memcpy(&endCheck, dstBuffer+tooSmallSize, 4);
1709 CHECK(endCheck != endMark, "ZSTD_compressCCtx : dst buffer overflow"); }
1712 /* frame header decompression test */
1713 { ZSTD_frameHeader zfh;
1714 CHECK_Z( ZSTD_getFrameHeader(&zfh, cBuffer, cSize) );
1715 CHECK(zfh.frameContentSize != sampleSize, "Frame content size incorrect");
1718 /* Decompressed size test */
1719 { unsigned long long const rSize = ZSTD_findDecompressedSize(cBuffer, cSize);
1720 CHECK(rSize != sampleSize, "decompressed size incorrect");
1723 /* successful decompression test */
1724 DISPLAYLEVEL(5, "fuzzer t%u: simple decompression test \n", testNb);
1725 { size_t const margin = (FUZ_rand(&lseed) & 1) ? 0 : (FUZ_rand(&lseed) & 31) + 1;
1726 size_t const dSize = ZSTD_decompress(dstBuffer, sampleSize + margin, cBuffer, cSize);
1727 CHECK(dSize != sampleSize, "ZSTD_decompress failed (%s) (srcSize : %u ; cSize : %u)", ZSTD_getErrorName(dSize), (U32)sampleSize, (U32)cSize);
1728 { U64 const crcDest = XXH64(dstBuffer, sampleSize, 0);
1729 CHECK(crcOrig != crcDest, "decompression result corrupted (pos %u / %u)", (U32)findDiff(sampleBuffer, dstBuffer, sampleSize), (U32)sampleSize);
1732 free(sampleBuffer); /* no longer useful after this point */
1734 /* truncated src decompression test */
1735 DISPLAYLEVEL(5, "fuzzer t%u: decompression of truncated source \n", testNb);
1736 { size_t const missing = (FUZ_rand(&lseed) % (cSize-2)) + 1; /* no problem, as cSize > 4 (frameHeaderSizer) */
1737 size_t const tooSmallSize = cSize - missing;
1738 void* cBufferTooSmall = malloc(tooSmallSize); /* valgrind will catch read overflows */
1739 CHECK(cBufferTooSmall == NULL, "not enough memory !");
1740 memcpy(cBufferTooSmall, cBuffer, tooSmallSize);
1741 { size_t const errorCode = ZSTD_decompress(dstBuffer, dstBufferSize, cBufferTooSmall, tooSmallSize);
1742 CHECK(!ZSTD_isError(errorCode), "ZSTD_decompress should have failed ! (truncated src buffer)"); }
1743 free(cBufferTooSmall);
1746 /* too small dst decompression test */
1747 DISPLAYLEVEL(5, "fuzzer t%u: decompress into too small dst buffer \n", testNb);
1748 if (sampleSize > 3) {
1749 size_t const missing = (FUZ_rand(&lseed) % (sampleSize-2)) + 1; /* no problem, as cSize > 4 (frameHeaderSizer) */
1750 size_t const tooSmallSize = sampleSize - missing;
1751 static const BYTE token = 0xA9;
1752 dstBuffer[tooSmallSize] = token;
1753 { size_t const errorCode = ZSTD_decompress(dstBuffer, tooSmallSize, cBuffer, cSize);
1754 CHECK(!ZSTD_isError(errorCode), "ZSTD_decompress should have failed : %u > %u (dst buffer too small)", (U32)errorCode, (U32)tooSmallSize); }
1755 CHECK(dstBuffer[tooSmallSize] != token, "ZSTD_decompress : dst buffer overflow");
1758 /* noisy src decompression test */
1760 /* insert noise into src */
1761 { U32 const maxNbBits = FUZ_highbit32((U32)(cSize-4));
1762 size_t pos = 4; /* preserve magic number (too easy to detect) */
1764 /* keep some original src */
1765 { U32 const nbBits = FUZ_rand(&lseed) % maxNbBits;
1766 size_t const mask = (1<<nbBits) - 1;
1767 size_t const skipLength = FUZ_rand(&lseed) & mask;
1770 if (pos >= cSize) break;
1772 { U32 const nbBitsCodes = FUZ_rand(&lseed) % maxNbBits;
1773 U32 const nbBits = nbBitsCodes ? nbBitsCodes-1 : 0;
1774 size_t const mask = (1<<nbBits) - 1;
1775 size_t const rNoiseLength = (FUZ_rand(&lseed) & mask) + 1;
1776 size_t const noiseLength = MIN(rNoiseLength, cSize-pos);
1777 size_t const noiseStart = FUZ_rand(&lseed) % (srcBufferSize - noiseLength);
1778 memcpy(cBuffer + pos, srcBuffer + noiseStart, noiseLength);
1782 /* decompress noisy source */
1783 DISPLAYLEVEL(5, "fuzzer t%u: decompress noisy source \n", testNb);
1784 { U32 const endMark = 0xA9B1C3D6;
1785 memcpy(dstBuffer+sampleSize, &endMark, 4);
1786 { size_t const decompressResult = ZSTD_decompress(dstBuffer, sampleSize, cBuffer, cSize);
1787 /* result *may* be an unlikely success, but even then, it must strictly respect dst buffer boundaries */
1788 CHECK((!ZSTD_isError(decompressResult)) && (decompressResult>sampleSize),
1789 "ZSTD_decompress on noisy src : result is too large : %u > %u (dst buffer)", (U32)decompressResult, (U32)sampleSize);
1791 { U32 endCheck; memcpy(&endCheck, dstBuffer+sampleSize, 4);
1792 CHECK(endMark!=endCheck, "ZSTD_decompress on noisy src : dst buffer overflow");
1793 } } } /* noisy src decompression test */
1795 /*===== Bufferless streaming compression test, scattered segments and dictionary =====*/
1796 DISPLAYLEVEL(5, "fuzzer t%u: Bufferless streaming compression test \n", testNb);
1797 { U32 const testLog = FUZ_rand(&lseed) % maxSrcLog;
1798 U32 const dictLog = FUZ_rand(&lseed) % maxSrcLog;
1799 int const cLevel = (FUZ_rand(&lseed) %
1801 (MAX(testLog, dictLog) / cLevelLimiter))) +
1803 maxTestSize = FUZ_rLogLength(&lseed, testLog);
1804 if (maxTestSize >= dstBufferSize) maxTestSize = dstBufferSize-1;
1806 dictSize = FUZ_rLogLength(&lseed, dictLog); /* needed also for decompression */
1807 dict = srcBuffer + (FUZ_rand(&lseed) % (srcBufferSize - dictSize));
1809 DISPLAYLEVEL(6, "fuzzer t%u: Compressing up to <=%u bytes at level %i with dictionary size %u \n",
1810 testNb, (U32)maxTestSize, cLevel, (U32)dictSize);
1812 if (FUZ_rand(&lseed) & 0xF) {
1813 CHECK_Z ( ZSTD_compressBegin_usingDict(refCtx, dict, dictSize, cLevel) );
1815 ZSTD_compressionParameters const cPar = ZSTD_getCParams(cLevel, ZSTD_CONTENTSIZE_UNKNOWN, dictSize);
1816 ZSTD_frameParameters const fPar = { FUZ_rand(&lseed)&1 /* contentSizeFlag */,
1817 !(FUZ_rand(&lseed)&3) /* contentChecksumFlag*/,
1818 0 /*NodictID*/ }; /* note : since dictionary is fake, dictIDflag has no impact */
1819 ZSTD_parameters const p = FUZ_makeParams(cPar, fPar);
1820 CHECK_Z ( ZSTD_compressBegin_advanced(refCtx, dict, dictSize, p, 0) );
1822 CHECK_Z( ZSTD_copyCCtx(ctx, refCtx, 0) );
1825 { U32 const nbChunks = (FUZ_rand(&lseed) & 127) + 2;
1827 XXH64_state_t xxhState;
1828 XXH64_reset(&xxhState, 0);
1829 for (totalTestSize=0, cSize=0, n=0 ; n<nbChunks ; n++) {
1830 size_t const segmentSize = FUZ_randomLength(&lseed, maxSampleLog);
1831 size_t const segmentStart = FUZ_rand(&lseed) % (srcBufferSize - segmentSize);
1833 if (cBufferSize-cSize < ZSTD_compressBound(segmentSize)) break; /* avoid invalid dstBufferTooSmall */
1834 if (totalTestSize+segmentSize > maxTestSize) break;
1836 { size_t const compressResult = ZSTD_compressContinue(ctx, cBuffer+cSize, cBufferSize-cSize, srcBuffer+segmentStart, segmentSize);
1837 CHECK (ZSTD_isError(compressResult), "multi-segments compression error : %s", ZSTD_getErrorName(compressResult));
1838 cSize += compressResult;
1840 XXH64_update(&xxhState, srcBuffer+segmentStart, segmentSize);
1841 memcpy(mirrorBuffer + totalTestSize, srcBuffer+segmentStart, segmentSize);
1842 totalTestSize += segmentSize;
1845 { size_t const flushResult = ZSTD_compressEnd(ctx, cBuffer+cSize, cBufferSize-cSize, NULL, 0);
1846 CHECK (ZSTD_isError(flushResult), "multi-segments epilogue error : %s", ZSTD_getErrorName(flushResult));
1847 cSize += flushResult;
1849 crcOrig = XXH64_digest(&xxhState);
1852 /* streaming decompression test */
1853 DISPLAYLEVEL(5, "fuzzer t%u: Bufferless streaming decompression test \n", testNb);
1854 /* ensure memory requirement is good enough (should always be true) */
1855 { ZSTD_frameHeader zfh;
1856 CHECK( ZSTD_getFrameHeader(&zfh, cBuffer, ZSTD_frameHeaderSize_max),
1857 "ZSTD_getFrameHeader(): error retrieving frame information");
1858 { size_t const roundBuffSize = ZSTD_decodingBufferSize_min(zfh.windowSize, zfh.frameContentSize);
1859 CHECK_Z(roundBuffSize);
1860 CHECK((roundBuffSize > totalTestSize) && (zfh.frameContentSize!=ZSTD_CONTENTSIZE_UNKNOWN),
1861 "ZSTD_decodingBufferSize_min() requires more memory (%u) than necessary (%u)",
1862 (U32)roundBuffSize, (U32)totalTestSize );
1864 if (dictSize<8) dictSize=0, dict=NULL; /* disable dictionary */
1865 CHECK_Z( ZSTD_decompressBegin_usingDict(dctx, dict, dictSize) );
1868 while (totalCSize < cSize) {
1869 size_t const inSize = ZSTD_nextSrcSizeToDecompress(dctx);
1870 size_t const genSize = ZSTD_decompressContinue(dctx, dstBuffer+totalGenSize, dstBufferSize-totalGenSize, cBuffer+totalCSize, inSize);
1871 CHECK (ZSTD_isError(genSize), "ZSTD_decompressContinue error : %s", ZSTD_getErrorName(genSize));
1872 totalGenSize += genSize;
1873 totalCSize += inSize;
1875 CHECK (ZSTD_nextSrcSizeToDecompress(dctx) != 0, "frame not fully decoded");
1876 CHECK (totalGenSize != totalTestSize, "streaming decompressed data : wrong size")
1877 CHECK (totalCSize != cSize, "compressed data should be fully read")
1878 { U64 const crcDest = XXH64(dstBuffer, totalTestSize, 0);
1879 CHECK(crcOrig != crcDest, "streaming decompressed data corrupted (pos %u / %u)",
1880 (U32)findDiff(mirrorBuffer, dstBuffer, totalTestSize), (U32)totalTestSize);
1882 } /* for ( ; (testNb <= nbTests) */
1883 DISPLAY("\r%u fuzzer tests completed \n", testNb-1);
1886 ZSTD_freeCCtx(refCtx);
1888 ZSTD_freeDCtx(dctx);
1889 free(cNoiseBuffer[0]);
1890 free(cNoiseBuffer[1]);
1891 free(cNoiseBuffer[2]);
1892 free(cNoiseBuffer[3]);
1893 free(cNoiseBuffer[4]);
1905 /*_*******************************************************
1907 *********************************************************/
1908 static int FUZ_usage(const char* programName)
1910 DISPLAY( "Usage :\n");
1911 DISPLAY( " %s [args]\n", programName);
1913 DISPLAY( "Arguments :\n");
1914 DISPLAY( " -i# : Nb of tests (default:%u) \n", nbTestsDefault);
1915 DISPLAY( " -s# : Select seed (default:prompt user)\n");
1916 DISPLAY( " -t# : Select starting test number (default:0)\n");
1917 DISPLAY( " -P# : Select compressibility in %% (default:%u%%)\n", FUZ_compressibility_default);
1918 DISPLAY( " -v : verbose\n");
1919 DISPLAY( " -p : pause at the end\n");
1920 DISPLAY( " -h : display help and exit\n");
1924 /*! readU32FromChar() :
1925 @return : unsigned integer value read from input in `char` format
1926 allows and interprets K, KB, KiB, M, MB and MiB suffix.
1927 Will also modify `*stringPtr`, advancing it to position where it stopped reading.
1928 Note : function result can overflow if digit string > MAX_UINT */
1929 static unsigned readU32FromChar(const char** stringPtr)
1931 unsigned result = 0;
1932 while ((**stringPtr >='0') && (**stringPtr <='9'))
1933 result *= 10, result += **stringPtr - '0', (*stringPtr)++ ;
1934 if ((**stringPtr=='K') || (**stringPtr=='M')) {
1936 if (**stringPtr=='M') result <<= 10;
1938 if (**stringPtr=='i') (*stringPtr)++;
1939 if (**stringPtr=='B') (*stringPtr)++;
1944 /** longCommandWArg() :
1945 * check if *stringPtr is the same as longCommand.
1946 * If yes, @return 1 and advances *stringPtr to the position which immediately follows longCommand.
1947 * @return 0 and doesn't modify *stringPtr otherwise.
1949 static unsigned longCommandWArg(const char** stringPtr, const char* longCommand)
1951 size_t const comSize = strlen(longCommand);
1952 int const result = !strncmp(*stringPtr, longCommand, comSize);
1953 if (result) *stringPtr += comSize;
1957 int main(int argc, const char** argv)
1962 int nbTests = nbTestsDefault;
1964 U32 proba = FUZ_compressibility_default;
1967 U32 maxDuration = 0;
1969 U32 memTestsOnly = 0;
1970 const char* const programName = argv[0];
1972 /* Check command line */
1973 for (argNb=1; argNb<argc; argNb++) {
1974 const char* argument = argv[argNb];
1975 if(!argument) continue; /* Protection if argument empty */
1977 /* Handle commands. Aggregated commands are allowed */
1978 if (argument[0]=='-') {
1980 if (longCommandWArg(&argument, "--memtest=")) { memTestsOnly = readU32FromChar(&argument); continue; }
1982 if (!strcmp(argument, "--memtest")) { memTestsOnly=1; continue; }
1983 if (!strcmp(argument, "--no-big-tests")) { bigTests=0; continue; }
1986 while (*argument!=0) {
1990 return FUZ_usage(programName);
2002 case 'p': /* pause at the end */
2008 argument++; maxDuration = 0;
2009 nbTests = readU32FromChar(&argument);
2015 maxDuration = readU32FromChar(&argument);
2016 if (*argument=='s') argument++; /* seconds */
2017 if (*argument=='m') maxDuration *= 60, argument++; /* minutes */
2018 if (*argument=='n') argument++;
2024 seed = readU32FromChar(&argument);
2029 testNb = readU32FromChar(&argument);
2032 case 'P': /* compressibility % */
2034 proba = readU32FromChar(&argument);
2035 if (proba>100) proba = 100;
2039 return (FUZ_usage(programName), 1);
2040 } } } } /* for (argNb=1; argNb<argc; argNb++) */
2043 DISPLAY("Starting zstd tester (%i-bits, %s)\n", (int)(sizeof(size_t)*8), ZSTD_VERSION_STRING);
2046 time_t const t = time(NULL);
2047 U32 const h = XXH32(&t, sizeof(t), 1);
2051 DISPLAY("Seed = %u\n", seed);
2052 if (proba!=FUZ_compressibility_default) DISPLAY("Compressibility : %u%%\n", proba);
2055 g_displayLevel = MAX(3, g_displayLevel);
2056 return FUZ_mallocTests(seed, ((double)proba) / 100, memTestsOnly);
2059 if (nbTests < testNb) nbTests = testNb;
2062 result = basicUnitTests(0, ((double)proba) / 100); /* constant seed for predictability */
2064 result = fuzzerTests(seed, nbTests, testNb, maxDuration, ((double)proba) / 100, bigTests);
2067 DISPLAY("Press Enter \n");