]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - sys/contrib/zstd/tests/zstreamtest.c
Update our devicetree to 4.19 for arm and arm64
[FreeBSD/FreeBSD.git] / sys / contrib / zstd / tests / zstreamtest.c
1 /*
2  * Copyright (c) 2016-present, Yann Collet, Facebook, Inc.
3  * All rights reserved.
4  *
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.
9  */
10
11
12 /*-************************************
13  *  Compiler specific
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 */
19 #endif
20
21
22 /*-************************************
23  *  Includes
24  **************************************/
25 #include <stdlib.h>       /* free */
26 #include <stdio.h>        /* fgets, sscanf */
27 #include <string.h>       /* strcmp */
28 #include <assert.h>       /* assert */
29 #include "mem.h"
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_* */
38 #include "seqgen.h"
39 #include "util.h"
40
41
42 /*-************************************
43  *  Constants
44  **************************************/
45 #define KB *(1U<<10)
46 #define MB *(1U<<20)
47 #define GB *(1U<<30)
48
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;
54
55
56 /*-************************************
57  *  Display Macros
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;
64
65 static const U64 g_refreshRate = SEC_TO_MICRO / 6;
66 static UTIL_time_t g_displayClock = UTIL_TIME_INITIALIZER;
67
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); } }
72
73 static U64 g_clockTime = 0;
74
75
76 /*-*******************************************************
77  *  Check macros
78  *********************************************************/
79 #undef MIN
80 #undef MAX
81 #define MIN(a,b) ((a)<(b)?(a):(b))
82 #define MAX(a,b) ((a)>(b)?(a):(b))
83 /*! FUZ_rand() :
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)
88 {
89     static const U32 prime2 = 2246822519U;
90     U32 rand32 = *seedPtr;
91     rand32 *= prime32;
92     rand32 += prime2;
93     rand32  = FUZ_rotl32(rand32, 13);
94     *seedPtr = rand32;
95     return rand32 >> 5;
96 }
97
98 #define CHECK(cond, ...) {                                   \
99     if (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;                                  \
105 }   }
106
107 #define CHECK_Z(f) {                                         \
108     size_t const err = f;                                    \
109     CHECK(ZSTD_isError(err), "%s : %s ",                     \
110           #f, ZSTD_getErrorName(err));                       \
111 }
112
113 #define CHECK_RET(ret, cond, ...) {                          \
114     if (cond) {                                              \
115         DISPLAY("Error %llu => ", (unsigned long long)ret);  \
116         DISPLAY(__VA_ARGS__);                                \
117         DISPLAY(" (line %u)\n", __LINE__);                   \
118         return ret;                                          \
119 }   }
120
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));                       \
125 }
126
127
128 /*======================================================
129  *   Basic Unit tests
130  *======================================================*/
131
132 typedef struct {
133     void* start;
134     size_t size;
135     size_t filled;
136 } buffer_t;
137
138 static const buffer_t kBuffNull = { NULL, 0 , 0 };
139
140 static void FUZ_freeDictionary(buffer_t dict)
141 {
142     free(dict.start);
143 }
144
145 static buffer_t FUZ_createDictionary(const void* src, size_t srcSize, size_t blockSize, size_t requestedDictSize)
146 {
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; }
153     {   size_t nb;
154         for (nb=0; nb<nbBlocks-1; nb++) blockSizes[nb] = blockSize;
155         blockSizes[nbBlocks-1] = srcSize - (blockSize * (nbBlocks-1));
156     }
157     {   size_t const dictSize = ZDICT_trainFromBuffer(dict.start, requestedDictSize, src, blockSizes, (unsigned)nbBlocks);
158         free(blockSizes);
159         if (ZDICT_isError(dictSize)) { FUZ_freeDictionary(dict); return kBuffNull; }
160         dict.size = requestedDictSize;
161         dict.filled = dictSize;
162         return dict;
163     }
164 }
165
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)
170 {
171     static BYTE compressed[1024];
172     static BYTE uncompressed[1024];
173
174     ZSTD_inBuffer cin = {data, size, 0};
175     size_t cret;
176
177     do {
178         ZSTD_outBuffer cout = {compressed, sizeof(compressed), 0};
179         ZSTD_inBuffer din = {compressed, 0, 0};
180         ZSTD_outBuffer dout = {uncompressed, 0, 0};
181
182         cret = ZSTD_compress_generic(cctx, &cout, &cin, endOp);
183         if (ZSTD_isError(cret))
184             return cret;
185
186         din.size = cout.pos;
187         while (din.pos < din.size || (endOp == ZSTD_e_end && cret == 0)) {
188             size_t dret;
189
190             dout.pos = 0;
191             dout.size = sizeof(uncompressed);
192             dret = ZSTD_decompressStream(dctx, &dout, &din);
193             if (ZSTD_isError(dret))
194                 return dret;
195             XXH64_update(xxh, dout.dst, dout.pos);
196             if (dret == 0)
197                 break;
198         }
199     } while (cin.pos < cin.size || (endOp != ZSTD_e_continue && cret != 0));
200     return 0;
201 }
202
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)
207 {
208     static BYTE data[1024];
209     size_t gen;
210
211     do {
212         SEQ_outBuffer sout = {data, sizeof(data), 0};
213         size_t ret;
214         gen = SEQ_gen(seq, type, value, &sout);
215
216         ret = SEQ_roundTrip(cctx, dctx, xxh, sout.dst, sout.pos, ZSTD_e_continue);
217         if (ZSTD_isError(ret))
218             return ret;
219     } while (gen != 0);
220
221     return 0;
222 }
223
224 static size_t getCCtxParams(ZSTD_CCtx* zc, ZSTD_parameters* savedParams)
225 {
226     unsigned value;
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;
235
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;
240     return 0;
241 }
242
243 static U32 badParameters(ZSTD_CCtx* zc, ZSTD_parameters const savedParams)
244 {
245     ZSTD_parameters params;
246     if (ZSTD_isError(getCCtxParams(zc, &params))) 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");
253
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");
257     return 0;
258 }
259
260 static int basicUnitTests(U32 seed, double compressibility)
261 {
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);
269     size_t cSize;
270     int testResult = 0;
271     U32 testNb = 1;
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);
276
277     ZSTD_inBuffer  inBuff, inBuff2;
278     ZSTD_outBuffer outBuff;
279     buffer_t dictionary = kBuffNull;
280     size_t const dictSize = 128 KB;
281     unsigned dictID = 0;
282
283     /* Create compressible test buffer */
284     if (!CNBuffer || !compressedBuffer || !decodedBuffer || !zc || !zd) {
285         DISPLAY("Not enough memory, aborting \n");
286         goto _output_error;
287     }
288     RDG_genBuffer(CNBuffer, CNBufferSize, compressibility, 0., seed);
289
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");
295         goto _output_error;
296     }
297     dictID = ZDICT_getDictID(dictionary.start, dictionary.filled);
298
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;
304     outBuff.pos = 0;
305     inBuff.src = CNBuffer;
306     inBuff.size = CNBufferSize;
307     inBuff.pos = 0;
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);
313
314     /* generate skippable frame */
315     MEM_writeLE32(compressedBuffer, ZSTD_MAGIC_SKIPPABLE_START);
316     MEM_writeLE32(((char*)compressedBuffer)+4, (U32)skippableFrameSize);
317     cSize = skippableFrameSize + 8;
318
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;
325     outBuff.pos = 0;
326     inBuff.src = CNBuffer;
327     inBuff.size = CNBufferSize;
328     inBuff.pos = 0;
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);
335
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));
344     }
345
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);
350     }
351
352     /* Attempt bad compression parameters */
353     DISPLAYLEVEL(3, "test%3i : use bad compression parameters : ", testNb++);
354     {   size_t r;
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));
360     }
361
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;
366     inBuff.size = cSize;
367     inBuff.pos = 0;
368     outBuff.dst = decodedBuffer;
369     outBuff.size = CNBufferSize;
370     outBuff.pos = 0;
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;
374     }
375     if (outBuff.pos != 0) goto _output_error;   /* skippable frame output len is 0 */
376     DISPLAYLEVEL(3, "OK \n");
377
378     /* Basic decompression test */
379     inBuff2 = inBuff;
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");
388
389     /* Re-use without init */
390     DISPLAYLEVEL(3, "test%3i : decompress again without init (re-use previous settings): ", testNb++);
391     outBuff.pos = 0;
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");
397
398     /* check regenerated data is byte exact */
399     DISPLAYLEVEL(3, "test%3i : check decompressed result : ", testNb++);
400     {   size_t i;
401         for (i=0; i<CNBufferSize; i++) {
402             if (((BYTE*)decodedBuffer)[i] != ((BYTE*)CNBuffer)[i]) goto _output_error;
403     }   }
404     DISPLAYLEVEL(3, "OK \n");
405
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);
418     }   }
419
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);
424     }
425
426     /* Decompression by small increment */
427     DISPLAYLEVEL(3, "test%3i : decompress byte-by-byte : ", testNb++);
428     {   /* skippable frame */
429         size_t r = 1;
430         ZSTD_initDStream_usingDict(zd, CNBuffer, dictSize);
431         inBuff.src = compressedBuffer;
432         outBuff.dst = decodedBuffer;
433         inBuff.pos = 0;
434         outBuff.pos = 0;
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;
443         }
444         /* normal frame */
445         ZSTD_initDStream_usingDict(zd, CNBuffer, dictSize);
446         r=1;
447         while (r) {
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;
455         }
456     }
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");
462
463     /* check regenerated data is byte exact */
464     DISPLAYLEVEL(3, "test%3i : check decompressed result : ", testNb++);
465     {   size_t i;
466         for (i=0; i<CNBufferSize; i++) {
467             if (((BYTE*)decodedBuffer)[i] != ((BYTE*)CNBuffer)[i]) goto _output_error;;
468     }   }
469     DISPLAYLEVEL(3, "OK \n");
470
471     /* Decompression forward progress */
472     DISPLAYLEVEL(3, "test%3i : generate error when ZSTD_decompressStream() doesn't progress : ", testNb++);
473     {   /* skippable frame */
474         size_t r = 0;
475         int decNb = 0;
476         int const maxDec = 100;
477         inBuff.src = compressedBuffer;
478         inBuff.size = cSize;
479         inBuff.pos = 0;
480
481         outBuff.dst = decodedBuffer;
482         outBuff.pos = 0;
483         outBuff.size = CNBufferSize-1;   /* 1 byte missing */
484
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;
489         }
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 */
492     }
493     DISPLAYLEVEL(3, "OK \n");
494
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;
500     outBuff.pos = 0;
501     inBuff.src = CNBuffer;
502     inBuff.size = CNBufferSize;
503     inBuff.pos = 0;
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);
511
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;
517     outBuff.pos = 0;
518     inBuff.src = CNBuffer;
519     inBuff.size = CNBufferSize;
520     inBuff.pos = 0;
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)); }
526
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;
532     outBuff.pos = 0;
533     inBuff.src = CNBuffer;
534     inBuff.size = CNBufferSize;
535     inBuff.pos = 0;
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));
539     }
540
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;
547         outBuff.pos = 0;
548         inBuff.src = CNBuffer;
549         inBuff.size = CNBufferSize;
550         inBuff.pos = 0;
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));
554     }   }
555
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 */
561     /* use 1 */
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;
567         inBuff.pos = 0;
568         outBuff.dst = (char*)(compressedBuffer)+cSize;
569         outBuff.size = ZSTD_compressBound(inSize);
570         outBuff.pos = 0;
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 */
577     }
578     /* use 2 */
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;
584         inBuff.pos = 0;
585         outBuff.dst = (char*)(compressedBuffer)+cSize;
586         outBuff.size = ZSTD_compressBound(inSize);
587         outBuff.pos = 0;
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 */
594     }
595     DISPLAYLEVEL(3, "OK \n");
596
597     /* CDict scenario */
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;
605         outBuff.pos = 0;
606         inBuff.src = CNBuffer;
607         inBuff.size = CNBufferSize;
608         inBuff.pos = 0;
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 */
615         }
616         cSize = outBuff.pos;
617         ZSTD_freeCDict(cdict);
618         DISPLAYLEVEL(3, "OK (%u bytes : %.2f%%)\n", (U32)cSize, (double)cSize/CNBufferSize*100);
619     }
620
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);
625     }
626
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);
631     }
632
633     /* DDict scenario */
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;
640         outBuff.pos = 0;
641         inBuff.src = compressedBuffer;
642         inBuff.size = cSize;
643         inBuff.pos = 0;
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");
650     }
651
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");
657
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;
664     outBuff.pos = 0;
665     inBuff.src = compressedBuffer;
666     inBuff.size = cSize;
667     inBuff.pos = 0;
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 */
672
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 */
676         int level;
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);
682             size_t size;
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;
690                 outBuff.pos = 0;
691                 inBuff.src = CNBuffer;
692                 inBuff.size = size;
693                 inBuff.pos = 0;
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;
705                 }   }
706                 ZSTD_freeCCtx(cctx);
707             }
708             ZSTD_freeCDict(cdict);
709         }
710         ZSTD_freeDCtx(dctx);
711     }
712     DISPLAYLEVEL(3, "OK\n");
713
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;
722         outBuff.pos = 0;
723         inBuff.src = CNBuffer;
724         inBuff.size = CNBufferSize;
725         inBuff.pos = 0;
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 */
730         cSize = outBuff.pos;
731         ZSTD_freeCDict(cdict);
732         DISPLAYLEVEL(3, "OK (%u bytes : %.2f%%)\n", (U32)cSize, (double)cSize/CNBufferSize*100);
733     }
734
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;
738     }
739     DISPLAYLEVEL(3, "OK (not detected) \n");
740
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));
745     }
746
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;
751     outBuff.pos = 0;
752     inBuff.src = CNBuffer;
753     inBuff.size = CNBufferSize;
754     inBuff.pos = 0;
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 */
757     cSize = outBuff.pos;
758     DISPLAYLEVEL(3, "OK (%u bytes : %.2f%%)\n", (U32)cSize, (double)cSize/CNBufferSize*100);
759
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;
764     outBuff.pos = 0;
765     inBuff.src = compressedBuffer;
766     inBuff.size = cSize;
767     inBuff.pos = 0;
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");
772
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));
777     }
778
779     DISPLAYLEVEL(3, "test%3i : compress again with ZSTD_compress_generic : ", testNb++);
780     outBuff.dst = compressedBuffer;
781     outBuff.size = compressedBufferSize;
782     outBuff.pos = 0;
783     inBuff.src = CNBuffer;
784     inBuff.size = CNBufferSize;
785     inBuff.pos = 0;
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 */
788     cSize = outBuff.pos;
789     DISPLAYLEVEL(3, "OK (%u bytes : %.2f%%)\n", (U32)cSize, (double)cSize/CNBufferSize*100);
790
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");
794
795     /* Empty srcSize */
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;
803     outBuff.pos = 0;
804     inBuff.src = CNBuffer;
805     inBuff.size = 0;
806     inBuff.pos = 0;
807     CHECK_Z( ZSTD_compressStream(zc, &outBuff, &inBuff) );
808     if (ZSTD_endStream(zc, &outBuff) != 0) goto _output_error;
809     cSize = outBuff.pos;
810     if (ZSTD_findDecompressedSize(compressedBuffer, cSize) != 0) goto _output_error;
811     DISPLAYLEVEL(3, "OK \n");
812
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;
819     inBuff.size = 0;
820     inBuff.pos = 0;
821     outBuff.dst = compressedBuffer;
822     outBuff.size = compressedBufferSize;
823     outBuff.pos = 0;
824     CHECK_Z( ZSTD_compressStream(zc, &outBuff, &inBuff) );
825     if (ZSTD_endStream(zc, &outBuff) != 0) goto _output_error;
826     cSize = outBuff.pos;
827     if (ZSTD_findDecompressedSize(compressedBuffer, cSize) != 0) goto _output_error;
828
829     ZSTD_resetCStream(zc, 0); /* resetCStream should treat 0 as unknown */
830     outBuff.dst = compressedBuffer;
831     outBuff.size = compressedBufferSize;
832     outBuff.pos = 0;
833     inBuff.src = CNBuffer;
834     inBuff.size = 0;
835     inBuff.pos = 0;
836     CHECK_Z( ZSTD_compressStream(zc, &outBuff, &inBuff) );
837     if (ZSTD_endStream(zc, &outBuff) != 0) goto _output_error;
838     cSize = outBuff.pos;
839     if (ZSTD_findDecompressedSize(compressedBuffer, cSize) != ZSTD_CONTENTSIZE_UNKNOWN) goto _output_error;
840     DISPLAYLEVEL(3, "OK \n");
841
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);
845         unsigned jobSize;
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");
851     }
852     outBuff.dst = compressedBuffer;
853     outBuff.size = compressedBufferSize;
854     outBuff.pos = 0;
855     inBuff.src = CNBuffer;
856     inBuff.size = CNBufferSize;
857     inBuff.pos = 0;
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 */
860     }
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 */
864     }
865     DISPLAYLEVEL(3, "OK \n");
866
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;
885         outBuff.pos = 0;
886         inBuff.src = CNBuffer;
887         inBuff.size = srcSize; assert(srcSize < COMPRESSIBLE_NOISE_LENGTH);
888         inBuff.pos = 0;
889     }
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);
897     }
898     if (inBuff.pos != inBuff.size) goto _output_error;   /* entire input should be consumed */
899     cSize = outBuff.pos;
900     DISPLAYLEVEL(3, "OK \n");
901
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;
909         outBuff.pos = 0;
910         inBuff.src = compressedBuffer;
911         inBuff.pos = 0;
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) );
915         inBuff.size = cSize;
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);
919     }
920     DISPLAYLEVEL(3, "OK \n");
921
922     DISPLAYLEVEL(3, "test%3i : check dictionary FSE tables can represent every code : ", testNb++);
923     {   unsigned const kMaxWindowLog = 24;
924         unsigned value;
925         ZSTD_compressionParameters cParams = ZSTD_getCParams(3, 1U << kMaxWindowLog, 1024);
926         ZSTD_CDict* cdict;
927         ZSTD_DDict* ddict;
928         SEQ_stream seq = SEQ_initStream(0x87654321);
929         SEQ_gen_type type;
930         XXH64_state_t xxh;
931
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);
936
937         if (!cdict || !ddict) goto _output_error;
938
939         ZSTD_CCtx_reset(zc);
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));
948             }
949         }
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)));
955             }
956         }
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));
960         }
961
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");
964
965         ZSTD_freeCDict(cdict);
966         ZSTD_freeDDict(ddict);
967     }
968     DISPLAYLEVEL(3, "OK \n");
969
970     DISPLAYLEVEL(3, "test%3i : ZSTD_initCStream_srcSize sets requestedParams : ", testNb++);
971     {   unsigned level;
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");
978     }
979     DISPLAYLEVEL(3, "OK \n");
980
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");
987     }
988     DISPLAYLEVEL(3, "OK \n");
989
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) */
999
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;
1006
1007         CHECK_Z( ZSTD_initDStream(zds) );
1008         inBuff.src = testCase;
1009         inBuff.size = 47;
1010         inBuff.pos = 0;
1011         outBuff.dst = decodedBuffer;
1012         outBuff.size = CNBufferSize;
1013         outBuff.pos = 0;
1014
1015         while (inBuff.pos < inBuff.size) {
1016             CHECK_Z( ZSTD_decompressStream(zds, &outBuff, &inBuff) );
1017         }
1018
1019         ZSTD_freeDStream(zds);
1020     }
1021     DISPLAYLEVEL(3, "OK \n");
1022
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),
1028             ZSTD_defaultCMem);
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);
1036         size_t ret;
1037
1038         CHECK(cdict == NULL, "failed to alloc cdict");
1039         CHECK(inbuf == NULL, "failed to alloc input buffer");
1040
1041         /* first block is uncompressible */
1042         cursegmentlen = 128 * 1024;
1043         RDG_genBuffer(inbuf + inbufpos, cursegmentlen, 0., 0., seed);
1044         inbufpos += cursegmentlen;
1045
1046         /* second block is compressible */
1047         cursegmentlen = 128 * 1024 - 256;
1048         RDG_genBuffer(inbuf + inbufpos, cursegmentlen, 0.05, 0., seed);
1049         inbufpos += cursegmentlen;
1050
1051         /* and includes a very long backref */
1052         cursegmentlen = 128;
1053         memcpy(inbuf + inbufpos, dictionary.start + 256, cursegmentlen);
1054         inbufpos += cursegmentlen;
1055
1056         /* and includes a very long backref */
1057         cursegmentlen = 128;
1058         memcpy(inbuf + inbufpos, dictionary.start + 128, cursegmentlen);
1059         inbufpos += cursegmentlen;
1060
1061         ret = ZSTD_compress_usingCDict(zc, outbuf, outbufsize, inbuf, inbufpos, cdict);
1062         CHECK_Z(ret);
1063
1064         ret = ZSTD_decompress_usingDict(zd, checkbuf, inbufsize, outbuf, ret, dictionary.start, dictionary.filled);
1065         CHECK_Z(ret);
1066
1067         CHECK(memcmp(inbuf, checkbuf, inbufpos), "start and finish buffers don't match");
1068
1069         ZSTD_freeCDict(cdict);
1070         free(inbuf);
1071         free(outbuf);
1072         free(checkbuf);
1073     }
1074     DISPLAYLEVEL(3, "OK \n");
1075
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),
1081             ZSTD_defaultCMem);
1082         ZSTD_outBuffer out = {compressedBuffer, compressedBufferSize, 0};
1083         int remainingInput = 256 * 1024;
1084         int offset;
1085
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};
1095
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;
1099         }
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");
1106         }
1107         /* Ensure decompression works */
1108         CHECK_Z(ZSTD_decompress_usingDict(zd, decodedBuffer, CNBufferSize, out.dst, out.pos, dictionary.start, dictionary.filled));
1109
1110         ZSTD_freeCDict(cdict);
1111     }
1112     DISPLAYLEVEL(3, "OK \n");
1113
1114 _end:
1115     FUZ_freeDictionary(dictionary);
1116     ZSTD_freeCStream(zc);
1117     ZSTD_freeDStream(zd);
1118     ZSTDMT_freeCCtx(mtctx);
1119     free(CNBuffer);
1120     free(compressedBuffer);
1121     free(decodedBuffer);
1122     return testResult;
1123
1124 _output_error:
1125     testResult = 1;
1126     DISPLAY("Error detected in Unit tests ! \n");
1127     goto _end;
1128 }
1129
1130
1131 /* ======   Fuzzer tests   ====== */
1132
1133 static size_t findDiff(const void* buf1, const void* buf2, size_t max)
1134 {
1135     const BYTE* b1 = (const BYTE*)buf1;
1136     const BYTE* b2 = (const BYTE*)buf2;
1137     size_t u;
1138     for (u=0; u<max; u++) {
1139         if (b1[u] != b2[u]) break;
1140     }
1141     if (u==max) {
1142         DISPLAY("=> No difference detected within %u bytes \n", (U32)max);
1143         return u;
1144     }
1145     DISPLAY("Error at position %u / %u \n", (U32)u, (U32)max);
1146     if (u>=3)
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]);
1151     if (u>=3)
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]);
1156     return u;
1157 }
1158
1159 static size_t FUZ_rLogLength(U32* seed, U32 logLength)
1160 {
1161     size_t const lengthMask = ((size_t)1 << logLength) - 1;
1162     return (lengthMask+1) + (FUZ_rand(seed) & lengthMask);
1163 }
1164
1165 static size_t FUZ_randomLength(U32* seed, U32 maxLog)
1166 {
1167     U32 const logLength = FUZ_rand(seed) % maxLog;
1168     return FUZ_rLogLength(seed, logLength);
1169 }
1170
1171 /* Return value in range minVal <= v <= maxVal */
1172 static U32 FUZ_randomClampedLength(U32* seed, U32 minVal, U32 maxVal)
1173 {
1174     U32 const mod = maxVal < minVal ? 1 : (maxVal + 1) - minVal;
1175     return (U32)((FUZ_rand(seed) % mod) + minVal);
1176 }
1177
1178 static int fuzzerTests(U32 seed, U32 nbTests, unsigned startTest, double compressibility, int bigTests)
1179 {
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);
1190     U32 result = 0;
1191     U32 testNb = 0;
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;
1199     U32 oldTestLog = 0;
1200     U32 const cLevelMax = bigTests ? (U32)ZSTD_maxCLevel() : g_cLevelMax_smallTests;
1201
1202     /* allocations */
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");
1211
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 */
1220
1221     /* catch up testNb */
1222     for (testNb=1; testNb < startTest; testNb++)
1223         FUZ_rand(&coreSeed);
1224
1225     /* test loop */
1226     for ( ; (testNb <= nbTests) || (UTIL_clockSpanMicro(startClock) < g_clockTime) ; testNb++ ) {
1227         U32 lseed;
1228         const BYTE* srcBuffer;
1229         size_t totalTestSize, totalGenSize, cSize;
1230         XXH64_state_t xxhState;
1231         U64 crcOrig;
1232         U32 resetAllowed = 1;
1233         size_t maxTestSize;
1234
1235         /* init */
1236         FUZ_rand(&coreSeed);
1237         lseed = coreSeed ^ prime32;
1238         if (nbTests >= testNb) {
1239             DISPLAYUPDATE(2, "\r%6u/%6u    ", testNb, nbTests);
1240         } else {
1241             DISPLAYUPDATE(2, "\r%6u        ", testNb);
1242         }
1243
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");
1250             resetAllowed=0;
1251         }
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 */
1257         }
1258
1259         /* srcBuffer selection [0-4] */
1260         {   U32 buffNb = FUZ_rand(&lseed) & 0x7F;
1261             if (buffNb & 7) buffNb=2;   /* most common : compressible (P) */
1262             else {
1263                 buffNb >>= 3;
1264                 if (buffNb & 7) {
1265                     const U32 tnb[2] = { 1, 3 };   /* barely/highly compressible */
1266                     buffNb = tnb[buffNb >> 3];
1267                 } else {
1268                     const U32 tnb[2] = { 0, 4 };   /* not compressible / sparse */
1269                     buffNb = tnb[buffNb >> 3];
1270             }   }
1271             srcBuffer = cNoiseBuffer[buffNb];
1272         }
1273
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) );
1281             }
1282         } else {
1283             U32 const testLog = FUZ_rand(&lseed) % maxSrcLog;
1284             U32 const dictLog = FUZ_rand(&lseed) % maxSrcLog;
1285             U32 const cLevelCandidate = ( FUZ_rand(&lseed) %
1286                                 (ZSTD_maxCLevel() -
1287                                 (MAX(testLog, dictLog) / 3)))
1288                                  + 1;
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;
1296             }
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) );
1303         }   }
1304
1305         /* multi-segments compression test */
1306         XXH64_reset(&xxhState, 0);
1307         {   ZSTD_outBuffer outBuff = { cBuffer, cBufferSize, 0 } ;
1308             U32 n;
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;
1318
1319                     CHECK_Z( ZSTD_compressStream(zc, &outBuff, &inBuff) );
1320
1321                     XXH64_update(&xxhState, srcBuffer+srcStart, inBuff.pos);
1322                     memcpy(copyBuffer+totalTestSize, srcBuffer+srcStart, inBuff.pos);
1323                     totalTestSize += inBuff.pos;
1324                 }
1325
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) );
1332             }   }
1333
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));
1342             }   }
1343             crcOrig = XXH64_digest(&xxhState);
1344             cSize = outBuff.pos;
1345         }
1346
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) );
1350         } else {
1351             CHECK_Z ( ZSTD_initDStream_usingDict(zd, dict, dictSize) );
1352         }
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);
1366                 }
1367                 CHECK( ZSTD_isError(decompressionResult), "decompression error : %s",
1368                        ZSTD_getErrorName(decompressionResult) );
1369             }
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");
1377         }   }
1378
1379         /*=====   noisy/erroneous src decompression test   =====*/
1380
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);
1389         }   }
1390
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;
1406     }   }   }   }
1407     DISPLAY("\r%u fuzzer tests completed   \n", testNb);
1408
1409 _cleanup:
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]);
1418     free(copyBuffer);
1419     free(cBuffer);
1420     free(dstBuffer);
1421     return result;
1422
1423 _output_error:
1424     result = 1;
1425     goto _cleanup;
1426 }
1427
1428
1429 /* fuzzing ZSTDMT_* interface */
1430 static int fuzzerTests_MT(U32 seed, U32 nbTests, unsigned startTest,
1431                           double compressibility, int bigTests)
1432 {
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);
1443     U32 result = 0;
1444     U32 testNb = 0;
1445     U32 coreSeed = seed;
1446     U32 nbThreads = 2;
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;
1455
1456     /* allocations */
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");
1465
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);
1475
1476     /* catch up testNb */
1477     for (testNb=1; testNb < startTest; testNb++)
1478         FUZ_rand(&coreSeed);
1479
1480     /* test loop */
1481     for ( ; (testNb <= nbTests) || (UTIL_clockSpanMicro(startClock) < g_clockTime) ; testNb++ ) {
1482         U32 lseed;
1483         const BYTE* srcBuffer;
1484         size_t totalTestSize, totalGenSize, cSize;
1485         XXH64_state_t xxhState;
1486         U64 crcOrig;
1487         size_t maxTestSize;
1488
1489         FUZ_rand(&coreSeed);
1490         if (nbTests >= testNb) {
1491             DISPLAYUPDATE(2, "\r%6u/%6u    ", testNb, nbTests);
1492         } else {
1493             DISPLAYUPDATE(2, "\r%6u         ", testNb);
1494         }
1495         lseed = coreSeed ^ prime32;
1496
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")
1505         }
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 */
1511         }
1512
1513         /* srcBuffer selection [0-4] */
1514         {   U32 buffNb = FUZ_rand(&lseed) & 0x7F;
1515             if (buffNb & 7) buffNb=2;   /* most common : compressible (P) */
1516             else {
1517                 buffNb >>= 3;
1518                 if (buffNb & 7) {
1519                     const U32 tnb[2] = { 1, 3 };   /* barely/highly compressible */
1520                     buffNb = tnb[buffNb >> 3];
1521                 } else {
1522                     const U32 tnb[2] = { 0, 4 };   /* not compressible / sparse */
1523                     buffNb = tnb[buffNb >> 3];
1524             }   }
1525             srcBuffer = cNoiseBuffer[buffNb];
1526         }
1527
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)) )
1533                             + 1;
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);
1538
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;
1548                 }
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) );
1560         }   }   }
1561
1562         /* multi-segments compression test */
1563         XXH64_reset(&xxhState, 0);
1564         {   ZSTD_outBuffer outBuff = { cBuffer, cBufferSize, 0 } ;
1565             U32 n;
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;
1575
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);
1579
1580                     XXH64_update(&xxhState, srcBuffer+srcStart, inBuff.pos);
1581                     memcpy(copyBuffer+totalTestSize, srcBuffer+srcStart, inBuff.pos);
1582                     totalTestSize += inBuff.pos;
1583                 }
1584
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));
1595             }   }
1596
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);
1610             }   }
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);
1615         }
1616
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) );
1622         } else {
1623             CHECK_Z( ZSTD_initDStream_usingDict(zd, dict, dictSize) );
1624         }
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);
1640                 }
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);
1644             }
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");
1650         }   }
1651
1652         /*=====   noisy/erroneous src decompression test   =====*/
1653
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);
1662         }   }
1663
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;
1679     }   }   }   }
1680     DISPLAY("\r%u fuzzer tests completed   \n", testNb);
1681
1682 _cleanup:
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]);
1691     free(copyBuffer);
1692     free(cBuffer);
1693     free(dstBuffer);
1694     return result;
1695
1696 _output_error:
1697     result = 1;
1698     goto _cleanup;
1699 }
1700
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,
1705                                int useOpaqueAPI)
1706 {
1707     if (useOpaqueAPI) {
1708         return ZSTD_CCtxParam_setParameter(cctxParams, param, value);
1709     } else {
1710         return ZSTD_CCtx_setParameter(zc, param, value);
1711     }
1712 }
1713
1714 /* Tests for ZSTD_compress_generic() API */
1715 static int fuzzerTests_newAPI(U32 seed, U32 nbTests, unsigned startTest,
1716                               double compressibility, int bigTests)
1717 {
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);
1728     U32 result = 0;
1729     U32 testNb = 0;
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;
1737     U32 oldTestLog = 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();
1742
1743     /* allocations */
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");
1752
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 */
1761
1762     /* catch up testNb */
1763     for (testNb=1; testNb < startTest; testNb++)
1764         FUZ_rand(&coreSeed);
1765
1766     /* test loop */
1767     for ( ; (testNb <= nbTests) || (UTIL_clockSpanMicro(startClock) < g_clockTime) ; testNb++ ) {
1768         U32 lseed;
1769         int opaqueAPI;
1770         const BYTE* srcBuffer;
1771         size_t totalTestSize, totalGenSize, cSize;
1772         XXH64_state_t xxhState;
1773         U64 crcOrig;
1774         U32 resetAllowed = 1;
1775         size_t maxTestSize;
1776         ZSTD_parameters savedParams;
1777
1778         /* init */
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;
1785
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");
1790             ZSTD_freeCCtx(zc);
1791             zc = ZSTD_createCCtx();
1792             CHECK(zc == NULL, "ZSTD_createCCtx allocation error");
1793             resetAllowed = 0;
1794         }
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 */
1800         }
1801
1802         /* srcBuffer selection [0-4] */
1803         {   U32 buffNb = FUZ_rand(&lseed) & 0x7F;
1804             if (buffNb & 7) buffNb=2;   /* most common : compressible (P) */
1805             else {
1806                 buffNb >>= 3;
1807                 if (buffNb & 7) {
1808                     const U32 tnb[2] = { 1, 3 };   /* barely/highly compressible */
1809                     buffNb = tnb[buffNb >> 3];
1810                 } else {
1811                     const U32 tnb[2] = { 0, 4 };   /* not compressible / sparse */
1812                     buffNb = tnb[buffNb >> 3];
1813             }   }
1814             srcBuffer = cNoiseBuffer[buffNb];
1815         }
1816
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 */
1821           && resetAllowed) {
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) );
1828             }
1829         } else {
1830             U32 const testLog = FUZ_rand(&lseed) % maxSrcLog;
1831             U32 const dictLog = FUZ_rand(&lseed) % maxSrcLog;
1832             U32 const cLevelCandidate = (FUZ_rand(&lseed) %
1833                                (ZSTD_maxCLevel() -
1834                                (MAX(testLog, dictLog) / 2))) +
1835                                1;
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;
1846             }
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;
1851                 if (dictSize)
1852                     DISPLAYLEVEL(5, "t%u: with dictionary of size : %zu \n", testNb, dictSize);
1853
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);
1864
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;
1870                 }
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) );
1874                 }
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) );
1878                 }
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) );
1882
1883                 /* mess with long distance matching parameters */
1884                 if (bigTests) {
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) );
1890                 }
1891
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) );
1897                 }
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) );
1903                 }
1904
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) );
1916                     }
1917                 }
1918
1919                 if (FUZ_rand(&lseed) & 1) CHECK_Z( setCCtxParameter(zc, cctxParams, ZSTD_p_forceMaxWindow, FUZ_rand(&lseed) & 1, opaqueAPI) );
1920
1921                 /* Apply parameters */
1922                 if (opaqueAPI) {
1923                     DISPLAYLEVEL(5, "t%u: applying CCtxParams \n", testNb);
1924                     CHECK_Z (ZSTD_CCtx_setParametersUsingCCtxParams(zc, cctxParams) );
1925                 }
1926
1927                 if (FUZ_rand(&lseed) & 1) {
1928                     if (FUZ_rand(&lseed) & 1) {
1929                         CHECK_Z( ZSTD_CCtx_loadDictionary(zc, dict, dictSize) );
1930                     } else {
1931                         CHECK_Z( ZSTD_CCtx_loadDictionary_byReference(zc, dict, dictSize) );
1932                     }
1933                     if (dict && dictSize) {
1934                         /* test that compression parameters are rejected (correctly) after loading a non-NULL dictionary */
1935                         if (opaqueAPI) {
1936                             size_t const setError = ZSTD_CCtx_setParametersUsingCCtxParams(zc, cctxParams);
1937                             CHECK(!ZSTD_isError(setError), "ZSTD_CCtx_setParametersUsingCCtxParams should have failed");
1938                         } else {
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");
1941                         }
1942                     }
1943                 } else {
1944                     CHECK_Z( ZSTD_CCtx_refPrefix(zc, dict, dictSize) );
1945                 }
1946         }   }
1947
1948         CHECK_Z(getCCtxParams(zc, &savedParams));
1949
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;
1963
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);
1967
1968                 XXH64_update(&xxhState, srcBuffer+srcStart, inBuff.pos);
1969                 memcpy(copyBuffer+totalTestSize, srcBuffer+srcStart, inBuff.pos);
1970                 totalTestSize += inBuff.pos;
1971             }
1972
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) );
1986             }   }
1987             crcOrig = XXH64_digest(&xxhState);
1988             cSize = outBuff.pos;
1989             DISPLAYLEVEL(5, "Frame completed : %zu bytes \n", cSize);
1990         }
1991
1992         CHECK(badParameters(zc, savedParams), "CCtx params are wrong");
1993
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) );
1998         } else {
1999             if (dictSize)
2000                 DISPLAYLEVEL(5, "using dictionary of size %zu \n", dictSize);
2001             CHECK_Z( ZSTD_initDStream_usingDict(zd, dict, dictSize) );
2002         }
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);
2020                 }
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);
2023             }
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");
2029         }   }
2030
2031         /*=====   noisy/erroneous src decompression test   =====*/
2032
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);
2041         }   }
2042
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;
2058     }   }   }   }
2059     DISPLAY("\r%u fuzzer tests completed   \n", testNb-1);
2060
2061 _cleanup:
2062     ZSTD_freeCCtx(zc);
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]);
2071     free(copyBuffer);
2072     free(cBuffer);
2073     free(dstBuffer);
2074     return result;
2075
2076 _output_error:
2077     result = 1;
2078     goto _cleanup;
2079 }
2080
2081 /*-*******************************************************
2082 *  Command line
2083 *********************************************************/
2084 static int FUZ_usage(const char* programName)
2085 {
2086     DISPLAY( "Usage :\n");
2087     DISPLAY( "      %s [args]\n", programName);
2088     DISPLAY( "\n");
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");
2097     return 0;
2098 }
2099
2100 typedef enum { simple_api, mt_api, advanced_api } e_api;
2101
2102 int main(int argc, const char** argv)
2103 {
2104     U32 seed = 0;
2105     int seedset = 0;
2106     int nbTests = nbTestsDefault;
2107     int testNb = 0;
2108     int proba = FUZ_COMPRESSIBILITY_DEFAULT;
2109     int result = 0;
2110     int mainPause = 0;
2111     int bigTests = (sizeof(size_t) == 8);
2112     e_api selected_api = simple_api;
2113     const char* const programName = argv[0];
2114     int argNb;
2115
2116     /* Check command line */
2117     for(argNb=1; argNb<argc; argNb++) {
2118         const char* argument = argv[argNb];
2119         assert(argument != NULL);
2120
2121         /* Parsing commands. Aggregated commands are allowed */
2122         if (argument[0]=='-') {
2123
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; }
2127
2128             argument++;
2129             while (*argument!=0) {
2130                 switch(*argument)
2131                 {
2132                 case 'h':
2133                     return FUZ_usage(programName);
2134
2135                 case 'v':
2136                     argument++;
2137                     g_displayLevel++;
2138                     break;
2139
2140                 case 'q':
2141                     argument++;
2142                     g_displayLevel--;
2143                     break;
2144
2145                 case 'p': /* pause at the end */
2146                     argument++;
2147                     mainPause = 1;
2148                     break;
2149
2150                 case 'i':   /* limit tests by nb of iterations (default) */
2151                     argument++;
2152                     nbTests=0; g_clockTime=0;
2153                     while ((*argument>='0') && (*argument<='9')) {
2154                         nbTests *= 10;
2155                         nbTests += *argument - '0';
2156                         argument++;
2157                     }
2158                     break;
2159
2160                 case 'T':   /* limit tests by time */
2161                     argument++;
2162                     nbTests=0; g_clockTime=0;
2163                     while ((*argument>='0') && (*argument<='9')) {
2164                         g_clockTime *= 10;
2165                         g_clockTime += *argument - '0';
2166                         argument++;
2167                     }
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;
2173                     break;
2174
2175                 case 's':   /* manually select seed */
2176                     argument++;
2177                     seedset=1;
2178                     seed=0;
2179                     while ((*argument>='0') && (*argument<='9')) {
2180                         seed *= 10;
2181                         seed += *argument - '0';
2182                         argument++;
2183                     }
2184                     break;
2185
2186                 case 't':   /* select starting test number */
2187                     argument++;
2188                     testNb=0;
2189                     while ((*argument>='0') && (*argument<='9')) {
2190                         testNb *= 10;
2191                         testNb += *argument - '0';
2192                         argument++;
2193                     }
2194                     break;
2195
2196                 case 'P':   /* compressibility % */
2197                     argument++;
2198                     proba=0;
2199                     while ((*argument>='0') && (*argument<='9')) {
2200                         proba *= 10;
2201                         proba += *argument - '0';
2202                         argument++;
2203                     }
2204                     if (proba<0) proba=0;
2205                     if (proba>100) proba=100;
2206                     break;
2207
2208                 default:
2209                     return FUZ_usage(programName);
2210                 }
2211     }   }   }   /* for(argNb=1; argNb<argc; argNb++) */
2212
2213     /* Get Seed */
2214     DISPLAY("Starting zstream tester (%i-bits, %s)\n", (int)(sizeof(size_t)*8), ZSTD_VERSION_STRING);
2215
2216     if (!seedset) {
2217         time_t const t = time(NULL);
2218         U32 const h = XXH32(&t, sizeof(t), 1);
2219         seed = h % 10000;
2220     }
2221
2222     DISPLAY("Seed = %u\n", seed);
2223     if (proba!=FUZ_COMPRESSIBILITY_DEFAULT) DISPLAY("Compressibility : %i%%\n", proba);
2224
2225     if (nbTests<=0) nbTests=1;
2226
2227     if (testNb==0) {
2228         result = basicUnitTests(0, ((double)proba) / 100);  /* constant seed for predictability */
2229     }
2230
2231     if (!result) {
2232         switch(selected_api)
2233         {
2234         case simple_api :
2235             result = fuzzerTests(seed, nbTests, testNb, ((double)proba) / 100, bigTests);
2236             break;
2237         case mt_api :
2238             result = fuzzerTests_MT(seed, nbTests, testNb, ((double)proba) / 100, bigTests);
2239             break;
2240         case advanced_api :
2241             result = fuzzerTests_newAPI(seed, nbTests, testNb, ((double)proba) / 100, bigTests);
2242             break;
2243         default :
2244             assert(0);   /* impossible */
2245         }
2246     }
2247
2248     if (mainPause) {
2249         int unused;
2250         DISPLAY("Press Enter \n");
2251         unused = getchar();
2252         (void)unused;
2253     }
2254     return result;
2255 }