2 * Copyright (c) 2016-present, Yann Collet, Facebook, Inc.
5 * This source code is licensed under both the BSD-style license (found in the
6 * LICENSE file in the root directory of this source tree) and the GPLv2 (found
7 * in the COPYING file in the root directory of this source tree).
8 * You may select, at your option, one of the above-listed licenses.
12 /*-************************************
14 **************************************/
15 #ifdef _MSC_VER /* Visual Studio */
16 # define _CRT_SECURE_NO_WARNINGS /* fgets */
17 # pragma warning(disable : 4127) /* disable: C4127: conditional expression is constant */
18 # pragma warning(disable : 4146) /* disable: C4146: minus unsigned expression */
22 /*-************************************
24 **************************************/
25 #include <stdlib.h> /* free */
26 #include <stdio.h> /* fgets, sscanf */
27 #include <string.h> /* strcmp */
28 #include <assert.h> /* assert */
30 #define ZSTD_STATIC_LINKING_ONLY /* ZSTD_maxCLevel, ZSTD_customMem, ZSTD_getDictID_fromFrame */
31 #include "zstd.h" /* ZSTD_compressBound */
32 #include "zstd_errors.h" /* ZSTD_error_srcSize_wrong */
33 #include "zstdmt_compress.h"
34 #include "zdict.h" /* ZDICT_trainFromBuffer */
35 #include "datagen.h" /* RDG_genBuffer */
36 #define XXH_STATIC_LINKING_ONLY /* XXH64_state_t */
37 #include "xxhash.h" /* XXH64_* */
42 /*-************************************
44 **************************************/
49 static const U32 nbTestsDefault = 10000;
50 static const U32 g_cLevelMax_smallTests = 10;
51 #define COMPRESSIBLE_NOISE_LENGTH (10 MB)
52 #define FUZ_COMPRESSIBILITY_DEFAULT 50
53 static const U32 prime32 = 2654435761U;
56 /*-************************************
58 **************************************/
59 #define DISPLAY(...) fprintf(stderr, __VA_ARGS__)
60 #define DISPLAYLEVEL(l, ...) if (g_displayLevel>=l) { \
61 DISPLAY(__VA_ARGS__); \
62 if (g_displayLevel>=4) fflush(stderr); }
63 static U32 g_displayLevel = 2;
65 static const U64 g_refreshRate = SEC_TO_MICRO / 6;
66 static UTIL_time_t g_displayClock = UTIL_TIME_INITIALIZER;
68 #define DISPLAYUPDATE(l, ...) if (g_displayLevel>=l) { \
69 if ((UTIL_clockSpanMicro(g_displayClock) > g_refreshRate) || (g_displayLevel>=4)) \
70 { g_displayClock = UTIL_getTime(); DISPLAY(__VA_ARGS__); \
71 if (g_displayLevel>=4) fflush(stderr); } }
73 static U64 g_clockTime = 0;
76 /*-*******************************************************
78 *********************************************************/
81 #define MIN(a,b) ((a)<(b)?(a):(b))
82 #define MAX(a,b) ((a)>(b)?(a):(b))
84 @return : a 27 bits random value, from a 32-bits `seed`.
85 `seed` is also modified */
86 #define FUZ_rotl32(x,r) ((x << r) | (x >> (32 - r)))
87 static unsigned int FUZ_rand(unsigned int* seedPtr)
89 static const U32 prime2 = 2246822519U;
90 U32 rand32 = *seedPtr;
93 rand32 = FUZ_rotl32(rand32, 13);
98 #define CHECK(cond, ...) { \
100 DISPLAY("Error => "); \
101 DISPLAY(__VA_ARGS__); \
102 DISPLAY(" (seed %u, test nb %u, line %u) \n", \
103 seed, testNb, __LINE__); \
104 goto _output_error; \
107 #define CHECK_Z(f) { \
108 size_t const err = f; \
109 CHECK(ZSTD_isError(err), "%s : %s ", \
110 #f, ZSTD_getErrorName(err)); \
113 #define CHECK_RET(ret, cond, ...) { \
115 DISPLAY("Error %llu => ", (unsigned long long)ret); \
116 DISPLAY(__VA_ARGS__); \
117 DISPLAY(" (line %u)\n", __LINE__); \
121 #define CHECK_RET_Z(f) { \
122 size_t const err = f; \
123 CHECK_RET(err, ZSTD_isError(err), "%s : %s ", \
124 #f, ZSTD_getErrorName(err)); \
128 /*======================================================
130 *======================================================*/
138 static const buffer_t kBuffNull = { NULL, 0 , 0 };
140 static void FUZ_freeDictionary(buffer_t dict)
145 static buffer_t FUZ_createDictionary(const void* src, size_t srcSize, size_t blockSize, size_t requestedDictSize)
147 buffer_t dict = kBuffNull;
148 size_t const nbBlocks = (srcSize + (blockSize-1)) / blockSize;
149 size_t* const blockSizes = (size_t*)malloc(nbBlocks * sizeof(size_t));
150 if (!blockSizes) return kBuffNull;
151 dict.start = malloc(requestedDictSize);
152 if (!dict.start) { free(blockSizes); return kBuffNull; }
154 for (nb=0; nb<nbBlocks-1; nb++) blockSizes[nb] = blockSize;
155 blockSizes[nbBlocks-1] = srcSize - (blockSize * (nbBlocks-1));
157 { size_t const dictSize = ZDICT_trainFromBuffer(dict.start, requestedDictSize, src, blockSizes, (unsigned)nbBlocks);
159 if (ZDICT_isError(dictSize)) { FUZ_freeDictionary(dict); return kBuffNull; }
160 dict.size = requestedDictSize;
161 dict.filled = dictSize;
166 /* Round trips data and updates xxh with the decompressed data produced */
167 static size_t SEQ_roundTrip(ZSTD_CCtx* cctx, ZSTD_DCtx* dctx,
168 XXH64_state_t* xxh, void* data, size_t size,
169 ZSTD_EndDirective endOp)
171 static BYTE compressed[1024];
172 static BYTE uncompressed[1024];
174 ZSTD_inBuffer cin = {data, size, 0};
178 ZSTD_outBuffer cout = {compressed, sizeof(compressed), 0};
179 ZSTD_inBuffer din = {compressed, 0, 0};
180 ZSTD_outBuffer dout = {uncompressed, 0, 0};
182 cret = ZSTD_compress_generic(cctx, &cout, &cin, endOp);
183 if (ZSTD_isError(cret))
187 while (din.pos < din.size || (endOp == ZSTD_e_end && cret == 0)) {
191 dout.size = sizeof(uncompressed);
192 dret = ZSTD_decompressStream(dctx, &dout, &din);
193 if (ZSTD_isError(dret))
195 XXH64_update(xxh, dout.dst, dout.pos);
199 } while (cin.pos < cin.size || (endOp != ZSTD_e_continue && cret != 0));
203 /* Generates some data and round trips it */
204 static size_t SEQ_generateRoundTrip(ZSTD_CCtx* cctx, ZSTD_DCtx* dctx,
205 XXH64_state_t* xxh, SEQ_stream* seq,
206 SEQ_gen_type type, unsigned value)
208 static BYTE data[1024];
212 SEQ_outBuffer sout = {data, sizeof(data), 0};
214 gen = SEQ_gen(seq, type, value, &sout);
216 ret = SEQ_roundTrip(cctx, dctx, xxh, sout.dst, sout.pos, ZSTD_e_continue);
217 if (ZSTD_isError(ret))
224 static size_t getCCtxParams(ZSTD_CCtx* zc, ZSTD_parameters* savedParams)
227 CHECK_RET_Z(ZSTD_CCtx_getParameter(zc, ZSTD_p_windowLog, &savedParams->cParams.windowLog));
228 CHECK_RET_Z(ZSTD_CCtx_getParameter(zc, ZSTD_p_hashLog, &savedParams->cParams.hashLog));
229 CHECK_RET_Z(ZSTD_CCtx_getParameter(zc, ZSTD_p_chainLog, &savedParams->cParams.chainLog));
230 CHECK_RET_Z(ZSTD_CCtx_getParameter(zc, ZSTD_p_searchLog, &savedParams->cParams.searchLog));
231 CHECK_RET_Z(ZSTD_CCtx_getParameter(zc, ZSTD_p_minMatch, &savedParams->cParams.searchLength));
232 CHECK_RET_Z(ZSTD_CCtx_getParameter(zc, ZSTD_p_targetLength, &savedParams->cParams.targetLength));
233 CHECK_RET_Z(ZSTD_CCtx_getParameter(zc, ZSTD_p_compressionStrategy, &value));
234 savedParams->cParams.strategy = value;
236 CHECK_RET_Z(ZSTD_CCtx_getParameter(zc, ZSTD_p_checksumFlag, &savedParams->fParams.checksumFlag));
237 CHECK_RET_Z(ZSTD_CCtx_getParameter(zc, ZSTD_p_contentSizeFlag, &savedParams->fParams.contentSizeFlag));
238 CHECK_RET_Z(ZSTD_CCtx_getParameter(zc, ZSTD_p_dictIDFlag, &value));
239 savedParams->fParams.noDictIDFlag = !value;
243 static U32 badParameters(ZSTD_CCtx* zc, ZSTD_parameters const savedParams)
245 ZSTD_parameters params;
246 if (ZSTD_isError(getCCtxParams(zc, ¶ms))) return 10;
247 CHECK_RET(1, params.cParams.windowLog != savedParams.cParams.windowLog, "windowLog");
248 CHECK_RET(2, params.cParams.hashLog != savedParams.cParams.hashLog, "hashLog");
249 CHECK_RET(3, params.cParams.chainLog != savedParams.cParams.chainLog, "chainLog");
250 CHECK_RET(4, params.cParams.searchLog != savedParams.cParams.searchLog, "searchLog");
251 CHECK_RET(5, params.cParams.searchLength != savedParams.cParams.searchLength, "searchLength");
252 CHECK_RET(6, params.cParams.targetLength != savedParams.cParams.targetLength, "targetLength");
254 CHECK_RET(7, params.fParams.checksumFlag != savedParams.fParams.checksumFlag, "checksumFlag");
255 CHECK_RET(8, params.fParams.contentSizeFlag != savedParams.fParams.contentSizeFlag, "contentSizeFlag");
256 CHECK_RET(9, params.fParams.noDictIDFlag != savedParams.fParams.noDictIDFlag, "noDictIDFlag");
260 static int basicUnitTests(U32 seed, double compressibility)
262 size_t const CNBufferSize = COMPRESSIBLE_NOISE_LENGTH;
263 void* CNBuffer = malloc(CNBufferSize);
264 size_t const skippableFrameSize = 200 KB;
265 size_t const compressedBufferSize = (8 + skippableFrameSize) + ZSTD_compressBound(COMPRESSIBLE_NOISE_LENGTH);
266 void* compressedBuffer = malloc(compressedBufferSize);
267 size_t const decodedBufferSize = CNBufferSize;
268 void* decodedBuffer = malloc(decodedBufferSize);
272 U32 coreSeed = 0; /* this name to conform with CHECK_Z macro display */
273 ZSTD_CStream* zc = ZSTD_createCStream();
274 ZSTD_DStream* zd = ZSTD_createDStream();
275 ZSTDMT_CCtx* mtctx = ZSTDMT_createCCtx(2);
277 ZSTD_inBuffer inBuff, inBuff2;
278 ZSTD_outBuffer outBuff;
279 buffer_t dictionary = kBuffNull;
280 size_t const dictSize = 128 KB;
283 /* Create compressible test buffer */
284 if (!CNBuffer || !compressedBuffer || !decodedBuffer || !zc || !zd) {
285 DISPLAY("Not enough memory, aborting \n");
288 RDG_genBuffer(CNBuffer, CNBufferSize, compressibility, 0., seed);
290 /* Create dictionary */
291 DISPLAYLEVEL(3, "creating dictionary for unit tests \n");
292 dictionary = FUZ_createDictionary(CNBuffer, CNBufferSize / 3, 16 KB, 48 KB);
293 if (!dictionary.start) {
294 DISPLAY("Error creating dictionary, aborting \n");
297 dictID = ZDICT_getDictID(dictionary.start, dictionary.filled);
299 /* Basic compression test */
300 DISPLAYLEVEL(3, "test%3i : compress %u bytes : ", testNb++, COMPRESSIBLE_NOISE_LENGTH);
301 CHECK_Z( ZSTD_initCStream(zc, 1 /* cLevel */) );
302 outBuff.dst = (char*)(compressedBuffer);
303 outBuff.size = compressedBufferSize;
305 inBuff.src = CNBuffer;
306 inBuff.size = CNBufferSize;
308 CHECK_Z( ZSTD_compressStream(zc, &outBuff, &inBuff) );
309 if (inBuff.pos != inBuff.size) goto _output_error; /* entire input should be consumed */
310 { size_t const r = ZSTD_endStream(zc, &outBuff);
311 if (r != 0) goto _output_error; } /* error, or some data not flushed */
312 DISPLAYLEVEL(3, "OK (%u bytes)\n", (U32)outBuff.pos);
314 /* generate skippable frame */
315 MEM_writeLE32(compressedBuffer, ZSTD_MAGIC_SKIPPABLE_START);
316 MEM_writeLE32(((char*)compressedBuffer)+4, (U32)skippableFrameSize);
317 cSize = skippableFrameSize + 8;
319 /* Basic compression test using dict */
320 DISPLAYLEVEL(3, "test%3i : skipframe + compress %u bytes : ", testNb++, COMPRESSIBLE_NOISE_LENGTH);
321 CHECK_Z( ZSTD_initCStream_usingDict(zc, CNBuffer, dictSize, 1 /* cLevel */) );
322 outBuff.dst = (char*)(compressedBuffer)+cSize;
323 assert(compressedBufferSize > cSize);
324 outBuff.size = compressedBufferSize - cSize;
326 inBuff.src = CNBuffer;
327 inBuff.size = CNBufferSize;
329 CHECK_Z( ZSTD_compressStream(zc, &outBuff, &inBuff) );
330 if (inBuff.pos != inBuff.size) goto _output_error; /* entire input should be consumed */
331 { size_t const r = ZSTD_endStream(zc, &outBuff);
332 if (r != 0) goto _output_error; } /* error, or some data not flushed */
333 cSize += outBuff.pos;
334 DISPLAYLEVEL(3, "OK (%u bytes : %.2f%%)\n", (U32)cSize, (double)cSize/COMPRESSIBLE_NOISE_LENGTH*100);
336 /* context size functions */
337 DISPLAYLEVEL(3, "test%3i : estimate CStream size : ", testNb++);
338 { ZSTD_compressionParameters const cParams = ZSTD_getCParams(1, CNBufferSize, dictSize);
339 size_t const cstreamSize = ZSTD_estimateCStreamSize_usingCParams(cParams);
340 size_t const cdictSize = ZSTD_estimateCDictSize_advanced(dictSize, cParams, ZSTD_dlm_byCopy); /* uses ZSTD_initCStream_usingDict() */
341 if (ZSTD_isError(cstreamSize)) goto _output_error;
342 if (ZSTD_isError(cdictSize)) goto _output_error;
343 DISPLAYLEVEL(3, "OK (%u bytes) \n", (U32)(cstreamSize + cdictSize));
346 DISPLAYLEVEL(3, "test%3i : check actual CStream size : ", testNb++);
347 { size_t const s = ZSTD_sizeof_CStream(zc);
348 if (ZSTD_isError(s)) goto _output_error;
349 DISPLAYLEVEL(3, "OK (%u bytes) \n", (U32)s);
352 /* Attempt bad compression parameters */
353 DISPLAYLEVEL(3, "test%3i : use bad compression parameters : ", testNb++);
355 ZSTD_parameters params = ZSTD_getParams(1, 0, 0);
356 params.cParams.searchLength = 2;
357 r = ZSTD_initCStream_advanced(zc, NULL, 0, params, 0);
358 if (!ZSTD_isError(r)) goto _output_error;
359 DISPLAYLEVEL(3, "init error : %s \n", ZSTD_getErrorName(r));
362 /* skippable frame test */
363 DISPLAYLEVEL(3, "test%3i : decompress skippable frame : ", testNb++);
364 CHECK_Z( ZSTD_initDStream_usingDict(zd, CNBuffer, dictSize) );
365 inBuff.src = compressedBuffer;
368 outBuff.dst = decodedBuffer;
369 outBuff.size = CNBufferSize;
371 { size_t const r = ZSTD_decompressStream(zd, &outBuff, &inBuff);
372 DISPLAYLEVEL(5, " ( ZSTD_decompressStream => %u ) ", (U32)r);
373 if (r != 0) goto _output_error;
375 if (outBuff.pos != 0) goto _output_error; /* skippable frame output len is 0 */
376 DISPLAYLEVEL(3, "OK \n");
378 /* Basic decompression test */
380 DISPLAYLEVEL(3, "test%3i : decompress %u bytes : ", testNb++, COMPRESSIBLE_NOISE_LENGTH);
381 ZSTD_initDStream_usingDict(zd, CNBuffer, dictSize);
382 CHECK_Z( ZSTD_setDStreamParameter(zd, DStream_p_maxWindowSize, 1000000000) ); /* large limit */
383 { size_t const remaining = ZSTD_decompressStream(zd, &outBuff, &inBuff);
384 if (remaining != 0) goto _output_error; } /* should reach end of frame == 0; otherwise, some data left, or an error */
385 if (outBuff.pos != CNBufferSize) goto _output_error; /* should regenerate the same amount */
386 if (inBuff.pos != inBuff.size) goto _output_error; /* should have read the entire frame */
387 DISPLAYLEVEL(3, "OK \n");
389 /* Re-use without init */
390 DISPLAYLEVEL(3, "test%3i : decompress again without init (re-use previous settings): ", testNb++);
392 { size_t const remaining = ZSTD_decompressStream(zd, &outBuff, &inBuff2);
393 if (remaining != 0) goto _output_error; } /* should reach end of frame == 0; otherwise, some data left, or an error */
394 if (outBuff.pos != CNBufferSize) goto _output_error; /* should regenerate the same amount */
395 if (inBuff.pos != inBuff.size) goto _output_error; /* should have read the entire frame */
396 DISPLAYLEVEL(3, "OK \n");
398 /* check regenerated data is byte exact */
399 DISPLAYLEVEL(3, "test%3i : check decompressed result : ", testNb++);
401 for (i=0; i<CNBufferSize; i++) {
402 if (((BYTE*)decodedBuffer)[i] != ((BYTE*)CNBuffer)[i]) goto _output_error;
404 DISPLAYLEVEL(3, "OK \n");
406 /* context size functions */
407 DISPLAYLEVEL(3, "test%3i : estimate DStream size : ", testNb++);
408 { ZSTD_frameHeader fhi;
409 const void* cStart = (char*)compressedBuffer + (skippableFrameSize + 8);
410 size_t const gfhError = ZSTD_getFrameHeader(&fhi, cStart, cSize);
411 if (gfhError!=0) goto _output_error;
412 DISPLAYLEVEL(5, " (windowSize : %u) ", (U32)fhi.windowSize);
413 { size_t const s = ZSTD_estimateDStreamSize(fhi.windowSize)
414 /* uses ZSTD_initDStream_usingDict() */
415 + ZSTD_estimateDDictSize(dictSize, ZSTD_dlm_byCopy);
416 if (ZSTD_isError(s)) goto _output_error;
417 DISPLAYLEVEL(3, "OK (%u bytes) \n", (U32)s);
420 DISPLAYLEVEL(3, "test%3i : check actual DStream size : ", testNb++);
421 { size_t const s = ZSTD_sizeof_DStream(zd);
422 if (ZSTD_isError(s)) goto _output_error;
423 DISPLAYLEVEL(3, "OK (%u bytes) \n", (U32)s);
426 /* Decompression by small increment */
427 DISPLAYLEVEL(3, "test%3i : decompress byte-by-byte : ", testNb++);
428 { /* skippable frame */
430 ZSTD_initDStream_usingDict(zd, CNBuffer, dictSize);
431 inBuff.src = compressedBuffer;
432 outBuff.dst = decodedBuffer;
435 while (r) { /* skippable frame */
436 size_t const inSize = (FUZ_rand(&coreSeed) & 15) + 1;
437 size_t const outSize = (FUZ_rand(&coreSeed) & 15) + 1;
438 inBuff.size = inBuff.pos + inSize;
439 outBuff.size = outBuff.pos + outSize;
440 r = ZSTD_decompressStream(zd, &outBuff, &inBuff);
441 if (ZSTD_isError(r)) DISPLAYLEVEL(4, "ZSTD_decompressStream on skippable frame error : %s \n", ZSTD_getErrorName(r));
442 if (ZSTD_isError(r)) goto _output_error;
445 ZSTD_initDStream_usingDict(zd, CNBuffer, dictSize);
448 size_t const inSize = FUZ_rand(&coreSeed) & 15;
449 size_t const outSize = (FUZ_rand(&coreSeed) & 15) + (!inSize); /* avoid having both sizes at 0 => would trigger a no_forward_progress error */
450 inBuff.size = inBuff.pos + inSize;
451 outBuff.size = outBuff.pos + outSize;
452 r = ZSTD_decompressStream(zd, &outBuff, &inBuff);
453 if (ZSTD_isError(r)) DISPLAYLEVEL(4, "ZSTD_decompressStream error : %s \n", ZSTD_getErrorName(r));
454 if (ZSTD_isError(r)) goto _output_error;
457 if (outBuff.pos != CNBufferSize) DISPLAYLEVEL(4, "outBuff.pos != CNBufferSize : should have regenerated same amount ! \n");
458 if (outBuff.pos != CNBufferSize) goto _output_error; /* should regenerate the same amount */
459 if (inBuff.pos != cSize) DISPLAYLEVEL(4, "inBuff.pos != cSize : should have real all input ! \n");
460 if (inBuff.pos != cSize) goto _output_error; /* should have read the entire frame */
461 DISPLAYLEVEL(3, "OK \n");
463 /* check regenerated data is byte exact */
464 DISPLAYLEVEL(3, "test%3i : check decompressed result : ", testNb++);
466 for (i=0; i<CNBufferSize; i++) {
467 if (((BYTE*)decodedBuffer)[i] != ((BYTE*)CNBuffer)[i]) goto _output_error;;
469 DISPLAYLEVEL(3, "OK \n");
471 /* Decompression forward progress */
472 DISPLAYLEVEL(3, "test%3i : generate error when ZSTD_decompressStream() doesn't progress : ", testNb++);
473 { /* skippable frame */
476 int const maxDec = 100;
477 inBuff.src = compressedBuffer;
481 outBuff.dst = decodedBuffer;
483 outBuff.size = CNBufferSize-1; /* 1 byte missing */
485 for (decNb=0; decNb<maxDec; decNb++) {
486 if (r==0) ZSTD_initDStream_usingDict(zd, CNBuffer, dictSize);
487 r = ZSTD_decompressStream(zd, &outBuff, &inBuff);
488 if (ZSTD_isError(r)) break;
490 if (!ZSTD_isError(r)) DISPLAYLEVEL(4, "ZSTD_decompressStream should have triggered a no_forward_progress error \n");
491 if (!ZSTD_isError(r)) goto _output_error; /* should have triggered no_forward_progress error */
493 DISPLAYLEVEL(3, "OK \n");
495 /* _srcSize compression test */
496 DISPLAYLEVEL(3, "test%3i : compress_srcSize %u bytes : ", testNb++, COMPRESSIBLE_NOISE_LENGTH);
497 ZSTD_initCStream_srcSize(zc, 1, CNBufferSize);
498 outBuff.dst = (char*)(compressedBuffer);
499 outBuff.size = compressedBufferSize;
501 inBuff.src = CNBuffer;
502 inBuff.size = CNBufferSize;
504 CHECK_Z( ZSTD_compressStream(zc, &outBuff, &inBuff) );
505 if (inBuff.pos != inBuff.size) goto _output_error; /* entire input should be consumed */
506 { size_t const r = ZSTD_endStream(zc, &outBuff);
507 if (r != 0) goto _output_error; } /* error, or some data not flushed */
508 { unsigned long long origSize = ZSTD_findDecompressedSize(outBuff.dst, outBuff.pos);
509 if ((size_t)origSize != CNBufferSize) goto _output_error; } /* exact original size must be present */
510 DISPLAYLEVEL(3, "OK (%u bytes : %.2f%%)\n", (U32)cSize, (double)cSize/COMPRESSIBLE_NOISE_LENGTH*100);
512 /* wrong _srcSize compression test */
513 DISPLAYLEVEL(3, "test%3i : too large srcSize : %u bytes : ", testNb++, COMPRESSIBLE_NOISE_LENGTH-1);
514 ZSTD_initCStream_srcSize(zc, 1, CNBufferSize+1);
515 outBuff.dst = (char*)(compressedBuffer);
516 outBuff.size = compressedBufferSize;
518 inBuff.src = CNBuffer;
519 inBuff.size = CNBufferSize;
521 CHECK_Z( ZSTD_compressStream(zc, &outBuff, &inBuff) );
522 if (inBuff.pos != inBuff.size) goto _output_error; /* entire input should be consumed */
523 { size_t const r = ZSTD_endStream(zc, &outBuff);
524 if (ZSTD_getErrorCode(r) != ZSTD_error_srcSize_wrong) goto _output_error; /* must fail : wrong srcSize */
525 DISPLAYLEVEL(3, "OK (error detected : %s) \n", ZSTD_getErrorName(r)); }
527 /* wrong _srcSize compression test */
528 DISPLAYLEVEL(3, "test%3i : too small srcSize : %u bytes : ", testNb++, COMPRESSIBLE_NOISE_LENGTH-1);
529 ZSTD_initCStream_srcSize(zc, 1, CNBufferSize-1);
530 outBuff.dst = (char*)(compressedBuffer);
531 outBuff.size = compressedBufferSize;
533 inBuff.src = CNBuffer;
534 inBuff.size = CNBufferSize;
536 { size_t const r = ZSTD_compressStream(zc, &outBuff, &inBuff);
537 if (ZSTD_getErrorCode(r) != ZSTD_error_srcSize_wrong) goto _output_error; /* must fail : wrong srcSize */
538 DISPLAYLEVEL(3, "OK (error detected : %s) \n", ZSTD_getErrorName(r));
541 DISPLAYLEVEL(3, "test%3i : wrong srcSize !contentSizeFlag : %u bytes : ", testNb++, COMPRESSIBLE_NOISE_LENGTH-1);
542 { ZSTD_parameters params = ZSTD_getParams(1, CNBufferSize, 0);
543 params.fParams.contentSizeFlag = 0;
544 CHECK_Z(ZSTD_initCStream_advanced(zc, NULL, 0, params, CNBufferSize - MIN(CNBufferSize, 200 KB)));
545 outBuff.dst = (char*)compressedBuffer;
546 outBuff.size = compressedBufferSize;
548 inBuff.src = CNBuffer;
549 inBuff.size = CNBufferSize;
551 { size_t const r = ZSTD_compressStream(zc, &outBuff, &inBuff);
552 if (ZSTD_getErrorCode(r) != ZSTD_error_srcSize_wrong) goto _output_error; /* must fail : wrong srcSize */
553 DISPLAYLEVEL(3, "OK (error detected : %s) \n", ZSTD_getErrorName(r));
556 /* Complex context re-use scenario */
557 DISPLAYLEVEL(3, "test%3i : context re-use : ", testNb++);
558 ZSTD_freeCStream(zc);
559 zc = ZSTD_createCStream();
560 if (zc==NULL) goto _output_error; /* memory allocation issue */
562 { size_t const inSize = 513;
563 DISPLAYLEVEL(5, "use1 ");
564 ZSTD_initCStream_advanced(zc, NULL, 0, ZSTD_getParams(19, inSize, 0), inSize); /* needs btopt + search3 to trigger hashLog3 */
565 inBuff.src = CNBuffer;
566 inBuff.size = inSize;
568 outBuff.dst = (char*)(compressedBuffer)+cSize;
569 outBuff.size = ZSTD_compressBound(inSize);
571 DISPLAYLEVEL(5, "compress1 ");
572 CHECK_Z( ZSTD_compressStream(zc, &outBuff, &inBuff) );
573 if (inBuff.pos != inBuff.size) goto _output_error; /* entire input should be consumed */
574 DISPLAYLEVEL(5, "end1 ");
575 { size_t const r = ZSTD_endStream(zc, &outBuff);
576 if (r != 0) goto _output_error; } /* error, or some data not flushed */
579 { size_t const inSize = 1025; /* will not continue, because tables auto-adjust and are therefore different size */
580 DISPLAYLEVEL(5, "use2 ");
581 ZSTD_initCStream_advanced(zc, NULL, 0, ZSTD_getParams(19, inSize, 0), inSize); /* needs btopt + search3 to trigger hashLog3 */
582 inBuff.src = CNBuffer;
583 inBuff.size = inSize;
585 outBuff.dst = (char*)(compressedBuffer)+cSize;
586 outBuff.size = ZSTD_compressBound(inSize);
588 DISPLAYLEVEL(5, "compress2 ");
589 CHECK_Z( ZSTD_compressStream(zc, &outBuff, &inBuff) );
590 if (inBuff.pos != inBuff.size) goto _output_error; /* entire input should be consumed */
591 DISPLAYLEVEL(5, "end2 ");
592 { size_t const r = ZSTD_endStream(zc, &outBuff);
593 if (r != 0) goto _output_error; } /* error, or some data not flushed */
595 DISPLAYLEVEL(3, "OK \n");
598 DISPLAYLEVEL(3, "test%3i : digested dictionary : ", testNb++);
599 { ZSTD_CDict* const cdict = ZSTD_createCDict(dictionary.start, dictionary.filled, 1 /*byRef*/ );
600 size_t const initError = ZSTD_initCStream_usingCDict(zc, cdict);
601 DISPLAYLEVEL(5, "ZSTD_initCStream_usingCDict result : %u ", (U32)initError);
602 if (ZSTD_isError(initError)) goto _output_error;
603 outBuff.dst = compressedBuffer;
604 outBuff.size = compressedBufferSize;
606 inBuff.src = CNBuffer;
607 inBuff.size = CNBufferSize;
609 DISPLAYLEVEL(5, "- starting ZSTD_compressStream ");
610 CHECK_Z( ZSTD_compressStream(zc, &outBuff, &inBuff) );
611 if (inBuff.pos != inBuff.size) goto _output_error; /* entire input should be consumed */
612 { size_t const r = ZSTD_endStream(zc, &outBuff);
613 DISPLAYLEVEL(5, "- ZSTD_endStream result : %u ", (U32)r);
614 if (r != 0) goto _output_error; /* error, or some data not flushed */
617 ZSTD_freeCDict(cdict);
618 DISPLAYLEVEL(3, "OK (%u bytes : %.2f%%)\n", (U32)cSize, (double)cSize/CNBufferSize*100);
621 DISPLAYLEVEL(3, "test%3i : check CStream size : ", testNb++);
622 { size_t const s = ZSTD_sizeof_CStream(zc);
623 if (ZSTD_isError(s)) goto _output_error;
624 DISPLAYLEVEL(3, "OK (%u bytes) \n", (U32)s);
627 DISPLAYLEVEL(4, "test%3i : check Dictionary ID : ", testNb++);
628 { unsigned const dID = ZSTD_getDictID_fromFrame(compressedBuffer, cSize);
629 if (dID != dictID) goto _output_error;
630 DISPLAYLEVEL(4, "OK (%u) \n", dID);
634 DISPLAYLEVEL(3, "test%3i : decompress %u bytes with digested dictionary : ", testNb++, (U32)CNBufferSize);
635 { ZSTD_DDict* const ddict = ZSTD_createDDict(dictionary.start, dictionary.filled);
636 size_t const initError = ZSTD_initDStream_usingDDict(zd, ddict);
637 if (ZSTD_isError(initError)) goto _output_error;
638 outBuff.dst = decodedBuffer;
639 outBuff.size = CNBufferSize;
641 inBuff.src = compressedBuffer;
644 { size_t const r = ZSTD_decompressStream(zd, &outBuff, &inBuff);
645 if (r != 0) goto _output_error; } /* should reach end of frame == 0; otherwise, some data left, or an error */
646 if (outBuff.pos != CNBufferSize) goto _output_error; /* should regenerate the same amount */
647 if (inBuff.pos != inBuff.size) goto _output_error; /* should have read the entire frame */
648 ZSTD_freeDDict(ddict);
649 DISPLAYLEVEL(3, "OK \n");
652 /* test ZSTD_setDStreamParameter() resilience */
653 DISPLAYLEVEL(3, "test%3i : wrong parameter for ZSTD_setDStreamParameter(): ", testNb++);
654 { size_t const r = ZSTD_setDStreamParameter(zd, (ZSTD_DStreamParameter_e)999, 1); /* large limit */
655 if (!ZSTD_isError(r)) goto _output_error; }
656 DISPLAYLEVEL(3, "OK \n");
658 /* Memory restriction */
659 DISPLAYLEVEL(3, "test%3i : maxWindowSize < frame requirement : ", testNb++);
660 ZSTD_initDStream_usingDict(zd, CNBuffer, dictSize);
661 CHECK_Z( ZSTD_setDStreamParameter(zd, DStream_p_maxWindowSize, 1000) ); /* too small limit */
662 outBuff.dst = decodedBuffer;
663 outBuff.size = CNBufferSize;
665 inBuff.src = compressedBuffer;
668 { size_t const r = ZSTD_decompressStream(zd, &outBuff, &inBuff);
669 if (!ZSTD_isError(r)) goto _output_error; /* must fail : frame requires > 100 bytes */
670 DISPLAYLEVEL(3, "OK (%s)\n", ZSTD_getErrorName(r)); }
671 ZSTD_DCtx_reset(zd); /* leave zd in good shape for next tests */
673 DISPLAYLEVEL(3, "test%3i : dictionary source size and level : ", testNb++);
674 { ZSTD_DCtx* const dctx = ZSTD_createDCtx();
675 int const maxLevel = 16; /* first level with zstd_opt */
677 assert(maxLevel < ZSTD_maxCLevel());
678 CHECK_Z( ZSTD_DCtx_loadDictionary_byReference(dctx, dictionary.start, dictionary.filled) );
679 for (level = 1; level <= maxLevel; ++level) {
680 ZSTD_CDict* const cdict = ZSTD_createCDict(dictionary.start, dictionary.filled, level);
681 size_t const maxSize = MIN(1 MB, CNBufferSize);
683 for (size = 512; size <= maxSize; size <<= 1) {
684 U64 const crcOrig = XXH64(CNBuffer, size, 0);
685 ZSTD_CCtx* const cctx = ZSTD_createCCtx();
686 ZSTD_parameters savedParams;
687 getCCtxParams(cctx, &savedParams);
688 outBuff.dst = compressedBuffer;
689 outBuff.size = compressedBufferSize;
691 inBuff.src = CNBuffer;
694 CHECK_Z(ZSTD_CCtx_refCDict(cctx, cdict));
695 CHECK_Z(ZSTD_compress_generic(cctx, &outBuff, &inBuff, ZSTD_e_end));
696 CHECK(badParameters(cctx, savedParams), "Bad CCtx params");
697 if (inBuff.pos != inBuff.size) goto _output_error;
698 { ZSTD_outBuffer decOut = {decodedBuffer, size, 0};
699 ZSTD_inBuffer decIn = {outBuff.dst, outBuff.pos, 0};
700 CHECK_Z( ZSTD_decompress_generic(dctx, &decOut, &decIn) );
701 if (decIn.pos != decIn.size) goto _output_error;
702 if (decOut.pos != size) goto _output_error;
703 { U64 const crcDec = XXH64(decOut.dst, decOut.pos, 0);
704 if (crcDec != crcOrig) goto _output_error;
708 ZSTD_freeCDict(cdict);
712 DISPLAYLEVEL(3, "OK\n");
714 DISPLAYLEVEL(3, "test%3i : ZSTD_initCStream_usingCDict_advanced with masked dictID : ", testNb++);
715 { ZSTD_compressionParameters const cParams = ZSTD_getCParams(1, CNBufferSize, dictionary.filled);
716 ZSTD_frameParameters const fParams = { 1 /* contentSize */, 1 /* checksum */, 1 /* noDictID */};
717 ZSTD_CDict* const cdict = ZSTD_createCDict_advanced(dictionary.start, dictionary.filled, ZSTD_dlm_byRef, ZSTD_dct_auto, cParams, ZSTD_defaultCMem);
718 size_t const initError = ZSTD_initCStream_usingCDict_advanced(zc, cdict, fParams, CNBufferSize);
719 if (ZSTD_isError(initError)) goto _output_error;
720 outBuff.dst = compressedBuffer;
721 outBuff.size = compressedBufferSize;
723 inBuff.src = CNBuffer;
724 inBuff.size = CNBufferSize;
726 CHECK_Z( ZSTD_compressStream(zc, &outBuff, &inBuff) );
727 if (inBuff.pos != inBuff.size) goto _output_error; /* entire input should be consumed */
728 { size_t const r = ZSTD_endStream(zc, &outBuff);
729 if (r != 0) goto _output_error; } /* error, or some data not flushed */
731 ZSTD_freeCDict(cdict);
732 DISPLAYLEVEL(3, "OK (%u bytes : %.2f%%)\n", (U32)cSize, (double)cSize/CNBufferSize*100);
735 DISPLAYLEVEL(3, "test%3i : try retrieving dictID from frame : ", testNb++);
736 { U32 const did = ZSTD_getDictID_fromFrame(compressedBuffer, cSize);
737 if (did != 0) goto _output_error;
739 DISPLAYLEVEL(3, "OK (not detected) \n");
741 DISPLAYLEVEL(3, "test%3i : decompress without dictionary : ", testNb++);
742 { size_t const r = ZSTD_decompress(decodedBuffer, CNBufferSize, compressedBuffer, cSize);
743 if (!ZSTD_isError(r)) goto _output_error; /* must fail : dictionary not used */
744 DISPLAYLEVEL(3, "OK (%s)\n", ZSTD_getErrorName(r));
747 DISPLAYLEVEL(3, "test%3i : compress with ZSTD_CCtx_refPrefix : ", testNb++);
748 CHECK_Z( ZSTD_CCtx_refPrefix(zc, dictionary.start, dictionary.filled) );
749 outBuff.dst = compressedBuffer;
750 outBuff.size = compressedBufferSize;
752 inBuff.src = CNBuffer;
753 inBuff.size = CNBufferSize;
755 CHECK_Z( ZSTD_compress_generic(zc, &outBuff, &inBuff, ZSTD_e_end) );
756 if (inBuff.pos != inBuff.size) goto _output_error; /* entire input should be consumed */
758 DISPLAYLEVEL(3, "OK (%u bytes : %.2f%%)\n", (U32)cSize, (double)cSize/CNBufferSize*100);
760 DISPLAYLEVEL(3, "test%3i : decompress with ZSTD_DCtx_refPrefix : ", testNb++);
761 CHECK_Z( ZSTD_DCtx_refPrefix(zd, dictionary.start, dictionary.filled) );
762 outBuff.dst = decodedBuffer;
763 outBuff.size = CNBufferSize;
765 inBuff.src = compressedBuffer;
768 CHECK_Z( ZSTD_decompress_generic(zd, &outBuff, &inBuff) );
769 if (inBuff.pos != inBuff.size) goto _output_error; /* entire input should be consumed */
770 if (outBuff.pos != CNBufferSize) goto _output_error; /* must regenerate whole input */
771 DISPLAYLEVEL(3, "OK \n");
773 DISPLAYLEVEL(3, "test%3i : decompress without dictionary (should fail): ", testNb++);
774 { size_t const r = ZSTD_decompress(decodedBuffer, CNBufferSize, compressedBuffer, cSize);
775 if (!ZSTD_isError(r)) goto _output_error; /* must fail : dictionary not used */
776 DISPLAYLEVEL(3, "OK (%s)\n", ZSTD_getErrorName(r));
779 DISPLAYLEVEL(3, "test%3i : compress again with ZSTD_compress_generic : ", testNb++);
780 outBuff.dst = compressedBuffer;
781 outBuff.size = compressedBufferSize;
783 inBuff.src = CNBuffer;
784 inBuff.size = CNBufferSize;
786 CHECK_Z( ZSTD_compress_generic(zc, &outBuff, &inBuff, ZSTD_e_end) );
787 if (inBuff.pos != inBuff.size) goto _output_error; /* entire input should be consumed */
789 DISPLAYLEVEL(3, "OK (%u bytes : %.2f%%)\n", (U32)cSize, (double)cSize/CNBufferSize*100);
791 DISPLAYLEVEL(3, "test%3i : decompress without dictionary (should work): ", testNb++);
792 CHECK_Z( ZSTD_decompress(decodedBuffer, CNBufferSize, compressedBuffer, cSize) );
793 DISPLAYLEVEL(3, "OK \n");
796 DISPLAYLEVEL(3, "test%3i : ZSTD_initCStream_advanced with pledgedSrcSize=0 and dict : ", testNb++);
797 { ZSTD_parameters params = ZSTD_getParams(5, 0, 0);
798 params.fParams.contentSizeFlag = 1;
799 CHECK_Z( ZSTD_initCStream_advanced(zc, dictionary.start, dictionary.filled, params, 0 /* pledgedSrcSize==0 means "empty" when params.fParams.contentSizeFlag is set */) );
800 } /* cstream advanced shall write content size = 0 */
801 outBuff.dst = compressedBuffer;
802 outBuff.size = compressedBufferSize;
804 inBuff.src = CNBuffer;
807 CHECK_Z( ZSTD_compressStream(zc, &outBuff, &inBuff) );
808 if (ZSTD_endStream(zc, &outBuff) != 0) goto _output_error;
810 if (ZSTD_findDecompressedSize(compressedBuffer, cSize) != 0) goto _output_error;
811 DISPLAYLEVEL(3, "OK \n");
813 DISPLAYLEVEL(3, "test%3i : pledgedSrcSize == 0 behaves properly : ", testNb++);
814 { ZSTD_parameters params = ZSTD_getParams(5, 0, 0);
815 params.fParams.contentSizeFlag = 1;
816 CHECK_Z( ZSTD_initCStream_advanced(zc, NULL, 0, params, 0) );
817 } /* cstream advanced shall write content size = 0 */
818 inBuff.src = CNBuffer;
821 outBuff.dst = compressedBuffer;
822 outBuff.size = compressedBufferSize;
824 CHECK_Z( ZSTD_compressStream(zc, &outBuff, &inBuff) );
825 if (ZSTD_endStream(zc, &outBuff) != 0) goto _output_error;
827 if (ZSTD_findDecompressedSize(compressedBuffer, cSize) != 0) goto _output_error;
829 ZSTD_resetCStream(zc, 0); /* resetCStream should treat 0 as unknown */
830 outBuff.dst = compressedBuffer;
831 outBuff.size = compressedBufferSize;
833 inBuff.src = CNBuffer;
836 CHECK_Z( ZSTD_compressStream(zc, &outBuff, &inBuff) );
837 if (ZSTD_endStream(zc, &outBuff) != 0) goto _output_error;
839 if (ZSTD_findDecompressedSize(compressedBuffer, cSize) != ZSTD_CONTENTSIZE_UNKNOWN) goto _output_error;
840 DISPLAYLEVEL(3, "OK \n");
842 /* Basic multithreading compression test */
843 DISPLAYLEVEL(3, "test%3i : compress %u bytes with multiple threads : ", testNb++, COMPRESSIBLE_NOISE_LENGTH);
844 { ZSTD_parameters const params = ZSTD_getParams(1, 0, 0);
846 CHECK_Z( ZSTDMT_getMTCtxParameter(mtctx, ZSTDMT_p_jobSize, &jobSize));
847 CHECK(jobSize != 0, "job size non-zero");
848 CHECK_Z( ZSTDMT_initCStream_advanced(mtctx, CNBuffer, dictSize, params, CNBufferSize) );
849 CHECK_Z( ZSTDMT_getMTCtxParameter(mtctx, ZSTDMT_p_jobSize, &jobSize));
850 CHECK(jobSize != 0, "job size non-zero");
852 outBuff.dst = compressedBuffer;
853 outBuff.size = compressedBufferSize;
855 inBuff.src = CNBuffer;
856 inBuff.size = CNBufferSize;
858 { size_t const compressResult = ZSTDMT_compressStream_generic(mtctx, &outBuff, &inBuff, ZSTD_e_end);
859 if (compressResult != 0) goto _output_error; /* compression must be completed in a single round */
861 if (inBuff.pos != inBuff.size) goto _output_error; /* entire input should be consumed */
862 { size_t const compressedSize = ZSTD_findFrameCompressedSize(compressedBuffer, outBuff.pos);
863 if (compressedSize != outBuff.pos) goto _output_error; /* must be a full valid frame */
865 DISPLAYLEVEL(3, "OK \n");
867 /* Complex multithreading + dictionary test */
868 { U32 const nbWorkers = 2;
869 size_t const jobSize = 4 * 1 MB;
870 size_t const srcSize = jobSize * nbWorkers; /* we want each job to have predictable size */
871 size_t const segLength = 2 KB;
872 size_t const offset = 600 KB; /* must be larger than window defined in cdict */
873 size_t const start = jobSize + (offset-1);
874 const BYTE* const srcToCopy = (const BYTE*)CNBuffer + start;
875 BYTE* const dst = (BYTE*)CNBuffer + start - offset;
876 DISPLAYLEVEL(3, "test%3i : compress %u bytes with multiple threads + dictionary : ", testNb++, (U32)srcSize);
877 CHECK_Z( ZSTD_CCtx_setParameter(zc, ZSTD_p_compressionLevel, 3) );
878 CHECK_Z( ZSTD_CCtx_setParameter(zc, ZSTD_p_nbWorkers, nbWorkers) );
879 CHECK_Z( ZSTD_CCtx_setParameter(zc, ZSTD_p_jobSize, jobSize) );
880 assert(start > offset);
881 assert(start + segLength < COMPRESSIBLE_NOISE_LENGTH);
882 memcpy(dst, srcToCopy, segLength); /* create a long repetition at long distance for job 2 */
883 outBuff.dst = compressedBuffer;
884 outBuff.size = compressedBufferSize;
886 inBuff.src = CNBuffer;
887 inBuff.size = srcSize; assert(srcSize < COMPRESSIBLE_NOISE_LENGTH);
890 { ZSTD_compressionParameters const cParams = ZSTD_getCParams(1, 4 KB, dictionary.filled); /* intentionnally lies on estimatedSrcSize, to push cdict into targeting a small window size */
891 ZSTD_CDict* const cdict = ZSTD_createCDict_advanced(dictionary.start, dictionary.filled, ZSTD_dlm_byRef, ZSTD_dct_fullDict, cParams, ZSTD_defaultCMem);
892 DISPLAYLEVEL(5, "cParams.windowLog = %u : ", cParams.windowLog);
893 CHECK_Z( ZSTD_CCtx_refCDict(zc, cdict) );
894 CHECK_Z( ZSTD_compress_generic(zc, &outBuff, &inBuff, ZSTD_e_end) );
895 CHECK_Z( ZSTD_CCtx_refCDict(zc, NULL) ); /* do not keep a reference to cdict, as its lifetime ends */
896 ZSTD_freeCDict(cdict);
898 if (inBuff.pos != inBuff.size) goto _output_error; /* entire input should be consumed */
900 DISPLAYLEVEL(3, "OK \n");
902 DISPLAYLEVEL(3, "test%3i : decompress large frame created from multiple threads + dictionary : ", testNb++);
903 { ZSTD_DStream* const dstream = ZSTD_createDCtx();
904 ZSTD_frameHeader zfh;
905 ZSTD_getFrameHeader(&zfh, compressedBuffer, cSize);
906 DISPLAYLEVEL(5, "frame windowsize = %u : ", (U32)zfh.windowSize);
907 outBuff.dst = decodedBuffer;
908 outBuff.size = CNBufferSize;
910 inBuff.src = compressedBuffer;
912 CHECK_Z( ZSTD_initDStream_usingDict(dstream, dictionary.start, dictionary.filled) );
913 inBuff.size = 1; /* avoid shortcut to single-pass mode */
914 CHECK_Z( ZSTD_decompressStream(dstream, &outBuff, &inBuff) );
916 CHECK_Z( ZSTD_decompressStream(dstream, &outBuff, &inBuff) );
917 if (inBuff.pos != inBuff.size) goto _output_error; /* entire input should be consumed */
918 ZSTD_freeDStream(dstream);
920 DISPLAYLEVEL(3, "OK \n");
922 DISPLAYLEVEL(3, "test%3i : check dictionary FSE tables can represent every code : ", testNb++);
923 { unsigned const kMaxWindowLog = 24;
925 ZSTD_compressionParameters cParams = ZSTD_getCParams(3, 1U << kMaxWindowLog, 1024);
928 SEQ_stream seq = SEQ_initStream(0x87654321);
932 XXH64_reset(&xxh, 0);
933 cParams.windowLog = kMaxWindowLog;
934 cdict = ZSTD_createCDict_advanced(dictionary.start, dictionary.filled, ZSTD_dlm_byRef, ZSTD_dct_fullDict, cParams, ZSTD_defaultCMem);
935 ddict = ZSTD_createDDict(dictionary.start, dictionary.filled);
937 if (!cdict || !ddict) goto _output_error;
940 ZSTD_resetDStream(zd);
941 CHECK_Z(ZSTD_CCtx_refCDict(zc, cdict));
942 CHECK_Z(ZSTD_initDStream_usingDDict(zd, ddict));
943 CHECK_Z(ZSTD_setDStreamParameter(zd, DStream_p_maxWindowSize, 1U << kMaxWindowLog));
944 /* Test all values < 300 */
945 for (value = 0; value < 300; ++value) {
946 for (type = (SEQ_gen_type)0; type < SEQ_gen_max; ++type) {
947 CHECK_Z(SEQ_generateRoundTrip(zc, zd, &xxh, &seq, type, value));
950 /* Test values 2^8 to 2^17 */
951 for (value = (1 << 8); value < (1 << 17); value <<= 1) {
952 for (type = (SEQ_gen_type)0; type < SEQ_gen_max; ++type) {
953 CHECK_Z(SEQ_generateRoundTrip(zc, zd, &xxh, &seq, type, value));
954 CHECK_Z(SEQ_generateRoundTrip(zc, zd, &xxh, &seq, type, value + (value >> 2)));
957 /* Test offset values up to the max window log */
958 for (value = 8; value <= kMaxWindowLog; ++value) {
959 CHECK_Z(SEQ_generateRoundTrip(zc, zd, &xxh, &seq, SEQ_gen_of, (1U << value) - 1));
962 CHECK_Z(SEQ_roundTrip(zc, zd, &xxh, NULL, 0, ZSTD_e_end));
963 CHECK(SEQ_digest(&seq) != XXH64_digest(&xxh), "SEQ XXH64 does not match");
965 ZSTD_freeCDict(cdict);
966 ZSTD_freeDDict(ddict);
968 DISPLAYLEVEL(3, "OK \n");
970 DISPLAYLEVEL(3, "test%3i : ZSTD_initCStream_srcSize sets requestedParams : ", testNb++);
972 CHECK_Z(ZSTD_initCStream_srcSize(zc, 11, ZSTD_CONTENTSIZE_UNKNOWN));
973 CHECK_Z(ZSTD_CCtx_getParameter(zc, ZSTD_p_compressionLevel, &level));
974 CHECK(level != 11, "Compression level does not match");
975 ZSTD_resetCStream(zc, ZSTD_CONTENTSIZE_UNKNOWN);
976 CHECK_Z(ZSTD_CCtx_getParameter(zc, ZSTD_p_compressionLevel, &level));
977 CHECK(level != 11, "Compression level does not match");
979 DISPLAYLEVEL(3, "OK \n");
981 DISPLAYLEVEL(3, "test%3i : ZSTD_initCStream_advanced sets requestedParams : ", testNb++);
982 { ZSTD_parameters const params = ZSTD_getParams(9, 0, 0);
983 CHECK_Z(ZSTD_initCStream_advanced(zc, NULL, 0, params, ZSTD_CONTENTSIZE_UNKNOWN));
984 CHECK(badParameters(zc, params), "Compression parameters do not match");
985 ZSTD_resetCStream(zc, ZSTD_CONTENTSIZE_UNKNOWN);
986 CHECK(badParameters(zc, params), "Compression parameters do not match");
988 DISPLAYLEVEL(3, "OK \n");
990 /* Overlen overwriting window data bug */
991 DISPLAYLEVEL(3, "test%3i : wildcopy doesn't overwrite potential match data : ", testNb++);
992 { /* This test has a window size of 1024 bytes and consists of 3 blocks:
993 1. 'a' repeated 517 times
994 2. 'b' repeated 516 times
995 3. a compressed block with no literals and 3 sequence commands:
996 litlength = 0, offset = 24, match length = 24
997 litlength = 0, offset = 24, match length = 3 (this one creates an overlength write of length 2*WILDCOPY_OVERLENGTH - 3)
998 litlength = 0, offset = 1021, match length = 3 (this one will try to read from overwritten data if the buffer is too small) */
1000 const char* testCase =
1001 "\x28\xB5\x2F\xFD\x04\x00\x4C\x00\x00\x10\x61\x61\x01\x00\x00\x2A"
1002 "\x80\x05\x44\x00\x00\x08\x62\x01\x00\x00\x2A\x20\x04\x5D\x00\x00"
1003 "\x00\x03\x40\x00\x00\x64\x60\x27\xB0\xE0\x0C\x67\x62\xCE\xE0";
1004 ZSTD_DStream* const zds = ZSTD_createDStream();
1005 if (zds==NULL) goto _output_error;
1007 CHECK_Z( ZSTD_initDStream(zds) );
1008 inBuff.src = testCase;
1011 outBuff.dst = decodedBuffer;
1012 outBuff.size = CNBufferSize;
1015 while (inBuff.pos < inBuff.size) {
1016 CHECK_Z( ZSTD_decompressStream(zds, &outBuff, &inBuff) );
1019 ZSTD_freeDStream(zds);
1021 DISPLAYLEVEL(3, "OK \n");
1023 DISPLAYLEVEL(3, "test%3i : dictionary + uncompressible block + reusing tables checks offset table validity: ", testNb++);
1024 { ZSTD_CDict* const cdict = ZSTD_createCDict_advanced(
1025 dictionary.start, dictionary.filled,
1026 ZSTD_dlm_byRef, ZSTD_dct_fullDict,
1027 ZSTD_getCParams(3, 0, dictionary.filled),
1029 const size_t inbufsize = 2 * 128 * 1024; /* 2 blocks */
1030 const size_t outbufsize = ZSTD_compressBound(inbufsize);
1031 size_t inbufpos = 0;
1032 size_t cursegmentlen;
1033 BYTE *inbuf = (BYTE *)malloc(inbufsize);
1034 BYTE *outbuf = (BYTE *)malloc(outbufsize);
1035 BYTE *checkbuf = (BYTE *)malloc(inbufsize);
1038 CHECK(cdict == NULL, "failed to alloc cdict");
1039 CHECK(inbuf == NULL, "failed to alloc input buffer");
1041 /* first block is uncompressible */
1042 cursegmentlen = 128 * 1024;
1043 RDG_genBuffer(inbuf + inbufpos, cursegmentlen, 0., 0., seed);
1044 inbufpos += cursegmentlen;
1046 /* second block is compressible */
1047 cursegmentlen = 128 * 1024 - 256;
1048 RDG_genBuffer(inbuf + inbufpos, cursegmentlen, 0.05, 0., seed);
1049 inbufpos += cursegmentlen;
1051 /* and includes a very long backref */
1052 cursegmentlen = 128;
1053 memcpy(inbuf + inbufpos, dictionary.start + 256, cursegmentlen);
1054 inbufpos += cursegmentlen;
1056 /* and includes a very long backref */
1057 cursegmentlen = 128;
1058 memcpy(inbuf + inbufpos, dictionary.start + 128, cursegmentlen);
1059 inbufpos += cursegmentlen;
1061 ret = ZSTD_compress_usingCDict(zc, outbuf, outbufsize, inbuf, inbufpos, cdict);
1064 ret = ZSTD_decompress_usingDict(zd, checkbuf, inbufsize, outbuf, ret, dictionary.start, dictionary.filled);
1067 CHECK(memcmp(inbuf, checkbuf, inbufpos), "start and finish buffers don't match");
1069 ZSTD_freeCDict(cdict);
1074 DISPLAYLEVEL(3, "OK \n");
1076 DISPLAYLEVEL(3, "test%3i : dictionary + small blocks + reusing tables checks offset table validity: ", testNb++);
1077 { ZSTD_CDict* const cdict = ZSTD_createCDict_advanced(
1078 dictionary.start, dictionary.filled,
1079 ZSTD_dlm_byRef, ZSTD_dct_fullDict,
1080 ZSTD_getCParams(3, 0, dictionary.filled),
1082 ZSTD_outBuffer out = {compressedBuffer, compressedBufferSize, 0};
1083 int remainingInput = 256 * 1024;
1086 ZSTD_CCtx_reset(zc);
1087 CHECK_Z(ZSTD_CCtx_resetParameters(zc));
1088 CHECK_Z(ZSTD_CCtx_refCDict(zc, cdict));
1089 CHECK_Z(ZSTD_CCtx_setParameter(zc, ZSTD_p_checksumFlag, 1));
1090 /* Write a bunch of 6 byte blocks */
1091 while (remainingInput > 0) {
1092 char testBuffer[6] = "\xAA\xAA\xAA\xAA\xAA\xAA";
1093 const size_t kSmallBlockSize = sizeof(testBuffer);
1094 ZSTD_inBuffer in = {testBuffer, kSmallBlockSize, 0};
1096 CHECK_Z(ZSTD_compress_generic(zc, &out, &in, ZSTD_e_flush));
1097 CHECK(in.pos != in.size, "input not fully consumed");
1098 remainingInput -= kSmallBlockSize;
1100 /* Write several very long offset matches into the dictionary */
1101 for (offset = 1024; offset >= 0; offset -= 128) {
1102 ZSTD_inBuffer in = {dictionary.start + offset, 128, 0};
1103 ZSTD_EndDirective flush = offset > 0 ? ZSTD_e_continue : ZSTD_e_end;
1104 CHECK_Z(ZSTD_compress_generic(zc, &out, &in, flush));
1105 CHECK(in.pos != in.size, "input not fully consumed");
1107 /* Ensure decompression works */
1108 CHECK_Z(ZSTD_decompress_usingDict(zd, decodedBuffer, CNBufferSize, out.dst, out.pos, dictionary.start, dictionary.filled));
1110 ZSTD_freeCDict(cdict);
1112 DISPLAYLEVEL(3, "OK \n");
1115 FUZ_freeDictionary(dictionary);
1116 ZSTD_freeCStream(zc);
1117 ZSTD_freeDStream(zd);
1118 ZSTDMT_freeCCtx(mtctx);
1120 free(compressedBuffer);
1121 free(decodedBuffer);
1126 DISPLAY("Error detected in Unit tests ! \n");
1131 /* ====== Fuzzer tests ====== */
1133 static size_t findDiff(const void* buf1, const void* buf2, size_t max)
1135 const BYTE* b1 = (const BYTE*)buf1;
1136 const BYTE* b2 = (const BYTE*)buf2;
1138 for (u=0; u<max; u++) {
1139 if (b1[u] != b2[u]) break;
1142 DISPLAY("=> No difference detected within %u bytes \n", (U32)max);
1145 DISPLAY("Error at position %u / %u \n", (U32)u, (U32)max);
1147 DISPLAY(" %02X %02X %02X ",
1148 b1[u-3], b1[u-2], b1[u-1]);
1149 DISPLAY(" :%02X: %02X %02X %02X %02X %02X \n",
1150 b1[u], b1[u+1], b1[u+2], b1[u+3], b1[u+4], b1[u+5]);
1152 DISPLAY(" %02X %02X %02X ",
1153 b2[u-3], b2[u-2], b2[u-1]);
1154 DISPLAY(" :%02X: %02X %02X %02X %02X %02X \n",
1155 b2[u], b2[u+1], b2[u+2], b2[u+3], b2[u+4], b2[u+5]);
1159 static size_t FUZ_rLogLength(U32* seed, U32 logLength)
1161 size_t const lengthMask = ((size_t)1 << logLength) - 1;
1162 return (lengthMask+1) + (FUZ_rand(seed) & lengthMask);
1165 static size_t FUZ_randomLength(U32* seed, U32 maxLog)
1167 U32 const logLength = FUZ_rand(seed) % maxLog;
1168 return FUZ_rLogLength(seed, logLength);
1171 /* Return value in range minVal <= v <= maxVal */
1172 static U32 FUZ_randomClampedLength(U32* seed, U32 minVal, U32 maxVal)
1174 U32 const mod = maxVal < minVal ? 1 : (maxVal + 1) - minVal;
1175 return (U32)((FUZ_rand(seed) % mod) + minVal);
1178 static int fuzzerTests(U32 seed, U32 nbTests, unsigned startTest, double compressibility, int bigTests)
1180 U32 const maxSrcLog = bigTests ? 24 : 22;
1181 static const U32 maxSampleLog = 19;
1182 size_t const srcBufferSize = (size_t)1<<maxSrcLog;
1183 BYTE* cNoiseBuffer[5];
1184 size_t const copyBufferSize = srcBufferSize + (1<<maxSampleLog);
1185 BYTE* const copyBuffer = (BYTE*)malloc (copyBufferSize);
1186 size_t const cBufferSize = ZSTD_compressBound(srcBufferSize);
1187 BYTE* const cBuffer = (BYTE*)malloc (cBufferSize);
1188 size_t const dstBufferSize = srcBufferSize;
1189 BYTE* const dstBuffer = (BYTE*)malloc (dstBufferSize);
1192 U32 coreSeed = seed;
1193 ZSTD_CStream* zc = ZSTD_createCStream(); /* will be re-created sometimes */
1194 ZSTD_DStream* zd = ZSTD_createDStream(); /* will be re-created sometimes */
1195 ZSTD_DStream* const zd_noise = ZSTD_createDStream();
1196 UTIL_time_t const startClock = UTIL_getTime();
1197 const BYTE* dict = NULL; /* can keep same dict on 2 consecutive tests */
1198 size_t dictSize = 0;
1200 U32 const cLevelMax = bigTests ? (U32)ZSTD_maxCLevel() : g_cLevelMax_smallTests;
1203 cNoiseBuffer[0] = (BYTE*)malloc (srcBufferSize);
1204 cNoiseBuffer[1] = (BYTE*)malloc (srcBufferSize);
1205 cNoiseBuffer[2] = (BYTE*)malloc (srcBufferSize);
1206 cNoiseBuffer[3] = (BYTE*)malloc (srcBufferSize);
1207 cNoiseBuffer[4] = (BYTE*)malloc (srcBufferSize);
1208 CHECK (!cNoiseBuffer[0] || !cNoiseBuffer[1] || !cNoiseBuffer[2] || !cNoiseBuffer[3] || !cNoiseBuffer[4] ||
1209 !copyBuffer || !dstBuffer || !cBuffer || !zc || !zd || !zd_noise ,
1210 "Not enough memory, fuzzer tests cancelled");
1212 /* Create initial samples */
1213 RDG_genBuffer(cNoiseBuffer[0], srcBufferSize, 0.00, 0., coreSeed); /* pure noise */
1214 RDG_genBuffer(cNoiseBuffer[1], srcBufferSize, 0.05, 0., coreSeed); /* barely compressible */
1215 RDG_genBuffer(cNoiseBuffer[2], srcBufferSize, compressibility, 0., coreSeed);
1216 RDG_genBuffer(cNoiseBuffer[3], srcBufferSize, 0.95, 0., coreSeed); /* highly compressible */
1217 RDG_genBuffer(cNoiseBuffer[4], srcBufferSize, 1.00, 0., coreSeed); /* sparse content */
1218 memset(copyBuffer, 0x65, copyBufferSize); /* make copyBuffer considered initialized */
1219 ZSTD_initDStream_usingDict(zd, NULL, 0); /* ensure at least one init */
1221 /* catch up testNb */
1222 for (testNb=1; testNb < startTest; testNb++)
1223 FUZ_rand(&coreSeed);
1226 for ( ; (testNb <= nbTests) || (UTIL_clockSpanMicro(startClock) < g_clockTime) ; testNb++ ) {
1228 const BYTE* srcBuffer;
1229 size_t totalTestSize, totalGenSize, cSize;
1230 XXH64_state_t xxhState;
1232 U32 resetAllowed = 1;
1236 FUZ_rand(&coreSeed);
1237 lseed = coreSeed ^ prime32;
1238 if (nbTests >= testNb) {
1239 DISPLAYUPDATE(2, "\r%6u/%6u ", testNb, nbTests);
1241 DISPLAYUPDATE(2, "\r%6u ", testNb);
1244 /* states full reset (deliberately not synchronized) */
1245 /* some issues can only happen when reusing states */
1246 if ((FUZ_rand(&lseed) & 0xFF) == 131) {
1247 ZSTD_freeCStream(zc);
1248 zc = ZSTD_createCStream();
1249 CHECK(zc==NULL, "ZSTD_createCStream : allocation error");
1252 if ((FUZ_rand(&lseed) & 0xFF) == 132) {
1253 ZSTD_freeDStream(zd);
1254 zd = ZSTD_createDStream();
1255 CHECK(zd==NULL, "ZSTD_createDStream : allocation error");
1256 CHECK_Z( ZSTD_initDStream_usingDict(zd, NULL, 0) ); /* ensure at least one init */
1259 /* srcBuffer selection [0-4] */
1260 { U32 buffNb = FUZ_rand(&lseed) & 0x7F;
1261 if (buffNb & 7) buffNb=2; /* most common : compressible (P) */
1265 const U32 tnb[2] = { 1, 3 }; /* barely/highly compressible */
1266 buffNb = tnb[buffNb >> 3];
1268 const U32 tnb[2] = { 0, 4 }; /* not compressible / sparse */
1269 buffNb = tnb[buffNb >> 3];
1271 srcBuffer = cNoiseBuffer[buffNb];
1274 /* compression init */
1275 if ((FUZ_rand(&lseed)&1) /* at beginning, to keep same nb of rand */
1276 && oldTestLog /* at least one test happened */ && resetAllowed) {
1277 maxTestSize = FUZ_randomLength(&lseed, oldTestLog+2);
1278 maxTestSize = MIN(maxTestSize, srcBufferSize-16);
1279 { U64 const pledgedSrcSize = (FUZ_rand(&lseed) & 3) ? 0 : maxTestSize;
1280 CHECK_Z( ZSTD_resetCStream(zc, pledgedSrcSize) );
1283 U32 const testLog = FUZ_rand(&lseed) % maxSrcLog;
1284 U32 const dictLog = FUZ_rand(&lseed) % maxSrcLog;
1285 U32 const cLevelCandidate = ( FUZ_rand(&lseed) %
1287 (MAX(testLog, dictLog) / 3)))
1289 U32 const cLevel = MIN(cLevelCandidate, cLevelMax);
1290 maxTestSize = FUZ_rLogLength(&lseed, testLog);
1291 oldTestLog = testLog;
1292 /* random dictionary selection */
1293 dictSize = ((FUZ_rand(&lseed)&7)==1) ? FUZ_rLogLength(&lseed, dictLog) : 0;
1294 { size_t const dictStart = FUZ_rand(&lseed) % (srcBufferSize - dictSize);
1295 dict = srcBuffer + dictStart;
1297 { U64 const pledgedSrcSize = (FUZ_rand(&lseed) & 3) ? ZSTD_CONTENTSIZE_UNKNOWN : maxTestSize;
1298 ZSTD_parameters params = ZSTD_getParams(cLevel, pledgedSrcSize, dictSize);
1299 params.fParams.checksumFlag = FUZ_rand(&lseed) & 1;
1300 params.fParams.noDictIDFlag = FUZ_rand(&lseed) & 1;
1301 params.fParams.contentSizeFlag = FUZ_rand(&lseed) & 1;
1302 CHECK_Z ( ZSTD_initCStream_advanced(zc, dict, dictSize, params, pledgedSrcSize) );
1305 /* multi-segments compression test */
1306 XXH64_reset(&xxhState, 0);
1307 { ZSTD_outBuffer outBuff = { cBuffer, cBufferSize, 0 } ;
1309 for (n=0, cSize=0, totalTestSize=0 ; totalTestSize < maxTestSize ; n++) {
1310 /* compress random chunks into randomly sized dst buffers */
1311 { size_t const randomSrcSize = FUZ_randomLength(&lseed, maxSampleLog);
1312 size_t const srcSize = MIN(maxTestSize-totalTestSize, randomSrcSize);
1313 size_t const srcStart = FUZ_rand(&lseed) % (srcBufferSize - srcSize);
1314 size_t const randomDstSize = FUZ_randomLength(&lseed, maxSampleLog);
1315 size_t const dstBuffSize = MIN(cBufferSize - cSize, randomDstSize);
1316 ZSTD_inBuffer inBuff = { srcBuffer+srcStart, srcSize, 0 };
1317 outBuff.size = outBuff.pos + dstBuffSize;
1319 CHECK_Z( ZSTD_compressStream(zc, &outBuff, &inBuff) );
1321 XXH64_update(&xxhState, srcBuffer+srcStart, inBuff.pos);
1322 memcpy(copyBuffer+totalTestSize, srcBuffer+srcStart, inBuff.pos);
1323 totalTestSize += inBuff.pos;
1326 /* random flush operation, to mess around */
1327 if ((FUZ_rand(&lseed) & 15) == 0) {
1328 size_t const randomDstSize = FUZ_randomLength(&lseed, maxSampleLog);
1329 size_t const adjustedDstSize = MIN(cBufferSize - cSize, randomDstSize);
1330 outBuff.size = outBuff.pos + adjustedDstSize;
1331 CHECK_Z( ZSTD_flushStream(zc, &outBuff) );
1334 /* final frame epilogue */
1335 { size_t remainingToFlush = (size_t)(-1);
1336 while (remainingToFlush) {
1337 size_t const randomDstSize = FUZ_randomLength(&lseed, maxSampleLog);
1338 size_t const adjustedDstSize = MIN(cBufferSize - cSize, randomDstSize);
1339 outBuff.size = outBuff.pos + adjustedDstSize;
1340 remainingToFlush = ZSTD_endStream(zc, &outBuff);
1341 CHECK (ZSTD_isError(remainingToFlush), "end error : %s", ZSTD_getErrorName(remainingToFlush));
1343 crcOrig = XXH64_digest(&xxhState);
1344 cSize = outBuff.pos;
1347 /* multi - fragments decompression test */
1348 if (!dictSize /* don't reset if dictionary : could be different */ && (FUZ_rand(&lseed) & 1)) {
1349 CHECK_Z ( ZSTD_resetDStream(zd) );
1351 CHECK_Z ( ZSTD_initDStream_usingDict(zd, dict, dictSize) );
1353 { size_t decompressionResult = 1;
1354 ZSTD_inBuffer inBuff = { cBuffer, cSize, 0 };
1355 ZSTD_outBuffer outBuff= { dstBuffer, dstBufferSize, 0 };
1356 for (totalGenSize = 0 ; decompressionResult ; ) {
1357 size_t const readCSrcSize = FUZ_randomLength(&lseed, maxSampleLog);
1358 size_t const randomDstSize = FUZ_randomLength(&lseed, maxSampleLog);
1359 size_t const dstBuffSize = MIN(dstBufferSize - totalGenSize, randomDstSize);
1360 inBuff.size = inBuff.pos + readCSrcSize;
1361 outBuff.size = outBuff.pos + dstBuffSize;
1362 decompressionResult = ZSTD_decompressStream(zd, &outBuff, &inBuff);
1363 if (ZSTD_getErrorCode(decompressionResult) == ZSTD_error_checksum_wrong) {
1364 DISPLAY("checksum error : \n");
1365 findDiff(copyBuffer, dstBuffer, totalTestSize);
1367 CHECK( ZSTD_isError(decompressionResult), "decompression error : %s",
1368 ZSTD_getErrorName(decompressionResult) );
1370 CHECK (decompressionResult != 0, "frame not fully decoded");
1371 CHECK (outBuff.pos != totalTestSize, "decompressed data : wrong size (%u != %u)",
1372 (U32)outBuff.pos, (U32)totalTestSize);
1373 CHECK (inBuff.pos != cSize, "compressed data should be fully read")
1374 { U64 const crcDest = XXH64(dstBuffer, totalTestSize, 0);
1375 if (crcDest!=crcOrig) findDiff(copyBuffer, dstBuffer, totalTestSize);
1376 CHECK (crcDest!=crcOrig, "decompressed data corrupted");
1379 /*===== noisy/erroneous src decompression test =====*/
1381 /* add some noise */
1382 { U32 const nbNoiseChunks = (FUZ_rand(&lseed) & 7) + 2;
1383 U32 nn; for (nn=0; nn<nbNoiseChunks; nn++) {
1384 size_t const randomNoiseSize = FUZ_randomLength(&lseed, maxSampleLog);
1385 size_t const noiseSize = MIN((cSize/3) , randomNoiseSize);
1386 size_t const noiseStart = FUZ_rand(&lseed) % (srcBufferSize - noiseSize);
1387 size_t const cStart = FUZ_rand(&lseed) % (cSize - noiseSize);
1388 memcpy(cBuffer+cStart, srcBuffer+noiseStart, noiseSize);
1391 /* try decompression on noisy data */
1392 CHECK_Z( ZSTD_initDStream(zd_noise) ); /* note : no dictionary */
1393 { ZSTD_inBuffer inBuff = { cBuffer, cSize, 0 };
1394 ZSTD_outBuffer outBuff= { dstBuffer, dstBufferSize, 0 };
1395 while (outBuff.pos < dstBufferSize) {
1396 size_t const randomCSrcSize = FUZ_randomLength(&lseed, maxSampleLog);
1397 size_t const randomDstSize = FUZ_randomLength(&lseed, maxSampleLog);
1398 size_t const adjustedDstSize = MIN(dstBufferSize - outBuff.pos, randomDstSize);
1399 size_t const adjustedCSrcSize = MIN(cSize - inBuff.pos, randomCSrcSize);
1400 outBuff.size = outBuff.pos + adjustedDstSize;
1401 inBuff.size = inBuff.pos + adjustedCSrcSize;
1402 { size_t const decompressError = ZSTD_decompressStream(zd, &outBuff, &inBuff);
1403 if (ZSTD_isError(decompressError)) break; /* error correctly detected */
1404 /* No forward progress possible */
1405 if (outBuff.pos < outBuff.size && inBuff.pos == cSize) break;
1407 DISPLAY("\r%u fuzzer tests completed \n", testNb);
1410 ZSTD_freeCStream(zc);
1411 ZSTD_freeDStream(zd);
1412 ZSTD_freeDStream(zd_noise);
1413 free(cNoiseBuffer[0]);
1414 free(cNoiseBuffer[1]);
1415 free(cNoiseBuffer[2]);
1416 free(cNoiseBuffer[3]);
1417 free(cNoiseBuffer[4]);
1429 /* fuzzing ZSTDMT_* interface */
1430 static int fuzzerTests_MT(U32 seed, U32 nbTests, unsigned startTest,
1431 double compressibility, int bigTests)
1433 const U32 maxSrcLog = bigTests ? 24 : 22;
1434 static const U32 maxSampleLog = 19;
1435 size_t const srcBufferSize = (size_t)1<<maxSrcLog;
1436 BYTE* cNoiseBuffer[5];
1437 size_t const copyBufferSize= srcBufferSize + (1<<maxSampleLog);
1438 BYTE* const copyBuffer = (BYTE*)malloc (copyBufferSize);
1439 size_t const cBufferSize = ZSTD_compressBound(srcBufferSize);
1440 BYTE* const cBuffer = (BYTE*)malloc (cBufferSize);
1441 size_t const dstBufferSize = srcBufferSize;
1442 BYTE* const dstBuffer = (BYTE*)malloc (dstBufferSize);
1445 U32 coreSeed = seed;
1447 ZSTDMT_CCtx* zc = ZSTDMT_createCCtx(nbThreads); /* will be reset sometimes */
1448 ZSTD_DStream* zd = ZSTD_createDStream(); /* will be reset sometimes */
1449 ZSTD_DStream* const zd_noise = ZSTD_createDStream();
1450 UTIL_time_t const startClock = UTIL_getTime();
1451 const BYTE* dict=NULL; /* can keep same dict on 2 consecutive tests */
1452 size_t dictSize = 0;
1453 int const cLevelMax = bigTests ? (U32)ZSTD_maxCLevel()-1 : g_cLevelMax_smallTests;
1454 U32 const nbThreadsMax = bigTests ? 4 : 2;
1457 cNoiseBuffer[0] = (BYTE*)malloc (srcBufferSize);
1458 cNoiseBuffer[1] = (BYTE*)malloc (srcBufferSize);
1459 cNoiseBuffer[2] = (BYTE*)malloc (srcBufferSize);
1460 cNoiseBuffer[3] = (BYTE*)malloc (srcBufferSize);
1461 cNoiseBuffer[4] = (BYTE*)malloc (srcBufferSize);
1462 CHECK (!cNoiseBuffer[0] || !cNoiseBuffer[1] || !cNoiseBuffer[2] || !cNoiseBuffer[3] || !cNoiseBuffer[4] ||
1463 !copyBuffer || !dstBuffer || !cBuffer || !zc || !zd || !zd_noise ,
1464 "Not enough memory, fuzzer tests cancelled");
1466 /* Create initial samples */
1467 RDG_genBuffer(cNoiseBuffer[0], srcBufferSize, 0.00, 0., coreSeed); /* pure noise */
1468 RDG_genBuffer(cNoiseBuffer[1], srcBufferSize, 0.05, 0., coreSeed); /* barely compressible */
1469 RDG_genBuffer(cNoiseBuffer[2], srcBufferSize, compressibility, 0., coreSeed);
1470 RDG_genBuffer(cNoiseBuffer[3], srcBufferSize, 0.95, 0., coreSeed); /* highly compressible */
1471 RDG_genBuffer(cNoiseBuffer[4], srcBufferSize, 1.00, 0., coreSeed); /* sparse content */
1472 memset(copyBuffer, 0x65, copyBufferSize); /* make copyBuffer considered initialized */
1473 ZSTD_initDStream_usingDict(zd, NULL, 0); /* ensure at least one init */
1474 DISPLAYLEVEL(6, "Creating initial context with %u threads \n", nbThreads);
1476 /* catch up testNb */
1477 for (testNb=1; testNb < startTest; testNb++)
1478 FUZ_rand(&coreSeed);
1481 for ( ; (testNb <= nbTests) || (UTIL_clockSpanMicro(startClock) < g_clockTime) ; testNb++ ) {
1483 const BYTE* srcBuffer;
1484 size_t totalTestSize, totalGenSize, cSize;
1485 XXH64_state_t xxhState;
1489 FUZ_rand(&coreSeed);
1490 if (nbTests >= testNb) {
1491 DISPLAYUPDATE(2, "\r%6u/%6u ", testNb, nbTests);
1493 DISPLAYUPDATE(2, "\r%6u ", testNb);
1495 lseed = coreSeed ^ prime32;
1497 /* states full reset (deliberately not synchronized) */
1498 /* some issues can only happen when reusing states */
1499 if ((FUZ_rand(&lseed) & 0xFF) == 131) {
1500 nbThreads = (FUZ_rand(&lseed) % nbThreadsMax) + 1;
1501 DISPLAYLEVEL(5, "Creating new context with %u threads \n", nbThreads);
1502 ZSTDMT_freeCCtx(zc);
1503 zc = ZSTDMT_createCCtx(nbThreads);
1504 CHECK(zc==NULL, "ZSTDMT_createCCtx allocation error")
1506 if ((FUZ_rand(&lseed) & 0xFF) == 132) {
1507 ZSTD_freeDStream(zd);
1508 zd = ZSTD_createDStream();
1509 CHECK(zd==NULL, "ZSTDMT_createCCtx allocation error")
1510 ZSTD_initDStream_usingDict(zd, NULL, 0); /* ensure at least one init */
1513 /* srcBuffer selection [0-4] */
1514 { U32 buffNb = FUZ_rand(&lseed) & 0x7F;
1515 if (buffNb & 7) buffNb=2; /* most common : compressible (P) */
1519 const U32 tnb[2] = { 1, 3 }; /* barely/highly compressible */
1520 buffNb = tnb[buffNb >> 3];
1522 const U32 tnb[2] = { 0, 4 }; /* not compressible / sparse */
1523 buffNb = tnb[buffNb >> 3];
1525 srcBuffer = cNoiseBuffer[buffNb];
1528 /* compression init */
1529 { U32 const testLog = FUZ_rand(&lseed) % maxSrcLog;
1530 U32 const dictLog = FUZ_rand(&lseed) % maxSrcLog;
1531 int const cLevelCandidate = ( FUZ_rand(&lseed)
1532 % (ZSTD_maxCLevel() - (MAX(testLog, dictLog) / 2)) )
1534 int const cLevelThreadAdjusted = cLevelCandidate - (nbThreads * 2) + 2; /* reduce cLevel when multiple threads to reduce memory consumption */
1535 int const cLevelMin = MAX(cLevelThreadAdjusted, 1); /* no negative cLevel yet */
1536 int const cLevel = MIN(cLevelMin, cLevelMax);
1537 maxTestSize = FUZ_rLogLength(&lseed, testLog);
1539 if (FUZ_rand(&lseed)&1) { /* simple init */
1540 int const compressionLevel = (FUZ_rand(&lseed) % 5) + 1;
1541 DISPLAYLEVEL(5, "Init with compression level = %i \n", compressionLevel);
1542 CHECK_Z( ZSTDMT_initCStream(zc, compressionLevel) );
1543 } else { /* advanced init */
1544 /* random dictionary selection */
1545 dictSize = ((FUZ_rand(&lseed)&63)==1) ? FUZ_rLogLength(&lseed, dictLog) : 0;
1546 { size_t const dictStart = FUZ_rand(&lseed) % (srcBufferSize - dictSize);
1547 dict = srcBuffer + dictStart;
1549 { U64 const pledgedSrcSize = (FUZ_rand(&lseed) & 3) ? ZSTD_CONTENTSIZE_UNKNOWN : maxTestSize;
1550 ZSTD_parameters params = ZSTD_getParams(cLevel, pledgedSrcSize, dictSize);
1551 DISPLAYLEVEL(5, "Init with windowLog = %u, pledgedSrcSize = %u, dictSize = %u \n",
1552 params.cParams.windowLog, (U32)pledgedSrcSize, (U32)dictSize);
1553 params.fParams.checksumFlag = FUZ_rand(&lseed) & 1;
1554 params.fParams.noDictIDFlag = FUZ_rand(&lseed) & 1;
1555 params.fParams.contentSizeFlag = FUZ_rand(&lseed) & 1;
1556 DISPLAYLEVEL(5, "checksumFlag : %u \n", params.fParams.checksumFlag);
1557 CHECK_Z( ZSTDMT_setMTCtxParameter(zc, ZSTDMT_p_overlapSectionLog, FUZ_rand(&lseed) % 12) );
1558 CHECK_Z( ZSTDMT_setMTCtxParameter(zc, ZSTDMT_p_jobSize, FUZ_rand(&lseed) % (2*maxTestSize+1)) ); /* custome job size */
1559 CHECK_Z( ZSTDMT_initCStream_advanced(zc, dict, dictSize, params, pledgedSrcSize) );
1562 /* multi-segments compression test */
1563 XXH64_reset(&xxhState, 0);
1564 { ZSTD_outBuffer outBuff = { cBuffer, cBufferSize, 0 } ;
1566 for (n=0, cSize=0, totalTestSize=0 ; totalTestSize < maxTestSize ; n++) {
1567 /* compress random chunks into randomly sized dst buffers */
1568 { size_t const randomSrcSize = FUZ_randomLength(&lseed, maxSampleLog);
1569 size_t const srcSize = MIN (maxTestSize-totalTestSize, randomSrcSize);
1570 size_t const srcStart = FUZ_rand(&lseed) % (srcBufferSize - srcSize);
1571 size_t const randomDstSize = FUZ_randomLength(&lseed, maxSampleLog);
1572 size_t const dstBuffSize = MIN(cBufferSize - cSize, randomDstSize);
1573 ZSTD_inBuffer inBuff = { srcBuffer+srcStart, srcSize, 0 };
1574 outBuff.size = outBuff.pos + dstBuffSize;
1576 DISPLAYLEVEL(6, "Sending %u bytes to compress \n", (U32)srcSize);
1577 CHECK_Z( ZSTDMT_compressStream(zc, &outBuff, &inBuff) );
1578 DISPLAYLEVEL(6, "%u bytes read by ZSTDMT_compressStream \n", (U32)inBuff.pos);
1580 XXH64_update(&xxhState, srcBuffer+srcStart, inBuff.pos);
1581 memcpy(copyBuffer+totalTestSize, srcBuffer+srcStart, inBuff.pos);
1582 totalTestSize += inBuff.pos;
1585 /* random flush operation, to mess around */
1586 if ((FUZ_rand(&lseed) & 15) == 0) {
1587 size_t const randomDstSize = FUZ_randomLength(&lseed, maxSampleLog);
1588 size_t const adjustedDstSize = MIN(cBufferSize - cSize, randomDstSize);
1589 size_t const previousPos = outBuff.pos;
1590 outBuff.size = outBuff.pos + adjustedDstSize;
1591 DISPLAYLEVEL(5, "Flushing into dst buffer of size %u \n", (U32)adjustedDstSize);
1592 CHECK_Z( ZSTDMT_flushStream(zc, &outBuff) );
1593 assert(outBuff.pos >= previousPos);
1594 DISPLAYLEVEL(6, "%u bytes flushed by ZSTDMT_flushStream \n", (U32)(outBuff.pos-previousPos));
1597 /* final frame epilogue */
1598 { size_t remainingToFlush = (size_t)(-1);
1599 while (remainingToFlush) {
1600 size_t const randomDstSize = FUZ_randomLength(&lseed, maxSampleLog);
1601 size_t const adjustedDstSize = MIN(cBufferSize - cSize, randomDstSize);
1602 size_t const previousPos = outBuff.pos;
1603 outBuff.size = outBuff.pos + adjustedDstSize;
1604 DISPLAYLEVEL(5, "Ending into dst buffer of size %u \n", (U32)adjustedDstSize);
1605 remainingToFlush = ZSTDMT_endStream(zc, &outBuff);
1606 CHECK (ZSTD_isError(remainingToFlush), "ZSTDMT_endStream error : %s", ZSTD_getErrorName(remainingToFlush));
1607 assert(outBuff.pos >= previousPos);
1608 DISPLAYLEVEL(6, "%u bytes flushed by ZSTDMT_endStream \n", (U32)(outBuff.pos-previousPos));
1609 DISPLAYLEVEL(5, "endStream : remainingToFlush : %u \n", (U32)remainingToFlush);
1611 crcOrig = XXH64_digest(&xxhState);
1612 cSize = outBuff.pos;
1613 DISPLAYLEVEL(5, "Frame completed : %u bytes compressed into %u bytes \n",
1614 (U32)totalTestSize, (U32)cSize);
1617 /* multi - fragments decompression test */
1618 assert(totalTestSize < dstBufferSize);
1619 memset(dstBuffer, 170, totalTestSize); /* init dest area */
1620 if (!dictSize /* don't reset if dictionary : could be different */ && (FUZ_rand(&lseed) & 1)) {
1621 CHECK_Z( ZSTD_resetDStream(zd) );
1623 CHECK_Z( ZSTD_initDStream_usingDict(zd, dict, dictSize) );
1625 { size_t decompressionResult = 1;
1626 ZSTD_inBuffer inBuff = { cBuffer, cSize, 0 };
1627 ZSTD_outBuffer outBuff= { dstBuffer, dstBufferSize, 0 };
1628 for (totalGenSize = 0 ; decompressionResult ; ) {
1629 size_t const readCSrcSize = FUZ_randomLength(&lseed, maxSampleLog);
1630 size_t const randomDstSize = FUZ_randomLength(&lseed, maxSampleLog);
1631 size_t const dstBuffSize = MIN(dstBufferSize - totalGenSize, randomDstSize);
1632 inBuff.size = inBuff.pos + readCSrcSize;
1633 outBuff.size = outBuff.pos + dstBuffSize;
1634 DISPLAYLEVEL(6, "ZSTD_decompressStream input %u bytes into outBuff %u bytes \n",
1635 (U32)readCSrcSize, (U32)dstBuffSize);
1636 decompressionResult = ZSTD_decompressStream(zd, &outBuff, &inBuff);
1637 if (ZSTD_isError(decompressionResult)) {
1638 DISPLAY("ZSTD_decompressStream error : %s \n", ZSTD_getErrorName(decompressionResult));
1639 findDiff(copyBuffer, dstBuffer, totalTestSize);
1641 CHECK (ZSTD_isError(decompressionResult), "decompression error : %s", ZSTD_getErrorName(decompressionResult));
1642 DISPLAYLEVEL(6, "total ingested (inBuff.pos) = %u and produced (outBuff.pos) = %u \n",
1643 (U32)inBuff.pos, (U32)outBuff.pos);
1645 CHECK (outBuff.pos != totalTestSize, "decompressed data : wrong size (%u != %u)", (U32)outBuff.pos, (U32)totalTestSize);
1646 CHECK (inBuff.pos != cSize, "compressed data should be fully read (%u != %u)", (U32)inBuff.pos, (U32)cSize);
1647 { U64 const crcDest = XXH64(dstBuffer, totalTestSize, 0);
1648 if (crcDest!=crcOrig) findDiff(copyBuffer, dstBuffer, totalTestSize);
1649 CHECK (crcDest!=crcOrig, "decompressed data corrupted");
1652 /*===== noisy/erroneous src decompression test =====*/
1654 /* add some noise */
1655 { U32 const nbNoiseChunks = (FUZ_rand(&lseed) & 7) + 2;
1656 U32 nn; for (nn=0; nn<nbNoiseChunks; nn++) {
1657 size_t const randomNoiseSize = FUZ_randomLength(&lseed, maxSampleLog);
1658 size_t const noiseSize = MIN((cSize/3) , randomNoiseSize);
1659 size_t const noiseStart = FUZ_rand(&lseed) % (srcBufferSize - noiseSize);
1660 size_t const cStart = FUZ_rand(&lseed) % (cSize - noiseSize);
1661 memcpy(cBuffer+cStart, srcBuffer+noiseStart, noiseSize);
1664 /* try decompression on noisy data */
1665 CHECK_Z( ZSTD_initDStream(zd_noise) ); /* note : no dictionary */
1666 { ZSTD_inBuffer inBuff = { cBuffer, cSize, 0 };
1667 ZSTD_outBuffer outBuff= { dstBuffer, dstBufferSize, 0 };
1668 while (outBuff.pos < dstBufferSize) {
1669 size_t const randomCSrcSize = FUZ_randomLength(&lseed, maxSampleLog);
1670 size_t const randomDstSize = FUZ_randomLength(&lseed, maxSampleLog);
1671 size_t const adjustedDstSize = MIN(dstBufferSize - outBuff.pos, randomDstSize);
1672 size_t const adjustedCSrcSize = MIN(cSize - inBuff.pos, randomCSrcSize);
1673 outBuff.size = outBuff.pos + adjustedDstSize;
1674 inBuff.size = inBuff.pos + adjustedCSrcSize;
1675 { size_t const decompressError = ZSTD_decompressStream(zd, &outBuff, &inBuff);
1676 if (ZSTD_isError(decompressError)) break; /* error correctly detected */
1677 /* No forward progress possible */
1678 if (outBuff.pos < outBuff.size && inBuff.pos == cSize) break;
1680 DISPLAY("\r%u fuzzer tests completed \n", testNb);
1683 ZSTDMT_freeCCtx(zc);
1684 ZSTD_freeDStream(zd);
1685 ZSTD_freeDStream(zd_noise);
1686 free(cNoiseBuffer[0]);
1687 free(cNoiseBuffer[1]);
1688 free(cNoiseBuffer[2]);
1689 free(cNoiseBuffer[3]);
1690 free(cNoiseBuffer[4]);
1701 /** If useOpaqueAPI, sets param in cctxParams.
1702 * Otherwise, sets the param in zc. */
1703 static size_t setCCtxParameter(ZSTD_CCtx* zc, ZSTD_CCtx_params* cctxParams,
1704 ZSTD_cParameter param, unsigned value,
1708 return ZSTD_CCtxParam_setParameter(cctxParams, param, value);
1710 return ZSTD_CCtx_setParameter(zc, param, value);
1714 /* Tests for ZSTD_compress_generic() API */
1715 static int fuzzerTests_newAPI(U32 seed, U32 nbTests, unsigned startTest,
1716 double compressibility, int bigTests)
1718 U32 const maxSrcLog = bigTests ? 24 : 22;
1719 static const U32 maxSampleLog = 19;
1720 size_t const srcBufferSize = (size_t)1<<maxSrcLog;
1721 BYTE* cNoiseBuffer[5];
1722 size_t const copyBufferSize= srcBufferSize + (1<<maxSampleLog);
1723 BYTE* const copyBuffer = (BYTE*)malloc (copyBufferSize);
1724 size_t const cBufferSize = ZSTD_compressBound(srcBufferSize);
1725 BYTE* const cBuffer = (BYTE*)malloc (cBufferSize);
1726 size_t const dstBufferSize = srcBufferSize;
1727 BYTE* const dstBuffer = (BYTE*)malloc (dstBufferSize);
1730 U32 coreSeed = seed;
1731 ZSTD_CCtx* zc = ZSTD_createCCtx(); /* will be reset sometimes */
1732 ZSTD_DStream* zd = ZSTD_createDStream(); /* will be reset sometimes */
1733 ZSTD_DStream* const zd_noise = ZSTD_createDStream();
1734 UTIL_time_t const startClock = UTIL_getTime();
1735 const BYTE* dict = NULL; /* can keep same dict on 2 consecutive tests */
1736 size_t dictSize = 0;
1738 U32 windowLogMalus = 0; /* can survive between 2 loops */
1739 U32 const cLevelMax = bigTests ? (U32)ZSTD_maxCLevel()-1 : g_cLevelMax_smallTests;
1740 U32 const nbThreadsMax = bigTests ? 4 : 2;
1741 ZSTD_CCtx_params* cctxParams = ZSTD_createCCtxParams();
1744 cNoiseBuffer[0] = (BYTE*)malloc (srcBufferSize);
1745 cNoiseBuffer[1] = (BYTE*)malloc (srcBufferSize);
1746 cNoiseBuffer[2] = (BYTE*)malloc (srcBufferSize);
1747 cNoiseBuffer[3] = (BYTE*)malloc (srcBufferSize);
1748 cNoiseBuffer[4] = (BYTE*)malloc (srcBufferSize);
1749 CHECK (!cNoiseBuffer[0] || !cNoiseBuffer[1] || !cNoiseBuffer[2] || !cNoiseBuffer[3] || !cNoiseBuffer[4] ||
1750 !copyBuffer || !dstBuffer || !cBuffer || !zc || !zd || !zd_noise ,
1751 "Not enough memory, fuzzer tests cancelled");
1753 /* Create initial samples */
1754 RDG_genBuffer(cNoiseBuffer[0], srcBufferSize, 0.00, 0., coreSeed); /* pure noise */
1755 RDG_genBuffer(cNoiseBuffer[1], srcBufferSize, 0.05, 0., coreSeed); /* barely compressible */
1756 RDG_genBuffer(cNoiseBuffer[2], srcBufferSize, compressibility, 0., coreSeed);
1757 RDG_genBuffer(cNoiseBuffer[3], srcBufferSize, 0.95, 0., coreSeed); /* highly compressible */
1758 RDG_genBuffer(cNoiseBuffer[4], srcBufferSize, 1.00, 0., coreSeed); /* sparse content */
1759 memset(copyBuffer, 0x65, copyBufferSize); /* make copyBuffer considered initialized */
1760 CHECK_Z( ZSTD_initDStream_usingDict(zd, NULL, 0) ); /* ensure at least one init */
1762 /* catch up testNb */
1763 for (testNb=1; testNb < startTest; testNb++)
1764 FUZ_rand(&coreSeed);
1767 for ( ; (testNb <= nbTests) || (UTIL_clockSpanMicro(startClock) < g_clockTime) ; testNb++ ) {
1770 const BYTE* srcBuffer;
1771 size_t totalTestSize, totalGenSize, cSize;
1772 XXH64_state_t xxhState;
1774 U32 resetAllowed = 1;
1776 ZSTD_parameters savedParams;
1779 if (nbTests >= testNb) { DISPLAYUPDATE(2, "\r%6u/%6u ", testNb, nbTests); }
1780 else { DISPLAYUPDATE(2, "\r%6u ", testNb); }
1781 FUZ_rand(&coreSeed);
1782 lseed = coreSeed ^ prime32;
1783 DISPLAYLEVEL(5, " *** Test %u *** \n", testNb);
1784 opaqueAPI = FUZ_rand(&lseed) & 1;
1786 /* states full reset (deliberately not synchronized) */
1787 /* some issues can only happen when reusing states */
1788 if ((FUZ_rand(&lseed) & 0xFF) == 131) {
1789 DISPLAYLEVEL(5, "Creating new context \n");
1791 zc = ZSTD_createCCtx();
1792 CHECK(zc == NULL, "ZSTD_createCCtx allocation error");
1795 if ((FUZ_rand(&lseed) & 0xFF) == 132) {
1796 ZSTD_freeDStream(zd);
1797 zd = ZSTD_createDStream();
1798 CHECK(zd == NULL, "ZSTD_createDStream allocation error");
1799 ZSTD_initDStream_usingDict(zd, NULL, 0); /* ensure at least one init */
1802 /* srcBuffer selection [0-4] */
1803 { U32 buffNb = FUZ_rand(&lseed) & 0x7F;
1804 if (buffNb & 7) buffNb=2; /* most common : compressible (P) */
1808 const U32 tnb[2] = { 1, 3 }; /* barely/highly compressible */
1809 buffNb = tnb[buffNb >> 3];
1811 const U32 tnb[2] = { 0, 4 }; /* not compressible / sparse */
1812 buffNb = tnb[buffNb >> 3];
1814 srcBuffer = cNoiseBuffer[buffNb];
1817 /* compression init */
1818 CHECK_Z( ZSTD_CCtx_loadDictionary(zc, NULL, 0) ); /* cancel previous dict /*/
1819 if ((FUZ_rand(&lseed)&1) /* at beginning, to keep same nb of rand */
1820 && oldTestLog /* at least one test happened */
1822 /* just set a compression level */
1823 maxTestSize = FUZ_randomLength(&lseed, oldTestLog+2);
1824 if (maxTestSize >= srcBufferSize) maxTestSize = srcBufferSize-1;
1825 { int const compressionLevel = (FUZ_rand(&lseed) % 5) + 1;
1826 DISPLAYLEVEL(5, "t%u : compression level : %i \n", testNb, compressionLevel);
1827 CHECK_Z (setCCtxParameter(zc, cctxParams, ZSTD_p_compressionLevel, compressionLevel, opaqueAPI) );
1830 U32 const testLog = FUZ_rand(&lseed) % maxSrcLog;
1831 U32 const dictLog = FUZ_rand(&lseed) % maxSrcLog;
1832 U32 const cLevelCandidate = (FUZ_rand(&lseed) %
1834 (MAX(testLog, dictLog) / 2))) +
1836 U32 const cLevel = MIN(cLevelCandidate, cLevelMax);
1837 DISPLAYLEVEL(5, "t%u: base cLevel : %u \n", testNb, cLevel);
1838 maxTestSize = FUZ_rLogLength(&lseed, testLog);
1839 DISPLAYLEVEL(5, "t%u: maxTestSize : %u \n", testNb, (U32)maxTestSize);
1840 oldTestLog = testLog;
1841 /* random dictionary selection */
1842 dictSize = ((FUZ_rand(&lseed)&63)==1) ? FUZ_rLogLength(&lseed, dictLog) : 0;
1843 { size_t const dictStart = FUZ_rand(&lseed) % (srcBufferSize - dictSize);
1844 dict = srcBuffer + dictStart;
1845 if (!dictSize) dict=NULL;
1847 { U64 const pledgedSrcSize = (FUZ_rand(&lseed) & 3) ? ZSTD_CONTENTSIZE_UNKNOWN : maxTestSize;
1848 ZSTD_compressionParameters cParams = ZSTD_getCParams(cLevel, pledgedSrcSize, dictSize);
1849 const U32 windowLogMax = bigTests ? 24 : 20;
1850 const U32 searchLogMax = bigTests ? 15 : 13;
1852 DISPLAYLEVEL(5, "t%u: with dictionary of size : %zu \n", testNb, dictSize);
1854 /* mess with compression parameters */
1855 cParams.windowLog += (FUZ_rand(&lseed) & 3) - 1;
1856 cParams.windowLog = MIN(windowLogMax, cParams.windowLog);
1857 cParams.hashLog += (FUZ_rand(&lseed) & 3) - 1;
1858 cParams.chainLog += (FUZ_rand(&lseed) & 3) - 1;
1859 cParams.searchLog += (FUZ_rand(&lseed) & 3) - 1;
1860 cParams.searchLog = MIN(searchLogMax, cParams.searchLog);
1861 cParams.searchLength += (FUZ_rand(&lseed) & 3) - 1;
1862 cParams.targetLength = (U32)((cParams.targetLength + 1 ) * (0.5 + ((double)(FUZ_rand(&lseed) & 127) / 128)));
1863 cParams = ZSTD_adjustCParams(cParams, pledgedSrcSize, dictSize);
1865 if (FUZ_rand(&lseed) & 1) {
1866 DISPLAYLEVEL(5, "t%u: windowLog : %u \n", testNb, cParams.windowLog);
1867 CHECK_Z( setCCtxParameter(zc, cctxParams, ZSTD_p_windowLog, cParams.windowLog, opaqueAPI) );
1868 assert(cParams.windowLog >= ZSTD_WINDOWLOG_MIN); /* guaranteed by ZSTD_adjustCParams() */
1869 windowLogMalus = (cParams.windowLog - ZSTD_WINDOWLOG_MIN) / 5;
1871 if (FUZ_rand(&lseed) & 1) {
1872 DISPLAYLEVEL(5, "t%u: hashLog : %u \n", testNb, cParams.hashLog);
1873 CHECK_Z( setCCtxParameter(zc, cctxParams, ZSTD_p_hashLog, cParams.hashLog, opaqueAPI) );
1875 if (FUZ_rand(&lseed) & 1) {
1876 DISPLAYLEVEL(5, "t%u: chainLog : %u \n", testNb, cParams.chainLog);
1877 CHECK_Z( setCCtxParameter(zc, cctxParams, ZSTD_p_chainLog, cParams.chainLog, opaqueAPI) );
1879 if (FUZ_rand(&lseed) & 1) CHECK_Z( setCCtxParameter(zc, cctxParams, ZSTD_p_searchLog, cParams.searchLog, opaqueAPI) );
1880 if (FUZ_rand(&lseed) & 1) CHECK_Z( setCCtxParameter(zc, cctxParams, ZSTD_p_minMatch, cParams.searchLength, opaqueAPI) );
1881 if (FUZ_rand(&lseed) & 1) CHECK_Z( setCCtxParameter(zc, cctxParams, ZSTD_p_targetLength, cParams.targetLength, opaqueAPI) );
1883 /* mess with long distance matching parameters */
1885 if (FUZ_rand(&lseed) & 1) CHECK_Z( setCCtxParameter(zc, cctxParams, ZSTD_p_enableLongDistanceMatching, FUZ_rand(&lseed) & 63, opaqueAPI) );
1886 if (FUZ_rand(&lseed) & 3) CHECK_Z( setCCtxParameter(zc, cctxParams, ZSTD_p_ldmHashLog, FUZ_randomClampedLength(&lseed, ZSTD_HASHLOG_MIN, 23), opaqueAPI) );
1887 if (FUZ_rand(&lseed) & 3) CHECK_Z( setCCtxParameter(zc, cctxParams, ZSTD_p_ldmMinMatch, FUZ_randomClampedLength(&lseed, ZSTD_LDM_MINMATCH_MIN, ZSTD_LDM_MINMATCH_MAX), opaqueAPI) );
1888 if (FUZ_rand(&lseed) & 3) CHECK_Z( setCCtxParameter(zc, cctxParams, ZSTD_p_ldmBucketSizeLog, FUZ_randomClampedLength(&lseed, 0, ZSTD_LDM_BUCKETSIZELOG_MAX), opaqueAPI) );
1889 if (FUZ_rand(&lseed) & 3) CHECK_Z( setCCtxParameter(zc, cctxParams, ZSTD_p_ldmHashEveryLog, FUZ_randomClampedLength(&lseed, 0, ZSTD_WINDOWLOG_MAX - ZSTD_HASHLOG_MIN), opaqueAPI) );
1892 /* mess with frame parameters */
1893 if (FUZ_rand(&lseed) & 1) {
1894 U32 const checksumFlag = FUZ_rand(&lseed) & 1;
1895 DISPLAYLEVEL(5, "t%u: frame checksum : %u \n", testNb, checksumFlag);
1896 CHECK_Z( setCCtxParameter(zc, cctxParams, ZSTD_p_checksumFlag, checksumFlag, opaqueAPI) );
1898 if (FUZ_rand(&lseed) & 1) CHECK_Z( setCCtxParameter(zc, cctxParams, ZSTD_p_dictIDFlag, FUZ_rand(&lseed) & 1, opaqueAPI) );
1899 if (FUZ_rand(&lseed) & 1) CHECK_Z( setCCtxParameter(zc, cctxParams, ZSTD_p_contentSizeFlag, FUZ_rand(&lseed) & 1, opaqueAPI) );
1900 if (FUZ_rand(&lseed) & 1) {
1901 DISPLAYLEVEL(5, "t%u: pledgedSrcSize : %u \n", testNb, (U32)pledgedSrcSize);
1902 CHECK_Z( ZSTD_CCtx_setPledgedSrcSize(zc, pledgedSrcSize) );
1905 /* multi-threading parameters. Only adjust ocassionally for small tests. */
1906 if (bigTests || (FUZ_rand(&lseed) & 0xF) == 0xF) {
1907 U32 const nbThreadsCandidate = (FUZ_rand(&lseed) & 4) + 1;
1908 U32 const nbThreadsAdjusted = (windowLogMalus < nbThreadsCandidate) ? nbThreadsCandidate - windowLogMalus : 1;
1909 U32 const nbThreads = MIN(nbThreadsAdjusted, nbThreadsMax);
1910 DISPLAYLEVEL(5, "t%u: nbThreads : %u \n", testNb, nbThreads);
1911 CHECK_Z( setCCtxParameter(zc, cctxParams, ZSTD_p_nbWorkers, nbThreads, opaqueAPI) );
1912 if (nbThreads > 1) {
1913 U32 const jobLog = FUZ_rand(&lseed) % (testLog+1);
1914 CHECK_Z( setCCtxParameter(zc, cctxParams, ZSTD_p_overlapSizeLog, FUZ_rand(&lseed) % 10, opaqueAPI) );
1915 CHECK_Z( setCCtxParameter(zc, cctxParams, ZSTD_p_jobSize, (U32)FUZ_rLogLength(&lseed, jobLog), opaqueAPI) );
1919 if (FUZ_rand(&lseed) & 1) CHECK_Z( setCCtxParameter(zc, cctxParams, ZSTD_p_forceMaxWindow, FUZ_rand(&lseed) & 1, opaqueAPI) );
1921 /* Apply parameters */
1923 DISPLAYLEVEL(5, "t%u: applying CCtxParams \n", testNb);
1924 CHECK_Z (ZSTD_CCtx_setParametersUsingCCtxParams(zc, cctxParams) );
1927 if (FUZ_rand(&lseed) & 1) {
1928 if (FUZ_rand(&lseed) & 1) {
1929 CHECK_Z( ZSTD_CCtx_loadDictionary(zc, dict, dictSize) );
1931 CHECK_Z( ZSTD_CCtx_loadDictionary_byReference(zc, dict, dictSize) );
1933 if (dict && dictSize) {
1934 /* test that compression parameters are rejected (correctly) after loading a non-NULL dictionary */
1936 size_t const setError = ZSTD_CCtx_setParametersUsingCCtxParams(zc, cctxParams);
1937 CHECK(!ZSTD_isError(setError), "ZSTD_CCtx_setParametersUsingCCtxParams should have failed");
1939 size_t const setError = ZSTD_CCtx_setParameter(zc, ZSTD_p_windowLog, cParams.windowLog-1);
1940 CHECK(!ZSTD_isError(setError), "ZSTD_CCtx_setParameter should have failed");
1944 CHECK_Z( ZSTD_CCtx_refPrefix(zc, dict, dictSize) );
1948 CHECK_Z(getCCtxParams(zc, &savedParams));
1950 /* multi-segments compression test */
1951 XXH64_reset(&xxhState, 0);
1952 { ZSTD_outBuffer outBuff = { cBuffer, cBufferSize, 0 } ;
1953 for (cSize=0, totalTestSize=0 ; (totalTestSize < maxTestSize) ; ) {
1954 /* compress random chunks into randomly sized dst buffers */
1955 size_t const randomSrcSize = FUZ_randomLength(&lseed, maxSampleLog);
1956 size_t const srcSize = MIN(maxTestSize-totalTestSize, randomSrcSize);
1957 size_t const srcStart = FUZ_rand(&lseed) % (srcBufferSize - srcSize);
1958 size_t const randomDstSize = FUZ_randomLength(&lseed, maxSampleLog+1);
1959 size_t const dstBuffSize = MIN(cBufferSize - cSize, randomDstSize);
1960 ZSTD_EndDirective const flush = (FUZ_rand(&lseed) & 15) ? ZSTD_e_continue : ZSTD_e_flush;
1961 ZSTD_inBuffer inBuff = { srcBuffer+srcStart, srcSize, 0 };
1962 outBuff.size = outBuff.pos + dstBuffSize;
1964 CHECK_Z( ZSTD_compress_generic(zc, &outBuff, &inBuff, flush) );
1965 DISPLAYLEVEL(6, "t%u: compress consumed %u bytes (total : %u) ; flush: %u (total : %u) \n",
1966 testNb, (U32)inBuff.pos, (U32)(totalTestSize + inBuff.pos), (U32)flush, (U32)outBuff.pos);
1968 XXH64_update(&xxhState, srcBuffer+srcStart, inBuff.pos);
1969 memcpy(copyBuffer+totalTestSize, srcBuffer+srcStart, inBuff.pos);
1970 totalTestSize += inBuff.pos;
1973 /* final frame epilogue */
1974 { size_t remainingToFlush = 1;
1975 while (remainingToFlush) {
1976 ZSTD_inBuffer inBuff = { NULL, 0, 0 };
1977 size_t const randomDstSize = FUZ_randomLength(&lseed, maxSampleLog+1);
1978 size_t const adjustedDstSize = MIN(cBufferSize - cSize, randomDstSize);
1979 outBuff.size = outBuff.pos + adjustedDstSize;
1980 DISPLAYLEVEL(6, "t%u: End-flush into dst buffer of size %u \n", testNb, (U32)adjustedDstSize);
1981 remainingToFlush = ZSTD_compress_generic(zc, &outBuff, &inBuff, ZSTD_e_end);
1982 DISPLAYLEVEL(6, "t%u: Total flushed so far : %u bytes \n", testNb, (U32)outBuff.pos);
1983 CHECK( ZSTD_isError(remainingToFlush),
1984 "ZSTD_compress_generic w/ ZSTD_e_end error : %s",
1985 ZSTD_getErrorName(remainingToFlush) );
1987 crcOrig = XXH64_digest(&xxhState);
1988 cSize = outBuff.pos;
1989 DISPLAYLEVEL(5, "Frame completed : %zu bytes \n", cSize);
1992 CHECK(badParameters(zc, savedParams), "CCtx params are wrong");
1994 /* multi - fragments decompression test */
1995 if (!dictSize /* don't reset if dictionary : could be different */ && (FUZ_rand(&lseed) & 1)) {
1996 DISPLAYLEVEL(5, "resetting DCtx (dict:%08X) \n", (U32)(size_t)dict);
1997 CHECK_Z( ZSTD_resetDStream(zd) );
2000 DISPLAYLEVEL(5, "using dictionary of size %zu \n", dictSize);
2001 CHECK_Z( ZSTD_initDStream_usingDict(zd, dict, dictSize) );
2003 { size_t decompressionResult = 1;
2004 ZSTD_inBuffer inBuff = { cBuffer, cSize, 0 };
2005 ZSTD_outBuffer outBuff= { dstBuffer, dstBufferSize, 0 };
2006 for (totalGenSize = 0 ; decompressionResult ; ) {
2007 size_t const readCSrcSize = FUZ_randomLength(&lseed, maxSampleLog);
2008 size_t const randomDstSize = FUZ_randomLength(&lseed, maxSampleLog);
2009 size_t const dstBuffSize = MIN(dstBufferSize - totalGenSize, randomDstSize);
2010 inBuff.size = inBuff.pos + readCSrcSize;
2011 outBuff.size = outBuff.pos + dstBuffSize;
2012 DISPLAYLEVEL(6, "decompression presented %u new bytes (pos:%u/%u)\n",
2013 (U32)readCSrcSize, (U32)inBuff.pos, (U32)cSize);
2014 decompressionResult = ZSTD_decompressStream(zd, &outBuff, &inBuff);
2015 DISPLAYLEVEL(6, "so far: consumed = %u, produced = %u \n",
2016 (U32)inBuff.pos, (U32)outBuff.pos);
2017 if (ZSTD_isError(decompressionResult)) {
2018 DISPLAY("ZSTD_decompressStream error : %s \n", ZSTD_getErrorName(decompressionResult));
2019 findDiff(copyBuffer, dstBuffer, totalTestSize);
2021 CHECK (ZSTD_isError(decompressionResult), "decompression error : %s", ZSTD_getErrorName(decompressionResult));
2022 CHECK (inBuff.pos > cSize, "ZSTD_decompressStream consumes too much input : %u > %u ", (U32)inBuff.pos, (U32)cSize);
2024 CHECK (inBuff.pos != cSize, "compressed data should be fully read (%u != %u)", (U32)inBuff.pos, (U32)cSize);
2025 CHECK (outBuff.pos != totalTestSize, "decompressed data : wrong size (%u != %u)", (U32)outBuff.pos, (U32)totalTestSize);
2026 { U64 const crcDest = XXH64(dstBuffer, totalTestSize, 0);
2027 if (crcDest!=crcOrig) findDiff(copyBuffer, dstBuffer, totalTestSize);
2028 CHECK (crcDest!=crcOrig, "decompressed data corrupted");
2031 /*===== noisy/erroneous src decompression test =====*/
2033 /* add some noise */
2034 { U32 const nbNoiseChunks = (FUZ_rand(&lseed) & 7) + 2;
2035 U32 nn; for (nn=0; nn<nbNoiseChunks; nn++) {
2036 size_t const randomNoiseSize = FUZ_randomLength(&lseed, maxSampleLog);
2037 size_t const noiseSize = MIN((cSize/3) , randomNoiseSize);
2038 size_t const noiseStart = FUZ_rand(&lseed) % (srcBufferSize - noiseSize);
2039 size_t const cStart = FUZ_rand(&lseed) % (cSize - noiseSize);
2040 memcpy(cBuffer+cStart, srcBuffer+noiseStart, noiseSize);
2043 /* try decompression on noisy data */
2044 CHECK_Z( ZSTD_initDStream(zd_noise) ); /* note : no dictionary */
2045 { ZSTD_inBuffer inBuff = { cBuffer, cSize, 0 };
2046 ZSTD_outBuffer outBuff= { dstBuffer, dstBufferSize, 0 };
2047 while (outBuff.pos < dstBufferSize) {
2048 size_t const randomCSrcSize = FUZ_randomLength(&lseed, maxSampleLog);
2049 size_t const randomDstSize = FUZ_randomLength(&lseed, maxSampleLog);
2050 size_t const adjustedDstSize = MIN(dstBufferSize - outBuff.pos, randomDstSize);
2051 size_t const adjustedCSrcSize = MIN(cSize - inBuff.pos, randomCSrcSize);
2052 outBuff.size = outBuff.pos + adjustedDstSize;
2053 inBuff.size = inBuff.pos + adjustedCSrcSize;
2054 { size_t const decompressError = ZSTD_decompressStream(zd, &outBuff, &inBuff);
2055 if (ZSTD_isError(decompressError)) break; /* error correctly detected */
2056 /* Good so far, but no more progress possible */
2057 if (outBuff.pos < outBuff.size && inBuff.pos == cSize) break;
2059 DISPLAY("\r%u fuzzer tests completed \n", testNb-1);
2063 ZSTD_freeDStream(zd);
2064 ZSTD_freeDStream(zd_noise);
2065 ZSTD_freeCCtxParams(cctxParams);
2066 free(cNoiseBuffer[0]);
2067 free(cNoiseBuffer[1]);
2068 free(cNoiseBuffer[2]);
2069 free(cNoiseBuffer[3]);
2070 free(cNoiseBuffer[4]);
2081 /*-*******************************************************
2083 *********************************************************/
2084 static int FUZ_usage(const char* programName)
2086 DISPLAY( "Usage :\n");
2087 DISPLAY( " %s [args]\n", programName);
2089 DISPLAY( "Arguments :\n");
2090 DISPLAY( " -i# : Nb of tests (default:%u) \n", nbTestsDefault);
2091 DISPLAY( " -s# : Select seed (default:prompt user)\n");
2092 DISPLAY( " -t# : Select starting test number (default:0)\n");
2093 DISPLAY( " -P# : Select compressibility in %% (default:%i%%)\n", FUZ_COMPRESSIBILITY_DEFAULT);
2094 DISPLAY( " -v : verbose\n");
2095 DISPLAY( " -p : pause at the end\n");
2096 DISPLAY( " -h : display help and exit\n");
2100 typedef enum { simple_api, mt_api, advanced_api } e_api;
2102 int main(int argc, const char** argv)
2106 int nbTests = nbTestsDefault;
2108 int proba = FUZ_COMPRESSIBILITY_DEFAULT;
2111 int bigTests = (sizeof(size_t) == 8);
2112 e_api selected_api = simple_api;
2113 const char* const programName = argv[0];
2116 /* Check command line */
2117 for(argNb=1; argNb<argc; argNb++) {
2118 const char* argument = argv[argNb];
2119 assert(argument != NULL);
2121 /* Parsing commands. Aggregated commands are allowed */
2122 if (argument[0]=='-') {
2124 if (!strcmp(argument, "--mt")) { selected_api=mt_api; testNb += !testNb; continue; }
2125 if (!strcmp(argument, "--newapi")) { selected_api=advanced_api; testNb += !testNb; continue; }
2126 if (!strcmp(argument, "--no-big-tests")) { bigTests=0; continue; }
2129 while (*argument!=0) {
2133 return FUZ_usage(programName);
2145 case 'p': /* pause at the end */
2150 case 'i': /* limit tests by nb of iterations (default) */
2152 nbTests=0; g_clockTime=0;
2153 while ((*argument>='0') && (*argument<='9')) {
2155 nbTests += *argument - '0';
2160 case 'T': /* limit tests by time */
2162 nbTests=0; g_clockTime=0;
2163 while ((*argument>='0') && (*argument<='9')) {
2165 g_clockTime += *argument - '0';
2168 if (*argument=='m') { /* -T1m == -T60 */
2169 g_clockTime *=60, argument++;
2170 if (*argument=='n') argument++; /* -T1mn == -T60 */
2171 } else if (*argument=='s') argument++; /* -T10s == -T10 */
2172 g_clockTime *= SEC_TO_MICRO;
2175 case 's': /* manually select seed */
2179 while ((*argument>='0') && (*argument<='9')) {
2181 seed += *argument - '0';
2186 case 't': /* select starting test number */
2189 while ((*argument>='0') && (*argument<='9')) {
2191 testNb += *argument - '0';
2196 case 'P': /* compressibility % */
2199 while ((*argument>='0') && (*argument<='9')) {
2201 proba += *argument - '0';
2204 if (proba<0) proba=0;
2205 if (proba>100) proba=100;
2209 return FUZ_usage(programName);
2211 } } } /* for(argNb=1; argNb<argc; argNb++) */
2214 DISPLAY("Starting zstream tester (%i-bits, %s)\n", (int)(sizeof(size_t)*8), ZSTD_VERSION_STRING);
2217 time_t const t = time(NULL);
2218 U32 const h = XXH32(&t, sizeof(t), 1);
2222 DISPLAY("Seed = %u\n", seed);
2223 if (proba!=FUZ_COMPRESSIBILITY_DEFAULT) DISPLAY("Compressibility : %i%%\n", proba);
2225 if (nbTests<=0) nbTests=1;
2228 result = basicUnitTests(0, ((double)proba) / 100); /* constant seed for predictability */
2232 switch(selected_api)
2235 result = fuzzerTests(seed, nbTests, testNb, ((double)proba) / 100, bigTests);
2238 result = fuzzerTests_MT(seed, nbTests, testNb, ((double)proba) / 100, bigTests);
2241 result = fuzzerTests_newAPI(seed, nbTests, testNb, ((double)proba) / 100, bigTests);
2244 assert(0); /* impossible */
2250 DISPLAY("Press Enter \n");