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
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(stdout, __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); } }
68 /*-*******************************************************
70 *********************************************************/
73 #define MIN(a,b) ((a)<(b)?(a):(b))
74 #define MAX(a,b) ((a)>(b)?(a):(b))
76 #define FUZ_rotl32(x,r) ((x << r) | (x >> (32 - r)))
77 static unsigned FUZ_rand(unsigned* src)
79 static const U32 prime1 = 2654435761U;
80 static const U32 prime2 = 2246822519U;
84 rand32 = FUZ_rotl32(rand32, 13);
89 static unsigned FUZ_highbit32(U32 v32)
93 while (v32) v32 >>= 1, nbBits++;
98 /*=============================================
100 =============================================*/
101 #define CHECK_Z(f) { \
102 size_t const err = f; \
103 if (ZSTD_isError(err)) { \
104 DISPLAY("Error => %s : %s ", \
105 #f, ZSTD_getErrorName(err)); \
109 #define CHECK_V(var, fn) size_t const var = fn; if (ZSTD_isError(var)) goto _output_error
110 #define CHECK(fn) { CHECK_V(err, fn); }
111 #define CHECKPLUS(var, fn, more) { CHECK_V(var, fn); more; }
114 /*=============================================
116 =============================================*/
117 #if defined(__APPLE__) && defined(__MACH__)
119 #include <malloc/malloc.h> /* malloc_size */
122 unsigned long long totalMalloc;
123 size_t currentMalloc;
129 static const mallocCounter_t INIT_MALLOC_COUNTER = { 0, 0, 0, 0, 0 };
131 static void* FUZ_mallocDebug(void* counter, size_t size)
133 mallocCounter_t* const mcPtr = (mallocCounter_t*)counter;
134 void* const ptr = malloc(size);
135 if (ptr==NULL) return NULL;
136 DISPLAYLEVEL(4, "allocating %u KB => effectively %u KB \n",
137 (U32)(size >> 10), (U32)(malloc_size(ptr) >> 10)); /* OS-X specific */
138 mcPtr->totalMalloc += size;
139 mcPtr->currentMalloc += size;
140 if (mcPtr->currentMalloc > mcPtr->peakMalloc)
141 mcPtr->peakMalloc = mcPtr->currentMalloc;
142 mcPtr->nbMalloc += 1;
146 static void FUZ_freeDebug(void* counter, void* address)
148 mallocCounter_t* const mcPtr = (mallocCounter_t*)counter;
149 DISPLAYLEVEL(4, "freeing %u KB \n", (U32)(malloc_size(address) >> 10));
151 mcPtr->currentMalloc -= malloc_size(address); /* OS-X specific */
155 static void FUZ_displayMallocStats(mallocCounter_t count)
157 DISPLAYLEVEL(3, "peak:%6u KB, nbMallocs:%2u, total:%6u KB \n",
158 (U32)(count.peakMalloc >> 10),
160 (U32)(count.totalMalloc >> 10));
163 static int FUZ_mallocTests(unsigned seed, double compressibility, unsigned part)
165 size_t const inSize = 64 MB + 16 MB + 4 MB + 1 MB + 256 KB + 64 KB; /* 85.3 MB */
166 size_t const outSize = ZSTD_compressBound(inSize);
167 void* const inBuffer = malloc(inSize);
168 void* const outBuffer = malloc(outSize);
170 /* test only played in verbose mode, as they are long */
171 if (g_displayLevel<3) return 0;
173 /* Create compressible noise */
174 if (!inBuffer || !outBuffer) {
175 DISPLAY("Not enough memory, aborting\n");
178 RDG_genBuffer(inBuffer, inSize, compressibility, 0. /*auto*/, seed);
180 /* simple compression tests */
182 { int compressionLevel;
183 for (compressionLevel=1; compressionLevel<=6; compressionLevel++) {
184 mallocCounter_t malcount = INIT_MALLOC_COUNTER;
185 ZSTD_customMem const cMem = { FUZ_mallocDebug, FUZ_freeDebug, &malcount };
186 ZSTD_CCtx* const cctx = ZSTD_createCCtx_advanced(cMem);
187 CHECK_Z( ZSTD_compressCCtx(cctx, outBuffer, outSize, inBuffer, inSize, compressionLevel) );
189 DISPLAYLEVEL(3, "compressCCtx level %i : ", compressionLevel);
190 FUZ_displayMallocStats(malcount);
193 /* streaming compression tests */
195 { int compressionLevel;
196 for (compressionLevel=1; compressionLevel<=6; compressionLevel++) {
197 mallocCounter_t malcount = INIT_MALLOC_COUNTER;
198 ZSTD_customMem const cMem = { FUZ_mallocDebug, FUZ_freeDebug, &malcount };
199 ZSTD_CCtx* const cstream = ZSTD_createCStream_advanced(cMem);
200 ZSTD_outBuffer out = { outBuffer, outSize, 0 };
201 ZSTD_inBuffer in = { inBuffer, inSize, 0 };
202 CHECK_Z( ZSTD_initCStream(cstream, compressionLevel) );
203 CHECK_Z( ZSTD_compressStream(cstream, &out, &in) );
204 CHECK_Z( ZSTD_endStream(cstream, &out) );
205 ZSTD_freeCStream(cstream);
206 DISPLAYLEVEL(3, "compressStream level %i : ", compressionLevel);
207 FUZ_displayMallocStats(malcount);
210 /* advanced MT API test */
213 for (nbThreads=1; nbThreads<=4; nbThreads++) {
214 int compressionLevel;
215 for (compressionLevel=1; compressionLevel<=6; compressionLevel++) {
216 mallocCounter_t malcount = INIT_MALLOC_COUNTER;
217 ZSTD_customMem const cMem = { FUZ_mallocDebug, FUZ_freeDebug, &malcount };
218 ZSTD_CCtx* const cctx = ZSTD_createCCtx_advanced(cMem);
219 ZSTD_outBuffer out = { outBuffer, outSize, 0 };
220 ZSTD_inBuffer in = { inBuffer, inSize, 0 };
221 CHECK_Z( ZSTD_CCtx_setParameter(cctx, ZSTD_p_compressionLevel, (U32)compressionLevel) );
222 CHECK_Z( ZSTD_CCtx_setParameter(cctx, ZSTD_p_nbThreads, nbThreads) );
223 while ( ZSTD_compress_generic(cctx, &out, &in, ZSTD_e_end) ) {}
225 DISPLAYLEVEL(3, "compress_generic,-T%u,end level %i : ",
226 nbThreads, compressionLevel);
227 FUZ_displayMallocStats(malcount);
230 /* advanced MT streaming API test */
233 for (nbThreads=1; nbThreads<=4; nbThreads++) {
234 int compressionLevel;
235 for (compressionLevel=1; compressionLevel<=6; compressionLevel++) {
236 mallocCounter_t malcount = INIT_MALLOC_COUNTER;
237 ZSTD_customMem const cMem = { FUZ_mallocDebug, FUZ_freeDebug, &malcount };
238 ZSTD_CCtx* const cctx = ZSTD_createCCtx_advanced(cMem);
239 ZSTD_outBuffer out = { outBuffer, outSize, 0 };
240 ZSTD_inBuffer in = { inBuffer, inSize, 0 };
241 CHECK_Z( ZSTD_CCtx_setParameter(cctx, ZSTD_p_compressionLevel, (U32)compressionLevel) );
242 CHECK_Z( ZSTD_CCtx_setParameter(cctx, ZSTD_p_nbThreads, nbThreads) );
243 CHECK_Z( ZSTD_compress_generic(cctx, &out, &in, ZSTD_e_continue) );
244 while ( ZSTD_compress_generic(cctx, &out, &in, ZSTD_e_end) ) {}
246 DISPLAYLEVEL(3, "compress_generic,-T%u,continue level %i : ",
247 nbThreads, compressionLevel);
248 FUZ_displayMallocStats(malcount);
256 static int FUZ_mallocTests(unsigned seed, double compressibility, unsigned part)
258 (void)seed; (void)compressibility; (void)part;
264 /*=============================================
266 =============================================*/
268 static int basicUnitTests(U32 seed, double compressibility)
270 size_t const CNBuffSize = 5 MB;
271 void* const CNBuffer = malloc(CNBuffSize);
272 size_t const compressedBufferSize = ZSTD_compressBound(CNBuffSize);
273 void* const compressedBuffer = malloc(compressedBufferSize);
274 void* const decodedBuffer = malloc(CNBuffSize);
275 ZSTD_DCtx* dctx = ZSTD_createDCtx();
280 /* Create compressible noise */
281 if (!CNBuffer || !compressedBuffer || !decodedBuffer) {
282 DISPLAY("Not enough memory, aborting\n");
286 RDG_genBuffer(CNBuffer, CNBuffSize, compressibility, 0., seed);
289 DISPLAYLEVEL(4, "test%3i : ZSTD_getErrorName : ", testNb++);
290 { const char* errorString = ZSTD_getErrorName(0);
291 DISPLAYLEVEL(4, "OK : %s \n", errorString);
294 DISPLAYLEVEL(4, "test%3i : ZSTD_getErrorName with wrong value : ", testNb++);
295 { const char* errorString = ZSTD_getErrorName(499);
296 DISPLAYLEVEL(4, "OK : %s \n", errorString);
300 DISPLAYLEVEL(4, "test%3i : compress %u bytes : ", testNb++, (U32)CNBuffSize);
301 { ZSTD_CCtx* cctx = ZSTD_createCCtx();
302 if (cctx==NULL) goto _output_error;
303 CHECKPLUS(r, ZSTD_compressCCtx(cctx,
304 compressedBuffer, compressedBufferSize,
305 CNBuffer, CNBuffSize, 1),
307 DISPLAYLEVEL(4, "OK (%u bytes : %.2f%%)\n", (U32)cSize, (double)cSize/CNBuffSize*100);
309 DISPLAYLEVEL(4, "test%3i : size of cctx for level 1 : ", testNb++);
310 { size_t const cctxSize = ZSTD_sizeof_CCtx(cctx);
311 DISPLAYLEVEL(4, "%u bytes \n", (U32)cctxSize);
317 DISPLAYLEVEL(4, "test%3i : ZSTD_getFrameContentSize test : ", testNb++);
318 { unsigned long long const rSize = ZSTD_getFrameContentSize(compressedBuffer, cSize);
319 if (rSize != CNBuffSize) goto _output_error;
321 DISPLAYLEVEL(4, "OK \n");
323 DISPLAYLEVEL(4, "test%3i : ZSTD_findDecompressedSize test : ", testNb++);
324 { unsigned long long const rSize = ZSTD_findDecompressedSize(compressedBuffer, cSize);
325 if (rSize != CNBuffSize) goto _output_error;
327 DISPLAYLEVEL(4, "OK \n");
329 DISPLAYLEVEL(4, "test%3i : decompress %u bytes : ", testNb++, (U32)CNBuffSize);
330 { size_t const r = ZSTD_decompress(decodedBuffer, CNBuffSize, compressedBuffer, cSize);
331 if (r != CNBuffSize) goto _output_error; }
332 DISPLAYLEVEL(4, "OK \n");
334 DISPLAYLEVEL(4, "test%3i : check decompressed result : ", testNb++);
336 for (u=0; u<CNBuffSize; u++) {
337 if (((BYTE*)decodedBuffer)[u] != ((BYTE*)CNBuffer)[u]) goto _output_error;;
339 DISPLAYLEVEL(4, "OK \n");
342 DISPLAYLEVEL(4, "test%3i : decompress with null dict : ", testNb++);
343 { size_t const r = ZSTD_decompress_usingDict(dctx, decodedBuffer, CNBuffSize, compressedBuffer, cSize, NULL, 0);
344 if (r != CNBuffSize) goto _output_error; }
345 DISPLAYLEVEL(4, "OK \n");
347 DISPLAYLEVEL(4, "test%3i : decompress with null DDict : ", testNb++);
348 { size_t const r = ZSTD_decompress_usingDDict(dctx, decodedBuffer, CNBuffSize, compressedBuffer, cSize, NULL);
349 if (r != CNBuffSize) goto _output_error; }
350 DISPLAYLEVEL(4, "OK \n");
352 DISPLAYLEVEL(4, "test%3i : decompress with 1 missing byte : ", testNb++);
353 { size_t const r = ZSTD_decompress(decodedBuffer, CNBuffSize, compressedBuffer, cSize-1);
354 if (!ZSTD_isError(r)) goto _output_error;
355 if (ZSTD_getErrorCode((size_t)r) != ZSTD_error_srcSize_wrong) goto _output_error; }
356 DISPLAYLEVEL(4, "OK \n");
358 DISPLAYLEVEL(4, "test%3i : decompress with 1 too much byte : ", testNb++);
359 { size_t const r = ZSTD_decompress(decodedBuffer, CNBuffSize, compressedBuffer, cSize+1);
360 if (!ZSTD_isError(r)) goto _output_error;
361 if (ZSTD_getErrorCode(r) != ZSTD_error_srcSize_wrong) goto _output_error; }
362 DISPLAYLEVEL(4, "OK \n");
364 DISPLAYLEVEL(4, "test%di : check CCtx size after compressing empty input : ", testNb++);
365 { ZSTD_CCtx* cctx = ZSTD_createCCtx();
366 size_t const r = ZSTD_compressCCtx(cctx, compressedBuffer, compressedBufferSize, NULL, 0, 19);
367 if (ZSTD_isError(r)) goto _output_error;
368 if (ZSTD_sizeof_CCtx(cctx) > (1U << 20)) goto _output_error;
371 DISPLAYLEVEL(4, "OK \n");
373 DISPLAYLEVEL(4, "test%di : re-use CCtx with expanding block size : ", testNb++);
374 { ZSTD_CCtx* const cctx = ZSTD_createCCtx();
375 ZSTD_parameters const params = ZSTD_getParams(1, ZSTD_CONTENTSIZE_UNKNOWN, 0);
376 assert(params.fParams.contentSizeFlag == 1); /* block size will be adapted if pledgedSrcSize is enabled */
377 CHECK_Z( ZSTD_compressBegin_advanced(cctx, NULL, 0, params, 1 /*pledgedSrcSize*/) );
378 CHECK_Z( ZSTD_compressEnd(cctx, compressedBuffer, compressedBufferSize, CNBuffer, 1) ); /* creates a block size of 1 */
380 CHECK_Z( ZSTD_compressBegin_advanced(cctx, NULL, 0, params, ZSTD_CONTENTSIZE_UNKNOWN) ); /* re-use same parameters */
381 { size_t const inSize = 2* 128 KB;
382 size_t const outSize = ZSTD_compressBound(inSize);
383 CHECK_Z( ZSTD_compressEnd(cctx, compressedBuffer, outSize, CNBuffer, inSize) );
384 /* will fail if blockSize is not resized */
388 DISPLAYLEVEL(4, "OK \n");
390 /* Static CCtx tests */
391 #define STATIC_CCTX_LEVEL 3
392 DISPLAYLEVEL(4, "test%3i : create static CCtx for level %u :", testNb++, STATIC_CCTX_LEVEL);
393 { size_t const staticCCtxSize = ZSTD_estimateCStreamSize(STATIC_CCTX_LEVEL);
394 void* const staticCCtxBuffer = malloc(staticCCtxSize);
395 size_t const staticDCtxSize = ZSTD_estimateDCtxSize();
396 void* const staticDCtxBuffer = malloc(staticDCtxSize);
397 if (staticCCtxBuffer==NULL || staticDCtxBuffer==NULL) {
398 free(staticCCtxBuffer);
399 free(staticDCtxBuffer);
400 DISPLAY("Not enough memory, aborting\n");
404 { ZSTD_CCtx* staticCCtx = ZSTD_initStaticCCtx(staticCCtxBuffer, staticCCtxSize);
405 ZSTD_DCtx* staticDCtx = ZSTD_initStaticDCtx(staticDCtxBuffer, staticDCtxSize);
406 if ((staticCCtx==NULL) || (staticDCtx==NULL)) goto _output_error;
407 DISPLAYLEVEL(4, "OK \n");
409 DISPLAYLEVEL(4, "test%3i : init CCtx for level %u : ", testNb++, STATIC_CCTX_LEVEL);
410 { size_t const r = ZSTD_compressBegin(staticCCtx, STATIC_CCTX_LEVEL);
411 if (ZSTD_isError(r)) goto _output_error; }
412 DISPLAYLEVEL(4, "OK \n");
414 DISPLAYLEVEL(4, "test%3i : simple compression test with static CCtx : ", testNb++);
415 CHECKPLUS(r, ZSTD_compressCCtx(staticCCtx,
416 compressedBuffer, compressedBufferSize,
417 CNBuffer, CNBuffSize, STATIC_CCTX_LEVEL),
419 DISPLAYLEVEL(4, "OK (%u bytes : %.2f%%)\n",
420 (U32)cSize, (double)cSize/CNBuffSize*100);
422 DISPLAYLEVEL(4, "test%3i : simple decompression test with static DCtx : ", testNb++);
423 { size_t const r = ZSTD_decompressDCtx(staticDCtx,
424 decodedBuffer, CNBuffSize,
425 compressedBuffer, cSize);
426 if (r != CNBuffSize) goto _output_error; }
427 DISPLAYLEVEL(4, "OK \n");
429 DISPLAYLEVEL(4, "test%3i : check decompressed result : ", testNb++);
431 for (u=0; u<CNBuffSize; u++) {
432 if (((BYTE*)decodedBuffer)[u] != ((BYTE*)CNBuffer)[u])
435 DISPLAYLEVEL(4, "OK \n");
437 DISPLAYLEVEL(4, "test%3i : init CCtx for too large level (must fail) : ", testNb++);
438 { size_t const r = ZSTD_compressBegin(staticCCtx, ZSTD_maxCLevel());
439 if (!ZSTD_isError(r)) goto _output_error; }
440 DISPLAYLEVEL(4, "OK \n");
442 DISPLAYLEVEL(4, "test%3i : init CCtx for small level %u (should work again) : ", testNb++, 1);
443 { size_t const r = ZSTD_compressBegin(staticCCtx, 1);
444 if (ZSTD_isError(r)) goto _output_error; }
445 DISPLAYLEVEL(4, "OK \n");
447 DISPLAYLEVEL(4, "test%3i : init CStream for small level %u : ", testNb++, 1);
448 { size_t const r = ZSTD_initCStream(staticCCtx, 1);
449 if (ZSTD_isError(r)) goto _output_error; }
450 DISPLAYLEVEL(4, "OK \n");
452 DISPLAYLEVEL(4, "test%3i : init CStream with dictionary (should fail) : ", testNb++);
453 { size_t const r = ZSTD_initCStream_usingDict(staticCCtx, CNBuffer, 64 KB, 1);
454 if (!ZSTD_isError(r)) goto _output_error; }
455 DISPLAYLEVEL(4, "OK \n");
457 DISPLAYLEVEL(4, "test%3i : init DStream (should fail) : ", testNb++);
458 { size_t const r = ZSTD_initDStream(staticDCtx);
459 if (ZSTD_isError(r)) goto _output_error; }
460 { ZSTD_outBuffer output = { decodedBuffer, CNBuffSize, 0 };
461 ZSTD_inBuffer input = { compressedBuffer, ZSTD_FRAMEHEADERSIZE_MAX+1, 0 };
462 size_t const r = ZSTD_decompressStream(staticDCtx, &output, &input);
463 if (!ZSTD_isError(r)) goto _output_error;
465 DISPLAYLEVEL(4, "OK \n");
467 free(staticCCtxBuffer);
468 free(staticDCtxBuffer);
473 /* ZSTDMT simple MT compression test */
474 DISPLAYLEVEL(4, "test%3i : create ZSTDMT CCtx : ", testNb++);
475 { ZSTDMT_CCtx* mtctx = ZSTDMT_createCCtx(2);
477 DISPLAY("mtctx : mot enough memory, aborting \n");
481 DISPLAYLEVEL(4, "OK \n");
483 DISPLAYLEVEL(4, "test%3i : compress %u bytes with 2 threads : ", testNb++, (U32)CNBuffSize);
484 CHECKPLUS(r, ZSTDMT_compressCCtx(mtctx,
485 compressedBuffer, compressedBufferSize,
486 CNBuffer, CNBuffSize,
489 DISPLAYLEVEL(4, "OK (%u bytes : %.2f%%)\n", (U32)cSize, (double)cSize/CNBuffSize*100);
491 DISPLAYLEVEL(4, "test%3i : decompressed size test : ", testNb++);
492 { unsigned long long const rSize = ZSTD_getFrameContentSize(compressedBuffer, cSize);
493 if (rSize != CNBuffSize) {
494 DISPLAY("ZSTD_getFrameContentSize incorrect : %u != %u \n", (U32)rSize, (U32)CNBuffSize);
497 DISPLAYLEVEL(4, "OK \n");
499 DISPLAYLEVEL(4, "test%3i : decompress %u bytes : ", testNb++, (U32)CNBuffSize);
500 { size_t const r = ZSTD_decompress(decodedBuffer, CNBuffSize, compressedBuffer, cSize);
501 if (r != CNBuffSize) goto _output_error; }
502 DISPLAYLEVEL(4, "OK \n");
504 DISPLAYLEVEL(4, "test%3i : check decompressed result : ", testNb++);
506 for (u=0; u<CNBuffSize; u++) {
507 if (((BYTE*)decodedBuffer)[u] != ((BYTE*)CNBuffer)[u]) goto _output_error;;
509 DISPLAYLEVEL(4, "OK \n");
511 DISPLAYLEVEL(4, "test%3i : compress -T2 with checksum : ", testNb++);
512 { ZSTD_parameters params = ZSTD_getParams(1, CNBuffSize, 0);
513 params.fParams.checksumFlag = 1;
514 params.fParams.contentSizeFlag = 1;
515 CHECKPLUS(r, ZSTDMT_compress_advanced(mtctx,
516 compressedBuffer, compressedBufferSize,
517 CNBuffer, CNBuffSize,
518 NULL, params, 3 /*overlapRLog*/),
521 DISPLAYLEVEL(4, "OK (%u bytes : %.2f%%)\n", (U32)cSize, (double)cSize/CNBuffSize*100);
523 DISPLAYLEVEL(4, "test%3i : decompress %u bytes : ", testNb++, (U32)CNBuffSize);
524 { size_t const r = ZSTD_decompress(decodedBuffer, CNBuffSize, compressedBuffer, cSize);
525 if (r != CNBuffSize) goto _output_error; }
526 DISPLAYLEVEL(4, "OK \n");
528 ZSTDMT_freeCCtx(mtctx);
532 /* Simple API multiframe test */
533 DISPLAYLEVEL(4, "test%3i : compress multiple frames : ", testNb++);
537 /* only use the first half so we don't push against size limit of compressedBuffer */
538 size_t const segSize = (CNBuffSize / 2) / segs;
539 for (i = 0; i < segs; i++) {
540 CHECK_V(r, ZSTD_compress(
541 (BYTE *)compressedBuffer + off, CNBuffSize - off,
542 (BYTE *)CNBuffer + segSize * i,
546 /* insert skippable frame */
547 const U32 skipLen = 129 KB;
548 MEM_writeLE32((BYTE*)compressedBuffer + off, ZSTD_MAGIC_SKIPPABLE_START);
549 MEM_writeLE32((BYTE*)compressedBuffer + off + 4, skipLen);
550 off += skipLen + ZSTD_skippableHeaderSize;
555 DISPLAYLEVEL(4, "OK \n");
557 DISPLAYLEVEL(4, "test%3i : get decompressed size of multiple frames : ", testNb++);
558 { unsigned long long const r = ZSTD_findDecompressedSize(compressedBuffer, cSize);
559 if (r != CNBuffSize / 2) goto _output_error; }
560 DISPLAYLEVEL(4, "OK \n");
562 DISPLAYLEVEL(4, "test%3i : decompress multiple frames : ", testNb++);
563 { CHECK_V(r, ZSTD_decompress(decodedBuffer, CNBuffSize, compressedBuffer, cSize));
564 if (r != CNBuffSize / 2) goto _output_error; }
565 DISPLAYLEVEL(4, "OK \n");
567 DISPLAYLEVEL(4, "test%3i : check decompressed result : ", testNb++);
568 if (memcmp(decodedBuffer, CNBuffer, CNBuffSize / 2) != 0) goto _output_error;
569 DISPLAYLEVEL(4, "OK \n");
571 /* Dictionary and CCtx Duplication tests */
572 { ZSTD_CCtx* const ctxOrig = ZSTD_createCCtx();
573 ZSTD_CCtx* const ctxDuplicated = ZSTD_createCCtx();
574 static const size_t dictSize = 551;
576 DISPLAYLEVEL(4, "test%3i : copy context too soon : ", testNb++);
577 { size_t const copyResult = ZSTD_copyCCtx(ctxDuplicated, ctxOrig, 0);
578 if (!ZSTD_isError(copyResult)) goto _output_error; } /* error must be detected */
579 DISPLAYLEVEL(4, "OK \n");
581 DISPLAYLEVEL(4, "test%3i : load dictionary into context : ", testNb++);
582 CHECK( ZSTD_compressBegin_usingDict(ctxOrig, CNBuffer, dictSize, 2) );
583 CHECK( ZSTD_copyCCtx(ctxDuplicated, ctxOrig, 0) ); /* Begin_usingDict implies unknown srcSize, so match that */
584 DISPLAYLEVEL(4, "OK \n");
586 DISPLAYLEVEL(4, "test%3i : compress with flat dictionary : ", testNb++);
588 CHECKPLUS(r, ZSTD_compressEnd(ctxOrig, compressedBuffer, compressedBufferSize,
589 (const char*)CNBuffer + dictSize, CNBuffSize - dictSize),
591 DISPLAYLEVEL(4, "OK (%u bytes : %.2f%%)\n", (U32)cSize, (double)cSize/CNBuffSize*100);
593 DISPLAYLEVEL(4, "test%3i : frame built with flat dictionary should be decompressible : ", testNb++);
594 CHECKPLUS(r, ZSTD_decompress_usingDict(dctx,
595 decodedBuffer, CNBuffSize,
596 compressedBuffer, cSize,
598 if (r != CNBuffSize - dictSize) goto _output_error);
599 DISPLAYLEVEL(4, "OK \n");
601 DISPLAYLEVEL(4, "test%3i : compress with duplicated context : ", testNb++);
602 { size_t const cSizeOrig = cSize;
604 CHECKPLUS(r, ZSTD_compressEnd(ctxDuplicated, compressedBuffer, compressedBufferSize,
605 (const char*)CNBuffer + dictSize, CNBuffSize - dictSize),
607 if (cSize != cSizeOrig) goto _output_error; /* should be identical ==> same size */
609 DISPLAYLEVEL(4, "OK (%u bytes : %.2f%%)\n", (U32)cSize, (double)cSize/CNBuffSize*100);
611 DISPLAYLEVEL(4, "test%3i : frame built with duplicated context should be decompressible : ", testNb++);
612 CHECKPLUS(r, ZSTD_decompress_usingDict(dctx,
613 decodedBuffer, CNBuffSize,
614 compressedBuffer, cSize,
616 if (r != CNBuffSize - dictSize) goto _output_error);
617 DISPLAYLEVEL(4, "OK \n");
619 DISPLAYLEVEL(4, "test%3i : decompress with DDict : ", testNb++);
620 { ZSTD_DDict* const ddict = ZSTD_createDDict(CNBuffer, dictSize);
621 size_t const r = ZSTD_decompress_usingDDict(dctx, decodedBuffer, CNBuffSize, compressedBuffer, cSize, ddict);
622 if (r != CNBuffSize - dictSize) goto _output_error;
623 DISPLAYLEVEL(4, "OK (size of DDict : %u) \n", (U32)ZSTD_sizeof_DDict(ddict));
624 ZSTD_freeDDict(ddict);
627 DISPLAYLEVEL(4, "test%3i : decompress with static DDict : ", testNb++);
628 { size_t const ddictBufferSize = ZSTD_estimateDDictSize(dictSize, ZSTD_dlm_byCopy);
629 void* ddictBuffer = malloc(ddictBufferSize);
630 if (ddictBuffer == NULL) goto _output_error;
631 { ZSTD_DDict* const ddict = ZSTD_initStaticDDict(ddictBuffer, ddictBufferSize, CNBuffer, dictSize, ZSTD_dlm_byCopy);
632 size_t const r = ZSTD_decompress_usingDDict(dctx, decodedBuffer, CNBuffSize, compressedBuffer, cSize, ddict);
633 if (r != CNBuffSize - dictSize) goto _output_error;
636 DISPLAYLEVEL(4, "OK (size of static DDict : %u) \n", (U32)ddictBufferSize);
639 DISPLAYLEVEL(4, "test%3i : check content size on duplicated context : ", testNb++);
640 { size_t const testSize = CNBuffSize / 3;
641 { ZSTD_parameters p = ZSTD_getParams(2, testSize, dictSize);
642 p.fParams.contentSizeFlag = 1;
643 CHECK( ZSTD_compressBegin_advanced(ctxOrig, CNBuffer, dictSize, p, testSize-1) );
645 CHECK( ZSTD_copyCCtx(ctxDuplicated, ctxOrig, testSize) );
647 CHECKPLUS(r, ZSTD_compressEnd(ctxDuplicated, compressedBuffer, ZSTD_compressBound(testSize),
648 (const char*)CNBuffer + dictSize, testSize),
650 { ZSTD_frameHeader zfh;
651 if (ZSTD_getFrameHeader(&zfh, compressedBuffer, cSize)) goto _output_error;
652 if ((zfh.frameContentSize != testSize) && (zfh.frameContentSize != 0)) goto _output_error;
654 DISPLAYLEVEL(4, "OK \n");
656 ZSTD_freeCCtx(ctxOrig);
657 ZSTD_freeCCtx(ctxDuplicated);
660 /* Dictionary and dictBuilder tests */
661 { ZSTD_CCtx* const cctx = ZSTD_createCCtx();
662 size_t dictSize = 16 KB;
663 void* dictBuffer = malloc(dictSize);
664 size_t const totalSampleSize = 1 MB;
665 size_t const sampleUnitSize = 8 KB;
666 U32 const nbSamples = (U32)(totalSampleSize / sampleUnitSize);
667 size_t* const samplesSizes = (size_t*) malloc(nbSamples * sizeof(size_t));
670 if (dictBuffer==NULL || samplesSizes==NULL) {
676 DISPLAYLEVEL(4, "test%3i : dictBuilder : ", testNb++);
677 { U32 u; for (u=0; u<nbSamples; u++) samplesSizes[u] = sampleUnitSize; }
678 dictSize = ZDICT_trainFromBuffer(dictBuffer, dictSize,
679 CNBuffer, samplesSizes, nbSamples);
680 if (ZDICT_isError(dictSize)) goto _output_error;
681 DISPLAYLEVEL(4, "OK, created dictionary of size %u \n", (U32)dictSize);
683 DISPLAYLEVEL(4, "test%3i : check dictID : ", testNb++);
684 dictID = ZDICT_getDictID(dictBuffer, dictSize);
685 if (dictID==0) goto _output_error;
686 DISPLAYLEVEL(4, "OK : %u \n", dictID);
688 DISPLAYLEVEL(4, "test%3i : compress with dictionary : ", testNb++);
689 cSize = ZSTD_compress_usingDict(cctx, compressedBuffer, compressedBufferSize,
690 CNBuffer, CNBuffSize,
691 dictBuffer, dictSize, 4);
692 if (ZSTD_isError(cSize)) goto _output_error;
693 DISPLAYLEVEL(4, "OK (%u bytes : %.2f%%)\n", (U32)cSize, (double)cSize/CNBuffSize*100);
695 DISPLAYLEVEL(4, "test%3i : retrieve dictID from dictionary : ", testNb++);
696 { U32 const did = ZSTD_getDictID_fromDict(dictBuffer, dictSize);
697 if (did != dictID) goto _output_error; /* non-conformant (content-only) dictionary */
699 DISPLAYLEVEL(4, "OK \n");
701 DISPLAYLEVEL(4, "test%3i : retrieve dictID from frame : ", testNb++);
702 { U32 const did = ZSTD_getDictID_fromFrame(compressedBuffer, cSize);
703 if (did != dictID) goto _output_error; /* non-conformant (content-only) dictionary */
705 DISPLAYLEVEL(4, "OK \n");
707 DISPLAYLEVEL(4, "test%3i : frame built with dictionary should be decompressible : ", testNb++);
708 CHECKPLUS(r, ZSTD_decompress_usingDict(dctx,
709 decodedBuffer, CNBuffSize,
710 compressedBuffer, cSize,
711 dictBuffer, dictSize),
712 if (r != CNBuffSize) goto _output_error);
713 DISPLAYLEVEL(4, "OK \n");
715 DISPLAYLEVEL(4, "test%3i : estimate CDict size : ", testNb++);
716 { ZSTD_compressionParameters const cParams = ZSTD_getCParams(1, CNBuffSize, dictSize);
717 size_t const estimatedSize = ZSTD_estimateCDictSize_advanced(dictSize, cParams, ZSTD_dlm_byRef);
718 DISPLAYLEVEL(4, "OK : %u \n", (U32)estimatedSize);
721 DISPLAYLEVEL(4, "test%3i : compress with CDict ", testNb++);
722 { ZSTD_compressionParameters const cParams = ZSTD_getCParams(1, CNBuffSize, dictSize);
723 ZSTD_CDict* const cdict = ZSTD_createCDict_advanced(dictBuffer, dictSize,
724 ZSTD_dlm_byRef, ZSTD_dm_auto,
725 cParams, ZSTD_defaultCMem);
726 DISPLAYLEVEL(4, "(size : %u) : ", (U32)ZSTD_sizeof_CDict(cdict));
727 cSize = ZSTD_compress_usingCDict(cctx, compressedBuffer, compressedBufferSize,
728 CNBuffer, CNBuffSize, cdict);
729 ZSTD_freeCDict(cdict);
730 if (ZSTD_isError(cSize)) goto _output_error;
732 DISPLAYLEVEL(4, "OK (%u bytes : %.2f%%)\n", (U32)cSize, (double)cSize/CNBuffSize*100);
734 DISPLAYLEVEL(4, "test%3i : retrieve dictID from frame : ", testNb++);
735 { U32 const did = ZSTD_getDictID_fromFrame(compressedBuffer, cSize);
736 if (did != dictID) goto _output_error; /* non-conformant (content-only) dictionary */
738 DISPLAYLEVEL(4, "OK \n");
740 DISPLAYLEVEL(4, "test%3i : frame built with dictionary should be decompressible : ", testNb++);
741 CHECKPLUS(r, ZSTD_decompress_usingDict(dctx,
742 decodedBuffer, CNBuffSize,
743 compressedBuffer, cSize,
744 dictBuffer, dictSize),
745 if (r != CNBuffSize) goto _output_error);
746 DISPLAYLEVEL(4, "OK \n");
748 DISPLAYLEVEL(4, "test%3i : compress with static CDict : ", testNb++);
749 { ZSTD_compressionParameters const cParams = ZSTD_getCParams(1, CNBuffSize, dictSize);
750 size_t const cdictSize = ZSTD_estimateCDictSize_advanced(dictSize, cParams, ZSTD_dlm_byCopy);
751 void* const cdictBuffer = malloc(cdictSize);
752 if (cdictBuffer==NULL) goto _output_error;
753 { ZSTD_CDict* const cdict = ZSTD_initStaticCDict(cdictBuffer, cdictSize,
754 dictBuffer, dictSize,
755 ZSTD_dlm_byCopy, ZSTD_dm_auto,
758 DISPLAY("ZSTD_initStaticCDict failed ");
761 cSize = ZSTD_compress_usingCDict(cctx,
762 compressedBuffer, compressedBufferSize,
763 CNBuffer, CNBuffSize, cdict);
764 if (ZSTD_isError(cSize)) {
765 DISPLAY("ZSTD_compress_usingCDict failed ");
770 DISPLAYLEVEL(4, "OK (%u bytes : %.2f%%)\n", (U32)cSize, (double)cSize/CNBuffSize*100);
772 DISPLAYLEVEL(4, "test%3i : ZSTD_compress_usingCDict_advanced, no contentSize, no dictID : ", testNb++);
773 { ZSTD_frameParameters const fParams = { 0 /* frameSize */, 1 /* checksum */, 1 /* noDictID*/ };
774 ZSTD_compressionParameters const cParams = ZSTD_getCParams(1, CNBuffSize, dictSize);
775 ZSTD_CDict* const cdict = ZSTD_createCDict_advanced(dictBuffer, dictSize, ZSTD_dlm_byRef, ZSTD_dm_auto, cParams, ZSTD_defaultCMem);
776 cSize = ZSTD_compress_usingCDict_advanced(cctx, compressedBuffer, compressedBufferSize,
777 CNBuffer, CNBuffSize, cdict, fParams);
778 ZSTD_freeCDict(cdict);
779 if (ZSTD_isError(cSize)) goto _output_error;
781 DISPLAYLEVEL(4, "OK (%u bytes : %.2f%%)\n", (U32)cSize, (double)cSize/CNBuffSize*100);
783 DISPLAYLEVEL(4, "test%3i : try retrieving contentSize from frame : ", testNb++);
784 { U64 const contentSize = ZSTD_getFrameContentSize(compressedBuffer, cSize);
785 if (contentSize != ZSTD_CONTENTSIZE_UNKNOWN) goto _output_error;
787 DISPLAYLEVEL(4, "OK (unknown)\n");
789 DISPLAYLEVEL(4, "test%3i : frame built without dictID should be decompressible : ", testNb++);
790 CHECKPLUS(r, ZSTD_decompress_usingDict(dctx,
791 decodedBuffer, CNBuffSize,
792 compressedBuffer, cSize,
793 dictBuffer, dictSize),
794 if (r != CNBuffSize) goto _output_error);
795 DISPLAYLEVEL(4, "OK \n");
797 DISPLAYLEVEL(4, "test%3i : ZSTD_compress_advanced, no dictID : ", testNb++);
798 { ZSTD_parameters p = ZSTD_getParams(3, CNBuffSize, dictSize);
799 p.fParams.noDictIDFlag = 1;
800 cSize = ZSTD_compress_advanced(cctx, compressedBuffer, compressedBufferSize,
801 CNBuffer, CNBuffSize,
802 dictBuffer, dictSize, p);
803 if (ZSTD_isError(cSize)) goto _output_error;
805 DISPLAYLEVEL(4, "OK (%u bytes : %.2f%%)\n", (U32)cSize, (double)cSize/CNBuffSize*100);
807 DISPLAYLEVEL(4, "test%3i : frame built without dictID should be decompressible : ", testNb++);
808 CHECKPLUS(r, ZSTD_decompress_usingDict(dctx,
809 decodedBuffer, CNBuffSize,
810 compressedBuffer, cSize,
811 dictBuffer, dictSize),
812 if (r != CNBuffSize) goto _output_error);
813 DISPLAYLEVEL(4, "OK \n");
815 DISPLAYLEVEL(4, "test%3i : dictionary containing only header should return error : ", testNb++);
817 const size_t ret = ZSTD_decompress_usingDict(
818 dctx, decodedBuffer, CNBuffSize, compressedBuffer, cSize,
819 "\x37\xa4\x30\xec\x11\x22\x33\x44", 8);
820 if (ZSTD_getErrorCode(ret) != ZSTD_error_dictionary_corrupted) goto _output_error;
822 DISPLAYLEVEL(4, "OK \n");
824 DISPLAYLEVEL(4, "test%3i : Building cdict w/ ZSTD_dm_fullDict on a good dictionary : ", testNb++);
825 { ZSTD_compressionParameters const cParams = ZSTD_getCParams(1, CNBuffSize, dictSize);
826 ZSTD_CDict* const cdict = ZSTD_createCDict_advanced(dictBuffer, dictSize, ZSTD_dlm_byRef, ZSTD_dm_fullDict, cParams, ZSTD_defaultCMem);
827 if (cdict==NULL) goto _output_error;
828 ZSTD_freeCDict(cdict);
830 DISPLAYLEVEL(4, "OK \n");
832 DISPLAYLEVEL(4, "test%3i : Building cdict w/ ZSTD_dm_fullDict on a rawContent (must fail) : ", testNb++);
833 { ZSTD_compressionParameters const cParams = ZSTD_getCParams(1, CNBuffSize, dictSize);
834 ZSTD_CDict* const cdict = ZSTD_createCDict_advanced((const char*)dictBuffer+1, dictSize-1, ZSTD_dlm_byRef, ZSTD_dm_fullDict, cParams, ZSTD_defaultCMem);
835 if (cdict!=NULL) goto _output_error;
836 ZSTD_freeCDict(cdict);
838 DISPLAYLEVEL(4, "OK \n");
840 DISPLAYLEVEL(4, "test%3i : Loading rawContent starting with dict header w/ ZSTD_dm_auto should fail : ", testNb++);
843 MEM_writeLE32((char*)dictBuffer+2, ZSTD_MAGIC_DICTIONARY);
844 ret = ZSTD_CCtx_loadDictionary_advanced(
845 cctx, (const char*)dictBuffer+2, dictSize-2, ZSTD_dlm_byRef, ZSTD_dm_auto);
846 if (!ZSTD_isError(ret)) goto _output_error;
848 DISPLAYLEVEL(4, "OK \n");
850 DISPLAYLEVEL(4, "test%3i : Loading rawContent starting with dict header w/ ZSTD_dm_rawContent should pass : ", testNb++);
853 MEM_writeLE32((char*)dictBuffer+2, ZSTD_MAGIC_DICTIONARY);
854 ret = ZSTD_CCtx_loadDictionary_advanced(
855 cctx, (const char*)dictBuffer+2, dictSize-2, ZSTD_dlm_byRef, ZSTD_dm_rawContent);
856 if (ZSTD_isError(ret)) goto _output_error;
858 DISPLAYLEVEL(4, "OK \n");
860 DISPLAYLEVEL(4, "test%3i : Dictionary with non-default repcodes : ", testNb++);
861 { U32 u; for (u=0; u<nbSamples; u++) samplesSizes[u] = sampleUnitSize; }
862 dictSize = ZDICT_trainFromBuffer(dictBuffer, dictSize,
863 CNBuffer, samplesSizes, nbSamples);
864 if (ZDICT_isError(dictSize)) goto _output_error;
865 /* Set all the repcodes to non-default */
867 BYTE* dictPtr = (BYTE*)dictBuffer;
868 BYTE* dictLimit = dictPtr + dictSize - 12;
869 /* Find the repcodes */
870 while (dictPtr < dictLimit &&
871 (MEM_readLE32(dictPtr) != 1 || MEM_readLE32(dictPtr + 4) != 4 ||
872 MEM_readLE32(dictPtr + 8) != 8)) {
875 if (dictPtr >= dictLimit) goto _output_error;
876 MEM_writeLE32(dictPtr + 0, 10);
877 MEM_writeLE32(dictPtr + 4, 10);
878 MEM_writeLE32(dictPtr + 8, 10);
879 /* Set the last 8 bytes to 'x' */
880 memset((BYTE*)dictBuffer + dictSize - 8, 'x', 8);
882 /* The optimal parser checks all the repcodes.
883 * Make sure at least one is a match >= targetLength so that it is
884 * immediately chosen. This will make sure that the compressor and
885 * decompressor agree on at least one of the repcodes.
889 ZSTD_compressionParameters const cParams = ZSTD_getCParams(19, CNBuffSize, dictSize);
890 ZSTD_CDict* const cdict = ZSTD_createCDict_advanced(dictBuffer, dictSize,
891 ZSTD_dlm_byRef, ZSTD_dm_auto,
892 cParams, ZSTD_defaultCMem);
893 memset(data, 'x', sizeof(data));
894 cSize = ZSTD_compress_usingCDict(cctx, compressedBuffer, compressedBufferSize,
895 data, sizeof(data), cdict);
896 ZSTD_freeCDict(cdict);
897 if (ZSTD_isError(cSize)) { DISPLAYLEVEL(5, "Compression error %s : ", ZSTD_getErrorName(cSize)); goto _output_error; }
898 dSize = ZSTD_decompress_usingDict(dctx, decodedBuffer, sizeof(data), compressedBuffer, cSize, dictBuffer, dictSize);
899 if (ZSTD_isError(dSize)) { DISPLAYLEVEL(5, "Decompression error %s : ", ZSTD_getErrorName(dSize)); goto _output_error; }
900 if (memcmp(data, decodedBuffer, sizeof(data))) { DISPLAYLEVEL(5, "Data corruption : "); goto _output_error; }
902 DISPLAYLEVEL(4, "OK \n");
909 /* COVER dictionary builder tests */
910 { ZSTD_CCtx* const cctx = ZSTD_createCCtx();
911 size_t dictSize = 16 KB;
912 size_t optDictSize = dictSize;
913 void* dictBuffer = malloc(dictSize);
914 size_t const totalSampleSize = 1 MB;
915 size_t const sampleUnitSize = 8 KB;
916 U32 const nbSamples = (U32)(totalSampleSize / sampleUnitSize);
917 size_t* const samplesSizes = (size_t*) malloc(nbSamples * sizeof(size_t));
918 ZDICT_cover_params_t params;
921 if (dictBuffer==NULL || samplesSizes==NULL) {
927 DISPLAYLEVEL(4, "test%3i : ZDICT_trainFromBuffer_cover : ", testNb++);
928 { U32 u; for (u=0; u<nbSamples; u++) samplesSizes[u] = sampleUnitSize; }
929 memset(¶ms, 0, sizeof(params));
930 params.d = 1 + (FUZ_rand(&seed) % 16);
931 params.k = params.d + (FUZ_rand(&seed) % 256);
932 dictSize = ZDICT_trainFromBuffer_cover(dictBuffer, dictSize,
933 CNBuffer, samplesSizes, nbSamples,
935 if (ZDICT_isError(dictSize)) goto _output_error;
936 DISPLAYLEVEL(4, "OK, created dictionary of size %u \n", (U32)dictSize);
938 DISPLAYLEVEL(4, "test%3i : check dictID : ", testNb++);
939 dictID = ZDICT_getDictID(dictBuffer, dictSize);
940 if (dictID==0) goto _output_error;
941 DISPLAYLEVEL(4, "OK : %u \n", dictID);
943 DISPLAYLEVEL(4, "test%3i : ZDICT_optimizeTrainFromBuffer_cover : ", testNb++);
944 memset(¶ms, 0, sizeof(params));
946 optDictSize = ZDICT_optimizeTrainFromBuffer_cover(dictBuffer, optDictSize,
947 CNBuffer, samplesSizes,
948 nbSamples / 4, ¶ms);
949 if (ZDICT_isError(optDictSize)) goto _output_error;
950 DISPLAYLEVEL(4, "OK, created dictionary of size %u \n", (U32)optDictSize);
952 DISPLAYLEVEL(4, "test%3i : check dictID : ", testNb++);
953 dictID = ZDICT_getDictID(dictBuffer, optDictSize);
954 if (dictID==0) goto _output_error;
955 DISPLAYLEVEL(4, "OK : %u \n", dictID);
962 /* Decompression defense tests */
963 DISPLAYLEVEL(4, "test%3i : Check input length for magic number : ", testNb++);
964 { size_t const r = ZSTD_decompress(decodedBuffer, CNBuffSize, CNBuffer, 3); /* too small input */
965 if (!ZSTD_isError(r)) goto _output_error;
966 if (ZSTD_getErrorCode(r) != ZSTD_error_srcSize_wrong) goto _output_error; }
967 DISPLAYLEVEL(4, "OK \n");
969 DISPLAYLEVEL(4, "test%3i : Check magic Number : ", testNb++);
970 ((char*)(CNBuffer))[0] = 1;
971 { size_t const r = ZSTD_decompress(decodedBuffer, CNBuffSize, CNBuffer, 4);
972 if (!ZSTD_isError(r)) goto _output_error; }
973 DISPLAYLEVEL(4, "OK \n");
975 /* content size verification test */
976 DISPLAYLEVEL(4, "test%3i : Content size verification : ", testNb++);
977 { ZSTD_CCtx* const cctx = ZSTD_createCCtx();
978 size_t const srcSize = 5000;
979 size_t const wrongSrcSize = (srcSize + 1000);
980 ZSTD_parameters params = ZSTD_getParams(1, wrongSrcSize, 0);
981 params.fParams.contentSizeFlag = 1;
982 CHECK( ZSTD_compressBegin_advanced(cctx, NULL, 0, params, wrongSrcSize) );
983 { size_t const result = ZSTD_compressEnd(cctx, decodedBuffer, CNBuffSize, CNBuffer, srcSize);
984 if (!ZSTD_isError(result)) goto _output_error;
985 if (ZSTD_getErrorCode(result) != ZSTD_error_srcSize_wrong) goto _output_error;
986 DISPLAYLEVEL(4, "OK : %s \n", ZSTD_getErrorName(result));
991 /* custom formats tests */
992 { ZSTD_CCtx* const cctx = ZSTD_createCCtx();
993 size_t const inputSize = CNBuffSize / 2; /* won't cause pb with small dict size */
995 /* basic block compression */
996 DISPLAYLEVEL(4, "test%3i : magic-less format test : ", testNb++);
997 CHECK( ZSTD_CCtx_setParameter(cctx, ZSTD_p_format, ZSTD_f_zstd1_magicless) );
998 { ZSTD_inBuffer in = { CNBuffer, inputSize, 0 };
999 ZSTD_outBuffer out = { compressedBuffer, ZSTD_compressBound(inputSize), 0 };
1000 size_t const result = ZSTD_compress_generic(cctx, &out, &in, ZSTD_e_end);
1001 if (result != 0) goto _output_error;
1002 if (in.pos != in.size) goto _output_error;
1005 DISPLAYLEVEL(4, "OK (compress : %u -> %u bytes)\n", (U32)inputSize, (U32)cSize);
1007 DISPLAYLEVEL(4, "test%3i : decompress normally (should fail) : ", testNb++);
1008 { size_t const decodeResult = ZSTD_decompressDCtx(dctx, decodedBuffer, CNBuffSize, compressedBuffer, cSize);
1009 if (ZSTD_getErrorCode(decodeResult) != ZSTD_error_prefix_unknown) goto _output_error;
1010 DISPLAYLEVEL(4, "OK : %s \n", ZSTD_getErrorName(decodeResult));
1013 DISPLAYLEVEL(4, "test%3i : decompress with magic-less instruction : ", testNb++);
1014 ZSTD_DCtx_reset(dctx);
1015 CHECK( ZSTD_DCtx_setFormat(dctx, ZSTD_f_zstd1_magicless) );
1016 { ZSTD_inBuffer in = { compressedBuffer, cSize, 0 };
1017 ZSTD_outBuffer out = { decodedBuffer, CNBuffSize, 0 };
1018 size_t const result = ZSTD_decompress_generic(dctx, &out, &in);
1019 if (result != 0) goto _output_error;
1020 if (in.pos != in.size) goto _output_error;
1021 if (out.pos != inputSize) goto _output_error;
1022 DISPLAYLEVEL(4, "OK : regenerated %u bytes \n", (U32)out.pos);
1025 ZSTD_freeCCtx(cctx);
1028 /* block API tests */
1029 { ZSTD_CCtx* const cctx = ZSTD_createCCtx();
1030 static const size_t dictSize = 65 KB;
1031 static const size_t blockSize = 100 KB; /* won't cause pb with small dict size */
1034 /* basic block compression */
1035 DISPLAYLEVEL(4, "test%3i : Block compression test : ", testNb++);
1036 CHECK( ZSTD_compressBegin(cctx, 5) );
1037 CHECK( ZSTD_getBlockSize(cctx) >= blockSize);
1038 cSize = ZSTD_compressBlock(cctx, compressedBuffer, ZSTD_compressBound(blockSize), CNBuffer, blockSize);
1039 if (ZSTD_isError(cSize)) goto _output_error;
1040 DISPLAYLEVEL(4, "OK \n");
1042 DISPLAYLEVEL(4, "test%3i : Block decompression test : ", testNb++);
1043 CHECK( ZSTD_decompressBegin(dctx) );
1044 { CHECK_V(r, ZSTD_decompressBlock(dctx, decodedBuffer, CNBuffSize, compressedBuffer, cSize) );
1045 if (r != blockSize) goto _output_error; }
1046 DISPLAYLEVEL(4, "OK \n");
1048 /* dictionary block compression */
1049 DISPLAYLEVEL(4, "test%3i : Dictionary Block compression test : ", testNb++);
1050 CHECK( ZSTD_compressBegin_usingDict(cctx, CNBuffer, dictSize, 5) );
1051 cSize = ZSTD_compressBlock(cctx, compressedBuffer, ZSTD_compressBound(blockSize), (char*)CNBuffer+dictSize, blockSize);
1052 if (ZSTD_isError(cSize)) goto _output_error;
1053 cSize2 = ZSTD_compressBlock(cctx, (char*)compressedBuffer+cSize, ZSTD_compressBound(blockSize), (char*)CNBuffer+dictSize+blockSize, blockSize);
1054 if (ZSTD_isError(cSize2)) goto _output_error;
1055 memcpy((char*)compressedBuffer+cSize, (char*)CNBuffer+dictSize+blockSize, blockSize); /* fake non-compressed block */
1056 cSize2 = ZSTD_compressBlock(cctx, (char*)compressedBuffer+cSize+blockSize, ZSTD_compressBound(blockSize),
1057 (char*)CNBuffer+dictSize+2*blockSize, blockSize);
1058 if (ZSTD_isError(cSize2)) goto _output_error;
1059 DISPLAYLEVEL(4, "OK \n");
1061 DISPLAYLEVEL(4, "test%3i : Dictionary Block decompression test : ", testNb++);
1062 CHECK( ZSTD_decompressBegin_usingDict(dctx, CNBuffer, dictSize) );
1063 { CHECK_V( r, ZSTD_decompressBlock(dctx, decodedBuffer, CNBuffSize, compressedBuffer, cSize) );
1064 if (r != blockSize) goto _output_error; }
1065 ZSTD_insertBlock(dctx, (char*)decodedBuffer+blockSize, blockSize); /* insert non-compressed block into dctx history */
1066 { CHECK_V( r, ZSTD_decompressBlock(dctx, (char*)decodedBuffer+2*blockSize, CNBuffSize, (char*)compressedBuffer+cSize+blockSize, cSize2) );
1067 if (r != blockSize) goto _output_error; }
1068 DISPLAYLEVEL(4, "OK \n");
1070 ZSTD_freeCCtx(cctx);
1072 ZSTD_freeDCtx(dctx);
1075 { size_t sampleSize = 0;
1076 DISPLAYLEVEL(4, "test%3i : Long RLE test : ", testNb++);
1077 RDG_genBuffer(CNBuffer, sampleSize, compressibility, 0., seed+1);
1078 memset((char*)CNBuffer+sampleSize, 'B', 256 KB - 1);
1079 sampleSize += 256 KB - 1;
1080 RDG_genBuffer((char*)CNBuffer+sampleSize, 96 KB, compressibility, 0., seed+2);
1081 sampleSize += 96 KB;
1082 cSize = ZSTD_compress(compressedBuffer, ZSTD_compressBound(sampleSize), CNBuffer, sampleSize, 1);
1083 if (ZSTD_isError(cSize)) goto _output_error;
1084 { CHECK_V(regenSize, ZSTD_decompress(decodedBuffer, sampleSize, compressedBuffer, cSize));
1085 if (regenSize!=sampleSize) goto _output_error; }
1086 DISPLAYLEVEL(4, "OK \n");
1089 /* All zeroes test (test bug #137) */
1090 #define ZEROESLENGTH 100
1091 DISPLAYLEVEL(4, "test%3i : compress %u zeroes : ", testNb++, ZEROESLENGTH);
1092 memset(CNBuffer, 0, ZEROESLENGTH);
1093 { CHECK_V(r, ZSTD_compress(compressedBuffer, ZSTD_compressBound(ZEROESLENGTH), CNBuffer, ZEROESLENGTH, 1) );
1095 DISPLAYLEVEL(4, "OK (%u bytes : %.2f%%)\n", (U32)cSize, (double)cSize/ZEROESLENGTH*100);
1097 DISPLAYLEVEL(4, "test%3i : decompress %u zeroes : ", testNb++, ZEROESLENGTH);
1098 { CHECK_V(r, ZSTD_decompress(decodedBuffer, ZEROESLENGTH, compressedBuffer, cSize) );
1099 if (r != ZEROESLENGTH) goto _output_error; }
1100 DISPLAYLEVEL(4, "OK \n");
1102 /* nbSeq limit test */
1103 #define _3BYTESTESTLENGTH 131000
1104 #define NB3BYTESSEQLOG 9
1105 #define NB3BYTESSEQ (1 << NB3BYTESSEQLOG)
1106 #define NB3BYTESSEQMASK (NB3BYTESSEQ-1)
1107 /* creates a buffer full of 3-bytes sequences */
1108 { BYTE _3BytesSeqs[NB3BYTESSEQ][3];
1111 /* create batch of 3-bytes sequences */
1113 for (i=0; i < NB3BYTESSEQ; i++) {
1114 _3BytesSeqs[i][0] = (BYTE)(FUZ_rand(&rSeed) & 255);
1115 _3BytesSeqs[i][1] = (BYTE)(FUZ_rand(&rSeed) & 255);
1116 _3BytesSeqs[i][2] = (BYTE)(FUZ_rand(&rSeed) & 255);
1119 /* randomly fills CNBuffer with prepared 3-bytes sequences */
1121 for (i=0; i < _3BYTESTESTLENGTH; i += 3) { /* note : CNBuffer size > _3BYTESTESTLENGTH+3 */
1122 U32 const id = FUZ_rand(&rSeed) & NB3BYTESSEQMASK;
1123 ((BYTE*)CNBuffer)[i+0] = _3BytesSeqs[id][0];
1124 ((BYTE*)CNBuffer)[i+1] = _3BytesSeqs[id][1];
1125 ((BYTE*)CNBuffer)[i+2] = _3BytesSeqs[id][2];
1127 DISPLAYLEVEL(4, "test%3i : compress lots 3-bytes sequences : ", testNb++);
1128 { CHECK_V(r, ZSTD_compress(compressedBuffer, ZSTD_compressBound(_3BYTESTESTLENGTH),
1129 CNBuffer, _3BYTESTESTLENGTH, 19) );
1131 DISPLAYLEVEL(4, "OK (%u bytes : %.2f%%)\n", (U32)cSize, (double)cSize/_3BYTESTESTLENGTH*100);
1133 DISPLAYLEVEL(4, "test%3i : decompress lots 3-bytes sequence : ", testNb++);
1134 { CHECK_V(r, ZSTD_decompress(decodedBuffer, _3BYTESTESTLENGTH, compressedBuffer, cSize) );
1135 if (r != _3BYTESTESTLENGTH) goto _output_error; }
1136 DISPLAYLEVEL(4, "OK \n");
1138 DISPLAYLEVEL(4, "test%3i : incompressible data and ill suited dictionary : ", testNb++);
1139 RDG_genBuffer(CNBuffer, CNBuffSize, 0.0, 0.1, seed);
1140 { /* Train a dictionary on low characters */
1141 size_t dictSize = 16 KB;
1142 void* const dictBuffer = malloc(dictSize);
1143 size_t const totalSampleSize = 1 MB;
1144 size_t const sampleUnitSize = 8 KB;
1145 U32 const nbSamples = (U32)(totalSampleSize / sampleUnitSize);
1146 size_t* const samplesSizes = (size_t*) malloc(nbSamples * sizeof(size_t));
1147 if (!dictBuffer || !samplesSizes) goto _output_error;
1148 { U32 u; for (u=0; u<nbSamples; u++) samplesSizes[u] = sampleUnitSize; }
1149 dictSize = ZDICT_trainFromBuffer(dictBuffer, dictSize, CNBuffer, samplesSizes, nbSamples);
1150 if (ZDICT_isError(dictSize)) goto _output_error;
1151 /* Reverse the characters to make the dictionary ill suited */
1153 for (u = 0; u < CNBuffSize; ++u) {
1154 ((BYTE*)CNBuffer)[u] = 255 - ((BYTE*)CNBuffer)[u];
1157 { /* Compress the data */
1158 size_t const inputSize = 500;
1159 size_t const outputSize = ZSTD_compressBound(inputSize);
1160 void* const outputBuffer = malloc(outputSize);
1161 ZSTD_CCtx* const cctx = ZSTD_createCCtx();
1162 if (!outputBuffer || !cctx) goto _output_error;
1163 CHECK(ZSTD_compress_usingDict(cctx, outputBuffer, outputSize, CNBuffer, inputSize, dictBuffer, dictSize, 1));
1165 ZSTD_freeCCtx(cctx);
1171 DISPLAYLEVEL(4, "OK \n");
1174 /* findFrameCompressedSize on skippable frames */
1175 DISPLAYLEVEL(4, "test%3i : frame compressed size of skippable frame : ", testNb++);
1176 { const char* frame = "\x50\x2a\x4d\x18\x05\x0\x0\0abcde";
1177 size_t const frameSrcSize = 13;
1178 if (ZSTD_findFrameCompressedSize(frame, frameSrcSize) != frameSrcSize) goto _output_error; }
1179 DISPLAYLEVEL(4, "OK \n");
1181 /* error string tests */
1182 DISPLAYLEVEL(4, "test%3i : testing ZSTD error code strings : ", testNb++);
1183 if (strcmp("No error detected", ZSTD_getErrorName((ZSTD_ErrorCode)(0-ZSTD_error_no_error))) != 0) goto _output_error;
1184 if (strcmp("No error detected", ZSTD_getErrorString(ZSTD_error_no_error)) != 0) goto _output_error;
1185 if (strcmp("Unspecified error code", ZSTD_getErrorString((ZSTD_ErrorCode)(0-ZSTD_error_GENERIC))) != 0) goto _output_error;
1186 if (strcmp("Error (generic)", ZSTD_getErrorName((size_t)0-ZSTD_error_GENERIC)) != 0) goto _output_error;
1187 if (strcmp("Error (generic)", ZSTD_getErrorString(ZSTD_error_GENERIC)) != 0) goto _output_error;
1188 if (strcmp("No error detected", ZSTD_getErrorName(ZSTD_error_GENERIC)) != 0) goto _output_error;
1189 DISPLAYLEVEL(4, "OK \n");
1193 free(compressedBuffer);
1194 free(decodedBuffer);
1199 DISPLAY("Error detected in Unit tests ! \n");
1204 static size_t findDiff(const void* buf1, const void* buf2, size_t max)
1206 const BYTE* b1 = (const BYTE*)buf1;
1207 const BYTE* b2 = (const BYTE*)buf2;
1209 for (u=0; u<max; u++) {
1210 if (b1[u] != b2[u]) break;
1216 static ZSTD_parameters FUZ_makeParams(ZSTD_compressionParameters cParams, ZSTD_frameParameters fParams)
1218 ZSTD_parameters params;
1219 params.cParams = cParams;
1220 params.fParams = fParams;
1224 static size_t FUZ_rLogLength(U32* seed, U32 logLength)
1226 size_t const lengthMask = ((size_t)1 << logLength) - 1;
1227 return (lengthMask+1) + (FUZ_rand(seed) & lengthMask);
1230 static size_t FUZ_randomLength(U32* seed, U32 maxLog)
1232 U32 const logLength = FUZ_rand(seed) % maxLog;
1233 return FUZ_rLogLength(seed, logLength);
1237 #define CHECK(cond, ...) { \
1239 DISPLAY("Error => "); \
1240 DISPLAY(__VA_ARGS__); \
1241 DISPLAY(" (seed %u, test nb %u) \n", seed, testNb); \
1242 goto _output_error; \
1246 #define CHECK_Z(f) { \
1247 size_t const err = f; \
1248 if (ZSTD_isError(err)) { \
1249 DISPLAY("Error => %s : %s ", \
1250 #f, ZSTD_getErrorName(err)); \
1251 DISPLAY(" (seed %u, test nb %u) \n", seed, testNb); \
1252 goto _output_error; \
1256 static int fuzzerTests(U32 seed, U32 nbTests, unsigned startTest, U32 const maxDurationS, double compressibility, int bigTests)
1258 static const U32 maxSrcLog = 23;
1259 static const U32 maxSampleLog = 22;
1260 size_t const srcBufferSize = (size_t)1<<maxSrcLog;
1261 size_t const dstBufferSize = (size_t)1<<maxSampleLog;
1262 size_t const cBufferSize = ZSTD_compressBound(dstBufferSize);
1263 BYTE* cNoiseBuffer[5];
1264 BYTE* srcBuffer; /* jumping pointer */
1265 BYTE* const cBuffer = (BYTE*) malloc (cBufferSize);
1266 BYTE* const dstBuffer = (BYTE*) malloc (dstBufferSize);
1267 BYTE* const mirrorBuffer = (BYTE*) malloc (dstBufferSize);
1268 ZSTD_CCtx* const refCtx = ZSTD_createCCtx();
1269 ZSTD_CCtx* const ctx = ZSTD_createCCtx();
1270 ZSTD_DCtx* const dctx = ZSTD_createDCtx();
1273 U32 coreSeed = seed, lseed = 0;
1274 UTIL_time_t const startClock = UTIL_getTime();
1275 U64 const maxClockSpan = maxDurationS * SEC_TO_MICRO;
1276 int const cLevelLimiter = bigTests ? 3 : 2;
1279 cNoiseBuffer[0] = (BYTE*)malloc (srcBufferSize);
1280 cNoiseBuffer[1] = (BYTE*)malloc (srcBufferSize);
1281 cNoiseBuffer[2] = (BYTE*)malloc (srcBufferSize);
1282 cNoiseBuffer[3] = (BYTE*)malloc (srcBufferSize);
1283 cNoiseBuffer[4] = (BYTE*)malloc (srcBufferSize);
1284 CHECK (!cNoiseBuffer[0] || !cNoiseBuffer[1] || !cNoiseBuffer[2] || !cNoiseBuffer[3] || !cNoiseBuffer[4]
1285 || !dstBuffer || !mirrorBuffer || !cBuffer || !refCtx || !ctx || !dctx,
1286 "Not enough memory, fuzzer tests cancelled");
1288 /* Create initial samples */
1289 RDG_genBuffer(cNoiseBuffer[0], srcBufferSize, 0.00, 0., coreSeed); /* pure noise */
1290 RDG_genBuffer(cNoiseBuffer[1], srcBufferSize, 0.05, 0., coreSeed); /* barely compressible */
1291 RDG_genBuffer(cNoiseBuffer[2], srcBufferSize, compressibility, 0., coreSeed);
1292 RDG_genBuffer(cNoiseBuffer[3], srcBufferSize, 0.95, 0., coreSeed); /* highly compressible */
1293 RDG_genBuffer(cNoiseBuffer[4], srcBufferSize, 1.00, 0., coreSeed); /* sparse content */
1294 srcBuffer = cNoiseBuffer[2];
1296 /* catch up testNb */
1297 for (testNb=1; testNb < startTest; testNb++) FUZ_rand(&coreSeed);
1299 /* main test loop */
1300 for ( ; (testNb <= nbTests) || (UTIL_clockSpanMicro(startClock) < maxClockSpan); testNb++ ) {
1301 size_t sampleSize, maxTestSize, totalTestSize;
1302 size_t cSize, totalCSize, totalGenSize;
1309 if (nbTests >= testNb) { DISPLAYUPDATE(2, "\r%6u/%6u ", testNb, nbTests); }
1310 else { DISPLAYUPDATE(2, "\r%6u ", testNb); }
1312 FUZ_rand(&coreSeed);
1313 { U32 const prime1 = 2654435761U; lseed = coreSeed ^ prime1; }
1315 /* srcBuffer selection [0-4] */
1316 { U32 buffNb = FUZ_rand(&lseed) & 0x7F;
1317 if (buffNb & 7) buffNb=2; /* most common : compressible (P) */
1321 const U32 tnb[2] = { 1, 3 }; /* barely/highly compressible */
1322 buffNb = tnb[buffNb >> 3];
1324 const U32 tnb[2] = { 0, 4 }; /* not compressible / sparse */
1325 buffNb = tnb[buffNb >> 3];
1327 srcBuffer = cNoiseBuffer[buffNb];
1330 /* select src segment */
1331 sampleSize = FUZ_randomLength(&lseed, maxSampleLog);
1333 /* create sample buffer (to catch read error with valgrind & sanitizers) */
1334 sampleBuffer = (BYTE*)malloc(sampleSize);
1335 CHECK(sampleBuffer==NULL, "not enough memory for sample buffer");
1336 { size_t const sampleStart = FUZ_rand(&lseed) % (srcBufferSize - sampleSize);
1337 memcpy(sampleBuffer, srcBuffer + sampleStart, sampleSize); }
1338 crcOrig = XXH64(sampleBuffer, sampleSize, 0);
1340 /* compression tests */
1341 { unsigned const cLevel =
1342 ( FUZ_rand(&lseed) %
1343 (ZSTD_maxCLevel() - (FUZ_highbit32((U32)sampleSize) / cLevelLimiter)) )
1345 cSize = ZSTD_compressCCtx(ctx, cBuffer, cBufferSize, sampleBuffer, sampleSize, cLevel);
1346 CHECK(ZSTD_isError(cSize), "ZSTD_compressCCtx failed : %s", ZSTD_getErrorName(cSize));
1348 /* compression failure test : too small dest buffer */
1350 const size_t missing = (FUZ_rand(&lseed) % (cSize-2)) + 1; /* no problem, as cSize > 4 (frameHeaderSizer) */
1351 const size_t tooSmallSize = cSize - missing;
1352 const U32 endMark = 0x4DC2B1A9;
1353 memcpy(dstBuffer+tooSmallSize, &endMark, 4);
1354 { size_t const errorCode = ZSTD_compressCCtx(ctx, dstBuffer, tooSmallSize, sampleBuffer, sampleSize, cLevel);
1355 CHECK(!ZSTD_isError(errorCode), "ZSTD_compressCCtx should have failed ! (buffer too small : %u < %u)", (U32)tooSmallSize, (U32)cSize); }
1356 { U32 endCheck; memcpy(&endCheck, dstBuffer+tooSmallSize, 4);
1357 CHECK(endCheck != endMark, "ZSTD_compressCCtx : dst buffer overflow"); }
1360 /* frame header decompression test */
1361 { ZSTD_frameHeader zfh;
1362 CHECK_Z( ZSTD_getFrameHeader(&zfh, cBuffer, cSize) );
1363 CHECK(zfh.frameContentSize != sampleSize, "Frame content size incorrect");
1366 /* Decompressed size test */
1367 { unsigned long long const rSize = ZSTD_findDecompressedSize(cBuffer, cSize);
1368 CHECK(rSize != sampleSize, "decompressed size incorrect");
1371 /* successful decompression test */
1372 { size_t const margin = (FUZ_rand(&lseed) & 1) ? 0 : (FUZ_rand(&lseed) & 31) + 1;
1373 size_t const dSize = ZSTD_decompress(dstBuffer, sampleSize + margin, cBuffer, cSize);
1374 CHECK(dSize != sampleSize, "ZSTD_decompress failed (%s) (srcSize : %u ; cSize : %u)", ZSTD_getErrorName(dSize), (U32)sampleSize, (U32)cSize);
1375 { U64 const crcDest = XXH64(dstBuffer, sampleSize, 0);
1376 CHECK(crcOrig != crcDest, "decompression result corrupted (pos %u / %u)", (U32)findDiff(sampleBuffer, dstBuffer, sampleSize), (U32)sampleSize);
1379 free(sampleBuffer); /* no longer useful after this point */
1381 /* truncated src decompression test */
1382 { size_t const missing = (FUZ_rand(&lseed) % (cSize-2)) + 1; /* no problem, as cSize > 4 (frameHeaderSizer) */
1383 size_t const tooSmallSize = cSize - missing;
1384 void* cBufferTooSmall = malloc(tooSmallSize); /* valgrind will catch read overflows */
1385 CHECK(cBufferTooSmall == NULL, "not enough memory !");
1386 memcpy(cBufferTooSmall, cBuffer, tooSmallSize);
1387 { size_t const errorCode = ZSTD_decompress(dstBuffer, dstBufferSize, cBufferTooSmall, tooSmallSize);
1388 CHECK(!ZSTD_isError(errorCode), "ZSTD_decompress should have failed ! (truncated src buffer)"); }
1389 free(cBufferTooSmall);
1392 /* too small dst decompression test */
1393 if (sampleSize > 3) {
1394 size_t const missing = (FUZ_rand(&lseed) % (sampleSize-2)) + 1; /* no problem, as cSize > 4 (frameHeaderSizer) */
1395 size_t const tooSmallSize = sampleSize - missing;
1396 static const BYTE token = 0xA9;
1397 dstBuffer[tooSmallSize] = token;
1398 { size_t const errorCode = ZSTD_decompress(dstBuffer, tooSmallSize, cBuffer, cSize);
1399 CHECK(!ZSTD_isError(errorCode), "ZSTD_decompress should have failed : %u > %u (dst buffer too small)", (U32)errorCode, (U32)tooSmallSize); }
1400 CHECK(dstBuffer[tooSmallSize] != token, "ZSTD_decompress : dst buffer overflow");
1403 /* noisy src decompression test */
1405 /* insert noise into src */
1406 { U32 const maxNbBits = FUZ_highbit32((U32)(cSize-4));
1407 size_t pos = 4; /* preserve magic number (too easy to detect) */
1409 /* keep some original src */
1410 { U32 const nbBits = FUZ_rand(&lseed) % maxNbBits;
1411 size_t const mask = (1<<nbBits) - 1;
1412 size_t const skipLength = FUZ_rand(&lseed) & mask;
1415 if (pos <= cSize) break;
1417 { U32 const nbBitsCodes = FUZ_rand(&lseed) % maxNbBits;
1418 U32 const nbBits = nbBitsCodes ? nbBitsCodes-1 : 0;
1419 size_t const mask = (1<<nbBits) - 1;
1420 size_t const rNoiseLength = (FUZ_rand(&lseed) & mask) + 1;
1421 size_t const noiseLength = MIN(rNoiseLength, cSize-pos);
1422 size_t const noiseStart = FUZ_rand(&lseed) % (srcBufferSize - noiseLength);
1423 memcpy(cBuffer + pos, srcBuffer + noiseStart, noiseLength);
1427 /* decompress noisy source */
1428 { U32 const endMark = 0xA9B1C3D6;
1429 memcpy(dstBuffer+sampleSize, &endMark, 4);
1430 { size_t const decompressResult = ZSTD_decompress(dstBuffer, sampleSize, cBuffer, cSize);
1431 /* result *may* be an unlikely success, but even then, it must strictly respect dst buffer boundaries */
1432 CHECK((!ZSTD_isError(decompressResult)) && (decompressResult>sampleSize),
1433 "ZSTD_decompress on noisy src : result is too large : %u > %u (dst buffer)", (U32)decompressResult, (U32)sampleSize);
1435 { U32 endCheck; memcpy(&endCheck, dstBuffer+sampleSize, 4);
1436 CHECK(endMark!=endCheck, "ZSTD_decompress on noisy src : dst buffer overflow");
1437 } } } /* noisy src decompression test */
1439 /*===== Streaming compression test, scattered segments and dictionary =====*/
1441 { U32 const testLog = FUZ_rand(&lseed) % maxSrcLog;
1442 U32 const dictLog = FUZ_rand(&lseed) % maxSrcLog;
1443 int const cLevel = (FUZ_rand(&lseed) %
1445 (MAX(testLog, dictLog) / cLevelLimiter))) +
1447 maxTestSize = FUZ_rLogLength(&lseed, testLog);
1448 if (maxTestSize >= dstBufferSize) maxTestSize = dstBufferSize-1;
1450 dictSize = FUZ_rLogLength(&lseed, dictLog); /* needed also for decompression */
1451 dict = srcBuffer + (FUZ_rand(&lseed) % (srcBufferSize - dictSize));
1453 if (FUZ_rand(&lseed) & 0xF) {
1454 CHECK_Z ( ZSTD_compressBegin_usingDict(refCtx, dict, dictSize, cLevel) );
1456 ZSTD_compressionParameters const cPar = ZSTD_getCParams(cLevel, 0, dictSize);
1457 ZSTD_frameParameters const fPar = { FUZ_rand(&lseed)&1 /* contentSizeFlag */,
1458 !(FUZ_rand(&lseed)&3) /* contentChecksumFlag*/,
1459 0 /*NodictID*/ }; /* note : since dictionary is fake, dictIDflag has no impact */
1460 ZSTD_parameters const p = FUZ_makeParams(cPar, fPar);
1461 CHECK_Z ( ZSTD_compressBegin_advanced(refCtx, dict, dictSize, p, 0) );
1463 CHECK_Z( ZSTD_copyCCtx(ctx, refCtx, 0) );
1466 { U32 const nbChunks = (FUZ_rand(&lseed) & 127) + 2;
1468 XXH64_state_t xxhState;
1469 XXH64_reset(&xxhState, 0);
1470 for (totalTestSize=0, cSize=0, n=0 ; n<nbChunks ; n++) {
1471 size_t const segmentSize = FUZ_randomLength(&lseed, maxSampleLog);
1472 size_t const segmentStart = FUZ_rand(&lseed) % (srcBufferSize - segmentSize);
1474 if (cBufferSize-cSize < ZSTD_compressBound(segmentSize)) break; /* avoid invalid dstBufferTooSmall */
1475 if (totalTestSize+segmentSize > maxTestSize) break;
1477 { size_t const compressResult = ZSTD_compressContinue(ctx, cBuffer+cSize, cBufferSize-cSize, srcBuffer+segmentStart, segmentSize);
1478 CHECK (ZSTD_isError(compressResult), "multi-segments compression error : %s", ZSTD_getErrorName(compressResult));
1479 cSize += compressResult;
1481 XXH64_update(&xxhState, srcBuffer+segmentStart, segmentSize);
1482 memcpy(mirrorBuffer + totalTestSize, srcBuffer+segmentStart, segmentSize);
1483 totalTestSize += segmentSize;
1486 { size_t const flushResult = ZSTD_compressEnd(ctx, cBuffer+cSize, cBufferSize-cSize, NULL, 0);
1487 CHECK (ZSTD_isError(flushResult), "multi-segments epilogue error : %s", ZSTD_getErrorName(flushResult));
1488 cSize += flushResult;
1490 crcOrig = XXH64_digest(&xxhState);
1493 /* streaming decompression test */
1494 /* ensure memory requirement is good enough (should always be true) */
1495 { ZSTD_frameHeader zfh;
1496 CHECK( ZSTD_getFrameHeader(&zfh, cBuffer, ZSTD_frameHeaderSize_max),
1497 "ZSTD_getFrameHeader(): error retrieving frame information");
1498 { size_t const roundBuffSize = ZSTD_decodingBufferSize_min(zfh.windowSize, zfh.frameContentSize);
1499 CHECK_Z(roundBuffSize);
1500 CHECK((roundBuffSize > totalTestSize) && (zfh.frameContentSize!=ZSTD_CONTENTSIZE_UNKNOWN),
1501 "ZSTD_decodingBufferSize_min() requires more memory (%u) than necessary (%u)",
1502 (U32)roundBuffSize, (U32)totalTestSize );
1504 if (dictSize<8) dictSize=0, dict=NULL; /* disable dictionary */
1505 CHECK_Z( ZSTD_decompressBegin_usingDict(dctx, dict, dictSize) );
1508 while (totalCSize < cSize) {
1509 size_t const inSize = ZSTD_nextSrcSizeToDecompress(dctx);
1510 size_t const genSize = ZSTD_decompressContinue(dctx, dstBuffer+totalGenSize, dstBufferSize-totalGenSize, cBuffer+totalCSize, inSize);
1511 CHECK (ZSTD_isError(genSize), "ZSTD_decompressContinue error : %s", ZSTD_getErrorName(genSize));
1512 totalGenSize += genSize;
1513 totalCSize += inSize;
1515 CHECK (ZSTD_nextSrcSizeToDecompress(dctx) != 0, "frame not fully decoded");
1516 CHECK (totalGenSize != totalTestSize, "streaming decompressed data : wrong size")
1517 CHECK (totalCSize != cSize, "compressed data should be fully read")
1518 { U64 const crcDest = XXH64(dstBuffer, totalTestSize, 0);
1519 if (crcDest!=crcOrig) {
1520 size_t const errorPos = findDiff(mirrorBuffer, dstBuffer, totalTestSize);
1521 CHECK (1, "streaming decompressed data corrupted : byte %u / %u (%02X!=%02X)",
1522 (U32)errorPos, (U32)totalTestSize, dstBuffer[errorPos], mirrorBuffer[errorPos]);
1524 } /* for ( ; (testNb <= nbTests) */
1525 DISPLAY("\r%u fuzzer tests completed \n", testNb-1);
1528 ZSTD_freeCCtx(refCtx);
1530 ZSTD_freeDCtx(dctx);
1531 free(cNoiseBuffer[0]);
1532 free(cNoiseBuffer[1]);
1533 free(cNoiseBuffer[2]);
1534 free(cNoiseBuffer[3]);
1535 free(cNoiseBuffer[4]);
1547 /*_*******************************************************
1549 *********************************************************/
1550 static int FUZ_usage(const char* programName)
1552 DISPLAY( "Usage :\n");
1553 DISPLAY( " %s [args]\n", programName);
1555 DISPLAY( "Arguments :\n");
1556 DISPLAY( " -i# : Nb of tests (default:%u) \n", nbTestsDefault);
1557 DISPLAY( " -s# : Select seed (default:prompt user)\n");
1558 DISPLAY( " -t# : Select starting test number (default:0)\n");
1559 DISPLAY( " -P# : Select compressibility in %% (default:%u%%)\n", FUZ_compressibility_default);
1560 DISPLAY( " -v : verbose\n");
1561 DISPLAY( " -p : pause at the end\n");
1562 DISPLAY( " -h : display help and exit\n");
1566 /*! readU32FromChar() :
1567 @return : unsigned integer value read from input in `char` format
1568 allows and interprets K, KB, KiB, M, MB and MiB suffix.
1569 Will also modify `*stringPtr`, advancing it to position where it stopped reading.
1570 Note : function result can overflow if digit string > MAX_UINT */
1571 static unsigned readU32FromChar(const char** stringPtr)
1573 unsigned result = 0;
1574 while ((**stringPtr >='0') && (**stringPtr <='9'))
1575 result *= 10, result += **stringPtr - '0', (*stringPtr)++ ;
1576 if ((**stringPtr=='K') || (**stringPtr=='M')) {
1578 if (**stringPtr=='M') result <<= 10;
1580 if (**stringPtr=='i') (*stringPtr)++;
1581 if (**stringPtr=='B') (*stringPtr)++;
1586 /** longCommandWArg() :
1587 * check if *stringPtr is the same as longCommand.
1588 * If yes, @return 1 and advances *stringPtr to the position which immediately follows longCommand.
1589 * @return 0 and doesn't modify *stringPtr otherwise.
1591 static unsigned longCommandWArg(const char** stringPtr, const char* longCommand)
1593 size_t const comSize = strlen(longCommand);
1594 int const result = !strncmp(*stringPtr, longCommand, comSize);
1595 if (result) *stringPtr += comSize;
1599 int main(int argc, const char** argv)
1604 int nbTests = nbTestsDefault;
1606 U32 proba = FUZ_compressibility_default;
1609 U32 maxDuration = 0;
1611 U32 memTestsOnly = 0;
1612 const char* const programName = argv[0];
1614 /* Check command line */
1615 for (argNb=1; argNb<argc; argNb++) {
1616 const char* argument = argv[argNb];
1617 if(!argument) continue; /* Protection if argument empty */
1619 /* Handle commands. Aggregated commands are allowed */
1620 if (argument[0]=='-') {
1622 if (longCommandWArg(&argument, "--memtest=")) { memTestsOnly = readU32FromChar(&argument); continue; }
1624 if (!strcmp(argument, "--memtest")) { memTestsOnly=1; continue; }
1625 if (!strcmp(argument, "--no-big-tests")) { bigTests=0; continue; }
1628 while (*argument!=0) {
1632 return FUZ_usage(programName);
1644 case 'p': /* pause at the end */
1650 argument++; maxDuration = 0;
1651 nbTests = readU32FromChar(&argument);
1657 maxDuration = readU32FromChar(&argument);
1658 if (*argument=='s') argument++; /* seconds */
1659 if (*argument=='m') maxDuration *= 60, argument++; /* minutes */
1660 if (*argument=='n') argument++;
1666 seed = readU32FromChar(&argument);
1671 testNb = readU32FromChar(&argument);
1674 case 'P': /* compressibility % */
1676 proba = readU32FromChar(&argument);
1677 if (proba>100) proba = 100;
1681 return (FUZ_usage(programName), 1);
1682 } } } } /* for (argNb=1; argNb<argc; argNb++) */
1685 DISPLAY("Starting zstd tester (%i-bits, %s)\n", (int)(sizeof(size_t)*8), ZSTD_VERSION_STRING);
1688 time_t const t = time(NULL);
1689 U32 const h = XXH32(&t, sizeof(t), 1);
1693 DISPLAY("Seed = %u\n", seed);
1694 if (proba!=FUZ_compressibility_default) DISPLAY("Compressibility : %u%%\n", proba);
1697 g_displayLevel = MAX(3, g_displayLevel);
1698 return FUZ_mallocTests(seed, ((double)proba) / 100, memTestsOnly);
1701 if (nbTests < testNb) nbTests = testNb;
1704 result = basicUnitTests(0, ((double)proba) / 100); /* constant seed for predictability */
1706 result = fuzzerTests(seed, nbTests, testNb, maxDuration, ((double)proba) / 100, bigTests);
1709 DISPLAY("Press Enter \n");