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 */
30 #include "zstd.h" /* ZSTD_VERSION_STRING */
31 #include "zstd_errors.h" /* ZSTD_getErrorCode */
32 #include "zstdmt_compress.h"
33 #define ZDICT_STATIC_LINKING_ONLY
34 #include "zdict.h" /* ZDICT_trainFromBuffer */
35 #include "datagen.h" /* RDG_genBuffer */
37 #define XXH_STATIC_LINKING_ONLY /* XXH64_state_t */
38 #include "xxhash.h" /* XXH64 */
42 /*-************************************
44 **************************************/
49 static const U32 FUZ_compressibility_default = 50;
50 static const U32 nbTestsDefault = 30000;
53 /*-************************************
55 **************************************/
56 #define DISPLAY(...) fprintf(stderr, __VA_ARGS__)
57 #define DISPLAYLEVEL(l, ...) if (g_displayLevel>=l) { DISPLAY(__VA_ARGS__); }
58 static U32 g_displayLevel = 2;
60 static const U64 g_refreshRate = SEC_TO_MICRO / 6;
61 static UTIL_time_t g_displayClock = UTIL_TIME_INITIALIZER;
63 #define DISPLAYUPDATE(l, ...) if (g_displayLevel>=l) { \
64 if ((UTIL_clockSpanMicro(g_displayClock) > g_refreshRate) || (g_displayLevel>=4)) \
65 { g_displayClock = UTIL_getTime(); DISPLAY(__VA_ARGS__); \
66 if (g_displayLevel>=4) fflush(stderr); } }
72 { /* these constants shall not depend on MIN() macro */
73 assert(ZSTD_HASHLOG_MAX < 31);
74 assert(ZSTD_CHAINLOG_MAX < 31);
77 /*-*******************************************************
79 *********************************************************/
80 #define MIN(a,b) ((a)<(b)?(a):(b))
81 #define MAX(a,b) ((a)>(b)?(a):(b))
83 #define FUZ_rotl32(x,r) ((x << r) | (x >> (32 - r)))
84 static unsigned FUZ_rand(unsigned* src)
86 static const U32 prime1 = 2654435761U;
87 static const U32 prime2 = 2246822519U;
91 rand32 = FUZ_rotl32(rand32, 13);
96 static unsigned FUZ_highbit32(U32 v32)
100 while (v32) v32 >>= 1, nbBits++;
105 /*=============================================
107 =============================================*/
108 #define CHECK_Z(f) { \
109 size_t const err = f; \
110 if (ZSTD_isError(err)) { \
111 DISPLAY("Error => %s : %s ", \
112 #f, ZSTD_getErrorName(err)); \
116 #define CHECK_V(var, fn) size_t const var = fn; if (ZSTD_isError(var)) goto _output_error
117 #define CHECK(fn) { CHECK_V(err, fn); }
118 #define CHECKPLUS(var, fn, more) { CHECK_V(var, fn); more; }
121 /*=============================================
123 =============================================*/
124 #if defined(__APPLE__) && defined(__MACH__)
126 #include <malloc/malloc.h> /* malloc_size */
129 unsigned long long totalMalloc;
130 size_t currentMalloc;
136 static const mallocCounter_t INIT_MALLOC_COUNTER = { 0, 0, 0, 0, 0 };
138 static void* FUZ_mallocDebug(void* counter, size_t size)
140 mallocCounter_t* const mcPtr = (mallocCounter_t*)counter;
141 void* const ptr = malloc(size);
142 if (ptr==NULL) return NULL;
143 DISPLAYLEVEL(4, "allocating %u KB => effectively %u KB \n",
144 (U32)(size >> 10), (U32)(malloc_size(ptr) >> 10)); /* OS-X specific */
145 mcPtr->totalMalloc += size;
146 mcPtr->currentMalloc += size;
147 if (mcPtr->currentMalloc > mcPtr->peakMalloc)
148 mcPtr->peakMalloc = mcPtr->currentMalloc;
149 mcPtr->nbMalloc += 1;
153 static void FUZ_freeDebug(void* counter, void* address)
155 mallocCounter_t* const mcPtr = (mallocCounter_t*)counter;
156 DISPLAYLEVEL(4, "freeing %u KB \n", (U32)(malloc_size(address) >> 10));
158 mcPtr->currentMalloc -= malloc_size(address); /* OS-X specific */
162 static void FUZ_displayMallocStats(mallocCounter_t count)
164 DISPLAYLEVEL(3, "peak:%6u KB, nbMallocs:%2u, total:%6u KB \n",
165 (U32)(count.peakMalloc >> 10),
167 (U32)(count.totalMalloc >> 10));
170 static int FUZ_mallocTests(unsigned seed, double compressibility, unsigned part)
172 size_t const inSize = 64 MB + 16 MB + 4 MB + 1 MB + 256 KB + 64 KB; /* 85.3 MB */
173 size_t const outSize = ZSTD_compressBound(inSize);
174 void* const inBuffer = malloc(inSize);
175 void* const outBuffer = malloc(outSize);
177 /* test only played in verbose mode, as they are long */
178 if (g_displayLevel<3) return 0;
180 /* Create compressible noise */
181 if (!inBuffer || !outBuffer) {
182 DISPLAY("Not enough memory, aborting\n");
185 RDG_genBuffer(inBuffer, inSize, compressibility, 0. /*auto*/, seed);
187 /* simple compression tests */
189 { int compressionLevel;
190 for (compressionLevel=1; compressionLevel<=6; compressionLevel++) {
191 mallocCounter_t malcount = INIT_MALLOC_COUNTER;
192 ZSTD_customMem const cMem = { FUZ_mallocDebug, FUZ_freeDebug, &malcount };
193 ZSTD_CCtx* const cctx = ZSTD_createCCtx_advanced(cMem);
194 CHECK_Z( ZSTD_compressCCtx(cctx, outBuffer, outSize, inBuffer, inSize, compressionLevel) );
196 DISPLAYLEVEL(3, "compressCCtx level %i : ", compressionLevel);
197 FUZ_displayMallocStats(malcount);
200 /* streaming compression tests */
202 { int compressionLevel;
203 for (compressionLevel=1; compressionLevel<=6; compressionLevel++) {
204 mallocCounter_t malcount = INIT_MALLOC_COUNTER;
205 ZSTD_customMem const cMem = { FUZ_mallocDebug, FUZ_freeDebug, &malcount };
206 ZSTD_CCtx* const cstream = ZSTD_createCStream_advanced(cMem);
207 ZSTD_outBuffer out = { outBuffer, outSize, 0 };
208 ZSTD_inBuffer in = { inBuffer, inSize, 0 };
209 CHECK_Z( ZSTD_initCStream(cstream, compressionLevel) );
210 CHECK_Z( ZSTD_compressStream(cstream, &out, &in) );
211 CHECK_Z( ZSTD_endStream(cstream, &out) );
212 ZSTD_freeCStream(cstream);
213 DISPLAYLEVEL(3, "compressStream level %i : ", compressionLevel);
214 FUZ_displayMallocStats(malcount);
217 /* advanced MT API test */
220 for (nbThreads=1; nbThreads<=4; nbThreads++) {
221 int compressionLevel;
222 for (compressionLevel=1; compressionLevel<=6; compressionLevel++) {
223 mallocCounter_t malcount = INIT_MALLOC_COUNTER;
224 ZSTD_customMem const cMem = { FUZ_mallocDebug, FUZ_freeDebug, &malcount };
225 ZSTD_CCtx* const cctx = ZSTD_createCCtx_advanced(cMem);
226 ZSTD_outBuffer out = { outBuffer, outSize, 0 };
227 ZSTD_inBuffer in = { inBuffer, inSize, 0 };
228 CHECK_Z( ZSTD_CCtx_setParameter(cctx, ZSTD_p_compressionLevel, (U32)compressionLevel) );
229 CHECK_Z( ZSTD_CCtx_setParameter(cctx, ZSTD_p_nbWorkers, nbThreads) );
230 while ( ZSTD_compress_generic(cctx, &out, &in, ZSTD_e_end) ) {}
232 DISPLAYLEVEL(3, "compress_generic,-T%u,end level %i : ",
233 nbThreads, compressionLevel);
234 FUZ_displayMallocStats(malcount);
237 /* advanced MT streaming API test */
240 for (nbThreads=1; nbThreads<=4; nbThreads++) {
241 int compressionLevel;
242 for (compressionLevel=1; compressionLevel<=6; compressionLevel++) {
243 mallocCounter_t malcount = INIT_MALLOC_COUNTER;
244 ZSTD_customMem const cMem = { FUZ_mallocDebug, FUZ_freeDebug, &malcount };
245 ZSTD_CCtx* const cctx = ZSTD_createCCtx_advanced(cMem);
246 ZSTD_outBuffer out = { outBuffer, outSize, 0 };
247 ZSTD_inBuffer in = { inBuffer, inSize, 0 };
248 CHECK_Z( ZSTD_CCtx_setParameter(cctx, ZSTD_p_compressionLevel, (U32)compressionLevel) );
249 CHECK_Z( ZSTD_CCtx_setParameter(cctx, ZSTD_p_nbWorkers, nbThreads) );
250 CHECK_Z( ZSTD_compress_generic(cctx, &out, &in, ZSTD_e_continue) );
251 while ( ZSTD_compress_generic(cctx, &out, &in, ZSTD_e_end) ) {}
253 DISPLAYLEVEL(3, "compress_generic,-T%u,continue level %i : ",
254 nbThreads, compressionLevel);
255 FUZ_displayMallocStats(malcount);
263 static int FUZ_mallocTests(unsigned seed, double compressibility, unsigned part)
265 (void)seed; (void)compressibility; (void)part;
271 /*=============================================
273 =============================================*/
275 static int basicUnitTests(U32 seed, double compressibility)
277 size_t const CNBuffSize = 5 MB;
278 void* const CNBuffer = malloc(CNBuffSize);
279 size_t const compressedBufferSize = ZSTD_compressBound(CNBuffSize);
280 void* const compressedBuffer = malloc(compressedBufferSize);
281 void* const decodedBuffer = malloc(CNBuffSize);
282 ZSTD_DCtx* dctx = ZSTD_createDCtx();
287 /* Create compressible noise */
288 if (!CNBuffer || !compressedBuffer || !decodedBuffer) {
289 DISPLAY("Not enough memory, aborting\n");
293 RDG_genBuffer(CNBuffer, CNBuffSize, compressibility, 0., seed);
296 DISPLAYLEVEL(3, "test%3i : ZSTD_getErrorName : ", testNb++);
297 { const char* errorString = ZSTD_getErrorName(0);
298 DISPLAYLEVEL(3, "OK : %s \n", errorString);
301 DISPLAYLEVEL(3, "test%3i : ZSTD_getErrorName with wrong value : ", testNb++);
302 { const char* errorString = ZSTD_getErrorName(499);
303 DISPLAYLEVEL(3, "OK : %s \n", errorString);
307 DISPLAYLEVEL(3, "test%3i : compress %u bytes : ", testNb++, (U32)CNBuffSize);
308 { ZSTD_CCtx* cctx = ZSTD_createCCtx();
309 if (cctx==NULL) goto _output_error;
310 CHECKPLUS(r, ZSTD_compressCCtx(cctx,
311 compressedBuffer, compressedBufferSize,
312 CNBuffer, CNBuffSize, 1),
314 DISPLAYLEVEL(3, "OK (%u bytes : %.2f%%)\n", (U32)cSize, (double)cSize/CNBuffSize*100);
316 DISPLAYLEVEL(3, "test%3i : size of cctx for level 1 : ", testNb++);
317 { size_t const cctxSize = ZSTD_sizeof_CCtx(cctx);
318 DISPLAYLEVEL(3, "%u bytes \n", (U32)cctxSize);
324 DISPLAYLEVEL(3, "test%3i : ZSTD_getFrameContentSize test : ", testNb++);
325 { unsigned long long const rSize = ZSTD_getFrameContentSize(compressedBuffer, cSize);
326 if (rSize != CNBuffSize) goto _output_error;
328 DISPLAYLEVEL(3, "OK \n");
330 DISPLAYLEVEL(3, "test%3i : ZSTD_findDecompressedSize test : ", testNb++);
331 { unsigned long long const rSize = ZSTD_findDecompressedSize(compressedBuffer, cSize);
332 if (rSize != CNBuffSize) goto _output_error;
334 DISPLAYLEVEL(3, "OK \n");
336 DISPLAYLEVEL(3, "test%3i : decompress %u bytes : ", testNb++, (U32)CNBuffSize);
337 { size_t const r = ZSTD_decompress(decodedBuffer, CNBuffSize, compressedBuffer, cSize);
338 if (r != CNBuffSize) goto _output_error; }
339 DISPLAYLEVEL(3, "OK \n");
341 DISPLAYLEVEL(3, "test%3i : check decompressed result : ", testNb++);
343 for (u=0; u<CNBuffSize; u++) {
344 if (((BYTE*)decodedBuffer)[u] != ((BYTE*)CNBuffer)[u]) goto _output_error;;
346 DISPLAYLEVEL(3, "OK \n");
349 DISPLAYLEVEL(3, "test%3i : decompress with null dict : ", testNb++);
350 { size_t const r = ZSTD_decompress_usingDict(dctx, decodedBuffer, CNBuffSize, compressedBuffer, cSize, NULL, 0);
351 if (r != CNBuffSize) goto _output_error; }
352 DISPLAYLEVEL(3, "OK \n");
354 DISPLAYLEVEL(3, "test%3i : decompress with null DDict : ", testNb++);
355 { size_t const r = ZSTD_decompress_usingDDict(dctx, decodedBuffer, CNBuffSize, compressedBuffer, cSize, NULL);
356 if (r != CNBuffSize) goto _output_error; }
357 DISPLAYLEVEL(3, "OK \n");
359 DISPLAYLEVEL(3, "test%3i : decompress with 1 missing byte : ", testNb++);
360 { size_t const r = ZSTD_decompress(decodedBuffer, CNBuffSize, compressedBuffer, cSize-1);
361 if (!ZSTD_isError(r)) goto _output_error;
362 if (ZSTD_getErrorCode((size_t)r) != ZSTD_error_srcSize_wrong) goto _output_error; }
363 DISPLAYLEVEL(3, "OK \n");
365 DISPLAYLEVEL(3, "test%3i : decompress with 1 too much byte : ", testNb++);
366 { size_t const r = ZSTD_decompress(decodedBuffer, CNBuffSize, compressedBuffer, cSize+1);
367 if (!ZSTD_isError(r)) goto _output_error;
368 if (ZSTD_getErrorCode(r) != ZSTD_error_srcSize_wrong) goto _output_error; }
369 DISPLAYLEVEL(3, "OK \n");
371 DISPLAYLEVEL(3, "test%3d : check CCtx size after compressing empty input : ", testNb++);
372 { ZSTD_CCtx* cctx = ZSTD_createCCtx();
373 size_t const r = ZSTD_compressCCtx(cctx, compressedBuffer, compressedBufferSize, NULL, 0, 19);
374 if (ZSTD_isError(r)) goto _output_error;
375 if (ZSTD_sizeof_CCtx(cctx) > (1U << 20)) goto _output_error;
378 DISPLAYLEVEL(3, "OK \n");
380 DISPLAYLEVEL(3, "test%3d : re-use CCtx with expanding block size : ", testNb++);
381 { ZSTD_CCtx* const cctx = ZSTD_createCCtx();
382 ZSTD_parameters const params = ZSTD_getParams(1, ZSTD_CONTENTSIZE_UNKNOWN, 0);
383 assert(params.fParams.contentSizeFlag == 1); /* block size will be adapted if pledgedSrcSize is enabled */
384 CHECK_Z( ZSTD_compressBegin_advanced(cctx, NULL, 0, params, 1 /*pledgedSrcSize*/) );
385 CHECK_Z( ZSTD_compressEnd(cctx, compressedBuffer, compressedBufferSize, CNBuffer, 1) ); /* creates a block size of 1 */
387 CHECK_Z( ZSTD_compressBegin_advanced(cctx, NULL, 0, params, ZSTD_CONTENTSIZE_UNKNOWN) ); /* re-use same parameters */
388 { size_t const inSize = 2* 128 KB;
389 size_t const outSize = ZSTD_compressBound(inSize);
390 CHECK_Z( ZSTD_compressEnd(cctx, compressedBuffer, outSize, CNBuffer, inSize) );
391 /* will fail if blockSize is not resized */
395 DISPLAYLEVEL(3, "OK \n");
397 DISPLAYLEVEL(3, "test%3d : large window log smaller data : ", testNb++);
398 { ZSTD_CCtx* const cctx = ZSTD_createCCtx();
399 ZSTD_parameters params = ZSTD_getParams(1, ZSTD_CONTENTSIZE_UNKNOWN, 0);
400 size_t const nbCompressions = (1U << 31) / CNBuffSize + 1;
402 params.fParams.contentSizeFlag = 0;
403 params.cParams.windowLog = ZSTD_WINDOWLOG_MAX;
404 for (i = 0; i < nbCompressions; ++i) {
405 CHECK_Z( ZSTD_compressBegin_advanced(cctx, NULL, 0, params, ZSTD_CONTENTSIZE_UNKNOWN) ); /* re-use same parameters */
406 CHECK_Z( ZSTD_compressEnd(cctx, compressedBuffer, compressedBufferSize, CNBuffer, CNBuffSize) );
410 DISPLAYLEVEL(3, "OK \n");
412 /* Static CCtx tests */
413 #define STATIC_CCTX_LEVEL 3
414 DISPLAYLEVEL(3, "test%3i : create static CCtx for level %u :", testNb++, STATIC_CCTX_LEVEL);
415 { size_t const staticCCtxSize = ZSTD_estimateCStreamSize(STATIC_CCTX_LEVEL);
416 void* const staticCCtxBuffer = malloc(staticCCtxSize);
417 size_t const staticDCtxSize = ZSTD_estimateDCtxSize();
418 void* const staticDCtxBuffer = malloc(staticDCtxSize);
419 if (staticCCtxBuffer==NULL || staticDCtxBuffer==NULL) {
420 free(staticCCtxBuffer);
421 free(staticDCtxBuffer);
422 DISPLAY("Not enough memory, aborting\n");
426 { ZSTD_CCtx* staticCCtx = ZSTD_initStaticCCtx(staticCCtxBuffer, staticCCtxSize);
427 ZSTD_DCtx* staticDCtx = ZSTD_initStaticDCtx(staticDCtxBuffer, staticDCtxSize);
428 if ((staticCCtx==NULL) || (staticDCtx==NULL)) goto _output_error;
429 DISPLAYLEVEL(3, "OK \n");
431 DISPLAYLEVEL(3, "test%3i : init CCtx for level %u : ", testNb++, STATIC_CCTX_LEVEL);
432 { size_t const r = ZSTD_compressBegin(staticCCtx, STATIC_CCTX_LEVEL);
433 if (ZSTD_isError(r)) goto _output_error; }
434 DISPLAYLEVEL(3, "OK \n");
436 DISPLAYLEVEL(3, "test%3i : simple compression test with static CCtx : ", testNb++);
437 CHECKPLUS(r, ZSTD_compressCCtx(staticCCtx,
438 compressedBuffer, compressedBufferSize,
439 CNBuffer, CNBuffSize, STATIC_CCTX_LEVEL),
441 DISPLAYLEVEL(3, "OK (%u bytes : %.2f%%)\n",
442 (U32)cSize, (double)cSize/CNBuffSize*100);
444 DISPLAYLEVEL(3, "test%3i : simple decompression test with static DCtx : ", testNb++);
445 { size_t const r = ZSTD_decompressDCtx(staticDCtx,
446 decodedBuffer, CNBuffSize,
447 compressedBuffer, cSize);
448 if (r != CNBuffSize) goto _output_error; }
449 DISPLAYLEVEL(3, "OK \n");
451 DISPLAYLEVEL(3, "test%3i : check decompressed result : ", testNb++);
453 for (u=0; u<CNBuffSize; u++) {
454 if (((BYTE*)decodedBuffer)[u] != ((BYTE*)CNBuffer)[u])
457 DISPLAYLEVEL(3, "OK \n");
459 DISPLAYLEVEL(3, "test%3i : init CCtx for too large level (must fail) : ", testNb++);
460 { size_t const r = ZSTD_compressBegin(staticCCtx, ZSTD_maxCLevel());
461 if (!ZSTD_isError(r)) goto _output_error; }
462 DISPLAYLEVEL(3, "OK \n");
464 DISPLAYLEVEL(3, "test%3i : init CCtx for small level %u (should work again) : ", testNb++, 1);
465 { size_t const r = ZSTD_compressBegin(staticCCtx, 1);
466 if (ZSTD_isError(r)) goto _output_error; }
467 DISPLAYLEVEL(3, "OK \n");
469 DISPLAYLEVEL(3, "test%3i : init CStream for small level %u : ", testNb++, 1);
470 { size_t const r = ZSTD_initCStream(staticCCtx, 1);
471 if (ZSTD_isError(r)) goto _output_error; }
472 DISPLAYLEVEL(3, "OK \n");
474 DISPLAYLEVEL(3, "test%3i : init CStream with dictionary (should fail) : ", testNb++);
475 { size_t const r = ZSTD_initCStream_usingDict(staticCCtx, CNBuffer, 64 KB, 1);
476 if (!ZSTD_isError(r)) goto _output_error; }
477 DISPLAYLEVEL(3, "OK \n");
479 DISPLAYLEVEL(3, "test%3i : init DStream (should fail) : ", testNb++);
480 { size_t const r = ZSTD_initDStream(staticDCtx);
481 if (ZSTD_isError(r)) goto _output_error; }
482 { ZSTD_outBuffer output = { decodedBuffer, CNBuffSize, 0 };
483 ZSTD_inBuffer input = { compressedBuffer, ZSTD_FRAMEHEADERSIZE_MAX+1, 0 };
484 size_t const r = ZSTD_decompressStream(staticDCtx, &output, &input);
485 if (!ZSTD_isError(r)) goto _output_error;
487 DISPLAYLEVEL(3, "OK \n");
489 free(staticCCtxBuffer);
490 free(staticDCtxBuffer);
494 /* ZSTDMT simple MT compression test */
495 DISPLAYLEVEL(3, "test%3i : create ZSTDMT CCtx : ", testNb++);
496 { ZSTDMT_CCtx* mtctx = ZSTDMT_createCCtx(2);
498 DISPLAY("mtctx : mot enough memory, aborting \n");
502 DISPLAYLEVEL(3, "OK \n");
504 DISPLAYLEVEL(3, "test%3i : compress %u bytes with 2 threads : ", testNb++, (U32)CNBuffSize);
505 CHECKPLUS(r, ZSTDMT_compressCCtx(mtctx,
506 compressedBuffer, compressedBufferSize,
507 CNBuffer, CNBuffSize,
510 DISPLAYLEVEL(3, "OK (%u bytes : %.2f%%)\n", (U32)cSize, (double)cSize/CNBuffSize*100);
512 DISPLAYLEVEL(3, "test%3i : decompressed size test : ", testNb++);
513 { unsigned long long const rSize = ZSTD_getFrameContentSize(compressedBuffer, cSize);
514 if (rSize != CNBuffSize) {
515 DISPLAY("ZSTD_getFrameContentSize incorrect : %u != %u \n", (U32)rSize, (U32)CNBuffSize);
518 DISPLAYLEVEL(3, "OK \n");
520 DISPLAYLEVEL(3, "test%3i : decompress %u bytes : ", testNb++, (U32)CNBuffSize);
521 { size_t const r = ZSTD_decompress(decodedBuffer, CNBuffSize, compressedBuffer, cSize);
522 if (r != CNBuffSize) goto _output_error; }
523 DISPLAYLEVEL(3, "OK \n");
525 DISPLAYLEVEL(3, "test%3i : check decompressed result : ", testNb++);
527 for (u=0; u<CNBuffSize; u++) {
528 if (((BYTE*)decodedBuffer)[u] != ((BYTE*)CNBuffer)[u]) goto _output_error;;
530 DISPLAYLEVEL(3, "OK \n");
532 DISPLAYLEVEL(3, "test%3i : compress -T2 with checksum : ", testNb++);
533 { ZSTD_parameters params = ZSTD_getParams(1, CNBuffSize, 0);
534 params.fParams.checksumFlag = 1;
535 params.fParams.contentSizeFlag = 1;
536 CHECKPLUS(r, ZSTDMT_compress_advanced(mtctx,
537 compressedBuffer, compressedBufferSize,
538 CNBuffer, CNBuffSize,
539 NULL, params, 3 /*overlapRLog*/),
542 DISPLAYLEVEL(3, "OK (%u bytes : %.2f%%)\n", (U32)cSize, (double)cSize/CNBuffSize*100);
544 DISPLAYLEVEL(3, "test%3i : decompress %u bytes : ", testNb++, (U32)CNBuffSize);
545 { size_t const r = ZSTD_decompress(decodedBuffer, CNBuffSize, compressedBuffer, cSize);
546 if (r != CNBuffSize) goto _output_error; }
547 DISPLAYLEVEL(3, "OK \n");
549 ZSTDMT_freeCCtx(mtctx);
553 /* Simple API multiframe test */
554 DISPLAYLEVEL(3, "test%3i : compress multiple frames : ", testNb++);
558 /* only use the first half so we don't push against size limit of compressedBuffer */
559 size_t const segSize = (CNBuffSize / 2) / segs;
560 for (i = 0; i < segs; i++) {
561 CHECK_V(r, ZSTD_compress(
562 (BYTE *)compressedBuffer + off, CNBuffSize - off,
563 (BYTE *)CNBuffer + segSize * i,
567 /* insert skippable frame */
568 const U32 skipLen = 129 KB;
569 MEM_writeLE32((BYTE*)compressedBuffer + off, ZSTD_MAGIC_SKIPPABLE_START);
570 MEM_writeLE32((BYTE*)compressedBuffer + off + 4, skipLen);
571 off += skipLen + ZSTD_skippableHeaderSize;
576 DISPLAYLEVEL(3, "OK \n");
578 DISPLAYLEVEL(3, "test%3i : get decompressed size of multiple frames : ", testNb++);
579 { unsigned long long const r = ZSTD_findDecompressedSize(compressedBuffer, cSize);
580 if (r != CNBuffSize / 2) goto _output_error; }
581 DISPLAYLEVEL(3, "OK \n");
583 DISPLAYLEVEL(3, "test%3i : decompress multiple frames : ", testNb++);
584 { CHECK_V(r, ZSTD_decompress(decodedBuffer, CNBuffSize, compressedBuffer, cSize));
585 if (r != CNBuffSize / 2) goto _output_error; }
586 DISPLAYLEVEL(3, "OK \n");
588 DISPLAYLEVEL(3, "test%3i : check decompressed result : ", testNb++);
589 if (memcmp(decodedBuffer, CNBuffer, CNBuffSize / 2) != 0) goto _output_error;
590 DISPLAYLEVEL(3, "OK \n");
592 /* Dictionary and CCtx Duplication tests */
593 { ZSTD_CCtx* const ctxOrig = ZSTD_createCCtx();
594 ZSTD_CCtx* const ctxDuplicated = ZSTD_createCCtx();
595 static const size_t dictSize = 551;
597 DISPLAYLEVEL(3, "test%3i : copy context too soon : ", testNb++);
598 { size_t const copyResult = ZSTD_copyCCtx(ctxDuplicated, ctxOrig, 0);
599 if (!ZSTD_isError(copyResult)) goto _output_error; } /* error must be detected */
600 DISPLAYLEVEL(3, "OK \n");
602 DISPLAYLEVEL(3, "test%3i : load dictionary into context : ", testNb++);
603 CHECK( ZSTD_compressBegin_usingDict(ctxOrig, CNBuffer, dictSize, 2) );
604 CHECK( ZSTD_copyCCtx(ctxDuplicated, ctxOrig, 0) ); /* Begin_usingDict implies unknown srcSize, so match that */
605 DISPLAYLEVEL(3, "OK \n");
607 DISPLAYLEVEL(3, "test%3i : compress with flat dictionary : ", testNb++);
609 CHECKPLUS(r, ZSTD_compressEnd(ctxOrig, compressedBuffer, compressedBufferSize,
610 (const char*)CNBuffer + dictSize, CNBuffSize - dictSize),
612 DISPLAYLEVEL(3, "OK (%u bytes : %.2f%%)\n", (U32)cSize, (double)cSize/CNBuffSize*100);
614 DISPLAYLEVEL(3, "test%3i : frame built with flat dictionary should be decompressible : ", testNb++);
615 CHECKPLUS(r, ZSTD_decompress_usingDict(dctx,
616 decodedBuffer, CNBuffSize,
617 compressedBuffer, cSize,
619 if (r != CNBuffSize - dictSize) goto _output_error);
620 DISPLAYLEVEL(3, "OK \n");
622 DISPLAYLEVEL(3, "test%3i : compress with duplicated context : ", testNb++);
623 { size_t const cSizeOrig = cSize;
625 CHECKPLUS(r, ZSTD_compressEnd(ctxDuplicated, compressedBuffer, compressedBufferSize,
626 (const char*)CNBuffer + dictSize, CNBuffSize - dictSize),
628 if (cSize != cSizeOrig) goto _output_error; /* should be identical ==> same size */
630 DISPLAYLEVEL(3, "OK (%u bytes : %.2f%%)\n", (U32)cSize, (double)cSize/CNBuffSize*100);
632 DISPLAYLEVEL(3, "test%3i : frame built with duplicated context should be decompressible : ", testNb++);
633 CHECKPLUS(r, ZSTD_decompress_usingDict(dctx,
634 decodedBuffer, CNBuffSize,
635 compressedBuffer, cSize,
637 if (r != CNBuffSize - dictSize) goto _output_error);
638 DISPLAYLEVEL(3, "OK \n");
640 DISPLAYLEVEL(3, "test%3i : decompress with DDict : ", testNb++);
641 { ZSTD_DDict* const ddict = ZSTD_createDDict(CNBuffer, dictSize);
642 size_t const r = ZSTD_decompress_usingDDict(dctx, decodedBuffer, CNBuffSize, compressedBuffer, cSize, ddict);
643 if (r != CNBuffSize - dictSize) goto _output_error;
644 DISPLAYLEVEL(3, "OK (size of DDict : %u) \n", (U32)ZSTD_sizeof_DDict(ddict));
645 ZSTD_freeDDict(ddict);
648 DISPLAYLEVEL(3, "test%3i : decompress with static DDict : ", testNb++);
649 { size_t const ddictBufferSize = ZSTD_estimateDDictSize(dictSize, ZSTD_dlm_byCopy);
650 void* ddictBuffer = malloc(ddictBufferSize);
651 if (ddictBuffer == NULL) goto _output_error;
652 { const ZSTD_DDict* const ddict = ZSTD_initStaticDDict(ddictBuffer, ddictBufferSize, CNBuffer, dictSize, ZSTD_dlm_byCopy, ZSTD_dct_auto);
653 size_t const r = ZSTD_decompress_usingDDict(dctx, decodedBuffer, CNBuffSize, compressedBuffer, cSize, ddict);
654 if (r != CNBuffSize - dictSize) goto _output_error;
657 DISPLAYLEVEL(3, "OK (size of static DDict : %u) \n", (U32)ddictBufferSize);
660 DISPLAYLEVEL(3, "test%3i : check content size on duplicated context : ", testNb++);
661 { size_t const testSize = CNBuffSize / 3;
662 { ZSTD_parameters p = ZSTD_getParams(2, testSize, dictSize);
663 p.fParams.contentSizeFlag = 1;
664 CHECK( ZSTD_compressBegin_advanced(ctxOrig, CNBuffer, dictSize, p, testSize-1) );
666 CHECK( ZSTD_copyCCtx(ctxDuplicated, ctxOrig, testSize) );
668 CHECKPLUS(r, ZSTD_compressEnd(ctxDuplicated, compressedBuffer, ZSTD_compressBound(testSize),
669 (const char*)CNBuffer + dictSize, testSize),
671 { ZSTD_frameHeader zfh;
672 if (ZSTD_getFrameHeader(&zfh, compressedBuffer, cSize)) goto _output_error;
673 if ((zfh.frameContentSize != testSize) && (zfh.frameContentSize != 0)) goto _output_error;
675 DISPLAYLEVEL(3, "OK \n");
677 ZSTD_freeCCtx(ctxOrig);
678 ZSTD_freeCCtx(ctxDuplicated);
681 /* Dictionary and dictBuilder tests */
682 { ZSTD_CCtx* const cctx = ZSTD_createCCtx();
683 size_t const dictBufferCapacity = 16 KB;
684 void* dictBuffer = malloc(dictBufferCapacity);
685 size_t const totalSampleSize = 1 MB;
686 size_t const sampleUnitSize = 8 KB;
687 U32 const nbSamples = (U32)(totalSampleSize / sampleUnitSize);
688 size_t* const samplesSizes = (size_t*) malloc(nbSamples * sizeof(size_t));
692 if (dictBuffer==NULL || samplesSizes==NULL) {
698 DISPLAYLEVEL(3, "test%3i : dictBuilder on cyclic data : ", testNb++);
699 assert(compressedBufferSize >= totalSampleSize);
700 { U32 u; for (u=0; u<totalSampleSize; u++) ((BYTE*)decodedBuffer)[u] = (BYTE)u; }
701 { U32 u; for (u=0; u<nbSamples; u++) samplesSizes[u] = sampleUnitSize; }
702 { size_t const sDictSize = ZDICT_trainFromBuffer(dictBuffer, dictBufferCapacity,
703 decodedBuffer, samplesSizes, nbSamples);
704 if (ZDICT_isError(sDictSize)) goto _output_error;
705 DISPLAYLEVEL(3, "OK, created dictionary of size %u \n", (U32)sDictSize);
708 DISPLAYLEVEL(3, "test%3i : dictBuilder : ", testNb++);
709 { U32 u; for (u=0; u<nbSamples; u++) samplesSizes[u] = sampleUnitSize; }
710 dictSize = ZDICT_trainFromBuffer(dictBuffer, dictBufferCapacity,
711 CNBuffer, samplesSizes, nbSamples);
712 if (ZDICT_isError(dictSize)) goto _output_error;
713 DISPLAYLEVEL(3, "OK, created dictionary of size %u \n", (U32)dictSize);
715 DISPLAYLEVEL(3, "test%3i : check dictID : ", testNb++);
716 dictID = ZDICT_getDictID(dictBuffer, dictSize);
717 if (dictID==0) goto _output_error;
718 DISPLAYLEVEL(3, "OK : %u \n", dictID);
720 DISPLAYLEVEL(3, "test%3i : compress with dictionary : ", testNb++);
721 cSize = ZSTD_compress_usingDict(cctx, compressedBuffer, compressedBufferSize,
722 CNBuffer, CNBuffSize,
723 dictBuffer, dictSize, 4);
724 if (ZSTD_isError(cSize)) goto _output_error;
725 DISPLAYLEVEL(3, "OK (%u bytes : %.2f%%)\n", (U32)cSize, (double)cSize/CNBuffSize*100);
727 DISPLAYLEVEL(3, "test%3i : retrieve dictID from dictionary : ", testNb++);
728 { U32 const did = ZSTD_getDictID_fromDict(dictBuffer, dictSize);
729 if (did != dictID) goto _output_error; /* non-conformant (content-only) dictionary */
731 DISPLAYLEVEL(3, "OK \n");
733 DISPLAYLEVEL(3, "test%3i : retrieve dictID from frame : ", testNb++);
734 { U32 const did = ZSTD_getDictID_fromFrame(compressedBuffer, cSize);
735 if (did != dictID) goto _output_error; /* non-conformant (content-only) dictionary */
737 DISPLAYLEVEL(3, "OK \n");
739 DISPLAYLEVEL(3, "test%3i : frame built with dictionary should be decompressible : ", testNb++);
740 CHECKPLUS(r, ZSTD_decompress_usingDict(dctx,
741 decodedBuffer, CNBuffSize,
742 compressedBuffer, cSize,
743 dictBuffer, dictSize),
744 if (r != CNBuffSize) goto _output_error);
745 DISPLAYLEVEL(3, "OK \n");
747 DISPLAYLEVEL(3, "test%3i : estimate CDict size : ", testNb++);
748 { ZSTD_compressionParameters const cParams = ZSTD_getCParams(1, CNBuffSize, dictSize);
749 size_t const estimatedSize = ZSTD_estimateCDictSize_advanced(dictSize, cParams, ZSTD_dlm_byRef);
750 DISPLAYLEVEL(3, "OK : %u \n", (U32)estimatedSize);
753 DISPLAYLEVEL(3, "test%3i : compress with CDict ", testNb++);
754 { ZSTD_compressionParameters const cParams = ZSTD_getCParams(1, CNBuffSize, dictSize);
755 ZSTD_CDict* const cdict = ZSTD_createCDict_advanced(dictBuffer, dictSize,
756 ZSTD_dlm_byRef, ZSTD_dct_auto,
757 cParams, ZSTD_defaultCMem);
758 DISPLAYLEVEL(3, "(size : %u) : ", (U32)ZSTD_sizeof_CDict(cdict));
759 cSize = ZSTD_compress_usingCDict(cctx, compressedBuffer, compressedBufferSize,
760 CNBuffer, CNBuffSize, cdict);
761 ZSTD_freeCDict(cdict);
762 if (ZSTD_isError(cSize)) goto _output_error;
764 DISPLAYLEVEL(3, "OK (%u bytes : %.2f%%)\n", (U32)cSize, (double)cSize/CNBuffSize*100);
766 DISPLAYLEVEL(3, "test%3i : retrieve dictID from frame : ", testNb++);
767 { U32 const did = ZSTD_getDictID_fromFrame(compressedBuffer, cSize);
768 if (did != dictID) goto _output_error; /* non-conformant (content-only) dictionary */
770 DISPLAYLEVEL(3, "OK \n");
772 DISPLAYLEVEL(3, "test%3i : frame built with dictionary should be decompressible : ", testNb++);
773 CHECKPLUS(r, ZSTD_decompress_usingDict(dctx,
774 decodedBuffer, CNBuffSize,
775 compressedBuffer, cSize,
776 dictBuffer, dictSize),
777 if (r != CNBuffSize) goto _output_error);
778 DISPLAYLEVEL(3, "OK \n");
780 DISPLAYLEVEL(3, "test%3i : compress with static CDict : ", testNb++);
781 { int const maxLevel = ZSTD_maxCLevel();
783 for (level = 1; level <= maxLevel; ++level) {
784 ZSTD_compressionParameters const cParams = ZSTD_getCParams(level, CNBuffSize, dictSize);
785 size_t const cdictSize = ZSTD_estimateCDictSize_advanced(dictSize, cParams, ZSTD_dlm_byCopy);
786 void* const cdictBuffer = malloc(cdictSize);
787 if (cdictBuffer==NULL) goto _output_error;
788 { const ZSTD_CDict* const cdict = ZSTD_initStaticCDict(
789 cdictBuffer, cdictSize,
790 dictBuffer, dictSize,
791 ZSTD_dlm_byCopy, ZSTD_dct_auto,
794 DISPLAY("ZSTD_initStaticCDict failed ");
797 cSize = ZSTD_compress_usingCDict(cctx,
798 compressedBuffer, compressedBufferSize,
799 CNBuffer, MIN(10 KB, CNBuffSize), cdict);
800 if (ZSTD_isError(cSize)) {
801 DISPLAY("ZSTD_compress_usingCDict failed ");
806 DISPLAYLEVEL(3, "OK (%u bytes : %.2f%%)\n", (U32)cSize, (double)cSize/CNBuffSize*100);
808 DISPLAYLEVEL(3, "test%3i : ZSTD_compress_usingCDict_advanced, no contentSize, no dictID : ", testNb++);
809 { ZSTD_frameParameters const fParams = { 0 /* frameSize */, 1 /* checksum */, 1 /* noDictID*/ };
810 ZSTD_compressionParameters const cParams = ZSTD_getCParams(1, CNBuffSize, dictSize);
811 ZSTD_CDict* const cdict = ZSTD_createCDict_advanced(dictBuffer, dictSize, ZSTD_dlm_byRef, ZSTD_dct_auto, cParams, ZSTD_defaultCMem);
812 cSize = ZSTD_compress_usingCDict_advanced(cctx, compressedBuffer, compressedBufferSize,
813 CNBuffer, CNBuffSize, cdict, fParams);
814 ZSTD_freeCDict(cdict);
815 if (ZSTD_isError(cSize)) goto _output_error;
817 DISPLAYLEVEL(3, "OK (%u bytes : %.2f%%)\n", (U32)cSize, (double)cSize/CNBuffSize*100);
819 DISPLAYLEVEL(3, "test%3i : try retrieving contentSize from frame : ", testNb++);
820 { U64 const contentSize = ZSTD_getFrameContentSize(compressedBuffer, cSize);
821 if (contentSize != ZSTD_CONTENTSIZE_UNKNOWN) goto _output_error;
823 DISPLAYLEVEL(3, "OK (unknown)\n");
825 DISPLAYLEVEL(3, "test%3i : frame built without dictID should be decompressible : ", testNb++);
826 CHECKPLUS(r, ZSTD_decompress_usingDict(dctx,
827 decodedBuffer, CNBuffSize,
828 compressedBuffer, cSize,
829 dictBuffer, dictSize),
830 if (r != CNBuffSize) goto _output_error);
831 DISPLAYLEVEL(3, "OK \n");
833 DISPLAYLEVEL(3, "test%3i : ZSTD_compress_advanced, no dictID : ", testNb++);
834 { ZSTD_parameters p = ZSTD_getParams(3, CNBuffSize, dictSize);
835 p.fParams.noDictIDFlag = 1;
836 cSize = ZSTD_compress_advanced(cctx, compressedBuffer, compressedBufferSize,
837 CNBuffer, CNBuffSize,
838 dictBuffer, dictSize, p);
839 if (ZSTD_isError(cSize)) goto _output_error;
841 DISPLAYLEVEL(3, "OK (%u bytes : %.2f%%)\n", (U32)cSize, (double)cSize/CNBuffSize*100);
843 DISPLAYLEVEL(3, "test%3i : frame built without dictID should be decompressible : ", testNb++);
844 CHECKPLUS(r, ZSTD_decompress_usingDict(dctx,
845 decodedBuffer, CNBuffSize,
846 compressedBuffer, cSize,
847 dictBuffer, dictSize),
848 if (r != CNBuffSize) goto _output_error);
849 DISPLAYLEVEL(3, "OK \n");
851 DISPLAYLEVEL(3, "test%3i : dictionary containing only header should return error : ", testNb++);
853 const size_t ret = ZSTD_decompress_usingDict(
854 dctx, decodedBuffer, CNBuffSize, compressedBuffer, cSize,
855 "\x37\xa4\x30\xec\x11\x22\x33\x44", 8);
856 if (ZSTD_getErrorCode(ret) != ZSTD_error_dictionary_corrupted) goto _output_error;
858 DISPLAYLEVEL(3, "OK \n");
860 DISPLAYLEVEL(3, "test%3i : Building cdict w/ ZSTD_dm_fullDict on a good dictionary : ", testNb++);
861 { ZSTD_compressionParameters const cParams = ZSTD_getCParams(1, CNBuffSize, dictSize);
862 ZSTD_CDict* const cdict = ZSTD_createCDict_advanced(dictBuffer, dictSize, ZSTD_dlm_byRef, ZSTD_dct_fullDict, cParams, ZSTD_defaultCMem);
863 if (cdict==NULL) goto _output_error;
864 ZSTD_freeCDict(cdict);
866 DISPLAYLEVEL(3, "OK \n");
868 DISPLAYLEVEL(3, "test%3i : Building cdict w/ ZSTD_dm_fullDict on a rawContent (must fail) : ", testNb++);
869 { ZSTD_compressionParameters const cParams = ZSTD_getCParams(1, CNBuffSize, dictSize);
870 ZSTD_CDict* const cdict = ZSTD_createCDict_advanced((const char*)dictBuffer+1, dictSize-1, ZSTD_dlm_byRef, ZSTD_dct_fullDict, cParams, ZSTD_defaultCMem);
871 if (cdict!=NULL) goto _output_error;
872 ZSTD_freeCDict(cdict);
874 DISPLAYLEVEL(3, "OK \n");
876 DISPLAYLEVEL(3, "test%3i : Loading rawContent starting with dict header w/ ZSTD_dm_auto should fail : ", testNb++);
879 MEM_writeLE32((char*)dictBuffer+2, ZSTD_MAGIC_DICTIONARY);
880 ret = ZSTD_CCtx_loadDictionary_advanced(
881 cctx, (const char*)dictBuffer+2, dictSize-2, ZSTD_dlm_byRef, ZSTD_dct_auto);
882 if (!ZSTD_isError(ret)) goto _output_error;
884 DISPLAYLEVEL(3, "OK \n");
886 DISPLAYLEVEL(3, "test%3i : Loading rawContent starting with dict header w/ ZSTD_dm_rawContent should pass : ", testNb++);
889 MEM_writeLE32((char*)dictBuffer+2, ZSTD_MAGIC_DICTIONARY);
890 ret = ZSTD_CCtx_loadDictionary_advanced(
891 cctx, (const char*)dictBuffer+2, dictSize-2, ZSTD_dlm_byRef, ZSTD_dct_rawContent);
892 if (ZSTD_isError(ret)) goto _output_error;
894 DISPLAYLEVEL(3, "OK \n");
896 DISPLAYLEVEL(3, "test%3i : Dictionary with non-default repcodes : ", testNb++);
897 { U32 u; for (u=0; u<nbSamples; u++) samplesSizes[u] = sampleUnitSize; }
898 dictSize = ZDICT_trainFromBuffer(dictBuffer, dictSize,
899 CNBuffer, samplesSizes, nbSamples);
900 if (ZDICT_isError(dictSize)) goto _output_error;
901 /* Set all the repcodes to non-default */
903 BYTE* dictPtr = (BYTE*)dictBuffer;
904 BYTE* dictLimit = dictPtr + dictSize - 12;
905 /* Find the repcodes */
906 while (dictPtr < dictLimit &&
907 (MEM_readLE32(dictPtr) != 1 || MEM_readLE32(dictPtr + 4) != 4 ||
908 MEM_readLE32(dictPtr + 8) != 8)) {
911 if (dictPtr >= dictLimit) goto _output_error;
912 MEM_writeLE32(dictPtr + 0, 10);
913 MEM_writeLE32(dictPtr + 4, 10);
914 MEM_writeLE32(dictPtr + 8, 10);
915 /* Set the last 8 bytes to 'x' */
916 memset((BYTE*)dictBuffer + dictSize - 8, 'x', 8);
918 /* The optimal parser checks all the repcodes.
919 * Make sure at least one is a match >= targetLength so that it is
920 * immediately chosen. This will make sure that the compressor and
921 * decompressor agree on at least one of the repcodes.
925 ZSTD_compressionParameters const cParams = ZSTD_getCParams(19, CNBuffSize, dictSize);
926 ZSTD_CDict* const cdict = ZSTD_createCDict_advanced(dictBuffer, dictSize,
927 ZSTD_dlm_byRef, ZSTD_dct_auto,
928 cParams, ZSTD_defaultCMem);
929 memset(data, 'x', sizeof(data));
930 cSize = ZSTD_compress_usingCDict(cctx, compressedBuffer, compressedBufferSize,
931 data, sizeof(data), cdict);
932 ZSTD_freeCDict(cdict);
933 if (ZSTD_isError(cSize)) { DISPLAYLEVEL(5, "Compression error %s : ", ZSTD_getErrorName(cSize)); goto _output_error; }
934 dSize = ZSTD_decompress_usingDict(dctx, decodedBuffer, sizeof(data), compressedBuffer, cSize, dictBuffer, dictSize);
935 if (ZSTD_isError(dSize)) { DISPLAYLEVEL(5, "Decompression error %s : ", ZSTD_getErrorName(dSize)); goto _output_error; }
936 if (memcmp(data, decodedBuffer, sizeof(data))) { DISPLAYLEVEL(5, "Data corruption : "); goto _output_error; }
938 DISPLAYLEVEL(3, "OK \n");
945 /* COVER dictionary builder tests */
946 { ZSTD_CCtx* const cctx = ZSTD_createCCtx();
947 size_t dictSize = 16 KB;
948 size_t optDictSize = dictSize;
949 void* dictBuffer = malloc(dictSize);
950 size_t const totalSampleSize = 1 MB;
951 size_t const sampleUnitSize = 8 KB;
952 U32 const nbSamples = (U32)(totalSampleSize / sampleUnitSize);
953 size_t* const samplesSizes = (size_t*) malloc(nbSamples * sizeof(size_t));
954 ZDICT_cover_params_t params;
957 if (dictBuffer==NULL || samplesSizes==NULL) {
963 DISPLAYLEVEL(3, "test%3i : ZDICT_trainFromBuffer_cover : ", testNb++);
964 { U32 u; for (u=0; u<nbSamples; u++) samplesSizes[u] = sampleUnitSize; }
965 memset(¶ms, 0, sizeof(params));
966 params.d = 1 + (FUZ_rand(&seed) % 16);
967 params.k = params.d + (FUZ_rand(&seed) % 256);
968 dictSize = ZDICT_trainFromBuffer_cover(dictBuffer, dictSize,
969 CNBuffer, samplesSizes, nbSamples,
971 if (ZDICT_isError(dictSize)) goto _output_error;
972 DISPLAYLEVEL(3, "OK, created dictionary of size %u \n", (U32)dictSize);
974 DISPLAYLEVEL(3, "test%3i : check dictID : ", testNb++);
975 dictID = ZDICT_getDictID(dictBuffer, dictSize);
976 if (dictID==0) goto _output_error;
977 DISPLAYLEVEL(3, "OK : %u \n", dictID);
979 DISPLAYLEVEL(3, "test%3i : ZDICT_optimizeTrainFromBuffer_cover : ", testNb++);
980 memset(¶ms, 0, sizeof(params));
982 optDictSize = ZDICT_optimizeTrainFromBuffer_cover(dictBuffer, optDictSize,
983 CNBuffer, samplesSizes,
984 nbSamples / 4, ¶ms);
985 if (ZDICT_isError(optDictSize)) goto _output_error;
986 DISPLAYLEVEL(3, "OK, created dictionary of size %u \n", (U32)optDictSize);
988 DISPLAYLEVEL(3, "test%3i : check dictID : ", testNb++);
989 dictID = ZDICT_getDictID(dictBuffer, optDictSize);
990 if (dictID==0) goto _output_error;
991 DISPLAYLEVEL(3, "OK : %u \n", dictID);
998 /* Decompression defense tests */
999 DISPLAYLEVEL(3, "test%3i : Check input length for magic number : ", testNb++);
1000 { size_t const r = ZSTD_decompress(decodedBuffer, CNBuffSize, CNBuffer, 3); /* too small input */
1001 if (!ZSTD_isError(r)) goto _output_error;
1002 if (ZSTD_getErrorCode(r) != ZSTD_error_srcSize_wrong) goto _output_error; }
1003 DISPLAYLEVEL(3, "OK \n");
1005 DISPLAYLEVEL(3, "test%3i : Check magic Number : ", testNb++);
1006 ((char*)(CNBuffer))[0] = 1;
1007 { size_t const r = ZSTD_decompress(decodedBuffer, CNBuffSize, CNBuffer, 4);
1008 if (!ZSTD_isError(r)) goto _output_error; }
1009 DISPLAYLEVEL(3, "OK \n");
1011 /* content size verification test */
1012 DISPLAYLEVEL(3, "test%3i : Content size verification : ", testNb++);
1013 { ZSTD_CCtx* const cctx = ZSTD_createCCtx();
1014 size_t const srcSize = 5000;
1015 size_t const wrongSrcSize = (srcSize + 1000);
1016 ZSTD_parameters params = ZSTD_getParams(1, wrongSrcSize, 0);
1017 params.fParams.contentSizeFlag = 1;
1018 CHECK( ZSTD_compressBegin_advanced(cctx, NULL, 0, params, wrongSrcSize) );
1019 { size_t const result = ZSTD_compressEnd(cctx, decodedBuffer, CNBuffSize, CNBuffer, srcSize);
1020 if (!ZSTD_isError(result)) goto _output_error;
1021 if (ZSTD_getErrorCode(result) != ZSTD_error_srcSize_wrong) goto _output_error;
1022 DISPLAYLEVEL(3, "OK : %s \n", ZSTD_getErrorName(result));
1024 ZSTD_freeCCtx(cctx);
1027 /* parameters order test */
1028 { size_t const inputSize = CNBuffSize / 2;
1031 { ZSTD_CCtx* cctx = ZSTD_createCCtx();
1032 DISPLAYLEVEL(3, "test%3i : parameters in order : ", testNb++);
1033 CHECK( ZSTD_CCtx_setParameter(cctx, ZSTD_p_compressionLevel, 2) );
1034 CHECK( ZSTD_CCtx_setParameter(cctx, ZSTD_p_enableLongDistanceMatching, 1) );
1035 CHECK( ZSTD_CCtx_setParameter(cctx, ZSTD_p_windowLog, 18) );
1036 { ZSTD_inBuffer in = { CNBuffer, inputSize, 0 };
1037 ZSTD_outBuffer out = { compressedBuffer, ZSTD_compressBound(inputSize), 0 };
1038 size_t const result = ZSTD_compress_generic(cctx, &out, &in, ZSTD_e_end);
1039 if (result != 0) goto _output_error;
1040 if (in.pos != in.size) goto _output_error;
1042 xxh64 = XXH64(out.dst, out.pos, 0);
1044 DISPLAYLEVEL(3, "OK (compress : %u -> %u bytes)\n", (U32)inputSize, (U32)cSize);
1045 ZSTD_freeCCtx(cctx);
1048 { ZSTD_CCtx* cctx = ZSTD_createCCtx();
1049 DISPLAYLEVEL(3, "test%3i : parameters disordered : ", testNb++);
1050 CHECK( ZSTD_CCtx_setParameter(cctx, ZSTD_p_windowLog, 18) );
1051 CHECK( ZSTD_CCtx_setParameter(cctx, ZSTD_p_enableLongDistanceMatching, 1) );
1052 CHECK( ZSTD_CCtx_setParameter(cctx, ZSTD_p_compressionLevel, 2) );
1053 { ZSTD_inBuffer in = { CNBuffer, inputSize, 0 };
1054 ZSTD_outBuffer out = { compressedBuffer, ZSTD_compressBound(inputSize), 0 };
1055 size_t const result = ZSTD_compress_generic(cctx, &out, &in, ZSTD_e_end);
1056 if (result != 0) goto _output_error;
1057 if (in.pos != in.size) goto _output_error;
1058 if (out.pos != cSize) goto _output_error; /* must result in same compressed result, hence same size */
1059 if (XXH64(out.dst, out.pos, 0) != xxh64) goto _output_error; /* must result in exactly same content, hence same hash */
1060 DISPLAYLEVEL(3, "OK (compress : %u -> %u bytes)\n", (U32)inputSize, (U32)out.pos);
1062 ZSTD_freeCCtx(cctx);
1066 /* custom formats tests */
1067 { ZSTD_CCtx* const cctx = ZSTD_createCCtx();
1068 size_t const inputSize = CNBuffSize / 2; /* won't cause pb with small dict size */
1070 /* basic block compression */
1071 DISPLAYLEVEL(3, "test%3i : magic-less format test : ", testNb++);
1072 CHECK( ZSTD_CCtx_setParameter(cctx, ZSTD_p_format, ZSTD_f_zstd1_magicless) );
1073 { ZSTD_inBuffer in = { CNBuffer, inputSize, 0 };
1074 ZSTD_outBuffer out = { compressedBuffer, ZSTD_compressBound(inputSize), 0 };
1075 size_t const result = ZSTD_compress_generic(cctx, &out, &in, ZSTD_e_end);
1076 if (result != 0) goto _output_error;
1077 if (in.pos != in.size) goto _output_error;
1080 DISPLAYLEVEL(3, "OK (compress : %u -> %u bytes)\n", (U32)inputSize, (U32)cSize);
1082 DISPLAYLEVEL(3, "test%3i : decompress normally (should fail) : ", testNb++);
1083 { size_t const decodeResult = ZSTD_decompressDCtx(dctx, decodedBuffer, CNBuffSize, compressedBuffer, cSize);
1084 if (ZSTD_getErrorCode(decodeResult) != ZSTD_error_prefix_unknown) goto _output_error;
1085 DISPLAYLEVEL(3, "OK : %s \n", ZSTD_getErrorName(decodeResult));
1088 DISPLAYLEVEL(3, "test%3i : decompress with magic-less instruction : ", testNb++);
1089 ZSTD_DCtx_reset(dctx);
1090 CHECK( ZSTD_DCtx_setFormat(dctx, ZSTD_f_zstd1_magicless) );
1091 { ZSTD_inBuffer in = { compressedBuffer, cSize, 0 };
1092 ZSTD_outBuffer out = { decodedBuffer, CNBuffSize, 0 };
1093 size_t const result = ZSTD_decompress_generic(dctx, &out, &in);
1094 if (result != 0) goto _output_error;
1095 if (in.pos != in.size) goto _output_error;
1096 if (out.pos != inputSize) goto _output_error;
1097 DISPLAYLEVEL(3, "OK : regenerated %u bytes \n", (U32)out.pos);
1100 ZSTD_freeCCtx(cctx);
1103 /* block API tests */
1104 { ZSTD_CCtx* const cctx = ZSTD_createCCtx();
1105 static const size_t dictSize = 65 KB;
1106 static const size_t blockSize = 100 KB; /* won't cause pb with small dict size */
1109 /* basic block compression */
1110 DISPLAYLEVEL(3, "test%3i : Block compression test : ", testNb++);
1111 CHECK( ZSTD_compressBegin(cctx, 5) );
1112 CHECK( ZSTD_getBlockSize(cctx) >= blockSize);
1113 cSize = ZSTD_compressBlock(cctx, compressedBuffer, ZSTD_compressBound(blockSize), CNBuffer, blockSize);
1114 if (ZSTD_isError(cSize)) goto _output_error;
1115 DISPLAYLEVEL(3, "OK \n");
1117 DISPLAYLEVEL(3, "test%3i : Block decompression test : ", testNb++);
1118 CHECK( ZSTD_decompressBegin(dctx) );
1119 { CHECK_V(r, ZSTD_decompressBlock(dctx, decodedBuffer, CNBuffSize, compressedBuffer, cSize) );
1120 if (r != blockSize) goto _output_error; }
1121 DISPLAYLEVEL(3, "OK \n");
1123 /* dictionary block compression */
1124 DISPLAYLEVEL(3, "test%3i : Dictionary Block compression test : ", testNb++);
1125 CHECK( ZSTD_compressBegin_usingDict(cctx, CNBuffer, dictSize, 5) );
1126 cSize = ZSTD_compressBlock(cctx, compressedBuffer, ZSTD_compressBound(blockSize), (char*)CNBuffer+dictSize, blockSize);
1127 if (ZSTD_isError(cSize)) goto _output_error;
1128 cSize2 = ZSTD_compressBlock(cctx, (char*)compressedBuffer+cSize, ZSTD_compressBound(blockSize), (char*)CNBuffer+dictSize+blockSize, blockSize);
1129 if (ZSTD_isError(cSize2)) goto _output_error;
1130 memcpy((char*)compressedBuffer+cSize, (char*)CNBuffer+dictSize+blockSize, blockSize); /* fake non-compressed block */
1131 cSize2 = ZSTD_compressBlock(cctx, (char*)compressedBuffer+cSize+blockSize, ZSTD_compressBound(blockSize),
1132 (char*)CNBuffer+dictSize+2*blockSize, blockSize);
1133 if (ZSTD_isError(cSize2)) goto _output_error;
1134 DISPLAYLEVEL(3, "OK \n");
1136 DISPLAYLEVEL(3, "test%3i : Dictionary Block decompression test : ", testNb++);
1137 CHECK( ZSTD_decompressBegin_usingDict(dctx, CNBuffer, dictSize) );
1138 { CHECK_V( r, ZSTD_decompressBlock(dctx, decodedBuffer, CNBuffSize, compressedBuffer, cSize) );
1139 if (r != blockSize) goto _output_error; }
1140 ZSTD_insertBlock(dctx, (char*)decodedBuffer+blockSize, blockSize); /* insert non-compressed block into dctx history */
1141 { CHECK_V( r, ZSTD_decompressBlock(dctx, (char*)decodedBuffer+2*blockSize, CNBuffSize, (char*)compressedBuffer+cSize+blockSize, cSize2) );
1142 if (r != blockSize) goto _output_error; }
1143 DISPLAYLEVEL(3, "OK \n");
1145 ZSTD_freeCCtx(cctx);
1147 ZSTD_freeDCtx(dctx);
1150 { size_t sampleSize = 0;
1151 DISPLAYLEVEL(3, "test%3i : Long RLE test : ", testNb++);
1152 RDG_genBuffer(CNBuffer, sampleSize, compressibility, 0., seed+1);
1153 memset((char*)CNBuffer+sampleSize, 'B', 256 KB - 1);
1154 sampleSize += 256 KB - 1;
1155 RDG_genBuffer((char*)CNBuffer+sampleSize, 96 KB, compressibility, 0., seed+2);
1156 sampleSize += 96 KB;
1157 cSize = ZSTD_compress(compressedBuffer, ZSTD_compressBound(sampleSize), CNBuffer, sampleSize, 1);
1158 if (ZSTD_isError(cSize)) goto _output_error;
1159 { CHECK_V(regenSize, ZSTD_decompress(decodedBuffer, sampleSize, compressedBuffer, cSize));
1160 if (regenSize!=sampleSize) goto _output_error; }
1161 DISPLAYLEVEL(3, "OK \n");
1164 /* All zeroes test (test bug #137) */
1165 #define ZEROESLENGTH 100
1166 DISPLAYLEVEL(3, "test%3i : compress %u zeroes : ", testNb++, ZEROESLENGTH);
1167 memset(CNBuffer, 0, ZEROESLENGTH);
1168 { CHECK_V(r, ZSTD_compress(compressedBuffer, ZSTD_compressBound(ZEROESLENGTH), CNBuffer, ZEROESLENGTH, 1) );
1170 DISPLAYLEVEL(3, "OK (%u bytes : %.2f%%)\n", (U32)cSize, (double)cSize/ZEROESLENGTH*100);
1172 DISPLAYLEVEL(3, "test%3i : decompress %u zeroes : ", testNb++, ZEROESLENGTH);
1173 { CHECK_V(r, ZSTD_decompress(decodedBuffer, ZEROESLENGTH, compressedBuffer, cSize) );
1174 if (r != ZEROESLENGTH) goto _output_error; }
1175 DISPLAYLEVEL(3, "OK \n");
1177 /* nbSeq limit test */
1178 #define _3BYTESTESTLENGTH 131000
1179 #define NB3BYTESSEQLOG 9
1180 #define NB3BYTESSEQ (1 << NB3BYTESSEQLOG)
1181 #define NB3BYTESSEQMASK (NB3BYTESSEQ-1)
1182 /* creates a buffer full of 3-bytes sequences */
1183 { BYTE _3BytesSeqs[NB3BYTESSEQ][3];
1186 /* create batch of 3-bytes sequences */
1188 for (i=0; i < NB3BYTESSEQ; i++) {
1189 _3BytesSeqs[i][0] = (BYTE)(FUZ_rand(&rSeed) & 255);
1190 _3BytesSeqs[i][1] = (BYTE)(FUZ_rand(&rSeed) & 255);
1191 _3BytesSeqs[i][2] = (BYTE)(FUZ_rand(&rSeed) & 255);
1194 /* randomly fills CNBuffer with prepared 3-bytes sequences */
1196 for (i=0; i < _3BYTESTESTLENGTH; i += 3) { /* note : CNBuffer size > _3BYTESTESTLENGTH+3 */
1197 U32 const id = FUZ_rand(&rSeed) & NB3BYTESSEQMASK;
1198 ((BYTE*)CNBuffer)[i+0] = _3BytesSeqs[id][0];
1199 ((BYTE*)CNBuffer)[i+1] = _3BytesSeqs[id][1];
1200 ((BYTE*)CNBuffer)[i+2] = _3BytesSeqs[id][2];
1202 DISPLAYLEVEL(3, "test%3i : compress lots 3-bytes sequences : ", testNb++);
1203 { CHECK_V(r, ZSTD_compress(compressedBuffer, ZSTD_compressBound(_3BYTESTESTLENGTH),
1204 CNBuffer, _3BYTESTESTLENGTH, 19) );
1206 DISPLAYLEVEL(3, "OK (%u bytes : %.2f%%)\n", (U32)cSize, (double)cSize/_3BYTESTESTLENGTH*100);
1208 DISPLAYLEVEL(3, "test%3i : decompress lots 3-bytes sequence : ", testNb++);
1209 { CHECK_V(r, ZSTD_decompress(decodedBuffer, _3BYTESTESTLENGTH, compressedBuffer, cSize) );
1210 if (r != _3BYTESTESTLENGTH) goto _output_error; }
1211 DISPLAYLEVEL(3, "OK \n");
1213 DISPLAYLEVEL(3, "test%3i : incompressible data and ill suited dictionary : ", testNb++);
1214 RDG_genBuffer(CNBuffer, CNBuffSize, 0.0, 0.1, seed);
1215 { /* Train a dictionary on low characters */
1216 size_t dictSize = 16 KB;
1217 void* const dictBuffer = malloc(dictSize);
1218 size_t const totalSampleSize = 1 MB;
1219 size_t const sampleUnitSize = 8 KB;
1220 U32 const nbSamples = (U32)(totalSampleSize / sampleUnitSize);
1221 size_t* const samplesSizes = (size_t*) malloc(nbSamples * sizeof(size_t));
1222 if (!dictBuffer || !samplesSizes) goto _output_error;
1223 { U32 u; for (u=0; u<nbSamples; u++) samplesSizes[u] = sampleUnitSize; }
1224 dictSize = ZDICT_trainFromBuffer(dictBuffer, dictSize, CNBuffer, samplesSizes, nbSamples);
1225 if (ZDICT_isError(dictSize)) goto _output_error;
1226 /* Reverse the characters to make the dictionary ill suited */
1228 for (u = 0; u < CNBuffSize; ++u) {
1229 ((BYTE*)CNBuffer)[u] = 255 - ((BYTE*)CNBuffer)[u];
1232 { /* Compress the data */
1233 size_t const inputSize = 500;
1234 size_t const outputSize = ZSTD_compressBound(inputSize);
1235 void* const outputBuffer = malloc(outputSize);
1236 ZSTD_CCtx* const cctx = ZSTD_createCCtx();
1237 if (!outputBuffer || !cctx) goto _output_error;
1238 CHECK(ZSTD_compress_usingDict(cctx, outputBuffer, outputSize, CNBuffer, inputSize, dictBuffer, dictSize, 1));
1240 ZSTD_freeCCtx(cctx);
1246 DISPLAYLEVEL(3, "OK \n");
1249 /* findFrameCompressedSize on skippable frames */
1250 DISPLAYLEVEL(3, "test%3i : frame compressed size of skippable frame : ", testNb++);
1251 { const char* frame = "\x50\x2a\x4d\x18\x05\x0\x0\0abcde";
1252 size_t const frameSrcSize = 13;
1253 if (ZSTD_findFrameCompressedSize(frame, frameSrcSize) != frameSrcSize) goto _output_error; }
1254 DISPLAYLEVEL(3, "OK \n");
1256 /* error string tests */
1257 DISPLAYLEVEL(3, "test%3i : testing ZSTD error code strings : ", testNb++);
1258 if (strcmp("No error detected", ZSTD_getErrorName((ZSTD_ErrorCode)(0-ZSTD_error_no_error))) != 0) goto _output_error;
1259 if (strcmp("No error detected", ZSTD_getErrorString(ZSTD_error_no_error)) != 0) goto _output_error;
1260 if (strcmp("Unspecified error code", ZSTD_getErrorString((ZSTD_ErrorCode)(0-ZSTD_error_GENERIC))) != 0) goto _output_error;
1261 if (strcmp("Error (generic)", ZSTD_getErrorName((size_t)0-ZSTD_error_GENERIC)) != 0) goto _output_error;
1262 if (strcmp("Error (generic)", ZSTD_getErrorString(ZSTD_error_GENERIC)) != 0) goto _output_error;
1263 if (strcmp("No error detected", ZSTD_getErrorName(ZSTD_error_GENERIC)) != 0) goto _output_error;
1264 DISPLAYLEVEL(3, "OK \n");
1266 DISPLAYLEVEL(3, "test%3i : testing ZSTD dictionary sizes : ", testNb++);
1267 RDG_genBuffer(CNBuffer, CNBuffSize, compressibility, 0., seed);
1269 size_t const size = MIN(128 KB, CNBuffSize);
1270 ZSTD_CCtx* const cctx = ZSTD_createCCtx();
1271 ZSTD_CDict* const lgCDict = ZSTD_createCDict(CNBuffer, size, 1);
1272 ZSTD_CDict* const smCDict = ZSTD_createCDict(CNBuffer, 1 KB, 1);
1273 ZSTD_frameHeader lgHeader;
1274 ZSTD_frameHeader smHeader;
1276 CHECK_Z(ZSTD_compress_usingCDict(cctx, compressedBuffer, compressedBufferSize, CNBuffer, size, lgCDict));
1277 CHECK_Z(ZSTD_getFrameHeader(&lgHeader, compressedBuffer, compressedBufferSize));
1278 CHECK_Z(ZSTD_compress_usingCDict(cctx, compressedBuffer, compressedBufferSize, CNBuffer, size, smCDict));
1279 CHECK_Z(ZSTD_getFrameHeader(&smHeader, compressedBuffer, compressedBufferSize));
1281 if (lgHeader.windowSize != smHeader.windowSize) goto _output_error;
1283 ZSTD_freeCDict(smCDict);
1284 ZSTD_freeCDict(lgCDict);
1285 ZSTD_freeCCtx(cctx);
1287 DISPLAYLEVEL(3, "OK \n");
1291 free(compressedBuffer);
1292 free(decodedBuffer);
1297 DISPLAY("Error detected in Unit tests ! \n");
1302 static size_t findDiff(const void* buf1, const void* buf2, size_t max)
1304 const BYTE* b1 = (const BYTE*)buf1;
1305 const BYTE* b2 = (const BYTE*)buf2;
1307 for (u=0; u<max; u++) {
1308 if (b1[u] != b2[u]) break;
1314 static ZSTD_parameters FUZ_makeParams(ZSTD_compressionParameters cParams, ZSTD_frameParameters fParams)
1316 ZSTD_parameters params;
1317 params.cParams = cParams;
1318 params.fParams = fParams;
1322 static size_t FUZ_rLogLength(U32* seed, U32 logLength)
1324 size_t const lengthMask = ((size_t)1 << logLength) - 1;
1325 return (lengthMask+1) + (FUZ_rand(seed) & lengthMask);
1328 static size_t FUZ_randomLength(U32* seed, U32 maxLog)
1330 U32 const logLength = FUZ_rand(seed) % maxLog;
1331 return FUZ_rLogLength(seed, logLength);
1335 #define CHECK(cond, ...) { \
1337 DISPLAY("Error => "); \
1338 DISPLAY(__VA_ARGS__); \
1339 DISPLAY(" (seed %u, test nb %u) \n", seed, testNb); \
1340 goto _output_error; \
1344 #define CHECK_Z(f) { \
1345 size_t const err = f; \
1346 if (ZSTD_isError(err)) { \
1347 DISPLAY("Error => %s : %s ", \
1348 #f, ZSTD_getErrorName(err)); \
1349 DISPLAY(" (seed %u, test nb %u) \n", seed, testNb); \
1350 goto _output_error; \
1354 static int fuzzerTests(U32 seed, U32 nbTests, unsigned startTest, U32 const maxDurationS, double compressibility, int bigTests)
1356 static const U32 maxSrcLog = 23;
1357 static const U32 maxSampleLog = 22;
1358 size_t const srcBufferSize = (size_t)1<<maxSrcLog;
1359 size_t const dstBufferSize = (size_t)1<<maxSampleLog;
1360 size_t const cBufferSize = ZSTD_compressBound(dstBufferSize);
1361 BYTE* cNoiseBuffer[5];
1362 BYTE* srcBuffer; /* jumping pointer */
1363 BYTE* const cBuffer = (BYTE*) malloc (cBufferSize);
1364 BYTE* const dstBuffer = (BYTE*) malloc (dstBufferSize);
1365 BYTE* const mirrorBuffer = (BYTE*) malloc (dstBufferSize);
1366 ZSTD_CCtx* const refCtx = ZSTD_createCCtx();
1367 ZSTD_CCtx* const ctx = ZSTD_createCCtx();
1368 ZSTD_DCtx* const dctx = ZSTD_createDCtx();
1371 U32 coreSeed = seed, lseed = 0;
1372 UTIL_time_t const startClock = UTIL_getTime();
1373 U64 const maxClockSpan = maxDurationS * SEC_TO_MICRO;
1374 int const cLevelLimiter = bigTests ? 3 : 2;
1377 cNoiseBuffer[0] = (BYTE*)malloc (srcBufferSize);
1378 cNoiseBuffer[1] = (BYTE*)malloc (srcBufferSize);
1379 cNoiseBuffer[2] = (BYTE*)malloc (srcBufferSize);
1380 cNoiseBuffer[3] = (BYTE*)malloc (srcBufferSize);
1381 cNoiseBuffer[4] = (BYTE*)malloc (srcBufferSize);
1382 CHECK (!cNoiseBuffer[0] || !cNoiseBuffer[1] || !cNoiseBuffer[2] || !cNoiseBuffer[3] || !cNoiseBuffer[4]
1383 || !dstBuffer || !mirrorBuffer || !cBuffer || !refCtx || !ctx || !dctx,
1384 "Not enough memory, fuzzer tests cancelled");
1386 /* Create initial samples */
1387 RDG_genBuffer(cNoiseBuffer[0], srcBufferSize, 0.00, 0., coreSeed); /* pure noise */
1388 RDG_genBuffer(cNoiseBuffer[1], srcBufferSize, 0.05, 0., coreSeed); /* barely compressible */
1389 RDG_genBuffer(cNoiseBuffer[2], srcBufferSize, compressibility, 0., coreSeed);
1390 RDG_genBuffer(cNoiseBuffer[3], srcBufferSize, 0.95, 0., coreSeed); /* highly compressible */
1391 RDG_genBuffer(cNoiseBuffer[4], srcBufferSize, 1.00, 0., coreSeed); /* sparse content */
1392 srcBuffer = cNoiseBuffer[2];
1394 /* catch up testNb */
1395 for (testNb=1; testNb < startTest; testNb++) FUZ_rand(&coreSeed);
1397 /* main test loop */
1398 for ( ; (testNb <= nbTests) || (UTIL_clockSpanMicro(startClock) < maxClockSpan); testNb++ ) {
1399 size_t sampleSize, maxTestSize, totalTestSize;
1400 size_t cSize, totalCSize, totalGenSize;
1407 if (nbTests >= testNb) { DISPLAYUPDATE(2, "\r%6u/%6u ", testNb, nbTests); }
1408 else { DISPLAYUPDATE(2, "\r%6u ", testNb); }
1410 FUZ_rand(&coreSeed);
1411 { U32 const prime1 = 2654435761U; lseed = coreSeed ^ prime1; }
1413 /* srcBuffer selection [0-4] */
1414 { U32 buffNb = FUZ_rand(&lseed) & 0x7F;
1415 if (buffNb & 7) buffNb=2; /* most common : compressible (P) */
1419 const U32 tnb[2] = { 1, 3 }; /* barely/highly compressible */
1420 buffNb = tnb[buffNb >> 3];
1422 const U32 tnb[2] = { 0, 4 }; /* not compressible / sparse */
1423 buffNb = tnb[buffNb >> 3];
1425 srcBuffer = cNoiseBuffer[buffNb];
1428 /* select src segment */
1429 sampleSize = FUZ_randomLength(&lseed, maxSampleLog);
1431 /* create sample buffer (to catch read error with valgrind & sanitizers) */
1432 sampleBuffer = (BYTE*)malloc(sampleSize);
1433 CHECK(sampleBuffer==NULL, "not enough memory for sample buffer");
1434 { size_t const sampleStart = FUZ_rand(&lseed) % (srcBufferSize - sampleSize);
1435 memcpy(sampleBuffer, srcBuffer + sampleStart, sampleSize); }
1436 crcOrig = XXH64(sampleBuffer, sampleSize, 0);
1438 /* compression tests */
1439 { int const cLevelPositive =
1440 ( FUZ_rand(&lseed) %
1441 (ZSTD_maxCLevel() - (FUZ_highbit32((U32)sampleSize) / cLevelLimiter)) )
1443 int const cLevel = ((FUZ_rand(&lseed) & 15) == 3) ?
1444 - (int)((FUZ_rand(&lseed) & 7) + 1) : /* test negative cLevel */
1446 DISPLAYLEVEL(5, "fuzzer t%u: Simple compression test (level %i) \n", testNb, cLevel);
1447 cSize = ZSTD_compressCCtx(ctx, cBuffer, cBufferSize, sampleBuffer, sampleSize, cLevel);
1448 CHECK(ZSTD_isError(cSize), "ZSTD_compressCCtx failed : %s", ZSTD_getErrorName(cSize));
1450 /* compression failure test : too small dest buffer */
1452 const size_t missing = (FUZ_rand(&lseed) % (cSize-2)) + 1; /* no problem, as cSize > 4 (frameHeaderSizer) */
1453 const size_t tooSmallSize = cSize - missing;
1454 const U32 endMark = 0x4DC2B1A9;
1455 memcpy(dstBuffer+tooSmallSize, &endMark, 4);
1456 { size_t const errorCode = ZSTD_compressCCtx(ctx, dstBuffer, tooSmallSize, sampleBuffer, sampleSize, cLevel);
1457 CHECK(!ZSTD_isError(errorCode), "ZSTD_compressCCtx should have failed ! (buffer too small : %u < %u)", (U32)tooSmallSize, (U32)cSize); }
1458 { U32 endCheck; memcpy(&endCheck, dstBuffer+tooSmallSize, 4);
1459 CHECK(endCheck != endMark, "ZSTD_compressCCtx : dst buffer overflow"); }
1462 /* frame header decompression test */
1463 { ZSTD_frameHeader zfh;
1464 CHECK_Z( ZSTD_getFrameHeader(&zfh, cBuffer, cSize) );
1465 CHECK(zfh.frameContentSize != sampleSize, "Frame content size incorrect");
1468 /* Decompressed size test */
1469 { unsigned long long const rSize = ZSTD_findDecompressedSize(cBuffer, cSize);
1470 CHECK(rSize != sampleSize, "decompressed size incorrect");
1473 /* successful decompression test */
1474 DISPLAYLEVEL(5, "fuzzer t%u: simple decompression test \n", testNb);
1475 { size_t const margin = (FUZ_rand(&lseed) & 1) ? 0 : (FUZ_rand(&lseed) & 31) + 1;
1476 size_t const dSize = ZSTD_decompress(dstBuffer, sampleSize + margin, cBuffer, cSize);
1477 CHECK(dSize != sampleSize, "ZSTD_decompress failed (%s) (srcSize : %u ; cSize : %u)", ZSTD_getErrorName(dSize), (U32)sampleSize, (U32)cSize);
1478 { U64 const crcDest = XXH64(dstBuffer, sampleSize, 0);
1479 CHECK(crcOrig != crcDest, "decompression result corrupted (pos %u / %u)", (U32)findDiff(sampleBuffer, dstBuffer, sampleSize), (U32)sampleSize);
1482 free(sampleBuffer); /* no longer useful after this point */
1484 /* truncated src decompression test */
1485 DISPLAYLEVEL(5, "fuzzer t%u: decompression of truncated source \n", testNb);
1486 { size_t const missing = (FUZ_rand(&lseed) % (cSize-2)) + 1; /* no problem, as cSize > 4 (frameHeaderSizer) */
1487 size_t const tooSmallSize = cSize - missing;
1488 void* cBufferTooSmall = malloc(tooSmallSize); /* valgrind will catch read overflows */
1489 CHECK(cBufferTooSmall == NULL, "not enough memory !");
1490 memcpy(cBufferTooSmall, cBuffer, tooSmallSize);
1491 { size_t const errorCode = ZSTD_decompress(dstBuffer, dstBufferSize, cBufferTooSmall, tooSmallSize);
1492 CHECK(!ZSTD_isError(errorCode), "ZSTD_decompress should have failed ! (truncated src buffer)"); }
1493 free(cBufferTooSmall);
1496 /* too small dst decompression test */
1497 DISPLAYLEVEL(5, "fuzzer t%u: decompress into too small dst buffer \n", testNb);
1498 if (sampleSize > 3) {
1499 size_t const missing = (FUZ_rand(&lseed) % (sampleSize-2)) + 1; /* no problem, as cSize > 4 (frameHeaderSizer) */
1500 size_t const tooSmallSize = sampleSize - missing;
1501 static const BYTE token = 0xA9;
1502 dstBuffer[tooSmallSize] = token;
1503 { size_t const errorCode = ZSTD_decompress(dstBuffer, tooSmallSize, cBuffer, cSize);
1504 CHECK(!ZSTD_isError(errorCode), "ZSTD_decompress should have failed : %u > %u (dst buffer too small)", (U32)errorCode, (U32)tooSmallSize); }
1505 CHECK(dstBuffer[tooSmallSize] != token, "ZSTD_decompress : dst buffer overflow");
1508 /* noisy src decompression test */
1510 /* insert noise into src */
1511 { U32 const maxNbBits = FUZ_highbit32((U32)(cSize-4));
1512 size_t pos = 4; /* preserve magic number (too easy to detect) */
1514 /* keep some original src */
1515 { U32 const nbBits = FUZ_rand(&lseed) % maxNbBits;
1516 size_t const mask = (1<<nbBits) - 1;
1517 size_t const skipLength = FUZ_rand(&lseed) & mask;
1520 if (pos >= cSize) break;
1522 { U32 const nbBitsCodes = FUZ_rand(&lseed) % maxNbBits;
1523 U32 const nbBits = nbBitsCodes ? nbBitsCodes-1 : 0;
1524 size_t const mask = (1<<nbBits) - 1;
1525 size_t const rNoiseLength = (FUZ_rand(&lseed) & mask) + 1;
1526 size_t const noiseLength = MIN(rNoiseLength, cSize-pos);
1527 size_t const noiseStart = FUZ_rand(&lseed) % (srcBufferSize - noiseLength);
1528 memcpy(cBuffer + pos, srcBuffer + noiseStart, noiseLength);
1532 /* decompress noisy source */
1533 DISPLAYLEVEL(5, "fuzzer t%u: decompress noisy source \n", testNb);
1534 { U32 const endMark = 0xA9B1C3D6;
1535 memcpy(dstBuffer+sampleSize, &endMark, 4);
1536 { size_t const decompressResult = ZSTD_decompress(dstBuffer, sampleSize, cBuffer, cSize);
1537 /* result *may* be an unlikely success, but even then, it must strictly respect dst buffer boundaries */
1538 CHECK((!ZSTD_isError(decompressResult)) && (decompressResult>sampleSize),
1539 "ZSTD_decompress on noisy src : result is too large : %u > %u (dst buffer)", (U32)decompressResult, (U32)sampleSize);
1541 { U32 endCheck; memcpy(&endCheck, dstBuffer+sampleSize, 4);
1542 CHECK(endMark!=endCheck, "ZSTD_decompress on noisy src : dst buffer overflow");
1543 } } } /* noisy src decompression test */
1545 /*===== Bufferless streaming compression test, scattered segments and dictionary =====*/
1546 DISPLAYLEVEL(5, "fuzzer t%u: Bufferless streaming compression test \n", testNb);
1547 { U32 const testLog = FUZ_rand(&lseed) % maxSrcLog;
1548 U32 const dictLog = FUZ_rand(&lseed) % maxSrcLog;
1549 int const cLevel = (FUZ_rand(&lseed) %
1551 (MAX(testLog, dictLog) / cLevelLimiter))) +
1553 maxTestSize = FUZ_rLogLength(&lseed, testLog);
1554 if (maxTestSize >= dstBufferSize) maxTestSize = dstBufferSize-1;
1556 dictSize = FUZ_rLogLength(&lseed, dictLog); /* needed also for decompression */
1557 dict = srcBuffer + (FUZ_rand(&lseed) % (srcBufferSize - dictSize));
1559 DISPLAYLEVEL(6, "fuzzer t%u: Compressing up to <=%u bytes at level %i with dictionary size %u \n",
1560 testNb, (U32)maxTestSize, cLevel, (U32)dictSize);
1562 if (FUZ_rand(&lseed) & 0xF) {
1563 CHECK_Z ( ZSTD_compressBegin_usingDict(refCtx, dict, dictSize, cLevel) );
1565 ZSTD_compressionParameters const cPar = ZSTD_getCParams(cLevel, ZSTD_CONTENTSIZE_UNKNOWN, dictSize);
1566 ZSTD_frameParameters const fPar = { FUZ_rand(&lseed)&1 /* contentSizeFlag */,
1567 !(FUZ_rand(&lseed)&3) /* contentChecksumFlag*/,
1568 0 /*NodictID*/ }; /* note : since dictionary is fake, dictIDflag has no impact */
1569 ZSTD_parameters const p = FUZ_makeParams(cPar, fPar);
1570 CHECK_Z ( ZSTD_compressBegin_advanced(refCtx, dict, dictSize, p, 0) );
1572 CHECK_Z( ZSTD_copyCCtx(ctx, refCtx, 0) );
1575 { U32 const nbChunks = (FUZ_rand(&lseed) & 127) + 2;
1577 XXH64_state_t xxhState;
1578 XXH64_reset(&xxhState, 0);
1579 for (totalTestSize=0, cSize=0, n=0 ; n<nbChunks ; n++) {
1580 size_t const segmentSize = FUZ_randomLength(&lseed, maxSampleLog);
1581 size_t const segmentStart = FUZ_rand(&lseed) % (srcBufferSize - segmentSize);
1583 if (cBufferSize-cSize < ZSTD_compressBound(segmentSize)) break; /* avoid invalid dstBufferTooSmall */
1584 if (totalTestSize+segmentSize > maxTestSize) break;
1586 { size_t const compressResult = ZSTD_compressContinue(ctx, cBuffer+cSize, cBufferSize-cSize, srcBuffer+segmentStart, segmentSize);
1587 CHECK (ZSTD_isError(compressResult), "multi-segments compression error : %s", ZSTD_getErrorName(compressResult));
1588 cSize += compressResult;
1590 XXH64_update(&xxhState, srcBuffer+segmentStart, segmentSize);
1591 memcpy(mirrorBuffer + totalTestSize, srcBuffer+segmentStart, segmentSize);
1592 totalTestSize += segmentSize;
1595 { size_t const flushResult = ZSTD_compressEnd(ctx, cBuffer+cSize, cBufferSize-cSize, NULL, 0);
1596 CHECK (ZSTD_isError(flushResult), "multi-segments epilogue error : %s", ZSTD_getErrorName(flushResult));
1597 cSize += flushResult;
1599 crcOrig = XXH64_digest(&xxhState);
1602 /* streaming decompression test */
1603 DISPLAYLEVEL(5, "fuzzer t%u: Bufferless streaming decompression test \n", testNb);
1604 /* ensure memory requirement is good enough (should always be true) */
1605 { ZSTD_frameHeader zfh;
1606 CHECK( ZSTD_getFrameHeader(&zfh, cBuffer, ZSTD_frameHeaderSize_max),
1607 "ZSTD_getFrameHeader(): error retrieving frame information");
1608 { size_t const roundBuffSize = ZSTD_decodingBufferSize_min(zfh.windowSize, zfh.frameContentSize);
1609 CHECK_Z(roundBuffSize);
1610 CHECK((roundBuffSize > totalTestSize) && (zfh.frameContentSize!=ZSTD_CONTENTSIZE_UNKNOWN),
1611 "ZSTD_decodingBufferSize_min() requires more memory (%u) than necessary (%u)",
1612 (U32)roundBuffSize, (U32)totalTestSize );
1614 if (dictSize<8) dictSize=0, dict=NULL; /* disable dictionary */
1615 CHECK_Z( ZSTD_decompressBegin_usingDict(dctx, dict, dictSize) );
1618 while (totalCSize < cSize) {
1619 size_t const inSize = ZSTD_nextSrcSizeToDecompress(dctx);
1620 size_t const genSize = ZSTD_decompressContinue(dctx, dstBuffer+totalGenSize, dstBufferSize-totalGenSize, cBuffer+totalCSize, inSize);
1621 CHECK (ZSTD_isError(genSize), "ZSTD_decompressContinue error : %s", ZSTD_getErrorName(genSize));
1622 totalGenSize += genSize;
1623 totalCSize += inSize;
1625 CHECK (ZSTD_nextSrcSizeToDecompress(dctx) != 0, "frame not fully decoded");
1626 CHECK (totalGenSize != totalTestSize, "streaming decompressed data : wrong size")
1627 CHECK (totalCSize != cSize, "compressed data should be fully read")
1628 { U64 const crcDest = XXH64(dstBuffer, totalTestSize, 0);
1629 if (crcDest!=crcOrig) {
1630 size_t const errorPos = findDiff(mirrorBuffer, dstBuffer, totalTestSize);
1631 CHECK (1, "streaming decompressed data corrupted : byte %u / %u (%02X!=%02X)",
1632 (U32)errorPos, (U32)totalTestSize, dstBuffer[errorPos], mirrorBuffer[errorPos]);
1634 } /* for ( ; (testNb <= nbTests) */
1635 DISPLAY("\r%u fuzzer tests completed \n", testNb-1);
1638 ZSTD_freeCCtx(refCtx);
1640 ZSTD_freeDCtx(dctx);
1641 free(cNoiseBuffer[0]);
1642 free(cNoiseBuffer[1]);
1643 free(cNoiseBuffer[2]);
1644 free(cNoiseBuffer[3]);
1645 free(cNoiseBuffer[4]);
1657 /*_*******************************************************
1659 *********************************************************/
1660 static int FUZ_usage(const char* programName)
1662 DISPLAY( "Usage :\n");
1663 DISPLAY( " %s [args]\n", programName);
1665 DISPLAY( "Arguments :\n");
1666 DISPLAY( " -i# : Nb of tests (default:%u) \n", nbTestsDefault);
1667 DISPLAY( " -s# : Select seed (default:prompt user)\n");
1668 DISPLAY( " -t# : Select starting test number (default:0)\n");
1669 DISPLAY( " -P# : Select compressibility in %% (default:%u%%)\n", FUZ_compressibility_default);
1670 DISPLAY( " -v : verbose\n");
1671 DISPLAY( " -p : pause at the end\n");
1672 DISPLAY( " -h : display help and exit\n");
1676 /*! readU32FromChar() :
1677 @return : unsigned integer value read from input in `char` format
1678 allows and interprets K, KB, KiB, M, MB and MiB suffix.
1679 Will also modify `*stringPtr`, advancing it to position where it stopped reading.
1680 Note : function result can overflow if digit string > MAX_UINT */
1681 static unsigned readU32FromChar(const char** stringPtr)
1683 unsigned result = 0;
1684 while ((**stringPtr >='0') && (**stringPtr <='9'))
1685 result *= 10, result += **stringPtr - '0', (*stringPtr)++ ;
1686 if ((**stringPtr=='K') || (**stringPtr=='M')) {
1688 if (**stringPtr=='M') result <<= 10;
1690 if (**stringPtr=='i') (*stringPtr)++;
1691 if (**stringPtr=='B') (*stringPtr)++;
1696 /** longCommandWArg() :
1697 * check if *stringPtr is the same as longCommand.
1698 * If yes, @return 1 and advances *stringPtr to the position which immediately follows longCommand.
1699 * @return 0 and doesn't modify *stringPtr otherwise.
1701 static unsigned longCommandWArg(const char** stringPtr, const char* longCommand)
1703 size_t const comSize = strlen(longCommand);
1704 int const result = !strncmp(*stringPtr, longCommand, comSize);
1705 if (result) *stringPtr += comSize;
1709 int main(int argc, const char** argv)
1714 int nbTests = nbTestsDefault;
1716 U32 proba = FUZ_compressibility_default;
1719 U32 maxDuration = 0;
1721 U32 memTestsOnly = 0;
1722 const char* const programName = argv[0];
1724 /* Check command line */
1725 for (argNb=1; argNb<argc; argNb++) {
1726 const char* argument = argv[argNb];
1727 if(!argument) continue; /* Protection if argument empty */
1729 /* Handle commands. Aggregated commands are allowed */
1730 if (argument[0]=='-') {
1732 if (longCommandWArg(&argument, "--memtest=")) { memTestsOnly = readU32FromChar(&argument); continue; }
1734 if (!strcmp(argument, "--memtest")) { memTestsOnly=1; continue; }
1735 if (!strcmp(argument, "--no-big-tests")) { bigTests=0; continue; }
1738 while (*argument!=0) {
1742 return FUZ_usage(programName);
1754 case 'p': /* pause at the end */
1760 argument++; maxDuration = 0;
1761 nbTests = readU32FromChar(&argument);
1767 maxDuration = readU32FromChar(&argument);
1768 if (*argument=='s') argument++; /* seconds */
1769 if (*argument=='m') maxDuration *= 60, argument++; /* minutes */
1770 if (*argument=='n') argument++;
1776 seed = readU32FromChar(&argument);
1781 testNb = readU32FromChar(&argument);
1784 case 'P': /* compressibility % */
1786 proba = readU32FromChar(&argument);
1787 if (proba>100) proba = 100;
1791 return (FUZ_usage(programName), 1);
1792 } } } } /* for (argNb=1; argNb<argc; argNb++) */
1795 DISPLAY("Starting zstd tester (%i-bits, %s)\n", (int)(sizeof(size_t)*8), ZSTD_VERSION_STRING);
1798 time_t const t = time(NULL);
1799 U32 const h = XXH32(&t, sizeof(t), 1);
1803 DISPLAY("Seed = %u\n", seed);
1804 if (proba!=FUZ_compressibility_default) DISPLAY("Compressibility : %u%%\n", proba);
1807 g_displayLevel = MAX(3, g_displayLevel);
1808 return FUZ_mallocTests(seed, ((double)proba) / 100, memTestsOnly);
1811 if (nbTests < testNb) nbTests = testNb;
1814 result = basicUnitTests(0, ((double)proba) / 100); /* constant seed for predictability */
1816 result = fuzzerTests(seed, nbTests, testNb, maxDuration, ((double)proba) / 100, bigTests);
1819 DISPLAY("Press Enter \n");