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 int 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 U32 FUZ_rand(U32* 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 (unsigned)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_compressStream2(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_c_windowLog, (int*)&savedParams->cParams.windowLog));
228 CHECK_RET_Z(ZSTD_CCtx_getParameter(zc, ZSTD_c_hashLog, (int*)&savedParams->cParams.hashLog));
229 CHECK_RET_Z(ZSTD_CCtx_getParameter(zc, ZSTD_c_chainLog, (int*)&savedParams->cParams.chainLog));
230 CHECK_RET_Z(ZSTD_CCtx_getParameter(zc, ZSTD_c_searchLog, (int*)&savedParams->cParams.searchLog));
231 CHECK_RET_Z(ZSTD_CCtx_getParameter(zc, ZSTD_c_minMatch, (int*)&savedParams->cParams.minMatch));
232 CHECK_RET_Z(ZSTD_CCtx_getParameter(zc, ZSTD_c_targetLength, (int*)&savedParams->cParams.targetLength));
233 CHECK_RET_Z(ZSTD_CCtx_getParameter(zc, ZSTD_c_strategy, &value));
234 savedParams->cParams.strategy = value;
236 CHECK_RET_Z(ZSTD_CCtx_getParameter(zc, ZSTD_c_checksumFlag, &savedParams->fParams.checksumFlag));
237 CHECK_RET_Z(ZSTD_CCtx_getParameter(zc, ZSTD_c_contentSizeFlag, &savedParams->fParams.contentSizeFlag));
238 CHECK_RET_Z(ZSTD_CCtx_getParameter(zc, ZSTD_c_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.minMatch != savedParams.cParams.minMatch, "minMatch");
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", (unsigned)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",
335 (unsigned)cSize, (double)cSize/COMPRESSIBLE_NOISE_LENGTH*100);
337 /* context size functions */
338 DISPLAYLEVEL(3, "test%3i : estimate CStream size : ", testNb++);
339 { ZSTD_compressionParameters const cParams = ZSTD_getCParams(1, CNBufferSize, dictSize);
340 size_t const cstreamSize = ZSTD_estimateCStreamSize_usingCParams(cParams);
341 size_t const cdictSize = ZSTD_estimateCDictSize_advanced(dictSize, cParams, ZSTD_dlm_byCopy); /* uses ZSTD_initCStream_usingDict() */
342 if (ZSTD_isError(cstreamSize)) goto _output_error;
343 if (ZSTD_isError(cdictSize)) goto _output_error;
344 DISPLAYLEVEL(3, "OK (%u bytes) \n", (unsigned)(cstreamSize + cdictSize));
347 DISPLAYLEVEL(3, "test%3i : check actual CStream size : ", testNb++);
348 { size_t const s = ZSTD_sizeof_CStream(zc);
349 if (ZSTD_isError(s)) goto _output_error;
350 DISPLAYLEVEL(3, "OK (%u bytes) \n", (unsigned)s);
353 /* Attempt bad compression parameters */
354 DISPLAYLEVEL(3, "test%3i : use bad compression parameters : ", testNb++);
356 ZSTD_parameters params = ZSTD_getParams(1, 0, 0);
357 params.cParams.minMatch = 2;
358 r = ZSTD_initCStream_advanced(zc, NULL, 0, params, 0);
359 if (!ZSTD_isError(r)) goto _output_error;
360 DISPLAYLEVEL(3, "init error : %s \n", ZSTD_getErrorName(r));
363 /* skippable frame test */
364 DISPLAYLEVEL(3, "test%3i : decompress skippable frame : ", testNb++);
365 CHECK_Z( ZSTD_initDStream_usingDict(zd, CNBuffer, dictSize) );
366 inBuff.src = compressedBuffer;
369 outBuff.dst = decodedBuffer;
370 outBuff.size = CNBufferSize;
372 { size_t const r = ZSTD_decompressStream(zd, &outBuff, &inBuff);
373 DISPLAYLEVEL(5, " ( ZSTD_decompressStream => %u ) ", (unsigned)r);
374 if (r != 0) goto _output_error;
376 if (outBuff.pos != 0) goto _output_error; /* skippable frame output len is 0 */
377 DISPLAYLEVEL(3, "OK \n");
379 /* Basic decompression test */
381 DISPLAYLEVEL(3, "test%3i : decompress %u bytes : ", testNb++, COMPRESSIBLE_NOISE_LENGTH);
382 ZSTD_initDStream_usingDict(zd, CNBuffer, dictSize);
383 CHECK_Z( ZSTD_DCtx_setParameter(zd, ZSTD_d_windowLogMax, ZSTD_WINDOWLOG_LIMIT_DEFAULT+1) ); /* large limit */
384 { size_t const remaining = ZSTD_decompressStream(zd, &outBuff, &inBuff);
385 if (remaining != 0) goto _output_error; } /* should reach end of frame == 0; otherwise, some data left, or an error */
386 if (outBuff.pos != CNBufferSize) goto _output_error; /* should regenerate the same amount */
387 if (inBuff.pos != inBuff.size) goto _output_error; /* should have read the entire frame */
388 DISPLAYLEVEL(3, "OK \n");
390 /* Re-use without init */
391 DISPLAYLEVEL(3, "test%3i : decompress again without init (re-use previous settings): ", testNb++);
393 { size_t const remaining = ZSTD_decompressStream(zd, &outBuff, &inBuff2);
394 if (remaining != 0) goto _output_error; } /* should reach end of frame == 0; otherwise, some data left, or an error */
395 if (outBuff.pos != CNBufferSize) goto _output_error; /* should regenerate the same amount */
396 if (inBuff.pos != inBuff.size) goto _output_error; /* should have read the entire frame */
397 DISPLAYLEVEL(3, "OK \n");
399 /* check regenerated data is byte exact */
400 DISPLAYLEVEL(3, "test%3i : check decompressed result : ", testNb++);
402 for (i=0; i<CNBufferSize; i++) {
403 if (((BYTE*)decodedBuffer)[i] != ((BYTE*)CNBuffer)[i]) goto _output_error;
405 DISPLAYLEVEL(3, "OK \n");
407 /* context size functions */
408 DISPLAYLEVEL(3, "test%3i : estimate DStream size : ", testNb++);
409 { ZSTD_frameHeader fhi;
410 const void* cStart = (char*)compressedBuffer + (skippableFrameSize + 8);
411 size_t const gfhError = ZSTD_getFrameHeader(&fhi, cStart, cSize);
412 if (gfhError!=0) goto _output_error;
413 DISPLAYLEVEL(5, " (windowSize : %u) ", (unsigned)fhi.windowSize);
414 { size_t const s = ZSTD_estimateDStreamSize(fhi.windowSize)
415 /* uses ZSTD_initDStream_usingDict() */
416 + ZSTD_estimateDDictSize(dictSize, ZSTD_dlm_byCopy);
417 if (ZSTD_isError(s)) goto _output_error;
418 DISPLAYLEVEL(3, "OK (%u bytes) \n", (unsigned)s);
421 DISPLAYLEVEL(3, "test%3i : check actual DStream size : ", testNb++);
422 { size_t const s = ZSTD_sizeof_DStream(zd);
423 if (ZSTD_isError(s)) goto _output_error;
424 DISPLAYLEVEL(3, "OK (%u bytes) \n", (unsigned)s);
427 /* Decompression by small increment */
428 DISPLAYLEVEL(3, "test%3i : decompress byte-by-byte : ", testNb++);
429 { /* skippable frame */
431 ZSTD_initDStream_usingDict(zd, CNBuffer, dictSize);
432 inBuff.src = compressedBuffer;
433 outBuff.dst = decodedBuffer;
436 while (r) { /* skippable frame */
437 size_t const inSize = (FUZ_rand(&coreSeed) & 15) + 1;
438 size_t const outSize = (FUZ_rand(&coreSeed) & 15) + 1;
439 inBuff.size = inBuff.pos + inSize;
440 outBuff.size = outBuff.pos + outSize;
441 r = ZSTD_decompressStream(zd, &outBuff, &inBuff);
442 if (ZSTD_isError(r)) DISPLAYLEVEL(4, "ZSTD_decompressStream on skippable frame error : %s \n", ZSTD_getErrorName(r));
443 if (ZSTD_isError(r)) goto _output_error;
446 ZSTD_initDStream_usingDict(zd, CNBuffer, dictSize);
449 size_t const inSize = FUZ_rand(&coreSeed) & 15;
450 size_t const outSize = (FUZ_rand(&coreSeed) & 15) + (!inSize); /* avoid having both sizes at 0 => would trigger a no_forward_progress error */
451 inBuff.size = inBuff.pos + inSize;
452 outBuff.size = outBuff.pos + outSize;
453 r = ZSTD_decompressStream(zd, &outBuff, &inBuff);
454 if (ZSTD_isError(r)) DISPLAYLEVEL(4, "ZSTD_decompressStream error : %s \n", ZSTD_getErrorName(r));
455 if (ZSTD_isError(r)) goto _output_error;
458 if (outBuff.pos != CNBufferSize) DISPLAYLEVEL(4, "outBuff.pos != CNBufferSize : should have regenerated same amount ! \n");
459 if (outBuff.pos != CNBufferSize) goto _output_error; /* should regenerate the same amount */
460 if (inBuff.pos != cSize) DISPLAYLEVEL(4, "inBuff.pos != cSize : should have real all input ! \n");
461 if (inBuff.pos != cSize) goto _output_error; /* should have read the entire frame */
462 DISPLAYLEVEL(3, "OK \n");
464 /* check regenerated data is byte exact */
465 DISPLAYLEVEL(3, "test%3i : check decompressed result : ", testNb++);
467 for (i=0; i<CNBufferSize; i++) {
468 if (((BYTE*)decodedBuffer)[i] != ((BYTE*)CNBuffer)[i]) goto _output_error;;
470 DISPLAYLEVEL(3, "OK \n");
472 /* Decompression forward progress */
473 DISPLAYLEVEL(3, "test%3i : generate error when ZSTD_decompressStream() doesn't progress : ", testNb++);
474 { /* skippable frame */
477 int const maxDec = 100;
478 inBuff.src = compressedBuffer;
482 outBuff.dst = decodedBuffer;
484 outBuff.size = CNBufferSize-1; /* 1 byte missing */
486 for (decNb=0; decNb<maxDec; decNb++) {
487 if (r==0) ZSTD_initDStream_usingDict(zd, CNBuffer, dictSize);
488 r = ZSTD_decompressStream(zd, &outBuff, &inBuff);
489 if (ZSTD_isError(r)) break;
491 if (!ZSTD_isError(r)) DISPLAYLEVEL(4, "ZSTD_decompressStream should have triggered a no_forward_progress error \n");
492 if (!ZSTD_isError(r)) goto _output_error; /* should have triggered no_forward_progress error */
494 DISPLAYLEVEL(3, "OK \n");
496 /* _srcSize compression test */
497 DISPLAYLEVEL(3, "test%3i : compress_srcSize %u bytes : ", testNb++, COMPRESSIBLE_NOISE_LENGTH);
498 ZSTD_initCStream_srcSize(zc, 1, CNBufferSize);
499 outBuff.dst = (char*)(compressedBuffer);
500 outBuff.size = compressedBufferSize;
502 inBuff.src = CNBuffer;
503 inBuff.size = CNBufferSize;
505 CHECK_Z( ZSTD_compressStream(zc, &outBuff, &inBuff) );
506 if (inBuff.pos != inBuff.size) goto _output_error; /* entire input should be consumed */
507 { size_t const r = ZSTD_endStream(zc, &outBuff);
508 if (r != 0) goto _output_error; } /* error, or some data not flushed */
509 { unsigned long long origSize = ZSTD_findDecompressedSize(outBuff.dst, outBuff.pos);
510 if ((size_t)origSize != CNBufferSize) goto _output_error; } /* exact original size must be present */
511 DISPLAYLEVEL(3, "OK (%u bytes : %.2f%%)\n", (unsigned)cSize, (double)cSize/COMPRESSIBLE_NOISE_LENGTH*100);
513 /* wrong _srcSize compression test */
514 DISPLAYLEVEL(3, "test%3i : too large srcSize : %u bytes : ", testNb++, COMPRESSIBLE_NOISE_LENGTH-1);
515 ZSTD_initCStream_srcSize(zc, 1, CNBufferSize+1);
516 outBuff.dst = (char*)(compressedBuffer);
517 outBuff.size = compressedBufferSize;
519 inBuff.src = CNBuffer;
520 inBuff.size = CNBufferSize;
522 CHECK_Z( ZSTD_compressStream(zc, &outBuff, &inBuff) );
523 if (inBuff.pos != inBuff.size) goto _output_error; /* entire input should be consumed */
524 { size_t const r = ZSTD_endStream(zc, &outBuff);
525 if (ZSTD_getErrorCode(r) != ZSTD_error_srcSize_wrong) goto _output_error; /* must fail : wrong srcSize */
526 DISPLAYLEVEL(3, "OK (error detected : %s) \n", ZSTD_getErrorName(r)); }
528 /* wrong _srcSize compression test */
529 DISPLAYLEVEL(3, "test%3i : too small srcSize : %u bytes : ", testNb++, COMPRESSIBLE_NOISE_LENGTH-1);
530 ZSTD_initCStream_srcSize(zc, 1, CNBufferSize-1);
531 outBuff.dst = (char*)(compressedBuffer);
532 outBuff.size = compressedBufferSize;
534 inBuff.src = CNBuffer;
535 inBuff.size = CNBufferSize;
537 { size_t const r = ZSTD_compressStream(zc, &outBuff, &inBuff);
538 if (ZSTD_getErrorCode(r) != ZSTD_error_srcSize_wrong) goto _output_error; /* must fail : wrong srcSize */
539 DISPLAYLEVEL(3, "OK (error detected : %s) \n", ZSTD_getErrorName(r));
542 DISPLAYLEVEL(3, "test%3i : wrong srcSize !contentSizeFlag : %u bytes : ", testNb++, COMPRESSIBLE_NOISE_LENGTH-1);
543 { ZSTD_parameters params = ZSTD_getParams(1, CNBufferSize, 0);
544 params.fParams.contentSizeFlag = 0;
545 CHECK_Z(ZSTD_initCStream_advanced(zc, NULL, 0, params, CNBufferSize - MIN(CNBufferSize, 200 KB)));
546 outBuff.dst = (char*)compressedBuffer;
547 outBuff.size = compressedBufferSize;
549 inBuff.src = CNBuffer;
550 inBuff.size = CNBufferSize;
552 { size_t const r = ZSTD_compressStream(zc, &outBuff, &inBuff);
553 if (ZSTD_getErrorCode(r) != ZSTD_error_srcSize_wrong) goto _output_error; /* must fail : wrong srcSize */
554 DISPLAYLEVEL(3, "OK (error detected : %s) \n", ZSTD_getErrorName(r));
557 /* Complex context re-use scenario */
558 DISPLAYLEVEL(3, "test%3i : context re-use : ", testNb++);
559 ZSTD_freeCStream(zc);
560 zc = ZSTD_createCStream();
561 if (zc==NULL) goto _output_error; /* memory allocation issue */
563 { size_t const inSize = 513;
564 DISPLAYLEVEL(5, "use1 ");
565 ZSTD_initCStream_advanced(zc, NULL, 0, ZSTD_getParams(19, inSize, 0), inSize); /* needs btopt + search3 to trigger hashLog3 */
566 inBuff.src = CNBuffer;
567 inBuff.size = inSize;
569 outBuff.dst = (char*)(compressedBuffer)+cSize;
570 outBuff.size = ZSTD_compressBound(inSize);
572 DISPLAYLEVEL(5, "compress1 ");
573 CHECK_Z( ZSTD_compressStream(zc, &outBuff, &inBuff) );
574 if (inBuff.pos != inBuff.size) goto _output_error; /* entire input should be consumed */
575 DISPLAYLEVEL(5, "end1 ");
576 { size_t const r = ZSTD_endStream(zc, &outBuff);
577 if (r != 0) goto _output_error; } /* error, or some data not flushed */
580 { size_t const inSize = 1025; /* will not continue, because tables auto-adjust and are therefore different size */
581 DISPLAYLEVEL(5, "use2 ");
582 ZSTD_initCStream_advanced(zc, NULL, 0, ZSTD_getParams(19, inSize, 0), inSize); /* needs btopt + search3 to trigger hashLog3 */
583 inBuff.src = CNBuffer;
584 inBuff.size = inSize;
586 outBuff.dst = (char*)(compressedBuffer)+cSize;
587 outBuff.size = ZSTD_compressBound(inSize);
589 DISPLAYLEVEL(5, "compress2 ");
590 CHECK_Z( ZSTD_compressStream(zc, &outBuff, &inBuff) );
591 if (inBuff.pos != inBuff.size) goto _output_error; /* entire input should be consumed */
592 DISPLAYLEVEL(5, "end2 ");
593 { size_t const r = ZSTD_endStream(zc, &outBuff);
594 if (r != 0) goto _output_error; } /* error, or some data not flushed */
596 DISPLAYLEVEL(3, "OK \n");
599 DISPLAYLEVEL(3, "test%3i : digested dictionary : ", testNb++);
600 { ZSTD_CDict* const cdict = ZSTD_createCDict(dictionary.start, dictionary.filled, 1 /*byRef*/ );
601 size_t const initError = ZSTD_initCStream_usingCDict(zc, cdict);
602 DISPLAYLEVEL(5, "ZSTD_initCStream_usingCDict result : %u ", (unsigned)initError);
603 if (ZSTD_isError(initError)) goto _output_error;
604 outBuff.dst = compressedBuffer;
605 outBuff.size = compressedBufferSize;
607 inBuff.src = CNBuffer;
608 inBuff.size = CNBufferSize;
610 DISPLAYLEVEL(5, "- starting ZSTD_compressStream ");
611 CHECK_Z( ZSTD_compressStream(zc, &outBuff, &inBuff) );
612 if (inBuff.pos != inBuff.size) goto _output_error; /* entire input should be consumed */
613 { size_t const r = ZSTD_endStream(zc, &outBuff);
614 DISPLAYLEVEL(5, "- ZSTD_endStream result : %u ", (unsigned)r);
615 if (r != 0) goto _output_error; /* error, or some data not flushed */
618 ZSTD_freeCDict(cdict);
619 DISPLAYLEVEL(3, "OK (%u bytes : %.2f%%)\n", (unsigned)cSize, (double)cSize/CNBufferSize*100);
622 DISPLAYLEVEL(3, "test%3i : check CStream size : ", testNb++);
623 { size_t const s = ZSTD_sizeof_CStream(zc);
624 if (ZSTD_isError(s)) goto _output_error;
625 DISPLAYLEVEL(3, "OK (%u bytes) \n", (unsigned)s);
628 DISPLAYLEVEL(4, "test%3i : check Dictionary ID : ", testNb++);
629 { unsigned const dID = ZSTD_getDictID_fromFrame(compressedBuffer, cSize);
630 if (dID != dictID) goto _output_error;
631 DISPLAYLEVEL(4, "OK (%u) \n", dID);
635 DISPLAYLEVEL(3, "test%3i : decompress %u bytes with digested dictionary : ", testNb++, (unsigned)CNBufferSize);
636 { ZSTD_DDict* const ddict = ZSTD_createDDict(dictionary.start, dictionary.filled);
637 size_t const initError = ZSTD_initDStream_usingDDict(zd, ddict);
638 if (ZSTD_isError(initError)) goto _output_error;
639 outBuff.dst = decodedBuffer;
640 outBuff.size = CNBufferSize;
642 inBuff.src = compressedBuffer;
645 { size_t const r = ZSTD_decompressStream(zd, &outBuff, &inBuff);
646 if (r != 0) goto _output_error; } /* should reach end of frame == 0; otherwise, some data left, or an error */
647 if (outBuff.pos != CNBufferSize) goto _output_error; /* should regenerate the same amount */
648 if (inBuff.pos != inBuff.size) goto _output_error; /* should have read the entire frame */
649 ZSTD_freeDDict(ddict);
650 DISPLAYLEVEL(3, "OK \n");
653 /* Memory restriction */
654 DISPLAYLEVEL(3, "test%3i : maxWindowSize < frame requirement : ", testNb++);
655 ZSTD_initDStream_usingDict(zd, CNBuffer, dictSize);
656 CHECK_Z( ZSTD_DCtx_setParameter(zd, ZSTD_d_windowLogMax, 10) ); /* too small limit */
657 outBuff.dst = decodedBuffer;
658 outBuff.size = CNBufferSize;
660 inBuff.src = compressedBuffer;
663 { size_t const r = ZSTD_decompressStream(zd, &outBuff, &inBuff);
664 if (!ZSTD_isError(r)) goto _output_error; /* must fail : frame requires > 100 bytes */
665 DISPLAYLEVEL(3, "OK (%s)\n", ZSTD_getErrorName(r)); }
666 ZSTD_DCtx_reset(zd, ZSTD_reset_session_and_parameters); /* leave zd in good shape for next tests */
668 DISPLAYLEVEL(3, "test%3i : dictionary source size and level : ", testNb++);
669 { ZSTD_DCtx* const dctx = ZSTD_createDCtx();
670 int const maxLevel = 16; /* first level with zstd_opt */
672 assert(maxLevel < ZSTD_maxCLevel());
673 CHECK_Z( ZSTD_DCtx_loadDictionary_byReference(dctx, dictionary.start, dictionary.filled) );
674 for (level = 1; level <= maxLevel; ++level) {
675 ZSTD_CDict* const cdict = ZSTD_createCDict(dictionary.start, dictionary.filled, level);
676 size_t const maxSize = MIN(1 MB, CNBufferSize);
678 for (size = 512; size <= maxSize; size <<= 1) {
679 U64 const crcOrig = XXH64(CNBuffer, size, 0);
680 ZSTD_CCtx* const cctx = ZSTD_createCCtx();
681 ZSTD_parameters savedParams;
682 getCCtxParams(cctx, &savedParams);
683 outBuff.dst = compressedBuffer;
684 outBuff.size = compressedBufferSize;
686 inBuff.src = CNBuffer;
689 CHECK_Z(ZSTD_CCtx_refCDict(cctx, cdict));
690 CHECK_Z(ZSTD_compressStream2(cctx, &outBuff, &inBuff, ZSTD_e_end));
691 CHECK(badParameters(cctx, savedParams), "Bad CCtx params");
692 if (inBuff.pos != inBuff.size) goto _output_error;
693 { ZSTD_outBuffer decOut = {decodedBuffer, size, 0};
694 ZSTD_inBuffer decIn = {outBuff.dst, outBuff.pos, 0};
695 CHECK_Z( ZSTD_decompressStream(dctx, &decOut, &decIn) );
696 if (decIn.pos != decIn.size) goto _output_error;
697 if (decOut.pos != size) goto _output_error;
698 { U64 const crcDec = XXH64(decOut.dst, decOut.pos, 0);
699 if (crcDec != crcOrig) goto _output_error;
703 ZSTD_freeCDict(cdict);
707 DISPLAYLEVEL(3, "OK\n");
709 DISPLAYLEVEL(3, "test%3i : ZSTD_initCStream_usingCDict_advanced with masked dictID : ", testNb++);
710 { ZSTD_compressionParameters const cParams = ZSTD_getCParams(1, CNBufferSize, dictionary.filled);
711 ZSTD_frameParameters const fParams = { 1 /* contentSize */, 1 /* checksum */, 1 /* noDictID */};
712 ZSTD_CDict* const cdict = ZSTD_createCDict_advanced(dictionary.start, dictionary.filled, ZSTD_dlm_byRef, ZSTD_dct_auto, cParams, ZSTD_defaultCMem);
713 size_t const initError = ZSTD_initCStream_usingCDict_advanced(zc, cdict, fParams, CNBufferSize);
714 if (ZSTD_isError(initError)) goto _output_error;
715 outBuff.dst = compressedBuffer;
716 outBuff.size = compressedBufferSize;
718 inBuff.src = CNBuffer;
719 inBuff.size = CNBufferSize;
721 CHECK_Z( ZSTD_compressStream(zc, &outBuff, &inBuff) );
722 if (inBuff.pos != inBuff.size) goto _output_error; /* entire input should be consumed */
723 { size_t const r = ZSTD_endStream(zc, &outBuff);
724 if (r != 0) goto _output_error; } /* error, or some data not flushed */
726 ZSTD_freeCDict(cdict);
727 DISPLAYLEVEL(3, "OK (%u bytes : %.2f%%)\n", (unsigned)cSize, (double)cSize/CNBufferSize*100);
730 DISPLAYLEVEL(3, "test%3i : try retrieving dictID from frame : ", testNb++);
731 { U32 const did = ZSTD_getDictID_fromFrame(compressedBuffer, cSize);
732 if (did != 0) goto _output_error;
734 DISPLAYLEVEL(3, "OK (not detected) \n");
736 DISPLAYLEVEL(3, "test%3i : decompress without dictionary : ", testNb++);
737 { size_t const r = ZSTD_decompress(decodedBuffer, CNBufferSize, compressedBuffer, cSize);
738 if (!ZSTD_isError(r)) goto _output_error; /* must fail : dictionary not used */
739 DISPLAYLEVEL(3, "OK (%s)\n", ZSTD_getErrorName(r));
742 DISPLAYLEVEL(3, "test%3i : compress with ZSTD_CCtx_refPrefix : ", testNb++);
743 CHECK_Z( ZSTD_CCtx_refPrefix(zc, dictionary.start, dictionary.filled) );
744 outBuff.dst = compressedBuffer;
745 outBuff.size = compressedBufferSize;
747 inBuff.src = CNBuffer;
748 inBuff.size = CNBufferSize;
750 CHECK_Z( ZSTD_compressStream2(zc, &outBuff, &inBuff, ZSTD_e_end) );
751 if (inBuff.pos != inBuff.size) goto _output_error; /* entire input should be consumed */
753 DISPLAYLEVEL(3, "OK (%u bytes : %.2f%%)\n", (unsigned)cSize, (double)cSize/CNBufferSize*100);
755 DISPLAYLEVEL(3, "test%3i : decompress with ZSTD_DCtx_refPrefix : ", testNb++);
756 CHECK_Z( ZSTD_DCtx_refPrefix(zd, dictionary.start, dictionary.filled) );
757 outBuff.dst = decodedBuffer;
758 outBuff.size = CNBufferSize;
760 inBuff.src = compressedBuffer;
763 CHECK_Z( ZSTD_decompressStream(zd, &outBuff, &inBuff) );
764 if (inBuff.pos != inBuff.size) goto _output_error; /* entire input should be consumed */
765 if (outBuff.pos != CNBufferSize) goto _output_error; /* must regenerate whole input */
766 DISPLAYLEVEL(3, "OK \n");
768 DISPLAYLEVEL(3, "test%3i : decompress without dictionary (should fail): ", testNb++);
769 { size_t const r = ZSTD_decompress(decodedBuffer, CNBufferSize, compressedBuffer, cSize);
770 if (!ZSTD_isError(r)) goto _output_error; /* must fail : dictionary not used */
771 DISPLAYLEVEL(3, "OK (%s)\n", ZSTD_getErrorName(r));
774 DISPLAYLEVEL(3, "test%3i : compress again with ZSTD_compressStream2 : ", testNb++);
775 outBuff.dst = compressedBuffer;
776 outBuff.size = compressedBufferSize;
778 inBuff.src = CNBuffer;
779 inBuff.size = CNBufferSize;
781 CHECK_Z( ZSTD_compressStream2(zc, &outBuff, &inBuff, ZSTD_e_end) );
782 if (inBuff.pos != inBuff.size) goto _output_error; /* entire input should be consumed */
784 DISPLAYLEVEL(3, "OK (%u bytes : %.2f%%)\n", (unsigned)cSize, (double)cSize/CNBufferSize*100);
786 DISPLAYLEVEL(3, "test%3i : decompress without dictionary (should work): ", testNb++);
787 CHECK_Z( ZSTD_decompress(decodedBuffer, CNBufferSize, compressedBuffer, cSize) );
788 DISPLAYLEVEL(3, "OK \n");
791 DISPLAYLEVEL(3, "test%3i : ZSTD_initCStream_advanced with pledgedSrcSize=0 and dict : ", testNb++);
792 { ZSTD_parameters params = ZSTD_getParams(5, 0, 0);
793 params.fParams.contentSizeFlag = 1;
794 CHECK_Z( ZSTD_initCStream_advanced(zc, dictionary.start, dictionary.filled, params, 0 /* pledgedSrcSize==0 means "empty" when params.fParams.contentSizeFlag is set */) );
795 } /* cstream advanced shall write content size = 0 */
796 outBuff.dst = compressedBuffer;
797 outBuff.size = compressedBufferSize;
799 inBuff.src = CNBuffer;
802 CHECK_Z( ZSTD_compressStream(zc, &outBuff, &inBuff) );
803 if (ZSTD_endStream(zc, &outBuff) != 0) goto _output_error;
805 if (ZSTD_findDecompressedSize(compressedBuffer, cSize) != 0) goto _output_error;
806 DISPLAYLEVEL(3, "OK \n");
808 DISPLAYLEVEL(3, "test%3i : pledgedSrcSize == 0 behaves properly : ", testNb++);
809 { ZSTD_parameters params = ZSTD_getParams(5, 0, 0);
810 params.fParams.contentSizeFlag = 1;
811 CHECK_Z( ZSTD_initCStream_advanced(zc, NULL, 0, params, 0) );
812 } /* cstream advanced shall write content size = 0 */
813 inBuff.src = CNBuffer;
816 outBuff.dst = compressedBuffer;
817 outBuff.size = compressedBufferSize;
819 CHECK_Z( ZSTD_compressStream(zc, &outBuff, &inBuff) );
820 if (ZSTD_endStream(zc, &outBuff) != 0) goto _output_error;
822 if (ZSTD_findDecompressedSize(compressedBuffer, cSize) != 0) goto _output_error;
824 ZSTD_resetCStream(zc, 0); /* resetCStream should treat 0 as unknown */
825 outBuff.dst = compressedBuffer;
826 outBuff.size = compressedBufferSize;
828 inBuff.src = CNBuffer;
831 CHECK_Z( ZSTD_compressStream(zc, &outBuff, &inBuff) );
832 if (ZSTD_endStream(zc, &outBuff) != 0) goto _output_error;
834 if (ZSTD_findDecompressedSize(compressedBuffer, cSize) != ZSTD_CONTENTSIZE_UNKNOWN) goto _output_error;
835 DISPLAYLEVEL(3, "OK \n");
837 /* Basic multithreading compression test */
838 DISPLAYLEVEL(3, "test%3i : compress %u bytes with multiple threads : ", testNb++, COMPRESSIBLE_NOISE_LENGTH);
839 { ZSTD_parameters const params = ZSTD_getParams(1, 0, 0);
841 CHECK_Z( ZSTDMT_getMTCtxParameter(mtctx, ZSTDMT_p_jobSize, &jobSize));
842 CHECK(jobSize != 0, "job size non-zero");
843 CHECK_Z( ZSTDMT_initCStream_advanced(mtctx, CNBuffer, dictSize, params, CNBufferSize) );
844 CHECK_Z( ZSTDMT_getMTCtxParameter(mtctx, ZSTDMT_p_jobSize, &jobSize));
845 CHECK(jobSize != 0, "job size non-zero");
847 outBuff.dst = compressedBuffer;
848 outBuff.size = compressedBufferSize;
850 inBuff.src = CNBuffer;
851 inBuff.size = CNBufferSize;
853 { size_t const compressResult = ZSTDMT_compressStream_generic(mtctx, &outBuff, &inBuff, ZSTD_e_end);
854 if (compressResult != 0) goto _output_error; /* compression must be completed in a single round */
856 if (inBuff.pos != inBuff.size) goto _output_error; /* entire input should be consumed */
857 { size_t const compressedSize = ZSTD_findFrameCompressedSize(compressedBuffer, outBuff.pos);
858 if (compressedSize != outBuff.pos) goto _output_error; /* must be a full valid frame */
860 DISPLAYLEVEL(3, "OK \n");
862 /* Complex multithreading + dictionary test */
863 { U32 const nbWorkers = 2;
864 size_t const jobSize = 4 * 1 MB;
865 size_t const srcSize = jobSize * nbWorkers; /* we want each job to have predictable size */
866 size_t const segLength = 2 KB;
867 size_t const offset = 600 KB; /* must be larger than window defined in cdict */
868 size_t const start = jobSize + (offset-1);
869 const BYTE* const srcToCopy = (const BYTE*)CNBuffer + start;
870 BYTE* const dst = (BYTE*)CNBuffer + start - offset;
871 DISPLAYLEVEL(3, "test%3i : compress %u bytes with multiple threads + dictionary : ", testNb++, (unsigned)srcSize);
872 CHECK_Z( ZSTD_CCtx_setParameter(zc, ZSTD_c_compressionLevel, 3) );
873 CHECK_Z( ZSTD_CCtx_setParameter(zc, ZSTD_c_nbWorkers, nbWorkers) );
874 CHECK_Z( ZSTD_CCtx_setParameter(zc, ZSTD_c_jobSize, jobSize) );
875 assert(start > offset);
876 assert(start + segLength < COMPRESSIBLE_NOISE_LENGTH);
877 memcpy(dst, srcToCopy, segLength); /* create a long repetition at long distance for job 2 */
878 outBuff.dst = compressedBuffer;
879 outBuff.size = compressedBufferSize;
881 inBuff.src = CNBuffer;
882 inBuff.size = srcSize; assert(srcSize < COMPRESSIBLE_NOISE_LENGTH);
885 { ZSTD_compressionParameters const cParams = ZSTD_getCParams(1, 4 KB, dictionary.filled); /* intentionnally lies on estimatedSrcSize, to push cdict into targeting a small window size */
886 ZSTD_CDict* const cdict = ZSTD_createCDict_advanced(dictionary.start, dictionary.filled, ZSTD_dlm_byRef, ZSTD_dct_fullDict, cParams, ZSTD_defaultCMem);
887 DISPLAYLEVEL(5, "cParams.windowLog = %u : ", cParams.windowLog);
888 CHECK_Z( ZSTD_CCtx_refCDict(zc, cdict) );
889 CHECK_Z( ZSTD_compressStream2(zc, &outBuff, &inBuff, ZSTD_e_end) );
890 CHECK_Z( ZSTD_CCtx_refCDict(zc, NULL) ); /* do not keep a reference to cdict, as its lifetime ends */
891 ZSTD_freeCDict(cdict);
893 if (inBuff.pos != inBuff.size) goto _output_error; /* entire input should be consumed */
895 DISPLAYLEVEL(3, "OK \n");
897 DISPLAYLEVEL(3, "test%3i : decompress large frame created from multiple threads + dictionary : ", testNb++);
898 { ZSTD_DStream* const dstream = ZSTD_createDCtx();
899 ZSTD_frameHeader zfh;
900 ZSTD_getFrameHeader(&zfh, compressedBuffer, cSize);
901 DISPLAYLEVEL(5, "frame windowsize = %u : ", (unsigned)zfh.windowSize);
902 outBuff.dst = decodedBuffer;
903 outBuff.size = CNBufferSize;
905 inBuff.src = compressedBuffer;
907 CHECK_Z( ZSTD_initDStream_usingDict(dstream, dictionary.start, dictionary.filled) );
908 inBuff.size = 1; /* avoid shortcut to single-pass mode */
909 CHECK_Z( ZSTD_decompressStream(dstream, &outBuff, &inBuff) );
911 CHECK_Z( ZSTD_decompressStream(dstream, &outBuff, &inBuff) );
912 if (inBuff.pos != inBuff.size) goto _output_error; /* entire input should be consumed */
913 ZSTD_freeDStream(dstream);
915 DISPLAYLEVEL(3, "OK \n");
917 DISPLAYLEVEL(3, "test%3i : check dictionary FSE tables can represent every code : ", testNb++);
918 { unsigned const kMaxWindowLog = 24;
920 ZSTD_compressionParameters cParams = ZSTD_getCParams(3, 1U << kMaxWindowLog, 1024);
923 SEQ_stream seq = SEQ_initStream(0x87654321);
927 XXH64_reset(&xxh, 0);
928 cParams.windowLog = kMaxWindowLog;
929 cdict = ZSTD_createCDict_advanced(dictionary.start, dictionary.filled, ZSTD_dlm_byRef, ZSTD_dct_fullDict, cParams, ZSTD_defaultCMem);
930 ddict = ZSTD_createDDict(dictionary.start, dictionary.filled);
932 if (!cdict || !ddict) goto _output_error;
934 ZSTD_CCtx_reset(zc, ZSTD_reset_session_only);
935 ZSTD_resetDStream(zd);
936 CHECK_Z(ZSTD_CCtx_refCDict(zc, cdict));
937 CHECK_Z(ZSTD_initDStream_usingDDict(zd, ddict));
938 CHECK_Z(ZSTD_DCtx_setParameter(zd, ZSTD_d_windowLogMax, kMaxWindowLog));
939 /* Test all values < 300 */
940 for (value = 0; value < 300; ++value) {
941 for (type = (SEQ_gen_type)0; type < SEQ_gen_max; ++type) {
942 CHECK_Z(SEQ_generateRoundTrip(zc, zd, &xxh, &seq, type, value));
945 /* Test values 2^8 to 2^17 */
946 for (value = (1 << 8); value < (1 << 17); value <<= 1) {
947 for (type = (SEQ_gen_type)0; type < SEQ_gen_max; ++type) {
948 CHECK_Z(SEQ_generateRoundTrip(zc, zd, &xxh, &seq, type, value));
949 CHECK_Z(SEQ_generateRoundTrip(zc, zd, &xxh, &seq, type, value + (value >> 2)));
952 /* Test offset values up to the max window log */
953 for (value = 8; value <= kMaxWindowLog; ++value) {
954 CHECK_Z(SEQ_generateRoundTrip(zc, zd, &xxh, &seq, SEQ_gen_of, (1U << value) - 1));
957 CHECK_Z(SEQ_roundTrip(zc, zd, &xxh, NULL, 0, ZSTD_e_end));
958 CHECK(SEQ_digest(&seq) != XXH64_digest(&xxh), "SEQ XXH64 does not match");
960 ZSTD_freeCDict(cdict);
961 ZSTD_freeDDict(ddict);
963 DISPLAYLEVEL(3, "OK \n");
965 DISPLAYLEVEL(3, "test%3i : ZSTD_initCStream_srcSize sets requestedParams : ", testNb++);
967 CHECK_Z(ZSTD_initCStream_srcSize(zc, 11, ZSTD_CONTENTSIZE_UNKNOWN));
968 CHECK_Z(ZSTD_CCtx_getParameter(zc, ZSTD_c_compressionLevel, &level));
969 CHECK(level != 11, "Compression level does not match");
970 ZSTD_resetCStream(zc, ZSTD_CONTENTSIZE_UNKNOWN);
971 CHECK_Z(ZSTD_CCtx_getParameter(zc, ZSTD_c_compressionLevel, &level));
972 CHECK(level != 11, "Compression level does not match");
974 DISPLAYLEVEL(3, "OK \n");
976 DISPLAYLEVEL(3, "test%3i : ZSTD_initCStream_advanced sets requestedParams : ", testNb++);
977 { ZSTD_parameters const params = ZSTD_getParams(9, 0, 0);
978 CHECK_Z(ZSTD_initCStream_advanced(zc, NULL, 0, params, ZSTD_CONTENTSIZE_UNKNOWN));
979 CHECK(badParameters(zc, params), "Compression parameters do not match");
980 ZSTD_resetCStream(zc, ZSTD_CONTENTSIZE_UNKNOWN);
981 CHECK(badParameters(zc, params), "Compression parameters do not match");
983 DISPLAYLEVEL(3, "OK \n");
985 /* Overlen overwriting window data bug */
986 DISPLAYLEVEL(3, "test%3i : wildcopy doesn't overwrite potential match data : ", testNb++);
987 { /* This test has a window size of 1024 bytes and consists of 3 blocks:
988 1. 'a' repeated 517 times
989 2. 'b' repeated 516 times
990 3. a compressed block with no literals and 3 sequence commands:
991 litlength = 0, offset = 24, match length = 24
992 litlength = 0, offset = 24, match length = 3 (this one creates an overlength write of length 2*WILDCOPY_OVERLENGTH - 3)
993 litlength = 0, offset = 1021, match length = 3 (this one will try to read from overwritten data if the buffer is too small) */
995 const char* testCase =
996 "\x28\xB5\x2F\xFD\x04\x00\x4C\x00\x00\x10\x61\x61\x01\x00\x00\x2A"
997 "\x80\x05\x44\x00\x00\x08\x62\x01\x00\x00\x2A\x20\x04\x5D\x00\x00"
998 "\x00\x03\x40\x00\x00\x64\x60\x27\xB0\xE0\x0C\x67\x62\xCE\xE0";
999 ZSTD_DStream* const zds = ZSTD_createDStream();
1000 if (zds==NULL) goto _output_error;
1002 CHECK_Z( ZSTD_initDStream(zds) );
1003 inBuff.src = testCase;
1006 outBuff.dst = decodedBuffer;
1007 outBuff.size = CNBufferSize;
1010 while (inBuff.pos < inBuff.size) {
1011 CHECK_Z( ZSTD_decompressStream(zds, &outBuff, &inBuff) );
1014 ZSTD_freeDStream(zds);
1016 DISPLAYLEVEL(3, "OK \n");
1018 DISPLAYLEVEL(3, "test%3i : dictionary + uncompressible block + reusing tables checks offset table validity: ", testNb++);
1019 { ZSTD_CDict* const cdict = ZSTD_createCDict_advanced(
1020 dictionary.start, dictionary.filled,
1021 ZSTD_dlm_byRef, ZSTD_dct_fullDict,
1022 ZSTD_getCParams(3, 0, dictionary.filled),
1024 const size_t inbufsize = 2 * 128 * 1024; /* 2 blocks */
1025 const size_t outbufsize = ZSTD_compressBound(inbufsize);
1026 size_t inbufpos = 0;
1027 size_t cursegmentlen;
1028 BYTE *inbuf = (BYTE *)malloc(inbufsize);
1029 BYTE *outbuf = (BYTE *)malloc(outbufsize);
1030 BYTE *checkbuf = (BYTE *)malloc(inbufsize);
1033 CHECK(cdict == NULL, "failed to alloc cdict");
1034 CHECK(inbuf == NULL, "failed to alloc input buffer");
1036 /* first block is uncompressible */
1037 cursegmentlen = 128 * 1024;
1038 RDG_genBuffer(inbuf + inbufpos, cursegmentlen, 0., 0., seed);
1039 inbufpos += cursegmentlen;
1041 /* second block is compressible */
1042 cursegmentlen = 128 * 1024 - 256;
1043 RDG_genBuffer(inbuf + inbufpos, cursegmentlen, 0.05, 0., seed);
1044 inbufpos += cursegmentlen;
1046 /* and includes a very long backref */
1047 cursegmentlen = 128;
1048 memcpy(inbuf + inbufpos, dictionary.start + 256, cursegmentlen);
1049 inbufpos += cursegmentlen;
1051 /* and includes a very long backref */
1052 cursegmentlen = 128;
1053 memcpy(inbuf + inbufpos, dictionary.start + 128, cursegmentlen);
1054 inbufpos += cursegmentlen;
1056 ret = ZSTD_compress_usingCDict(zc, outbuf, outbufsize, inbuf, inbufpos, cdict);
1059 ret = ZSTD_decompress_usingDict(zd, checkbuf, inbufsize, outbuf, ret, dictionary.start, dictionary.filled);
1062 CHECK(memcmp(inbuf, checkbuf, inbufpos), "start and finish buffers don't match");
1064 ZSTD_freeCDict(cdict);
1069 DISPLAYLEVEL(3, "OK \n");
1071 DISPLAYLEVEL(3, "test%3i : dictionary + small blocks + reusing tables checks offset table validity: ", testNb++);
1072 { ZSTD_CDict* const cdict = ZSTD_createCDict_advanced(
1073 dictionary.start, dictionary.filled,
1074 ZSTD_dlm_byRef, ZSTD_dct_fullDict,
1075 ZSTD_getCParams(3, 0, dictionary.filled),
1077 ZSTD_outBuffer out = {compressedBuffer, compressedBufferSize, 0};
1078 int remainingInput = 256 * 1024;
1081 CHECK_Z(ZSTD_CCtx_reset(zc, ZSTD_reset_session_and_parameters));
1082 CHECK_Z(ZSTD_CCtx_refCDict(zc, cdict));
1083 CHECK_Z(ZSTD_CCtx_setParameter(zc, ZSTD_c_checksumFlag, 1));
1084 /* Write a bunch of 6 byte blocks */
1085 while (remainingInput > 0) {
1086 char testBuffer[6] = "\xAA\xAA\xAA\xAA\xAA\xAA";
1087 const size_t kSmallBlockSize = sizeof(testBuffer);
1088 ZSTD_inBuffer in = {testBuffer, kSmallBlockSize, 0};
1090 CHECK_Z(ZSTD_compressStream2(zc, &out, &in, ZSTD_e_flush));
1091 CHECK(in.pos != in.size, "input not fully consumed");
1092 remainingInput -= kSmallBlockSize;
1094 /* Write several very long offset matches into the dictionary */
1095 for (offset = 1024; offset >= 0; offset -= 128) {
1096 ZSTD_inBuffer in = {dictionary.start + offset, 128, 0};
1097 ZSTD_EndDirective flush = offset > 0 ? ZSTD_e_continue : ZSTD_e_end;
1098 CHECK_Z(ZSTD_compressStream2(zc, &out, &in, flush));
1099 CHECK(in.pos != in.size, "input not fully consumed");
1101 /* Ensure decompression works */
1102 CHECK_Z(ZSTD_decompress_usingDict(zd, decodedBuffer, CNBufferSize, out.dst, out.pos, dictionary.start, dictionary.filled));
1104 ZSTD_freeCDict(cdict);
1106 DISPLAYLEVEL(3, "OK \n");
1109 FUZ_freeDictionary(dictionary);
1110 ZSTD_freeCStream(zc);
1111 ZSTD_freeDStream(zd);
1112 ZSTDMT_freeCCtx(mtctx);
1114 free(compressedBuffer);
1115 free(decodedBuffer);
1120 DISPLAY("Error detected in Unit tests ! \n");
1125 /* ====== Fuzzer tests ====== */
1127 static size_t findDiff(const void* buf1, const void* buf2, size_t max)
1129 const BYTE* b1 = (const BYTE*)buf1;
1130 const BYTE* b2 = (const BYTE*)buf2;
1132 for (u=0; u<max; u++) {
1133 if (b1[u] != b2[u]) break;
1136 DISPLAY("=> No difference detected within %u bytes \n", (unsigned)max);
1139 DISPLAY("Error at position %u / %u \n", (unsigned)u, (unsigned)max);
1141 DISPLAY(" %02X %02X %02X ",
1142 b1[u-3], b1[u-2], b1[u-1]);
1143 DISPLAY(" :%02X: %02X %02X %02X %02X %02X \n",
1144 b1[u], b1[u+1], b1[u+2], b1[u+3], b1[u+4], b1[u+5]);
1146 DISPLAY(" %02X %02X %02X ",
1147 b2[u-3], b2[u-2], b2[u-1]);
1148 DISPLAY(" :%02X: %02X %02X %02X %02X %02X \n",
1149 b2[u], b2[u+1], b2[u+2], b2[u+3], b2[u+4], b2[u+5]);
1153 static size_t FUZ_rLogLength(U32* seed, U32 logLength)
1155 size_t const lengthMask = ((size_t)1 << logLength) - 1;
1156 return (lengthMask+1) + (FUZ_rand(seed) & lengthMask);
1159 static size_t FUZ_randomLength(U32* seed, U32 maxLog)
1161 U32 const logLength = FUZ_rand(seed) % maxLog;
1162 return FUZ_rLogLength(seed, logLength);
1165 /* Return value in range minVal <= v <= maxVal */
1166 static U32 FUZ_randomClampedLength(U32* seed, U32 minVal, U32 maxVal)
1168 U32 const mod = maxVal < minVal ? 1 : (maxVal + 1) - minVal;
1169 return (U32)((FUZ_rand(seed) % mod) + minVal);
1172 static int fuzzerTests(U32 seed, unsigned nbTests, unsigned startTest, double compressibility, int bigTests)
1174 U32 const maxSrcLog = bigTests ? 24 : 22;
1175 static const U32 maxSampleLog = 19;
1176 size_t const srcBufferSize = (size_t)1<<maxSrcLog;
1177 BYTE* cNoiseBuffer[5];
1178 size_t const copyBufferSize = srcBufferSize + (1<<maxSampleLog);
1179 BYTE* const copyBuffer = (BYTE*)malloc (copyBufferSize);
1180 size_t const cBufferSize = ZSTD_compressBound(srcBufferSize);
1181 BYTE* const cBuffer = (BYTE*)malloc (cBufferSize);
1182 size_t const dstBufferSize = srcBufferSize;
1183 BYTE* const dstBuffer = (BYTE*)malloc (dstBufferSize);
1185 unsigned testNb = 0;
1186 U32 coreSeed = seed;
1187 ZSTD_CStream* zc = ZSTD_createCStream(); /* will be re-created sometimes */
1188 ZSTD_DStream* zd = ZSTD_createDStream(); /* will be re-created sometimes */
1189 ZSTD_DStream* const zd_noise = ZSTD_createDStream();
1190 UTIL_time_t const startClock = UTIL_getTime();
1191 const BYTE* dict = NULL; /* can keep same dict on 2 consecutive tests */
1192 size_t dictSize = 0;
1194 U32 const cLevelMax = bigTests ? (U32)ZSTD_maxCLevel() : g_cLevelMax_smallTests;
1197 cNoiseBuffer[0] = (BYTE*)malloc (srcBufferSize);
1198 cNoiseBuffer[1] = (BYTE*)malloc (srcBufferSize);
1199 cNoiseBuffer[2] = (BYTE*)malloc (srcBufferSize);
1200 cNoiseBuffer[3] = (BYTE*)malloc (srcBufferSize);
1201 cNoiseBuffer[4] = (BYTE*)malloc (srcBufferSize);
1202 CHECK (!cNoiseBuffer[0] || !cNoiseBuffer[1] || !cNoiseBuffer[2] || !cNoiseBuffer[3] || !cNoiseBuffer[4] ||
1203 !copyBuffer || !dstBuffer || !cBuffer || !zc || !zd || !zd_noise ,
1204 "Not enough memory, fuzzer tests cancelled");
1206 /* Create initial samples */
1207 RDG_genBuffer(cNoiseBuffer[0], srcBufferSize, 0.00, 0., coreSeed); /* pure noise */
1208 RDG_genBuffer(cNoiseBuffer[1], srcBufferSize, 0.05, 0., coreSeed); /* barely compressible */
1209 RDG_genBuffer(cNoiseBuffer[2], srcBufferSize, compressibility, 0., coreSeed);
1210 RDG_genBuffer(cNoiseBuffer[3], srcBufferSize, 0.95, 0., coreSeed); /* highly compressible */
1211 RDG_genBuffer(cNoiseBuffer[4], srcBufferSize, 1.00, 0., coreSeed); /* sparse content */
1212 memset(copyBuffer, 0x65, copyBufferSize); /* make copyBuffer considered initialized */
1213 ZSTD_initDStream_usingDict(zd, NULL, 0); /* ensure at least one init */
1215 /* catch up testNb */
1216 for (testNb=1; testNb < startTest; testNb++)
1217 FUZ_rand(&coreSeed);
1220 for ( ; (testNb <= nbTests) || (UTIL_clockSpanMicro(startClock) < g_clockTime) ; testNb++ ) {
1222 const BYTE* srcBuffer;
1223 size_t totalTestSize, totalGenSize, cSize;
1224 XXH64_state_t xxhState;
1226 U32 resetAllowed = 1;
1230 FUZ_rand(&coreSeed);
1231 lseed = coreSeed ^ prime32;
1232 if (nbTests >= testNb) {
1233 DISPLAYUPDATE(2, "\r%6u/%6u ", testNb, nbTests);
1235 DISPLAYUPDATE(2, "\r%6u ", testNb);
1238 /* states full reset (deliberately not synchronized) */
1239 /* some issues can only happen when reusing states */
1240 if ((FUZ_rand(&lseed) & 0xFF) == 131) {
1241 ZSTD_freeCStream(zc);
1242 zc = ZSTD_createCStream();
1243 CHECK(zc==NULL, "ZSTD_createCStream : allocation error");
1246 if ((FUZ_rand(&lseed) & 0xFF) == 132) {
1247 ZSTD_freeDStream(zd);
1248 zd = ZSTD_createDStream();
1249 CHECK(zd==NULL, "ZSTD_createDStream : allocation error");
1250 CHECK_Z( ZSTD_initDStream_usingDict(zd, NULL, 0) ); /* ensure at least one init */
1253 /* srcBuffer selection [0-4] */
1254 { U32 buffNb = FUZ_rand(&lseed) & 0x7F;
1255 if (buffNb & 7) buffNb=2; /* most common : compressible (P) */
1259 const U32 tnb[2] = { 1, 3 }; /* barely/highly compressible */
1260 buffNb = tnb[buffNb >> 3];
1262 const U32 tnb[2] = { 0, 4 }; /* not compressible / sparse */
1263 buffNb = tnb[buffNb >> 3];
1265 srcBuffer = cNoiseBuffer[buffNb];
1268 /* compression init */
1269 if ((FUZ_rand(&lseed)&1) /* at beginning, to keep same nb of rand */
1270 && oldTestLog /* at least one test happened */ && resetAllowed) {
1271 maxTestSize = FUZ_randomLength(&lseed, oldTestLog+2);
1272 maxTestSize = MIN(maxTestSize, srcBufferSize-16);
1273 { U64 const pledgedSrcSize = (FUZ_rand(&lseed) & 3) ? 0 : maxTestSize;
1274 CHECK_Z( ZSTD_resetCStream(zc, pledgedSrcSize) );
1277 U32 const testLog = FUZ_rand(&lseed) % maxSrcLog;
1278 U32 const dictLog = FUZ_rand(&lseed) % maxSrcLog;
1279 U32 const cLevelCandidate = ( FUZ_rand(&lseed) %
1281 (MAX(testLog, dictLog) / 3)))
1283 U32 const cLevel = MIN(cLevelCandidate, cLevelMax);
1284 maxTestSize = FUZ_rLogLength(&lseed, testLog);
1285 oldTestLog = testLog;
1286 /* random dictionary selection */
1287 dictSize = ((FUZ_rand(&lseed)&7)==1) ? FUZ_rLogLength(&lseed, dictLog) : 0;
1288 { size_t const dictStart = FUZ_rand(&lseed) % (srcBufferSize - dictSize);
1289 dict = srcBuffer + dictStart;
1291 { U64 const pledgedSrcSize = (FUZ_rand(&lseed) & 3) ? ZSTD_CONTENTSIZE_UNKNOWN : maxTestSize;
1292 ZSTD_parameters params = ZSTD_getParams(cLevel, pledgedSrcSize, dictSize);
1293 params.fParams.checksumFlag = FUZ_rand(&lseed) & 1;
1294 params.fParams.noDictIDFlag = FUZ_rand(&lseed) & 1;
1295 params.fParams.contentSizeFlag = FUZ_rand(&lseed) & 1;
1296 CHECK_Z ( ZSTD_initCStream_advanced(zc, dict, dictSize, params, pledgedSrcSize) );
1299 /* multi-segments compression test */
1300 XXH64_reset(&xxhState, 0);
1301 { ZSTD_outBuffer outBuff = { cBuffer, cBufferSize, 0 } ;
1303 for (n=0, cSize=0, totalTestSize=0 ; totalTestSize < maxTestSize ; n++) {
1304 /* compress random chunks into randomly sized dst buffers */
1305 { size_t const randomSrcSize = FUZ_randomLength(&lseed, maxSampleLog);
1306 size_t const srcSize = MIN(maxTestSize-totalTestSize, randomSrcSize);
1307 size_t const srcStart = FUZ_rand(&lseed) % (srcBufferSize - srcSize);
1308 size_t const randomDstSize = FUZ_randomLength(&lseed, maxSampleLog);
1309 size_t const dstBuffSize = MIN(cBufferSize - cSize, randomDstSize);
1310 ZSTD_inBuffer inBuff = { srcBuffer+srcStart, srcSize, 0 };
1311 outBuff.size = outBuff.pos + dstBuffSize;
1313 CHECK_Z( ZSTD_compressStream(zc, &outBuff, &inBuff) );
1315 XXH64_update(&xxhState, srcBuffer+srcStart, inBuff.pos);
1316 memcpy(copyBuffer+totalTestSize, srcBuffer+srcStart, inBuff.pos);
1317 totalTestSize += inBuff.pos;
1320 /* random flush operation, to mess around */
1321 if ((FUZ_rand(&lseed) & 15) == 0) {
1322 size_t const randomDstSize = FUZ_randomLength(&lseed, maxSampleLog);
1323 size_t const adjustedDstSize = MIN(cBufferSize - cSize, randomDstSize);
1324 outBuff.size = outBuff.pos + adjustedDstSize;
1325 CHECK_Z( ZSTD_flushStream(zc, &outBuff) );
1328 /* final frame epilogue */
1329 { size_t remainingToFlush = (size_t)(-1);
1330 while (remainingToFlush) {
1331 size_t const randomDstSize = FUZ_randomLength(&lseed, maxSampleLog);
1332 size_t const adjustedDstSize = MIN(cBufferSize - cSize, randomDstSize);
1333 outBuff.size = outBuff.pos + adjustedDstSize;
1334 remainingToFlush = ZSTD_endStream(zc, &outBuff);
1335 CHECK (ZSTD_isError(remainingToFlush), "end error : %s", ZSTD_getErrorName(remainingToFlush));
1337 crcOrig = XXH64_digest(&xxhState);
1338 cSize = outBuff.pos;
1341 /* multi - fragments decompression test */
1342 if (!dictSize /* don't reset if dictionary : could be different */ && (FUZ_rand(&lseed) & 1)) {
1343 CHECK_Z ( ZSTD_resetDStream(zd) );
1345 CHECK_Z ( ZSTD_initDStream_usingDict(zd, dict, dictSize) );
1347 { size_t decompressionResult = 1;
1348 ZSTD_inBuffer inBuff = { cBuffer, cSize, 0 };
1349 ZSTD_outBuffer outBuff= { dstBuffer, dstBufferSize, 0 };
1350 for (totalGenSize = 0 ; decompressionResult ; ) {
1351 size_t const readCSrcSize = FUZ_randomLength(&lseed, maxSampleLog);
1352 size_t const randomDstSize = FUZ_randomLength(&lseed, maxSampleLog);
1353 size_t const dstBuffSize = MIN(dstBufferSize - totalGenSize, randomDstSize);
1354 inBuff.size = inBuff.pos + readCSrcSize;
1355 outBuff.size = outBuff.pos + dstBuffSize;
1356 decompressionResult = ZSTD_decompressStream(zd, &outBuff, &inBuff);
1357 if (ZSTD_getErrorCode(decompressionResult) == ZSTD_error_checksum_wrong) {
1358 DISPLAY("checksum error : \n");
1359 findDiff(copyBuffer, dstBuffer, totalTestSize);
1361 CHECK( ZSTD_isError(decompressionResult), "decompression error : %s",
1362 ZSTD_getErrorName(decompressionResult) );
1364 CHECK (decompressionResult != 0, "frame not fully decoded");
1365 CHECK (outBuff.pos != totalTestSize, "decompressed data : wrong size (%u != %u)",
1366 (unsigned)outBuff.pos, (unsigned)totalTestSize);
1367 CHECK (inBuff.pos != cSize, "compressed data should be fully read")
1368 { U64 const crcDest = XXH64(dstBuffer, totalTestSize, 0);
1369 if (crcDest!=crcOrig) findDiff(copyBuffer, dstBuffer, totalTestSize);
1370 CHECK (crcDest!=crcOrig, "decompressed data corrupted");
1373 /*===== noisy/erroneous src decompression test =====*/
1375 /* add some noise */
1376 { U32 const nbNoiseChunks = (FUZ_rand(&lseed) & 7) + 2;
1377 U32 nn; for (nn=0; nn<nbNoiseChunks; nn++) {
1378 size_t const randomNoiseSize = FUZ_randomLength(&lseed, maxSampleLog);
1379 size_t const noiseSize = MIN((cSize/3) , randomNoiseSize);
1380 size_t const noiseStart = FUZ_rand(&lseed) % (srcBufferSize - noiseSize);
1381 size_t const cStart = FUZ_rand(&lseed) % (cSize - noiseSize);
1382 memcpy(cBuffer+cStart, srcBuffer+noiseStart, noiseSize);
1385 /* try decompression on noisy data */
1386 CHECK_Z( ZSTD_initDStream(zd_noise) ); /* note : no dictionary */
1387 { ZSTD_inBuffer inBuff = { cBuffer, cSize, 0 };
1388 ZSTD_outBuffer outBuff= { dstBuffer, dstBufferSize, 0 };
1389 while (outBuff.pos < dstBufferSize) {
1390 size_t const randomCSrcSize = FUZ_randomLength(&lseed, maxSampleLog);
1391 size_t const randomDstSize = FUZ_randomLength(&lseed, maxSampleLog);
1392 size_t const adjustedDstSize = MIN(dstBufferSize - outBuff.pos, randomDstSize);
1393 size_t const adjustedCSrcSize = MIN(cSize - inBuff.pos, randomCSrcSize);
1394 outBuff.size = outBuff.pos + adjustedDstSize;
1395 inBuff.size = inBuff.pos + adjustedCSrcSize;
1396 { size_t const decompressError = ZSTD_decompressStream(zd, &outBuff, &inBuff);
1397 if (ZSTD_isError(decompressError)) break; /* error correctly detected */
1398 /* No forward progress possible */
1399 if (outBuff.pos < outBuff.size && inBuff.pos == cSize) break;
1401 DISPLAY("\r%u fuzzer tests completed \n", testNb);
1404 ZSTD_freeCStream(zc);
1405 ZSTD_freeDStream(zd);
1406 ZSTD_freeDStream(zd_noise);
1407 free(cNoiseBuffer[0]);
1408 free(cNoiseBuffer[1]);
1409 free(cNoiseBuffer[2]);
1410 free(cNoiseBuffer[3]);
1411 free(cNoiseBuffer[4]);
1423 /* fuzzing ZSTDMT_* interface */
1424 static int fuzzerTests_MT(U32 seed, int nbTests, int startTest,
1425 double compressibility, int bigTests)
1427 const U32 maxSrcLog = bigTests ? 24 : 22;
1428 static const U32 maxSampleLog = 19;
1429 size_t const srcBufferSize = (size_t)1<<maxSrcLog;
1430 BYTE* cNoiseBuffer[5];
1431 size_t const copyBufferSize= srcBufferSize + (1<<maxSampleLog);
1432 BYTE* const copyBuffer = (BYTE*)malloc (copyBufferSize);
1433 size_t const cBufferSize = ZSTD_compressBound(srcBufferSize);
1434 BYTE* const cBuffer = (BYTE*)malloc (cBufferSize);
1435 size_t const dstBufferSize = srcBufferSize;
1436 BYTE* const dstBuffer = (BYTE*)malloc (dstBufferSize);
1439 U32 coreSeed = seed;
1441 ZSTDMT_CCtx* zc = ZSTDMT_createCCtx(nbThreads); /* will be reset sometimes */
1442 ZSTD_DStream* zd = ZSTD_createDStream(); /* will be reset sometimes */
1443 ZSTD_DStream* const zd_noise = ZSTD_createDStream();
1444 UTIL_time_t const startClock = UTIL_getTime();
1445 const BYTE* dict=NULL; /* can keep same dict on 2 consecutive tests */
1446 size_t dictSize = 0;
1447 int const cLevelMax = bigTests ? (U32)ZSTD_maxCLevel()-1 : g_cLevelMax_smallTests;
1448 U32 const nbThreadsMax = bigTests ? 4 : 2;
1451 cNoiseBuffer[0] = (BYTE*)malloc (srcBufferSize);
1452 cNoiseBuffer[1] = (BYTE*)malloc (srcBufferSize);
1453 cNoiseBuffer[2] = (BYTE*)malloc (srcBufferSize);
1454 cNoiseBuffer[3] = (BYTE*)malloc (srcBufferSize);
1455 cNoiseBuffer[4] = (BYTE*)malloc (srcBufferSize);
1456 CHECK (!cNoiseBuffer[0] || !cNoiseBuffer[1] || !cNoiseBuffer[2] || !cNoiseBuffer[3] || !cNoiseBuffer[4] ||
1457 !copyBuffer || !dstBuffer || !cBuffer || !zc || !zd || !zd_noise ,
1458 "Not enough memory, fuzzer tests cancelled");
1460 /* Create initial samples */
1461 RDG_genBuffer(cNoiseBuffer[0], srcBufferSize, 0.00, 0., coreSeed); /* pure noise */
1462 RDG_genBuffer(cNoiseBuffer[1], srcBufferSize, 0.05, 0., coreSeed); /* barely compressible */
1463 RDG_genBuffer(cNoiseBuffer[2], srcBufferSize, compressibility, 0., coreSeed);
1464 RDG_genBuffer(cNoiseBuffer[3], srcBufferSize, 0.95, 0., coreSeed); /* highly compressible */
1465 RDG_genBuffer(cNoiseBuffer[4], srcBufferSize, 1.00, 0., coreSeed); /* sparse content */
1466 memset(copyBuffer, 0x65, copyBufferSize); /* make copyBuffer considered initialized */
1467 ZSTD_initDStream_usingDict(zd, NULL, 0); /* ensure at least one init */
1468 DISPLAYLEVEL(6, "Creating initial context with %i threads \n", nbThreads);
1470 /* catch up testNb */
1471 for (testNb=1; testNb < startTest; testNb++)
1472 FUZ_rand(&coreSeed);
1475 for ( ; (testNb <= nbTests) || (UTIL_clockSpanMicro(startClock) < g_clockTime) ; testNb++ ) {
1477 const BYTE* srcBuffer;
1478 size_t totalTestSize, totalGenSize, cSize;
1479 XXH64_state_t xxhState;
1483 FUZ_rand(&coreSeed);
1484 if (nbTests >= testNb) {
1485 DISPLAYUPDATE(2, "\r%6u/%6u ", testNb, nbTests);
1487 DISPLAYUPDATE(2, "\r%6u ", testNb);
1489 lseed = coreSeed ^ prime32;
1491 /* states full reset (deliberately not synchronized) */
1492 /* some issues can only happen when reusing states */
1493 if ((FUZ_rand(&lseed) & 0xFF) == 131) {
1494 nbThreads = (FUZ_rand(&lseed) % nbThreadsMax) + 1;
1495 DISPLAYLEVEL(5, "Creating new context with %u threads \n", nbThreads);
1496 ZSTDMT_freeCCtx(zc);
1497 zc = ZSTDMT_createCCtx(nbThreads);
1498 CHECK(zc==NULL, "ZSTDMT_createCCtx allocation error")
1500 if ((FUZ_rand(&lseed) & 0xFF) == 132) {
1501 ZSTD_freeDStream(zd);
1502 zd = ZSTD_createDStream();
1503 CHECK(zd==NULL, "ZSTDMT_createCCtx allocation error")
1504 ZSTD_initDStream_usingDict(zd, NULL, 0); /* ensure at least one init */
1507 /* srcBuffer selection [0-4] */
1508 { U32 buffNb = FUZ_rand(&lseed) & 0x7F;
1509 if (buffNb & 7) buffNb=2; /* most common : compressible (P) */
1513 const U32 tnb[2] = { 1, 3 }; /* barely/highly compressible */
1514 buffNb = tnb[buffNb >> 3];
1516 const U32 tnb[2] = { 0, 4 }; /* not compressible / sparse */
1517 buffNb = tnb[buffNb >> 3];
1519 srcBuffer = cNoiseBuffer[buffNb];
1522 /* compression init */
1523 { U32 const testLog = FUZ_rand(&lseed) % maxSrcLog;
1524 U32 const dictLog = FUZ_rand(&lseed) % maxSrcLog;
1525 int const cLevelCandidate = ( FUZ_rand(&lseed)
1526 % (ZSTD_maxCLevel() - (MAX(testLog, dictLog) / 2)) )
1528 int const cLevelThreadAdjusted = cLevelCandidate - (nbThreads * 2) + 2; /* reduce cLevel when multiple threads to reduce memory consumption */
1529 int const cLevelMin = MAX(cLevelThreadAdjusted, 1); /* no negative cLevel yet */
1530 int const cLevel = MIN(cLevelMin, cLevelMax);
1531 maxTestSize = FUZ_rLogLength(&lseed, testLog);
1533 if (FUZ_rand(&lseed)&1) { /* simple init */
1534 int const compressionLevel = (FUZ_rand(&lseed) % 5) + 1;
1535 DISPLAYLEVEL(5, "Init with compression level = %i \n", compressionLevel);
1536 CHECK_Z( ZSTDMT_initCStream(zc, compressionLevel) );
1537 } else { /* advanced init */
1538 /* random dictionary selection */
1539 dictSize = ((FUZ_rand(&lseed)&63)==1) ? FUZ_rLogLength(&lseed, dictLog) : 0;
1540 { size_t const dictStart = FUZ_rand(&lseed) % (srcBufferSize - dictSize);
1541 dict = srcBuffer + dictStart;
1543 { U64 const pledgedSrcSize = (FUZ_rand(&lseed) & 3) ? ZSTD_CONTENTSIZE_UNKNOWN : maxTestSize;
1544 ZSTD_parameters params = ZSTD_getParams(cLevel, pledgedSrcSize, dictSize);
1545 DISPLAYLEVEL(5, "Init with windowLog = %u, pledgedSrcSize = %u, dictSize = %u \n",
1546 params.cParams.windowLog, (unsigned)pledgedSrcSize, (unsigned)dictSize);
1547 params.fParams.checksumFlag = FUZ_rand(&lseed) & 1;
1548 params.fParams.noDictIDFlag = FUZ_rand(&lseed) & 1;
1549 params.fParams.contentSizeFlag = FUZ_rand(&lseed) & 1;
1550 DISPLAYLEVEL(5, "checksumFlag : %u \n", params.fParams.checksumFlag);
1551 CHECK_Z( ZSTDMT_setMTCtxParameter(zc, ZSTDMT_p_overlapLog, FUZ_rand(&lseed) % 12) );
1552 CHECK_Z( ZSTDMT_setMTCtxParameter(zc, ZSTDMT_p_jobSize, FUZ_rand(&lseed) % (2*maxTestSize+1)) ); /* custom job size */
1553 CHECK_Z( ZSTDMT_initCStream_advanced(zc, dict, dictSize, params, pledgedSrcSize) );
1556 /* multi-segments compression test */
1557 XXH64_reset(&xxhState, 0);
1558 { ZSTD_outBuffer outBuff = { cBuffer, cBufferSize, 0 } ;
1560 for (n=0, cSize=0, totalTestSize=0 ; totalTestSize < maxTestSize ; n++) {
1561 /* compress random chunks into randomly sized dst buffers */
1562 { size_t const randomSrcSize = FUZ_randomLength(&lseed, maxSampleLog);
1563 size_t const srcSize = MIN (maxTestSize-totalTestSize, randomSrcSize);
1564 size_t const srcStart = FUZ_rand(&lseed) % (srcBufferSize - srcSize);
1565 size_t const randomDstSize = FUZ_randomLength(&lseed, maxSampleLog);
1566 size_t const dstBuffSize = MIN(cBufferSize - cSize, randomDstSize);
1567 ZSTD_inBuffer inBuff = { srcBuffer+srcStart, srcSize, 0 };
1568 outBuff.size = outBuff.pos + dstBuffSize;
1570 DISPLAYLEVEL(6, "Sending %u bytes to compress \n", (unsigned)srcSize);
1571 CHECK_Z( ZSTDMT_compressStream(zc, &outBuff, &inBuff) );
1572 DISPLAYLEVEL(6, "%u bytes read by ZSTDMT_compressStream \n", (unsigned)inBuff.pos);
1574 XXH64_update(&xxhState, srcBuffer+srcStart, inBuff.pos);
1575 memcpy(copyBuffer+totalTestSize, srcBuffer+srcStart, inBuff.pos);
1576 totalTestSize += inBuff.pos;
1579 /* random flush operation, to mess around */
1580 if ((FUZ_rand(&lseed) & 15) == 0) {
1581 size_t const randomDstSize = FUZ_randomLength(&lseed, maxSampleLog);
1582 size_t const adjustedDstSize = MIN(cBufferSize - cSize, randomDstSize);
1583 size_t const previousPos = outBuff.pos;
1584 outBuff.size = outBuff.pos + adjustedDstSize;
1585 DISPLAYLEVEL(5, "Flushing into dst buffer of size %u \n", (unsigned)adjustedDstSize);
1586 CHECK_Z( ZSTDMT_flushStream(zc, &outBuff) );
1587 assert(outBuff.pos >= previousPos);
1588 DISPLAYLEVEL(6, "%u bytes flushed by ZSTDMT_flushStream \n", (unsigned)(outBuff.pos-previousPos));
1591 /* final frame epilogue */
1592 { size_t remainingToFlush = (size_t)(-1);
1593 while (remainingToFlush) {
1594 size_t const randomDstSize = FUZ_randomLength(&lseed, maxSampleLog);
1595 size_t const adjustedDstSize = MIN(cBufferSize - cSize, randomDstSize);
1596 size_t const previousPos = outBuff.pos;
1597 outBuff.size = outBuff.pos + adjustedDstSize;
1598 DISPLAYLEVEL(5, "Ending into dst buffer of size %u \n", (unsigned)adjustedDstSize);
1599 remainingToFlush = ZSTDMT_endStream(zc, &outBuff);
1600 CHECK (ZSTD_isError(remainingToFlush), "ZSTDMT_endStream error : %s", ZSTD_getErrorName(remainingToFlush));
1601 assert(outBuff.pos >= previousPos);
1602 DISPLAYLEVEL(6, "%u bytes flushed by ZSTDMT_endStream \n", (unsigned)(outBuff.pos-previousPos));
1603 DISPLAYLEVEL(5, "endStream : remainingToFlush : %u \n", (unsigned)remainingToFlush);
1605 crcOrig = XXH64_digest(&xxhState);
1606 cSize = outBuff.pos;
1607 DISPLAYLEVEL(5, "Frame completed : %u bytes compressed into %u bytes \n",
1608 (unsigned)totalTestSize, (unsigned)cSize);
1611 /* multi - fragments decompression test */
1612 assert(totalTestSize < dstBufferSize);
1613 memset(dstBuffer, 170, totalTestSize); /* init dest area */
1614 if (!dictSize /* don't reset if dictionary : could be different */ && (FUZ_rand(&lseed) & 1)) {
1615 CHECK_Z( ZSTD_resetDStream(zd) );
1617 CHECK_Z( ZSTD_initDStream_usingDict(zd, dict, dictSize) );
1619 { size_t decompressionResult = 1;
1620 ZSTD_inBuffer inBuff = { cBuffer, cSize, 0 };
1621 ZSTD_outBuffer outBuff= { dstBuffer, dstBufferSize, 0 };
1622 for (totalGenSize = 0 ; decompressionResult ; ) {
1623 size_t const readCSrcSize = FUZ_randomLength(&lseed, maxSampleLog);
1624 size_t const randomDstSize = FUZ_randomLength(&lseed, maxSampleLog);
1625 size_t const dstBuffSize = MIN(dstBufferSize - totalGenSize, randomDstSize);
1626 inBuff.size = inBuff.pos + readCSrcSize;
1627 outBuff.size = outBuff.pos + dstBuffSize;
1628 DISPLAYLEVEL(6, "ZSTD_decompressStream input %u bytes into outBuff %u bytes \n",
1629 (unsigned)readCSrcSize, (unsigned)dstBuffSize);
1630 decompressionResult = ZSTD_decompressStream(zd, &outBuff, &inBuff);
1631 if (ZSTD_isError(decompressionResult)) {
1632 DISPLAY("ZSTD_decompressStream error : %s \n", ZSTD_getErrorName(decompressionResult));
1633 findDiff(copyBuffer, dstBuffer, totalTestSize);
1635 CHECK (ZSTD_isError(decompressionResult), "decompression error : %s", ZSTD_getErrorName(decompressionResult));
1636 DISPLAYLEVEL(6, "total ingested (inBuff.pos) = %u and produced (outBuff.pos) = %u \n",
1637 (unsigned)inBuff.pos, (unsigned)outBuff.pos);
1639 CHECK (outBuff.pos != totalTestSize,
1640 "decompressed data : wrong size (%u != %u)",
1641 (unsigned)outBuff.pos, (unsigned)totalTestSize );
1642 CHECK (inBuff.pos != cSize,
1643 "compressed data should be fully read (%u != %u)",
1644 (unsigned)inBuff.pos, (unsigned)cSize );
1645 { U64 const crcDest = XXH64(dstBuffer, totalTestSize, 0);
1646 if (crcDest!=crcOrig) findDiff(copyBuffer, dstBuffer, totalTestSize);
1647 CHECK (crcDest!=crcOrig, "decompressed data corrupted");
1650 /*===== noisy/erroneous src decompression test =====*/
1652 /* add some noise */
1653 { U32 const nbNoiseChunks = (FUZ_rand(&lseed) & 7) + 2;
1654 U32 nn; for (nn=0; nn<nbNoiseChunks; nn++) {
1655 size_t const randomNoiseSize = FUZ_randomLength(&lseed, maxSampleLog);
1656 size_t const noiseSize = MIN((cSize/3) , randomNoiseSize);
1657 size_t const noiseStart = FUZ_rand(&lseed) % (srcBufferSize - noiseSize);
1658 size_t const cStart = FUZ_rand(&lseed) % (cSize - noiseSize);
1659 memcpy(cBuffer+cStart, srcBuffer+noiseStart, noiseSize);
1662 /* try decompression on noisy data */
1663 CHECK_Z( ZSTD_initDStream(zd_noise) ); /* note : no dictionary */
1664 { ZSTD_inBuffer inBuff = { cBuffer, cSize, 0 };
1665 ZSTD_outBuffer outBuff= { dstBuffer, dstBufferSize, 0 };
1666 while (outBuff.pos < dstBufferSize) {
1667 size_t const randomCSrcSize = FUZ_randomLength(&lseed, maxSampleLog);
1668 size_t const randomDstSize = FUZ_randomLength(&lseed, maxSampleLog);
1669 size_t const adjustedDstSize = MIN(dstBufferSize - outBuff.pos, randomDstSize);
1670 size_t const adjustedCSrcSize = MIN(cSize - inBuff.pos, randomCSrcSize);
1671 outBuff.size = outBuff.pos + adjustedDstSize;
1672 inBuff.size = inBuff.pos + adjustedCSrcSize;
1673 { size_t const decompressError = ZSTD_decompressStream(zd, &outBuff, &inBuff);
1674 if (ZSTD_isError(decompressError)) break; /* error correctly detected */
1675 /* No forward progress possible */
1676 if (outBuff.pos < outBuff.size && inBuff.pos == cSize) break;
1678 DISPLAY("\r%u fuzzer tests completed \n", testNb);
1681 ZSTDMT_freeCCtx(zc);
1682 ZSTD_freeDStream(zd);
1683 ZSTD_freeDStream(zd_noise);
1684 free(cNoiseBuffer[0]);
1685 free(cNoiseBuffer[1]);
1686 free(cNoiseBuffer[2]);
1687 free(cNoiseBuffer[3]);
1688 free(cNoiseBuffer[4]);
1699 /** If useOpaqueAPI, sets param in cctxParams.
1700 * Otherwise, sets the param in zc. */
1701 static size_t setCCtxParameter(ZSTD_CCtx* zc, ZSTD_CCtx_params* cctxParams,
1702 ZSTD_cParameter param, unsigned value,
1706 return ZSTD_CCtxParam_setParameter(cctxParams, param, value);
1708 return ZSTD_CCtx_setParameter(zc, param, value);
1712 /* Tests for ZSTD_compress_generic() API */
1713 static int fuzzerTests_newAPI(U32 seed, int nbTests, int startTest,
1714 double compressibility, int bigTests)
1716 U32 const maxSrcLog = bigTests ? 24 : 22;
1717 static const U32 maxSampleLog = 19;
1718 size_t const srcBufferSize = (size_t)1<<maxSrcLog;
1719 BYTE* cNoiseBuffer[5];
1720 size_t const copyBufferSize= srcBufferSize + (1<<maxSampleLog);
1721 BYTE* const copyBuffer = (BYTE*)malloc (copyBufferSize);
1722 size_t const cBufferSize = ZSTD_compressBound(srcBufferSize);
1723 BYTE* const cBuffer = (BYTE*)malloc (cBufferSize);
1724 size_t const dstBufferSize = srcBufferSize;
1725 BYTE* const dstBuffer = (BYTE*)malloc (dstBufferSize);
1728 U32 coreSeed = seed;
1729 ZSTD_CCtx* zc = ZSTD_createCCtx(); /* will be reset sometimes */
1730 ZSTD_DStream* zd = ZSTD_createDStream(); /* will be reset sometimes */
1731 ZSTD_DStream* const zd_noise = ZSTD_createDStream();
1732 UTIL_time_t const startClock = UTIL_getTime();
1733 const BYTE* dict = NULL; /* can keep same dict on 2 consecutive tests */
1734 size_t dictSize = 0;
1736 U32 windowLogMalus = 0; /* can survive between 2 loops */
1737 U32 const cLevelMax = bigTests ? (U32)ZSTD_maxCLevel()-1 : g_cLevelMax_smallTests;
1738 U32 const nbThreadsMax = bigTests ? 4 : 2;
1739 ZSTD_CCtx_params* cctxParams = ZSTD_createCCtxParams();
1742 cNoiseBuffer[0] = (BYTE*)malloc (srcBufferSize);
1743 cNoiseBuffer[1] = (BYTE*)malloc (srcBufferSize);
1744 cNoiseBuffer[2] = (BYTE*)malloc (srcBufferSize);
1745 cNoiseBuffer[3] = (BYTE*)malloc (srcBufferSize);
1746 cNoiseBuffer[4] = (BYTE*)malloc (srcBufferSize);
1747 CHECK (!cNoiseBuffer[0] || !cNoiseBuffer[1] || !cNoiseBuffer[2] || !cNoiseBuffer[3] || !cNoiseBuffer[4] ||
1748 !copyBuffer || !dstBuffer || !cBuffer || !zc || !zd || !zd_noise ,
1749 "Not enough memory, fuzzer tests cancelled");
1751 /* Create initial samples */
1752 RDG_genBuffer(cNoiseBuffer[0], srcBufferSize, 0.00, 0., coreSeed); /* pure noise */
1753 RDG_genBuffer(cNoiseBuffer[1], srcBufferSize, 0.05, 0., coreSeed); /* barely compressible */
1754 RDG_genBuffer(cNoiseBuffer[2], srcBufferSize, compressibility, 0., coreSeed);
1755 RDG_genBuffer(cNoiseBuffer[3], srcBufferSize, 0.95, 0., coreSeed); /* highly compressible */
1756 RDG_genBuffer(cNoiseBuffer[4], srcBufferSize, 1.00, 0., coreSeed); /* sparse content */
1757 memset(copyBuffer, 0x65, copyBufferSize); /* make copyBuffer considered initialized */
1758 CHECK_Z( ZSTD_initDStream_usingDict(zd, NULL, 0) ); /* ensure at least one init */
1760 /* catch up testNb */
1761 for (testNb=1; testNb < startTest; testNb++)
1762 FUZ_rand(&coreSeed);
1765 for ( ; (testNb <= nbTests) || (UTIL_clockSpanMicro(startClock) < g_clockTime) ; testNb++ ) {
1768 const BYTE* srcBuffer;
1769 size_t totalTestSize, totalGenSize, cSize;
1770 XXH64_state_t xxhState;
1772 U32 resetAllowed = 1;
1774 ZSTD_parameters savedParams;
1777 if (nbTests >= testNb) { DISPLAYUPDATE(2, "\r%6u/%6u ", testNb, nbTests); }
1778 else { DISPLAYUPDATE(2, "\r%6u ", testNb); }
1779 FUZ_rand(&coreSeed);
1780 lseed = coreSeed ^ prime32;
1781 DISPLAYLEVEL(5, " *** Test %u *** \n", testNb);
1782 opaqueAPI = FUZ_rand(&lseed) & 1;
1784 /* states full reset (deliberately not synchronized) */
1785 /* some issues can only happen when reusing states */
1786 if ((FUZ_rand(&lseed) & 0xFF) == 131) {
1787 DISPLAYLEVEL(5, "Creating new context \n");
1789 zc = ZSTD_createCCtx();
1790 CHECK(zc == NULL, "ZSTD_createCCtx allocation error");
1793 if ((FUZ_rand(&lseed) & 0xFF) == 132) {
1794 ZSTD_freeDStream(zd);
1795 zd = ZSTD_createDStream();
1796 CHECK(zd == NULL, "ZSTD_createDStream allocation error");
1797 ZSTD_initDStream_usingDict(zd, NULL, 0); /* ensure at least one init */
1800 /* srcBuffer selection [0-4] */
1801 { U32 buffNb = FUZ_rand(&lseed) & 0x7F;
1802 if (buffNb & 7) buffNb=2; /* most common : compressible (P) */
1806 const U32 tnb[2] = { 1, 3 }; /* barely/highly compressible */
1807 buffNb = tnb[buffNb >> 3];
1809 const U32 tnb[2] = { 0, 4 }; /* not compressible / sparse */
1810 buffNb = tnb[buffNb >> 3];
1812 srcBuffer = cNoiseBuffer[buffNb];
1815 /* compression init */
1816 CHECK_Z( ZSTD_CCtx_loadDictionary(zc, NULL, 0) ); /* cancel previous dict /*/
1817 if ((FUZ_rand(&lseed)&1) /* at beginning, to keep same nb of rand */
1818 && oldTestLog /* at least one test happened */
1820 /* just set a compression level */
1821 maxTestSize = FUZ_randomLength(&lseed, oldTestLog+2);
1822 if (maxTestSize >= srcBufferSize) maxTestSize = srcBufferSize-1;
1823 { int const compressionLevel = (FUZ_rand(&lseed) % 5) + 1;
1824 DISPLAYLEVEL(5, "t%u : compression level : %i \n", testNb, compressionLevel);
1825 CHECK_Z (setCCtxParameter(zc, cctxParams, ZSTD_c_compressionLevel, compressionLevel, opaqueAPI) );
1828 U32 const testLog = FUZ_rand(&lseed) % maxSrcLog;
1829 U32 const dictLog = FUZ_rand(&lseed) % maxSrcLog;
1830 U32 const cLevelCandidate = (FUZ_rand(&lseed) %
1832 (MAX(testLog, dictLog) / 2))) +
1834 int const cLevel = MIN(cLevelCandidate, cLevelMax);
1835 DISPLAYLEVEL(5, "t%i: base cLevel : %u \n", testNb, cLevel);
1836 maxTestSize = FUZ_rLogLength(&lseed, testLog);
1837 DISPLAYLEVEL(5, "t%i: maxTestSize : %u \n", testNb, (unsigned)maxTestSize);
1838 oldTestLog = testLog;
1839 /* random dictionary selection */
1840 dictSize = ((FUZ_rand(&lseed)&63)==1) ? FUZ_rLogLength(&lseed, dictLog) : 0;
1841 { size_t const dictStart = FUZ_rand(&lseed) % (srcBufferSize - dictSize);
1842 dict = srcBuffer + dictStart;
1843 if (!dictSize) dict=NULL;
1845 { U64 const pledgedSrcSize = (FUZ_rand(&lseed) & 3) ? ZSTD_CONTENTSIZE_UNKNOWN : maxTestSize;
1846 ZSTD_compressionParameters cParams = ZSTD_getCParams(cLevel, pledgedSrcSize, dictSize);
1847 const U32 windowLogMax = bigTests ? 24 : 20;
1848 const U32 searchLogMax = bigTests ? 15 : 13;
1850 DISPLAYLEVEL(5, "t%u: with dictionary of size : %zu \n", testNb, dictSize);
1852 /* mess with compression parameters */
1853 cParams.windowLog += (FUZ_rand(&lseed) & 3) - 1;
1854 cParams.windowLog = MIN(windowLogMax, cParams.windowLog);
1855 cParams.hashLog += (FUZ_rand(&lseed) & 3) - 1;
1856 cParams.chainLog += (FUZ_rand(&lseed) & 3) - 1;
1857 cParams.searchLog += (FUZ_rand(&lseed) & 3) - 1;
1858 cParams.searchLog = MIN(searchLogMax, cParams.searchLog);
1859 cParams.minMatch += (FUZ_rand(&lseed) & 3) - 1;
1860 cParams.targetLength = (U32)((cParams.targetLength + 1 ) * (0.5 + ((double)(FUZ_rand(&lseed) & 127) / 128)));
1861 cParams = ZSTD_adjustCParams(cParams, pledgedSrcSize, dictSize);
1863 if (FUZ_rand(&lseed) & 1) {
1864 DISPLAYLEVEL(5, "t%u: windowLog : %u \n", testNb, cParams.windowLog);
1865 CHECK_Z( setCCtxParameter(zc, cctxParams, ZSTD_c_windowLog, cParams.windowLog, opaqueAPI) );
1866 assert(cParams.windowLog >= ZSTD_WINDOWLOG_MIN); /* guaranteed by ZSTD_adjustCParams() */
1867 windowLogMalus = (cParams.windowLog - ZSTD_WINDOWLOG_MIN) / 5;
1869 if (FUZ_rand(&lseed) & 1) {
1870 DISPLAYLEVEL(5, "t%u: hashLog : %u \n", testNb, cParams.hashLog);
1871 CHECK_Z( setCCtxParameter(zc, cctxParams, ZSTD_c_hashLog, cParams.hashLog, opaqueAPI) );
1873 if (FUZ_rand(&lseed) & 1) {
1874 DISPLAYLEVEL(5, "t%u: chainLog : %u \n", testNb, cParams.chainLog);
1875 CHECK_Z( setCCtxParameter(zc, cctxParams, ZSTD_c_chainLog, cParams.chainLog, opaqueAPI) );
1877 if (FUZ_rand(&lseed) & 1) CHECK_Z( setCCtxParameter(zc, cctxParams, ZSTD_c_searchLog, cParams.searchLog, opaqueAPI) );
1878 if (FUZ_rand(&lseed) & 1) CHECK_Z( setCCtxParameter(zc, cctxParams, ZSTD_c_minMatch, cParams.minMatch, opaqueAPI) );
1879 if (FUZ_rand(&lseed) & 1) CHECK_Z( setCCtxParameter(zc, cctxParams, ZSTD_c_targetLength, cParams.targetLength, opaqueAPI) );
1881 /* mess with long distance matching parameters */
1883 if (FUZ_rand(&lseed) & 1) CHECK_Z( setCCtxParameter(zc, cctxParams, ZSTD_c_enableLongDistanceMatching, FUZ_rand(&lseed) & 63, opaqueAPI) );
1884 if (FUZ_rand(&lseed) & 3) CHECK_Z( setCCtxParameter(zc, cctxParams, ZSTD_c_ldmHashLog, FUZ_randomClampedLength(&lseed, ZSTD_HASHLOG_MIN, 23), opaqueAPI) );
1885 if (FUZ_rand(&lseed) & 3) CHECK_Z( setCCtxParameter(zc, cctxParams, ZSTD_c_ldmMinMatch, FUZ_randomClampedLength(&lseed, ZSTD_LDM_MINMATCH_MIN, ZSTD_LDM_MINMATCH_MAX), opaqueAPI) );
1886 if (FUZ_rand(&lseed) & 3) CHECK_Z( setCCtxParameter(zc, cctxParams, ZSTD_c_ldmBucketSizeLog, FUZ_randomClampedLength(&lseed, ZSTD_LDM_BUCKETSIZELOG_MIN, ZSTD_LDM_BUCKETSIZELOG_MAX), opaqueAPI) );
1887 if (FUZ_rand(&lseed) & 3) CHECK_Z( setCCtxParameter(zc, cctxParams, ZSTD_c_ldmHashRateLog, FUZ_randomClampedLength(&lseed, ZSTD_LDM_HASHRATELOG_MIN, ZSTD_LDM_HASHRATELOG_MAX), opaqueAPI) );
1890 /* mess with frame parameters */
1891 if (FUZ_rand(&lseed) & 1) {
1892 int const checksumFlag = FUZ_rand(&lseed) & 1;
1893 DISPLAYLEVEL(5, "t%u: frame checksum : %u \n", testNb, checksumFlag);
1894 CHECK_Z( setCCtxParameter(zc, cctxParams, ZSTD_c_checksumFlag, checksumFlag, opaqueAPI) );
1896 if (FUZ_rand(&lseed) & 1) CHECK_Z( setCCtxParameter(zc, cctxParams, ZSTD_c_dictIDFlag, FUZ_rand(&lseed) & 1, opaqueAPI) );
1897 if (FUZ_rand(&lseed) & 1) CHECK_Z( setCCtxParameter(zc, cctxParams, ZSTD_c_contentSizeFlag, FUZ_rand(&lseed) & 1, opaqueAPI) );
1898 if (FUZ_rand(&lseed) & 1) {
1899 DISPLAYLEVEL(5, "t%u: pledgedSrcSize : %u \n", testNb, (unsigned)pledgedSrcSize);
1900 CHECK_Z( ZSTD_CCtx_setPledgedSrcSize(zc, pledgedSrcSize) );
1903 /* multi-threading parameters. Only adjust ocassionally for small tests. */
1904 if (bigTests || (FUZ_rand(&lseed) & 0xF) == 0xF) {
1905 U32 const nbThreadsCandidate = (FUZ_rand(&lseed) & 4) + 1;
1906 U32 const nbThreadsAdjusted = (windowLogMalus < nbThreadsCandidate) ? nbThreadsCandidate - windowLogMalus : 1;
1907 int const nbThreads = MIN(nbThreadsAdjusted, nbThreadsMax);
1908 DISPLAYLEVEL(5, "t%i: nbThreads : %u \n", testNb, nbThreads);
1909 CHECK_Z( setCCtxParameter(zc, cctxParams, ZSTD_c_nbWorkers, nbThreads, opaqueAPI) );
1910 if (nbThreads > 1) {
1911 U32 const jobLog = FUZ_rand(&lseed) % (testLog+1);
1912 CHECK_Z( setCCtxParameter(zc, cctxParams, ZSTD_c_overlapLog, FUZ_rand(&lseed) % 10, opaqueAPI) );
1913 CHECK_Z( setCCtxParameter(zc, cctxParams, ZSTD_c_jobSize, (U32)FUZ_rLogLength(&lseed, jobLog), opaqueAPI) );
1916 /* Enable rsyncable mode 1 in 4 times. */
1917 setCCtxParameter(zc, cctxParams, ZSTD_c_rsyncable, (FUZ_rand(&lseed) % 4 == 0), opaqueAPI);
1919 if (FUZ_rand(&lseed) & 1) CHECK_Z( setCCtxParameter(zc, cctxParams, ZSTD_c_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_c_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_compressStream2(zc, &outBuff, &inBuff, flush) );
1965 DISPLAYLEVEL(6, "t%u: compress consumed %u bytes (total : %u) ; flush: %u (total : %u) \n",
1966 testNb, (unsigned)inBuff.pos, (unsigned)(totalTestSize + inBuff.pos), (unsigned)flush, (unsigned)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, (unsigned)adjustedDstSize);
1981 remainingToFlush = ZSTD_compressStream2(zc, &outBuff, &inBuff, ZSTD_e_end);
1982 DISPLAYLEVEL(6, "t%u: Total flushed so far : %u bytes \n", testNb, (unsigned)outBuff.pos);
1983 CHECK( ZSTD_isError(remainingToFlush),
1984 "ZSTD_compressStream2 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:%p) \n", 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 (unsigned)readCSrcSize, (unsigned)inBuff.pos, (unsigned)cSize);
2014 decompressionResult = ZSTD_decompressStream(zd, &outBuff, &inBuff);
2015 DISPLAYLEVEL(6, "so far: consumed = %u, produced = %u \n",
2016 (unsigned)inBuff.pos, (unsigned)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 ", (unsigned)inBuff.pos, (unsigned)cSize);
2024 CHECK (inBuff.pos != cSize, "compressed data should be fully read (%u != %u)", (unsigned)inBuff.pos, (unsigned)cSize);
2025 CHECK (outBuff.pos != totalTestSize, "decompressed data : wrong size (%u != %u)", (unsigned)outBuff.pos, (unsigned)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", (unsigned)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");