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