]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - sys/contrib/zstd/tests/zstreamtest.c
Import Intel Processor Trace decoder library from
[FreeBSD/FreeBSD.git] / sys / contrib / zstd / tests / zstreamtest.c
1 /*
2  * Copyright (c) 2016-present, Yann Collet, Facebook, Inc.
3  * All rights reserved.
4  *
5  * This source code is licensed under both the BSD-style license (found in the
6  * LICENSE file in the root directory of this source tree) and the GPLv2 (found
7  * in the COPYING file in the root directory of this source tree).
8  * You may select, at your option, one of the above-listed licenses.
9  */
10
11
12 /*-************************************
13 *  Compiler specific
14 **************************************/
15 #ifdef _MSC_VER    /* Visual Studio */
16 #  define _CRT_SECURE_NO_WARNINGS   /* fgets */
17 #  pragma warning(disable : 4127)   /* disable: C4127: conditional expression is constant */
18 #  pragma warning(disable : 4146)   /* disable: C4146: minus unsigned expression */
19 #endif
20
21
22 /*-************************************
23 *  Includes
24 **************************************/
25 #include <stdlib.h>       /* free */
26 #include <stdio.h>        /* fgets, sscanf */
27 #include <string.h>       /* strcmp */
28 #include <assert.h>       /* assert */
29 #include "mem.h"
30 #define ZSTD_STATIC_LINKING_ONLY  /* ZSTD_maxCLevel, ZSTD_customMem, ZSTD_getDictID_fromFrame */
31 #include "zstd.h"         /* ZSTD_compressBound */
32 #include "zstd_errors.h"  /* ZSTD_error_srcSize_wrong */
33 #include "zstdmt_compress.h"
34 #include "zdict.h"        /* ZDICT_trainFromBuffer */
35 #include "datagen.h"      /* RDG_genBuffer */
36 #define XXH_STATIC_LINKING_ONLY   /* XXH64_state_t */
37 #include "xxhash.h"       /* XXH64_* */
38 #include "seqgen.h"
39 #include "util.h"
40
41
42 /*-************************************
43 *  Constants
44 **************************************/
45 #define KB *(1U<<10)
46 #define MB *(1U<<20)
47 #define GB *(1U<<30)
48
49 static const U32 nbTestsDefault = 10000;
50 static const U32 g_cLevelMax_smallTests = 10;
51 #define COMPRESSIBLE_NOISE_LENGTH (10 MB)
52 #define FUZ_COMPRESSIBILITY_DEFAULT 50
53 static const U32 prime32 = 2654435761U;
54
55
56 /*-************************************
57 *  Display Macros
58 **************************************/
59 #define DISPLAY(...)          fprintf(stderr, __VA_ARGS__)
60 #define DISPLAYLEVEL(l, ...)  if (g_displayLevel>=l) {                     \
61                                   DISPLAY(__VA_ARGS__);                    \
62                                   if (g_displayLevel>=4) fflush(stderr); }
63 static U32 g_displayLevel = 2;
64
65 static const U64 g_refreshRate = SEC_TO_MICRO / 6;
66 static UTIL_time_t g_displayClock = UTIL_TIME_INITIALIZER;
67
68 #define DISPLAYUPDATE(l, ...) if (g_displayLevel>=l) { \
69             if ((UTIL_clockSpanMicro(g_displayClock) > g_refreshRate) || (g_displayLevel>=4)) \
70             { g_displayClock = UTIL_getTime(); DISPLAY(__VA_ARGS__); \
71             if (g_displayLevel>=4) fflush(stderr); } }
72
73 static U64 g_clockTime = 0;
74
75
76 /*-*******************************************************
77 *  Fuzzer functions
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 unsigned int FUZ_rand(unsigned int* seedPtr)
88 {
89     static const U32 prime2 = 2246822519U;
90     U32 rand32 = *seedPtr;
91     rand32 *= prime32;
92     rand32 += prime2;
93     rand32  = FUZ_rotl32(rand32, 13);
94     *seedPtr = rand32;
95     return rand32 >> 5;
96 }
97
98 #define CHECK(cond, ...) {                                   \
99     if (cond) {                                              \
100         DISPLAY("Error => ");                                \
101         DISPLAY(__VA_ARGS__);                                \
102         DISPLAY(" (seed %u, test nb %u, line %u)  \n",       \
103                 seed, testNb, __LINE__);                     \
104         goto _output_error;                                  \
105 }   }
106
107 #define CHECK_Z(f) {                                         \
108     size_t const err = f;                                    \
109     CHECK(ZSTD_isError(err), "%s : %s ",                     \
110           #f, ZSTD_getErrorName(err));                       \
111 }
112
113
114 /*======================================================
115 *   Basic Unit tests
116 ======================================================*/
117
118 typedef struct {
119     void* start;
120     size_t size;
121     size_t filled;
122 } buffer_t;
123
124 static const buffer_t g_nullBuffer = { NULL, 0 , 0 };
125
126 static buffer_t FUZ_createDictionary(const void* src, size_t srcSize, size_t blockSize, size_t requestedDictSize)
127 {
128     buffer_t dict = { NULL, 0, 0 };
129     size_t const nbBlocks = (srcSize + (blockSize-1)) / blockSize;
130     size_t* const blockSizes = (size_t*) malloc(nbBlocks * sizeof(size_t));
131     if (!blockSizes) return dict;
132     dict.start = malloc(requestedDictSize);
133     if (!dict.start) { free(blockSizes); return dict; }
134     {   size_t nb;
135         for (nb=0; nb<nbBlocks-1; nb++) blockSizes[nb] = blockSize;
136         blockSizes[nbBlocks-1] = srcSize - (blockSize * (nbBlocks-1));
137     }
138     {   size_t const dictSize = ZDICT_trainFromBuffer(dict.start, requestedDictSize, src, blockSizes, (unsigned)nbBlocks);
139         free(blockSizes);
140         if (ZDICT_isError(dictSize)) { free(dict.start); return g_nullBuffer; }
141         dict.size = requestedDictSize;
142         dict.filled = dictSize;
143         return dict;   /* how to return dictSize ? */
144     }
145 }
146
147 static void FUZ_freeDictionary(buffer_t dict)
148 {
149     free(dict.start);
150 }
151
152 /* Round trips data and updates xxh with the decompressed data produced */
153 static size_t SEQ_roundTrip(ZSTD_CCtx* cctx, ZSTD_DCtx* dctx,
154                             XXH64_state_t* xxh, void* data, size_t size,
155                             ZSTD_EndDirective endOp)
156 {
157     static BYTE compressed[1024];
158     static BYTE uncompressed[1024];
159
160     ZSTD_inBuffer cin = {data, size, 0};
161     size_t cret;
162
163     do {
164         ZSTD_outBuffer cout = {compressed, sizeof(compressed), 0};
165         ZSTD_inBuffer din = {compressed, 0, 0};
166         ZSTD_outBuffer dout = {uncompressed, 0, 0};
167
168         cret = ZSTD_compress_generic(cctx, &cout, &cin, endOp);
169         if (ZSTD_isError(cret))
170             return cret;
171
172         din.size = cout.pos;
173         while (din.pos < din.size || (endOp == ZSTD_e_end && cret == 0)) {
174             size_t dret;
175
176             dout.pos = 0;
177             dout.size = sizeof(uncompressed);
178             dret = ZSTD_decompressStream(dctx, &dout, &din);
179             if (ZSTD_isError(dret))
180                 return dret;
181             XXH64_update(xxh, dout.dst, dout.pos);
182             if (dret == 0)
183                 break;
184         }
185     } while (cin.pos < cin.size || (endOp != ZSTD_e_continue && cret != 0));
186     return 0;
187 }
188
189 /* Generates some data and round trips it */
190 static size_t SEQ_generateRoundTrip(ZSTD_CCtx* cctx, ZSTD_DCtx* dctx,
191                                     XXH64_state_t* xxh, SEQ_stream* seq,
192                                     SEQ_gen_type type, unsigned value)
193 {
194     static BYTE data[1024];
195     size_t gen;
196
197     do {
198         SEQ_outBuffer sout = {data, sizeof(data), 0};
199         size_t ret;
200         gen = SEQ_gen(seq, type, value, &sout);
201
202         ret = SEQ_roundTrip(cctx, dctx, xxh, sout.dst, sout.pos, ZSTD_e_continue);
203         if (ZSTD_isError(ret))
204             return ret;
205     } while (gen != 0);
206
207     return 0;
208 }
209
210 static int basicUnitTests(U32 seed, double compressibility)
211 {
212     size_t const CNBufferSize = COMPRESSIBLE_NOISE_LENGTH;
213     void* CNBuffer = malloc(CNBufferSize);
214     size_t const skippableFrameSize = 200 KB;
215     size_t const compressedBufferSize = (8 + skippableFrameSize) + ZSTD_compressBound(COMPRESSIBLE_NOISE_LENGTH);
216     void* compressedBuffer = malloc(compressedBufferSize);
217     size_t const decodedBufferSize = CNBufferSize;
218     void* decodedBuffer = malloc(decodedBufferSize);
219     size_t cSize;
220     int testResult = 0;
221     U32 testNb = 1;
222     ZSTD_CStream* zc = ZSTD_createCStream();
223     ZSTD_DStream* zd = ZSTD_createDStream();
224     ZSTDMT_CCtx* mtctx = ZSTDMT_createCCtx(2);
225
226     ZSTD_inBuffer  inBuff, inBuff2;
227     ZSTD_outBuffer outBuff;
228     buffer_t dictionary = g_nullBuffer;
229     size_t const dictSize = 128 KB;
230     unsigned dictID = 0;
231
232     /* Create compressible test buffer */
233     if (!CNBuffer || !compressedBuffer || !decodedBuffer || !zc || !zd) {
234         DISPLAY("Not enough memory, aborting \n");
235         goto _output_error;
236     }
237     RDG_genBuffer(CNBuffer, CNBufferSize, compressibility, 0., seed);
238
239     /* Create dictionary */
240     DISPLAYLEVEL(3, "creating dictionary for unit tests \n");
241     dictionary = FUZ_createDictionary(CNBuffer, CNBufferSize / 2, 8 KB, 40 KB);
242     if (!dictionary.start) {
243         DISPLAY("Error creating dictionary, aborting \n");
244         goto _output_error;
245     }
246     dictID = ZDICT_getDictID(dictionary.start, dictionary.filled);
247
248     /* Basic compression test */
249     DISPLAYLEVEL(3, "test%3i : compress %u bytes : ", testNb++, COMPRESSIBLE_NOISE_LENGTH);
250     CHECK_Z( ZSTD_initCStream(zc, 1 /* cLevel */) );
251     outBuff.dst = (char*)(compressedBuffer);
252     outBuff.size = compressedBufferSize;
253     outBuff.pos = 0;
254     inBuff.src = CNBuffer;
255     inBuff.size = CNBufferSize;
256     inBuff.pos = 0;
257     CHECK_Z( ZSTD_compressStream(zc, &outBuff, &inBuff) );
258     if (inBuff.pos != inBuff.size) goto _output_error;   /* entire input should be consumed */
259     { size_t const r = ZSTD_endStream(zc, &outBuff);
260       if (r != 0) goto _output_error; }  /* error, or some data not flushed */
261     DISPLAYLEVEL(3, "OK (%u bytes)\n", (U32)outBuff.pos);
262
263     /* generate skippable frame */
264     MEM_writeLE32(compressedBuffer, ZSTD_MAGIC_SKIPPABLE_START);
265     MEM_writeLE32(((char*)compressedBuffer)+4, (U32)skippableFrameSize);
266     cSize = skippableFrameSize + 8;
267
268     /* Basic compression test using dict */
269     DISPLAYLEVEL(3, "test%3i : skipframe + compress %u bytes : ", testNb++, COMPRESSIBLE_NOISE_LENGTH);
270     CHECK_Z( ZSTD_initCStream_usingDict(zc, CNBuffer, dictSize, 1 /* cLevel */) );
271     outBuff.dst = (char*)(compressedBuffer)+cSize;
272     assert(compressedBufferSize > cSize);
273     outBuff.size = compressedBufferSize - cSize;
274     outBuff.pos = 0;
275     inBuff.src = CNBuffer;
276     inBuff.size = CNBufferSize;
277     inBuff.pos = 0;
278     CHECK_Z( ZSTD_compressStream(zc, &outBuff, &inBuff) );
279     if (inBuff.pos != inBuff.size) goto _output_error;   /* entire input should be consumed */
280     { size_t const r = ZSTD_endStream(zc, &outBuff);
281       if (r != 0) goto _output_error; }  /* error, or some data not flushed */
282     cSize += outBuff.pos;
283     DISPLAYLEVEL(3, "OK (%u bytes : %.2f%%)\n", (U32)cSize, (double)cSize/COMPRESSIBLE_NOISE_LENGTH*100);
284
285     /* context size functions */
286     DISPLAYLEVEL(3, "test%3i : estimate CStream size : ", testNb++);
287     {   ZSTD_compressionParameters const cParams = ZSTD_getCParams(1, CNBufferSize, dictSize);
288         size_t const cstreamSize = ZSTD_estimateCStreamSize_usingCParams(cParams);
289         size_t const cdictSize = ZSTD_estimateCDictSize_advanced(dictSize, cParams, ZSTD_dlm_byCopy); /* uses ZSTD_initCStream_usingDict() */
290         if (ZSTD_isError(cstreamSize)) goto _output_error;
291         if (ZSTD_isError(cdictSize)) goto _output_error;
292         DISPLAYLEVEL(3, "OK (%u bytes) \n", (U32)(cstreamSize + cdictSize));
293     }
294
295     DISPLAYLEVEL(3, "test%3i : check actual CStream size : ", testNb++);
296     {   size_t const s = ZSTD_sizeof_CStream(zc);
297         if (ZSTD_isError(s)) goto _output_error;
298         DISPLAYLEVEL(3, "OK (%u bytes) \n", (U32)s);
299     }
300
301     /* Attempt bad compression parameters */
302     DISPLAYLEVEL(3, "test%3i : use bad compression parameters : ", testNb++);
303     {   size_t r;
304         ZSTD_parameters params = ZSTD_getParams(1, 0, 0);
305         params.cParams.searchLength = 2;
306         r = ZSTD_initCStream_advanced(zc, NULL, 0, params, 0);
307         if (!ZSTD_isError(r)) goto _output_error;
308         DISPLAYLEVEL(3, "init error : %s \n", ZSTD_getErrorName(r));
309     }
310
311     /* skippable frame test */
312     DISPLAYLEVEL(3, "test%3i : decompress skippable frame : ", testNb++);
313     CHECK_Z( ZSTD_initDStream_usingDict(zd, CNBuffer, dictSize) );
314     inBuff.src = compressedBuffer;
315     inBuff.size = cSize;
316     inBuff.pos = 0;
317     outBuff.dst = decodedBuffer;
318     outBuff.size = CNBufferSize;
319     outBuff.pos = 0;
320     {   size_t const r = ZSTD_decompressStream(zd, &outBuff, &inBuff);
321         DISPLAYLEVEL(5, " ( ZSTD_decompressStream => %u ) ", (U32)r);
322         if (r != 0) goto _output_error;
323     }
324     if (outBuff.pos != 0) goto _output_error;   /* skippable frame output len is 0 */
325     DISPLAYLEVEL(3, "OK \n");
326
327     /* Basic decompression test */
328     inBuff2 = inBuff;
329     DISPLAYLEVEL(3, "test%3i : decompress %u bytes : ", testNb++, COMPRESSIBLE_NOISE_LENGTH);
330     ZSTD_initDStream_usingDict(zd, CNBuffer, dictSize);
331     CHECK_Z( ZSTD_setDStreamParameter(zd, DStream_p_maxWindowSize, 1000000000) );  /* large limit */
332     { size_t const remaining = ZSTD_decompressStream(zd, &outBuff, &inBuff);
333       if (remaining != 0) goto _output_error; }  /* should reach end of frame == 0; otherwise, some data left, or an error */
334     if (outBuff.pos != CNBufferSize) goto _output_error;   /* should regenerate the same amount */
335     if (inBuff.pos != inBuff.size) goto _output_error;   /* should have read the entire frame */
336     DISPLAYLEVEL(3, "OK \n");
337
338     /* Re-use without init */
339     DISPLAYLEVEL(3, "test%3i : decompress again without init (re-use previous settings): ", testNb++);
340     outBuff.pos = 0;
341     { size_t const remaining = ZSTD_decompressStream(zd, &outBuff, &inBuff2);
342       if (remaining != 0) goto _output_error; }  /* should reach end of frame == 0; otherwise, some data left, or an error */
343     if (outBuff.pos != CNBufferSize) goto _output_error;   /* should regenerate the same amount */
344     if (inBuff.pos != inBuff.size) goto _output_error;   /* should have read the entire frame */
345     DISPLAYLEVEL(3, "OK \n");
346
347     /* check regenerated data is byte exact */
348     DISPLAYLEVEL(3, "test%3i : check decompressed result : ", testNb++);
349     {   size_t i;
350         for (i=0; i<CNBufferSize; i++) {
351             if (((BYTE*)decodedBuffer)[i] != ((BYTE*)CNBuffer)[i]) goto _output_error;
352     }   }
353     DISPLAYLEVEL(3, "OK \n");
354
355     /* context size functions */
356     DISPLAYLEVEL(3, "test%3i : estimate DStream size : ", testNb++);
357     {   ZSTD_frameHeader fhi;
358         const void* cStart = (char*)compressedBuffer + (skippableFrameSize + 8);
359         size_t const gfhError = ZSTD_getFrameHeader(&fhi, cStart, cSize);
360         if (gfhError!=0) goto _output_error;
361         DISPLAYLEVEL(5, " (windowSize : %u) ", (U32)fhi.windowSize);
362         {   size_t const s = ZSTD_estimateDStreamSize(fhi.windowSize)
363                             /* uses ZSTD_initDStream_usingDict() */
364                            + ZSTD_estimateDDictSize(dictSize, ZSTD_dlm_byCopy);
365             if (ZSTD_isError(s)) goto _output_error;
366             DISPLAYLEVEL(3, "OK (%u bytes) \n", (U32)s);
367     }   }
368
369     DISPLAYLEVEL(3, "test%3i : check actual DStream size : ", testNb++);
370     { size_t const s = ZSTD_sizeof_DStream(zd);
371       if (ZSTD_isError(s)) goto _output_error;
372       DISPLAYLEVEL(3, "OK (%u bytes) \n", (U32)s);
373     }
374
375     /* Byte-by-byte decompression test */
376     DISPLAYLEVEL(3, "test%3i : decompress byte-by-byte : ", testNb++);
377     {   /* skippable frame */
378         size_t r = 1;
379         ZSTD_initDStream_usingDict(zd, CNBuffer, dictSize);
380         inBuff.src = compressedBuffer;
381         outBuff.dst = decodedBuffer;
382         inBuff.pos = 0;
383         outBuff.pos = 0;
384         while (r) {   /* skippable frame */
385             inBuff.size = inBuff.pos + 1;
386             outBuff.size = outBuff.pos + 1;
387             r = ZSTD_decompressStream(zd, &outBuff, &inBuff);
388             if (ZSTD_isError(r)) goto _output_error;
389         }
390         /* normal frame */
391         ZSTD_initDStream_usingDict(zd, CNBuffer, dictSize);
392         r=1;
393         while (r) {
394             inBuff.size = inBuff.pos + 1;
395             outBuff.size = outBuff.pos + 1;
396             r = ZSTD_decompressStream(zd, &outBuff, &inBuff);
397             if (ZSTD_isError(r)) goto _output_error;
398         }
399     }
400     if (outBuff.pos != CNBufferSize) goto _output_error;   /* should regenerate the same amount */
401     if (inBuff.pos != cSize) goto _output_error;   /* should have read the entire frame */
402     DISPLAYLEVEL(3, "OK \n");
403
404     /* check regenerated data is byte exact */
405     DISPLAYLEVEL(3, "test%3i : check decompressed result : ", testNb++);
406     {   size_t i;
407         for (i=0; i<CNBufferSize; i++) {
408             if (((BYTE*)decodedBuffer)[i] != ((BYTE*)CNBuffer)[i]) goto _output_error;;
409     }   }
410     DISPLAYLEVEL(3, "OK \n");
411
412     /* _srcSize compression test */
413     DISPLAYLEVEL(3, "test%3i : compress_srcSize %u bytes : ", testNb++, COMPRESSIBLE_NOISE_LENGTH);
414     ZSTD_initCStream_srcSize(zc, 1, CNBufferSize);
415     outBuff.dst = (char*)(compressedBuffer);
416     outBuff.size = compressedBufferSize;
417     outBuff.pos = 0;
418     inBuff.src = CNBuffer;
419     inBuff.size = CNBufferSize;
420     inBuff.pos = 0;
421     CHECK_Z( ZSTD_compressStream(zc, &outBuff, &inBuff) );
422     if (inBuff.pos != inBuff.size) goto _output_error;   /* entire input should be consumed */
423     { size_t const r = ZSTD_endStream(zc, &outBuff);
424       if (r != 0) goto _output_error; }  /* error, or some data not flushed */
425     { unsigned long long origSize = ZSTD_findDecompressedSize(outBuff.dst, outBuff.pos);
426       if ((size_t)origSize != CNBufferSize) goto _output_error; }  /* exact original size must be present */
427     DISPLAYLEVEL(3, "OK (%u bytes : %.2f%%)\n", (U32)cSize, (double)cSize/COMPRESSIBLE_NOISE_LENGTH*100);
428
429     /* wrong _srcSize compression test */
430     DISPLAYLEVEL(3, "test%3i : wrong srcSize : %u bytes : ", testNb++, COMPRESSIBLE_NOISE_LENGTH-1);
431     ZSTD_initCStream_srcSize(zc, 1, CNBufferSize-1);
432     outBuff.dst = (char*)(compressedBuffer);
433     outBuff.size = compressedBufferSize;
434     outBuff.pos = 0;
435     inBuff.src = CNBuffer;
436     inBuff.size = CNBufferSize;
437     inBuff.pos = 0;
438     CHECK_Z( ZSTD_compressStream(zc, &outBuff, &inBuff) );
439     if (inBuff.pos != inBuff.size) goto _output_error;   /* entire input should be consumed */
440     { size_t const r = ZSTD_endStream(zc, &outBuff);
441       if (ZSTD_getErrorCode(r) != ZSTD_error_srcSize_wrong) goto _output_error;    /* must fail : wrong srcSize */
442       DISPLAYLEVEL(3, "OK (error detected : %s) \n", ZSTD_getErrorName(r)); }
443
444     /* Complex context re-use scenario */
445     DISPLAYLEVEL(3, "test%3i : context re-use : ", testNb++);
446     ZSTD_freeCStream(zc);
447     zc = ZSTD_createCStream();
448     if (zc==NULL) goto _output_error;   /* memory allocation issue */
449     /* use 1 */
450     {   size_t const inSize = 513;
451         DISPLAYLEVEL(5, "use1 ");
452         ZSTD_initCStream_advanced(zc, NULL, 0, ZSTD_getParams(19, inSize, 0), inSize);   /* needs btopt + search3 to trigger hashLog3 */
453         inBuff.src = CNBuffer;
454         inBuff.size = inSize;
455         inBuff.pos = 0;
456         outBuff.dst = (char*)(compressedBuffer)+cSize;
457         outBuff.size = ZSTD_compressBound(inSize);
458         outBuff.pos = 0;
459         DISPLAYLEVEL(5, "compress1 ");
460         CHECK_Z( ZSTD_compressStream(zc, &outBuff, &inBuff) );
461         if (inBuff.pos != inBuff.size) goto _output_error;   /* entire input should be consumed */
462         DISPLAYLEVEL(5, "end1 ");
463         { size_t const r = ZSTD_endStream(zc, &outBuff);
464             if (r != 0) goto _output_error; }  /* error, or some data not flushed */
465     }
466     /* use 2 */
467     {   size_t const inSize = 1025;   /* will not continue, because tables auto-adjust and are therefore different size */
468         DISPLAYLEVEL(5, "use2 ");
469         ZSTD_initCStream_advanced(zc, NULL, 0, ZSTD_getParams(19, inSize, 0), inSize);   /* needs btopt + search3 to trigger hashLog3 */
470         inBuff.src = CNBuffer;
471         inBuff.size = inSize;
472         inBuff.pos = 0;
473         outBuff.dst = (char*)(compressedBuffer)+cSize;
474         outBuff.size = ZSTD_compressBound(inSize);
475         outBuff.pos = 0;
476         DISPLAYLEVEL(5, "compress2 ");
477         CHECK_Z( ZSTD_compressStream(zc, &outBuff, &inBuff) );
478         if (inBuff.pos != inBuff.size) goto _output_error;   /* entire input should be consumed */
479         DISPLAYLEVEL(5, "end2 ");
480         { size_t const r = ZSTD_endStream(zc, &outBuff);
481             if (r != 0) goto _output_error; }  /* error, or some data not flushed */
482     }
483     DISPLAYLEVEL(3, "OK \n");
484
485     /* CDict scenario */
486     DISPLAYLEVEL(3, "test%3i : digested dictionary : ", testNb++);
487     {   ZSTD_CDict* const cdict = ZSTD_createCDict(dictionary.start, dictionary.filled, 1 /*byRef*/ );
488         size_t const initError = ZSTD_initCStream_usingCDict(zc, cdict);
489         DISPLAYLEVEL(5, "ZSTD_initCStream_usingCDict result : %u ", (U32)initError);
490         if (ZSTD_isError(initError)) goto _output_error;
491         cSize = 0;
492         outBuff.dst = compressedBuffer;
493         outBuff.size = compressedBufferSize;
494         outBuff.pos = 0;
495         inBuff.src = CNBuffer;
496         inBuff.size = CNBufferSize;
497         inBuff.pos = 0;
498         DISPLAYLEVEL(5, "- starting ZSTD_compressStream ");
499         CHECK_Z( ZSTD_compressStream(zc, &outBuff, &inBuff) );
500         if (inBuff.pos != inBuff.size) goto _output_error;   /* entire input should be consumed */
501         {   size_t const r = ZSTD_endStream(zc, &outBuff);
502             DISPLAYLEVEL(5, "- ZSTD_endStream result : %u ", (U32)r);
503             if (r != 0) goto _output_error;  /* error, or some data not flushed */
504         }
505         cSize = outBuff.pos;
506         ZSTD_freeCDict(cdict);
507         DISPLAYLEVEL(3, "OK (%u bytes : %.2f%%)\n", (U32)cSize, (double)cSize/CNBufferSize*100);
508     }
509
510     DISPLAYLEVEL(3, "test%3i : check CStream size : ", testNb++);
511     { size_t const s = ZSTD_sizeof_CStream(zc);
512       if (ZSTD_isError(s)) goto _output_error;
513       DISPLAYLEVEL(3, "OK (%u bytes) \n", (U32)s);
514     }
515
516     DISPLAYLEVEL(4, "test%3i : check Dictionary ID : ", testNb++);
517     { unsigned const dID = ZSTD_getDictID_fromFrame(compressedBuffer, cSize);
518       if (dID != dictID) goto _output_error;
519       DISPLAYLEVEL(4, "OK (%u) \n", dID);
520     }
521
522     /* DDict scenario */
523     DISPLAYLEVEL(3, "test%3i : decompress %u bytes with digested dictionary : ", testNb++, (U32)CNBufferSize);
524     {   ZSTD_DDict* const ddict = ZSTD_createDDict(dictionary.start, dictionary.filled);
525         size_t const initError = ZSTD_initDStream_usingDDict(zd, ddict);
526         if (ZSTD_isError(initError)) goto _output_error;
527         outBuff.dst = decodedBuffer;
528         outBuff.size = CNBufferSize;
529         outBuff.pos = 0;
530         inBuff.src = compressedBuffer;
531         inBuff.size = cSize;
532         inBuff.pos = 0;
533         { size_t const r = ZSTD_decompressStream(zd, &outBuff, &inBuff);
534           if (r != 0) goto _output_error; }  /* should reach end of frame == 0; otherwise, some data left, or an error */
535         if (outBuff.pos != CNBufferSize) goto _output_error;   /* should regenerate the same amount */
536         if (inBuff.pos != inBuff.size) goto _output_error;   /* should have read the entire frame */
537         ZSTD_freeDDict(ddict);
538         DISPLAYLEVEL(3, "OK \n");
539     }
540
541     /* test ZSTD_setDStreamParameter() resilience */
542     DISPLAYLEVEL(3, "test%3i : wrong parameter for ZSTD_setDStreamParameter(): ", testNb++);
543     { size_t const r = ZSTD_setDStreamParameter(zd, (ZSTD_DStreamParameter_e)999, 1);  /* large limit */
544       if (!ZSTD_isError(r)) goto _output_error; }
545     DISPLAYLEVEL(3, "OK \n");
546
547     /* Memory restriction */
548     DISPLAYLEVEL(3, "test%3i : maxWindowSize < frame requirement : ", testNb++);
549     ZSTD_initDStream_usingDict(zd, CNBuffer, dictSize);
550     CHECK_Z( ZSTD_setDStreamParameter(zd, DStream_p_maxWindowSize, 1000) );  /* too small limit */
551     outBuff.dst = decodedBuffer;
552     outBuff.size = CNBufferSize;
553     outBuff.pos = 0;
554     inBuff.src = compressedBuffer;
555     inBuff.size = cSize;
556     inBuff.pos = 0;
557     { size_t const r = ZSTD_decompressStream(zd, &outBuff, &inBuff);
558       if (!ZSTD_isError(r)) goto _output_error;  /* must fail : frame requires > 100 bytes */
559       DISPLAYLEVEL(3, "OK (%s)\n", ZSTD_getErrorName(r)); }
560
561     DISPLAYLEVEL(3, "test%3i : ZSTD_initCStream_usingCDict_advanced with masked dictID : ", testNb++);
562     {   ZSTD_compressionParameters const cParams = ZSTD_getCParams(1, CNBufferSize, dictionary.filled);
563         ZSTD_frameParameters const fParams = { 1 /* contentSize */, 1 /* checksum */, 1 /* noDictID */};
564         ZSTD_CDict* const cdict = ZSTD_createCDict_advanced(dictionary.start, dictionary.filled, ZSTD_dlm_byRef, ZSTD_dm_auto, cParams, ZSTD_defaultCMem);
565         size_t const initError = ZSTD_initCStream_usingCDict_advanced(zc, cdict, fParams, CNBufferSize);
566         if (ZSTD_isError(initError)) goto _output_error;
567         cSize = 0;
568         outBuff.dst = compressedBuffer;
569         outBuff.size = compressedBufferSize;
570         outBuff.pos = 0;
571         inBuff.src = CNBuffer;
572         inBuff.size = CNBufferSize;
573         inBuff.pos = 0;
574         CHECK_Z( ZSTD_compressStream(zc, &outBuff, &inBuff) );
575         if (inBuff.pos != inBuff.size) goto _output_error;  /* entire input should be consumed */
576         { size_t const r = ZSTD_endStream(zc, &outBuff);
577           if (r != 0) goto _output_error; }  /* error, or some data not flushed */
578         cSize = outBuff.pos;
579         ZSTD_freeCDict(cdict);
580         DISPLAYLEVEL(3, "OK (%u bytes : %.2f%%)\n", (U32)cSize, (double)cSize/CNBufferSize*100);
581     }
582
583     DISPLAYLEVEL(3, "test%3i : try retrieving dictID from frame : ", testNb++);
584     {   U32 const did = ZSTD_getDictID_fromFrame(compressedBuffer, cSize);
585         if (did != 0) goto _output_error;
586     }
587     DISPLAYLEVEL(3, "OK (not detected) \n");
588
589     DISPLAYLEVEL(3, "test%3i : decompress without dictionary : ", testNb++);
590     {   size_t const r = ZSTD_decompress(decodedBuffer, CNBufferSize, compressedBuffer, cSize);
591         if (!ZSTD_isError(r)) goto _output_error;  /* must fail : dictionary not used */
592         DISPLAYLEVEL(3, "OK (%s)\n", ZSTD_getErrorName(r));
593     }
594
595     DISPLAYLEVEL(3, "test%3i : compress with ZSTD_CCtx_refPrefix : ", testNb++);
596     CHECK_Z( ZSTD_CCtx_refPrefix(zc, dictionary.start, dictionary.filled) );
597     outBuff.dst = compressedBuffer;
598     outBuff.size = compressedBufferSize;
599     outBuff.pos = 0;
600     inBuff.src = CNBuffer;
601     inBuff.size = CNBufferSize;
602     inBuff.pos = 0;
603     CHECK_Z( ZSTD_compress_generic(zc, &outBuff, &inBuff, ZSTD_e_end) );
604     if (inBuff.pos != inBuff.size) goto _output_error;  /* entire input should be consumed */
605     cSize = outBuff.pos;
606     DISPLAYLEVEL(3, "OK (%u bytes : %.2f%%)\n", (U32)cSize, (double)cSize/CNBufferSize*100);
607
608     DISPLAYLEVEL(3, "test%3i : decompress with dictionary : ", testNb++);
609     {   size_t const r = ZSTD_decompress_usingDict(zd,
610                                         decodedBuffer, CNBufferSize,
611                                         compressedBuffer, cSize,
612                                         dictionary.start, dictionary.filled);
613         if (ZSTD_isError(r)) goto _output_error;  /* must fail : dictionary not used */
614         DISPLAYLEVEL(3, "OK \n");
615     }
616
617     DISPLAYLEVEL(3, "test%3i : decompress without dictionary (should fail): ", testNb++);
618     {   size_t const r = ZSTD_decompress(decodedBuffer, CNBufferSize, compressedBuffer, cSize);
619         if (!ZSTD_isError(r)) goto _output_error;  /* must fail : dictionary not used */
620         DISPLAYLEVEL(3, "OK (%s)\n", ZSTD_getErrorName(r));
621     }
622
623     DISPLAYLEVEL(3, "test%3i : compress again with ZSTD_compress_generic : ", testNb++);
624     outBuff.dst = compressedBuffer;
625     outBuff.size = compressedBufferSize;
626     outBuff.pos = 0;
627     inBuff.src = CNBuffer;
628     inBuff.size = CNBufferSize;
629     inBuff.pos = 0;
630     CHECK_Z( ZSTD_compress_generic(zc, &outBuff, &inBuff, ZSTD_e_end) );
631     if (inBuff.pos != inBuff.size) goto _output_error;  /* entire input should be consumed */
632     cSize = outBuff.pos;
633     DISPLAYLEVEL(3, "OK (%u bytes : %.2f%%)\n", (U32)cSize, (double)cSize/CNBufferSize*100);
634
635     DISPLAYLEVEL(3, "test%3i : decompress without dictionary (should work): ", testNb++);
636     CHECK_Z( ZSTD_decompress(decodedBuffer, CNBufferSize, compressedBuffer, cSize) );
637     DISPLAYLEVEL(3, "OK \n");
638
639     /* Empty srcSize */
640     DISPLAYLEVEL(3, "test%3i : ZSTD_initCStream_advanced with pledgedSrcSize=0 and dict : ", testNb++);
641     {   ZSTD_parameters params = ZSTD_getParams(5, 0, 0);
642         params.fParams.contentSizeFlag = 1;
643         CHECK_Z( ZSTD_initCStream_advanced(zc, dictionary.start, dictionary.filled, params, 0 /* pledgedSrcSize==0 means "empty" when params.fParams.contentSizeFlag is set */) );
644     } /* cstream advanced shall write content size = 0 */
645     outBuff.dst = compressedBuffer;
646     outBuff.size = compressedBufferSize;
647     outBuff.pos = 0;
648     inBuff.src = CNBuffer;
649     inBuff.size = 0;
650     inBuff.pos = 0;
651     CHECK_Z( ZSTD_compressStream(zc, &outBuff, &inBuff) );
652     if (ZSTD_endStream(zc, &outBuff) != 0) goto _output_error;
653     cSize = outBuff.pos;
654     if (ZSTD_findDecompressedSize(compressedBuffer, cSize) != 0) goto _output_error;
655     DISPLAYLEVEL(3, "OK \n");
656
657     DISPLAYLEVEL(3, "test%3i : pledgedSrcSize == 0 behaves properly : ", testNb++);
658     {   ZSTD_parameters params = ZSTD_getParams(5, 0, 0);
659         params.fParams.contentSizeFlag = 1;
660         CHECK_Z( ZSTD_initCStream_advanced(zc, NULL, 0, params, 0) );
661     } /* cstream advanced shall write content size = 0 */
662     inBuff.src = CNBuffer;
663     inBuff.size = 0;
664     inBuff.pos = 0;
665     outBuff.dst = compressedBuffer;
666     outBuff.size = compressedBufferSize;
667     outBuff.pos = 0;
668     CHECK_Z( ZSTD_compressStream(zc, &outBuff, &inBuff) );
669     if (ZSTD_endStream(zc, &outBuff) != 0) goto _output_error;
670     cSize = outBuff.pos;
671     if (ZSTD_findDecompressedSize(compressedBuffer, cSize) != 0) goto _output_error;
672
673     ZSTD_resetCStream(zc, 0); /* resetCStream should treat 0 as unknown */
674     outBuff.dst = compressedBuffer;
675     outBuff.size = compressedBufferSize;
676     outBuff.pos = 0;
677     inBuff.src = CNBuffer;
678     inBuff.size = 0;
679     inBuff.pos = 0;
680     CHECK_Z( ZSTD_compressStream(zc, &outBuff, &inBuff) );
681     if (ZSTD_endStream(zc, &outBuff) != 0) goto _output_error;
682     cSize = outBuff.pos;
683     if (ZSTD_findDecompressedSize(compressedBuffer, cSize) != ZSTD_CONTENTSIZE_UNKNOWN) goto _output_error;
684     DISPLAYLEVEL(3, "OK \n");
685
686     /* Basic multithreading compression test */
687     DISPLAYLEVEL(3, "test%3i : compress %u bytes with multiple threads : ", testNb++, COMPRESSIBLE_NOISE_LENGTH);
688     {   ZSTD_parameters const params = ZSTD_getParams(1, 0, 0);
689         CHECK_Z( ZSTDMT_initCStream_advanced(mtctx, CNBuffer, dictSize, params, CNBufferSize) );
690     }
691     outBuff.dst = compressedBuffer;
692     outBuff.size = compressedBufferSize;
693     outBuff.pos = 0;
694     inBuff.src = CNBuffer;
695     inBuff.size = CNBufferSize;
696     inBuff.pos = 0;
697     CHECK_Z( ZSTDMT_compressStream_generic(mtctx, &outBuff, &inBuff, ZSTD_e_end) );
698     if (inBuff.pos != inBuff.size) goto _output_error;   /* entire input should be consumed */
699     { size_t const r = ZSTDMT_endStream(mtctx, &outBuff);
700       if (r != 0) goto _output_error; }  /* error, or some data not flushed */
701     DISPLAYLEVEL(3, "OK \n");
702
703     /* Complex multithreading + dictionary test */
704     {   U32 const nbThreads = 2;
705         size_t const jobSize = 4 * 1 MB;
706         size_t const srcSize = jobSize * nbThreads;  /* we want each job to have predictable size */
707         size_t const segLength = 2 KB;
708         size_t const offset = 600 KB;   /* must be larger than window defined in cdict */
709         size_t const start = jobSize + (offset-1);
710         const BYTE* const srcToCopy = (const BYTE*)CNBuffer + start;
711         BYTE* const dst = (BYTE*)CNBuffer + start - offset;
712         DISPLAYLEVEL(3, "test%3i : compress %u bytes with multiple threads + dictionary : ", testNb++, (U32)srcSize);
713         CHECK_Z( ZSTD_CCtx_setParameter(zc, ZSTD_p_compressionLevel, 3) );
714         CHECK_Z( ZSTD_CCtx_setParameter(zc, ZSTD_p_nbThreads, 2) );
715         CHECK_Z( ZSTD_CCtx_setParameter(zc, ZSTD_p_jobSize, jobSize) );
716         assert(start > offset);
717         assert(start + segLength < COMPRESSIBLE_NOISE_LENGTH);
718         memcpy(dst, srcToCopy, segLength);   /* create a long repetition at long distance for job 2 */
719         outBuff.dst = compressedBuffer;
720         outBuff.size = compressedBufferSize;
721         outBuff.pos = 0;
722         inBuff.src = CNBuffer;
723         inBuff.size = srcSize; assert(srcSize < COMPRESSIBLE_NOISE_LENGTH);
724         inBuff.pos = 0;
725     }
726     {   ZSTD_compressionParameters const cParams = ZSTD_getCParams(1, 4 KB, dictionary.filled);   /* intentionnally lies on estimatedSrcSize, to push cdict into targeting a small window size */
727         ZSTD_CDict* const cdict = ZSTD_createCDict_advanced(dictionary.start, dictionary.filled, ZSTD_dlm_byRef, ZSTD_dm_fullDict, cParams, ZSTD_defaultCMem);
728         DISPLAYLEVEL(5, "cParams.windowLog = %u : ", cParams.windowLog);
729         CHECK_Z( ZSTD_CCtx_refCDict(zc, cdict) );
730         CHECK_Z( ZSTD_compress_generic(zc, &outBuff, &inBuff, ZSTD_e_end) );
731         CHECK_Z( ZSTD_CCtx_refCDict(zc, NULL) );  /* do not keep a reference to cdict, as its lifetime ends */
732         ZSTD_freeCDict(cdict);
733     }
734     if (inBuff.pos != inBuff.size) goto _output_error;   /* entire input should be consumed */
735     cSize = outBuff.pos;
736     DISPLAYLEVEL(3, "OK \n");
737
738     DISPLAYLEVEL(3, "test%3i : decompress large frame created from multiple threads + dictionary : ", testNb++);
739     {   ZSTD_DStream* const dstream = ZSTD_createDCtx();
740         ZSTD_frameHeader zfh;
741         ZSTD_getFrameHeader(&zfh, compressedBuffer, cSize);
742         DISPLAYLEVEL(5, "frame windowsize = %u : ", (U32)zfh.windowSize);
743         outBuff.dst = decodedBuffer;
744         outBuff.size = CNBufferSize;
745         outBuff.pos = 0;
746         inBuff.src = compressedBuffer;
747         inBuff.pos = 0;
748         CHECK_Z( ZSTD_initDStream_usingDict(dstream, dictionary.start, dictionary.filled) );
749         inBuff.size = 1;  /* avoid shortcut to single-pass mode */
750         CHECK_Z( ZSTD_decompressStream(dstream, &outBuff, &inBuff) );
751         inBuff.size = cSize;
752         CHECK_Z( ZSTD_decompressStream(dstream, &outBuff, &inBuff) );
753         if (inBuff.pos != inBuff.size) goto _output_error;   /* entire input should be consumed */
754         ZSTD_freeDStream(dstream);
755     }
756     DISPLAYLEVEL(3, "OK \n");
757
758     DISPLAYLEVEL(3, "test%3i : check dictionary FSE tables can represent every code : ", testNb++);
759     {   unsigned const kMaxWindowLog = 24;
760         unsigned value;
761         ZSTD_compressionParameters cParams = ZSTD_getCParams(3, 1U << kMaxWindowLog, 1024);
762         ZSTD_CDict* cdict;
763         ZSTD_DDict* ddict;
764         SEQ_stream seq = SEQ_initStream(0x87654321);
765         SEQ_gen_type type;
766         XXH64_state_t xxh;
767
768         XXH64_reset(&xxh, 0);
769         cParams.windowLog = kMaxWindowLog;
770         cdict = ZSTD_createCDict_advanced(dictionary.start, dictionary.filled, ZSTD_dlm_byRef, ZSTD_dm_fullDict, cParams, ZSTD_defaultCMem);
771         ddict = ZSTD_createDDict(dictionary.start, dictionary.filled);
772
773         if (!cdict || !ddict) goto _output_error;
774
775         ZSTD_CCtx_reset(zc);
776         ZSTD_resetDStream(zd);
777         CHECK_Z(ZSTD_CCtx_refCDict(zc, cdict));
778         CHECK_Z(ZSTD_initDStream_usingDDict(zd, ddict));
779         CHECK_Z(ZSTD_setDStreamParameter(zd, DStream_p_maxWindowSize, 1U << kMaxWindowLog));
780         /* Test all values < 300 */
781         for (value = 0; value < 300; ++value) {
782             for (type = (SEQ_gen_type)0; type < SEQ_gen_max; ++type) {
783                 CHECK_Z(SEQ_generateRoundTrip(zc, zd, &xxh, &seq, type, value));
784             }
785         }
786         /* Test values 2^8 to 2^17 */
787         for (value = (1 << 8); value < (1 << 17); value <<= 1) {
788             for (type = (SEQ_gen_type)0; type < SEQ_gen_max; ++type) {
789                 CHECK_Z(SEQ_generateRoundTrip(zc, zd, &xxh, &seq, type, value));
790                 CHECK_Z(SEQ_generateRoundTrip(zc, zd, &xxh, &seq, type, value + (value >> 2)));
791             }
792         }
793         /* Test offset values up to the max window log */
794         for (value = 8; value <= kMaxWindowLog; ++value) {
795             CHECK_Z(SEQ_generateRoundTrip(zc, zd, &xxh, &seq, SEQ_gen_of, (1U << value) - 1));
796         }
797
798         CHECK_Z(SEQ_roundTrip(zc, zd, &xxh, NULL, 0, ZSTD_e_end));
799         CHECK(SEQ_digest(&seq) != XXH64_digest(&xxh), "SEQ XXH64 does not match");
800
801         ZSTD_freeCDict(cdict);
802         ZSTD_freeDDict(ddict);
803     }
804     DISPLAYLEVEL(3, "OK \n");
805
806     /* Overlen overwriting window data bug */
807     DISPLAYLEVEL(3, "test%3i : wildcopy doesn't overwrite potential match data : ", testNb++);
808     {   /* This test has a window size of 1024 bytes and consists of 3 blocks:
809             1. 'a' repeated 517 times
810             2. 'b' repeated 516 times
811             3. a compressed block with no literals and 3 sequence commands:
812                 litlength = 0, offset = 24, match length = 24
813                 litlength = 0, offset = 24, match length = 3 (this one creates an overlength write of length 2*WILDCOPY_OVERLENGTH - 3)
814                 litlength = 0, offset = 1021, match length = 3 (this one will try to read from overwritten data if the buffer is too small) */
815
816         const char* testCase =
817             "\x28\xB5\x2F\xFD\x04\x00\x4C\x00\x00\x10\x61\x61\x01\x00\x00\x2A"
818             "\x80\x05\x44\x00\x00\x08\x62\x01\x00\x00\x2A\x20\x04\x5D\x00\x00"
819             "\x00\x03\x40\x00\x00\x64\x60\x27\xB0\xE0\x0C\x67\x62\xCE\xE0";
820         ZSTD_DStream* const zds = ZSTD_createDStream();
821         if (zds==NULL) goto _output_error;
822
823         CHECK_Z( ZSTD_initDStream(zds) );
824         inBuff.src = testCase;
825         inBuff.size = 47;
826         inBuff.pos = 0;
827         outBuff.dst = decodedBuffer;
828         outBuff.size = CNBufferSize;
829         outBuff.pos = 0;
830
831         while (inBuff.pos < inBuff.size) {
832             CHECK_Z( ZSTD_decompressStream(zds, &outBuff, &inBuff) );
833         }
834
835         ZSTD_freeDStream(zds);
836     }
837     DISPLAYLEVEL(3, "OK \n");
838
839 _end:
840     FUZ_freeDictionary(dictionary);
841     ZSTD_freeCStream(zc);
842     ZSTD_freeDStream(zd);
843     ZSTDMT_freeCCtx(mtctx);
844     free(CNBuffer);
845     free(compressedBuffer);
846     free(decodedBuffer);
847     return testResult;
848
849 _output_error:
850     testResult = 1;
851     DISPLAY("Error detected in Unit tests ! \n");
852     goto _end;
853 }
854
855
856 /* ======   Fuzzer tests   ====== */
857
858 static size_t findDiff(const void* buf1, const void* buf2, size_t max)
859 {
860     const BYTE* b1 = (const BYTE*)buf1;
861     const BYTE* b2 = (const BYTE*)buf2;
862     size_t u;
863     for (u=0; u<max; u++) {
864         if (b1[u] != b2[u]) break;
865     }
866     DISPLAY("Error at position %u / %u \n", (U32)u, (U32)max);
867     DISPLAY(" %02X %02X %02X  :%02X:  %02X %02X %02X %02X %02X \n",
868             b1[u-3], b1[u-2], b1[u-1], b1[u-0], b1[u+1], b1[u+2], b1[u+3], b1[u+4], b1[u+5]);
869     DISPLAY(" %02X %02X %02X  :%02X:  %02X %02X %02X %02X %02X \n",
870             b2[u-3], b2[u-2], b2[u-1], b2[u-0], b2[u+1], b2[u+2], b2[u+3], b2[u+4], b2[u+5]);
871     return u;
872 }
873
874 static size_t FUZ_rLogLength(U32* seed, U32 logLength)
875 {
876     size_t const lengthMask = ((size_t)1 << logLength) - 1;
877     return (lengthMask+1) + (FUZ_rand(seed) & lengthMask);
878 }
879
880 static size_t FUZ_randomLength(U32* seed, U32 maxLog)
881 {
882     U32 const logLength = FUZ_rand(seed) % maxLog;
883     return FUZ_rLogLength(seed, logLength);
884 }
885
886 /* Return value in range minVal <= v <= maxVal */
887 static U32 FUZ_randomClampedLength(U32* seed, U32 minVal, U32 maxVal)
888 {
889     U32 const mod = maxVal < minVal ? 1 : (maxVal + 1) - minVal;
890     return (U32)((FUZ_rand(seed) % mod) + minVal);
891 }
892
893 static int fuzzerTests(U32 seed, U32 nbTests, unsigned startTest, double compressibility, int bigTests)
894 {
895     U32 const maxSrcLog = bigTests ? 24 : 22;
896     static const U32 maxSampleLog = 19;
897     size_t const srcBufferSize = (size_t)1<<maxSrcLog;
898     BYTE* cNoiseBuffer[5];
899     size_t const copyBufferSize = srcBufferSize + (1<<maxSampleLog);
900     BYTE*  const copyBuffer = (BYTE*)malloc (copyBufferSize);
901     size_t const cBufferSize = ZSTD_compressBound(srcBufferSize);
902     BYTE*  const cBuffer = (BYTE*)malloc (cBufferSize);
903     size_t const dstBufferSize = srcBufferSize;
904     BYTE*  const dstBuffer = (BYTE*)malloc (dstBufferSize);
905     U32 result = 0;
906     U32 testNb = 0;
907     U32 coreSeed = seed;
908     ZSTD_CStream* zc = ZSTD_createCStream();   /* will be re-created sometimes */
909     ZSTD_DStream* zd = ZSTD_createDStream();   /* will be re-created sometimes */
910     ZSTD_DStream* const zd_noise = ZSTD_createDStream();
911     UTIL_time_t const startClock = UTIL_getTime();
912     const BYTE* dict = NULL;  /* can keep same dict on 2 consecutive tests */
913     size_t dictSize = 0;
914     U32 oldTestLog = 0;
915     U32 const cLevelMax = bigTests ? (U32)ZSTD_maxCLevel() : g_cLevelMax_smallTests;
916
917     /* allocations */
918     cNoiseBuffer[0] = (BYTE*)malloc (srcBufferSize);
919     cNoiseBuffer[1] = (BYTE*)malloc (srcBufferSize);
920     cNoiseBuffer[2] = (BYTE*)malloc (srcBufferSize);
921     cNoiseBuffer[3] = (BYTE*)malloc (srcBufferSize);
922     cNoiseBuffer[4] = (BYTE*)malloc (srcBufferSize);
923     CHECK (!cNoiseBuffer[0] || !cNoiseBuffer[1] || !cNoiseBuffer[2] || !cNoiseBuffer[3] || !cNoiseBuffer[4] ||
924            !copyBuffer || !dstBuffer || !cBuffer || !zc || !zd || !zd_noise ,
925            "Not enough memory, fuzzer tests cancelled");
926
927     /* Create initial samples */
928     RDG_genBuffer(cNoiseBuffer[0], srcBufferSize, 0.00, 0., coreSeed);    /* pure noise */
929     RDG_genBuffer(cNoiseBuffer[1], srcBufferSize, 0.05, 0., coreSeed);    /* barely compressible */
930     RDG_genBuffer(cNoiseBuffer[2], srcBufferSize, compressibility, 0., coreSeed);
931     RDG_genBuffer(cNoiseBuffer[3], srcBufferSize, 0.95, 0., coreSeed);    /* highly compressible */
932     RDG_genBuffer(cNoiseBuffer[4], srcBufferSize, 1.00, 0., coreSeed);    /* sparse content */
933     memset(copyBuffer, 0x65, copyBufferSize);                             /* make copyBuffer considered initialized */
934     ZSTD_initDStream_usingDict(zd, NULL, 0);  /* ensure at least one init */
935
936     /* catch up testNb */
937     for (testNb=1; testNb < startTest; testNb++)
938         FUZ_rand(&coreSeed);
939
940     /* test loop */
941     for ( ; (testNb <= nbTests) || (UTIL_clockSpanMicro(startClock) < g_clockTime) ; testNb++ ) {
942         U32 lseed;
943         const BYTE* srcBuffer;
944         size_t totalTestSize, totalGenSize, cSize;
945         XXH64_state_t xxhState;
946         U64 crcOrig;
947         U32 resetAllowed = 1;
948         size_t maxTestSize;
949
950         /* init */
951         if (nbTests >= testNb) { DISPLAYUPDATE(2, "\r%6u/%6u    ", testNb, nbTests); }
952         else { DISPLAYUPDATE(2, "\r%6u          ", testNb); }
953         FUZ_rand(&coreSeed);
954         lseed = coreSeed ^ prime32;
955
956         /* states full reset (deliberately not synchronized) */
957         /* some issues can only happen when reusing states */
958         if ((FUZ_rand(&lseed) & 0xFF) == 131) {
959             ZSTD_freeCStream(zc);
960             zc = ZSTD_createCStream();
961             CHECK(zc==NULL, "ZSTD_createCStream : allocation error");
962             resetAllowed=0;
963         }
964         if ((FUZ_rand(&lseed) & 0xFF) == 132) {
965             ZSTD_freeDStream(zd);
966             zd = ZSTD_createDStream();
967             CHECK(zd==NULL, "ZSTD_createDStream : allocation error");
968             CHECK_Z( ZSTD_initDStream_usingDict(zd, NULL, 0) );  /* ensure at least one init */
969         }
970
971         /* srcBuffer selection [0-4] */
972         {   U32 buffNb = FUZ_rand(&lseed) & 0x7F;
973             if (buffNb & 7) buffNb=2;   /* most common : compressible (P) */
974             else {
975                 buffNb >>= 3;
976                 if (buffNb & 7) {
977                     const U32 tnb[2] = { 1, 3 };   /* barely/highly compressible */
978                     buffNb = tnb[buffNb >> 3];
979                 } else {
980                     const U32 tnb[2] = { 0, 4 };   /* not compressible / sparse */
981                     buffNb = tnb[buffNb >> 3];
982             }   }
983             srcBuffer = cNoiseBuffer[buffNb];
984         }
985
986         /* compression init */
987         if ((FUZ_rand(&lseed)&1) /* at beginning, to keep same nb of rand */
988             && oldTestLog /* at least one test happened */ && resetAllowed) {
989             maxTestSize = FUZ_randomLength(&lseed, oldTestLog+2);
990             maxTestSize = MIN(maxTestSize, srcBufferSize-16);
991             {   U64 const pledgedSrcSize = (FUZ_rand(&lseed) & 3) ? 0 : maxTestSize;
992                 CHECK_Z( ZSTD_resetCStream(zc, pledgedSrcSize) );
993             }
994         } else {
995             U32 const testLog = FUZ_rand(&lseed) % maxSrcLog;
996             U32 const dictLog = FUZ_rand(&lseed) % maxSrcLog;
997             U32 const cLevelCandidate = ( FUZ_rand(&lseed) %
998                                 (ZSTD_maxCLevel() -
999                                 (MAX(testLog, dictLog) / 3)))
1000                                  + 1;
1001             U32 const cLevel = MIN(cLevelCandidate, cLevelMax);
1002             maxTestSize = FUZ_rLogLength(&lseed, testLog);
1003             oldTestLog = testLog;
1004             /* random dictionary selection */
1005             dictSize  = ((FUZ_rand(&lseed)&7)==1) ? FUZ_rLogLength(&lseed, dictLog) : 0;
1006             {   size_t const dictStart = FUZ_rand(&lseed) % (srcBufferSize - dictSize);
1007                 dict = srcBuffer + dictStart;
1008             }
1009             {   U64 const pledgedSrcSize = (FUZ_rand(&lseed) & 3) ? ZSTD_CONTENTSIZE_UNKNOWN : maxTestSize;
1010                 ZSTD_parameters params = ZSTD_getParams(cLevel, pledgedSrcSize, dictSize);
1011                 params.fParams.checksumFlag = FUZ_rand(&lseed) & 1;
1012                 params.fParams.noDictIDFlag = FUZ_rand(&lseed) & 1;
1013                 params.fParams.contentSizeFlag = FUZ_rand(&lseed) & 1;
1014                 CHECK_Z ( ZSTD_initCStream_advanced(zc, dict, dictSize, params, pledgedSrcSize) );
1015         }   }
1016
1017         /* multi-segments compression test */
1018         XXH64_reset(&xxhState, 0);
1019         {   ZSTD_outBuffer outBuff = { cBuffer, cBufferSize, 0 } ;
1020             U32 n;
1021             for (n=0, cSize=0, totalTestSize=0 ; totalTestSize < maxTestSize ; n++) {
1022                 /* compress random chunks into randomly sized dst buffers */
1023                 {   size_t const randomSrcSize = FUZ_randomLength(&lseed, maxSampleLog);
1024                     size_t const srcSize = MIN(maxTestSize-totalTestSize, randomSrcSize);
1025                     size_t const srcStart = FUZ_rand(&lseed) % (srcBufferSize - srcSize);
1026                     size_t const randomDstSize = FUZ_randomLength(&lseed, maxSampleLog);
1027                     size_t const dstBuffSize = MIN(cBufferSize - cSize, randomDstSize);
1028                     ZSTD_inBuffer inBuff = { srcBuffer+srcStart, srcSize, 0 };
1029                     outBuff.size = outBuff.pos + dstBuffSize;
1030
1031                     CHECK_Z( ZSTD_compressStream(zc, &outBuff, &inBuff) );
1032
1033                     XXH64_update(&xxhState, srcBuffer+srcStart, inBuff.pos);
1034                     memcpy(copyBuffer+totalTestSize, srcBuffer+srcStart, inBuff.pos);
1035                     totalTestSize += inBuff.pos;
1036                 }
1037
1038                 /* random flush operation, to mess around */
1039                 if ((FUZ_rand(&lseed) & 15) == 0) {
1040                     size_t const randomDstSize = FUZ_randomLength(&lseed, maxSampleLog);
1041                     size_t const adjustedDstSize = MIN(cBufferSize - cSize, randomDstSize);
1042                     outBuff.size = outBuff.pos + adjustedDstSize;
1043                     CHECK_Z( ZSTD_flushStream(zc, &outBuff) );
1044             }   }
1045
1046             /* final frame epilogue */
1047             {   size_t remainingToFlush = (size_t)(-1);
1048                 while (remainingToFlush) {
1049                     size_t const randomDstSize = FUZ_randomLength(&lseed, maxSampleLog);
1050                     size_t const adjustedDstSize = MIN(cBufferSize - cSize, randomDstSize);
1051                     outBuff.size = outBuff.pos + adjustedDstSize;
1052                     remainingToFlush = ZSTD_endStream(zc, &outBuff);
1053                     CHECK (ZSTD_isError(remainingToFlush), "end error : %s", ZSTD_getErrorName(remainingToFlush));
1054             }   }
1055             crcOrig = XXH64_digest(&xxhState);
1056             cSize = outBuff.pos;
1057         }
1058
1059         /* multi - fragments decompression test */
1060         if (!dictSize /* don't reset if dictionary : could be different */ && (FUZ_rand(&lseed) & 1)) {
1061             CHECK_Z ( ZSTD_resetDStream(zd) );
1062         } else {
1063             CHECK_Z ( ZSTD_initDStream_usingDict(zd, dict, dictSize) );
1064         }
1065         {   size_t decompressionResult = 1;
1066             ZSTD_inBuffer  inBuff = { cBuffer, cSize, 0 };
1067             ZSTD_outBuffer outBuff= { dstBuffer, dstBufferSize, 0 };
1068             for (totalGenSize = 0 ; decompressionResult ; ) {
1069                 size_t const readCSrcSize = FUZ_randomLength(&lseed, maxSampleLog);
1070                 size_t const randomDstSize = FUZ_randomLength(&lseed, maxSampleLog);
1071                 size_t const dstBuffSize = MIN(dstBufferSize - totalGenSize, randomDstSize);
1072                 inBuff.size = inBuff.pos + readCSrcSize;
1073                 outBuff.size = outBuff.pos + dstBuffSize;
1074                 decompressionResult = ZSTD_decompressStream(zd, &outBuff, &inBuff);
1075                 if (ZSTD_getErrorCode(decompressionResult) == ZSTD_error_checksum_wrong) {
1076                     DISPLAY("checksum error : \n");
1077                     findDiff(copyBuffer, dstBuffer, totalTestSize);
1078                 }
1079                 CHECK( ZSTD_isError(decompressionResult), "decompression error : %s",
1080                        ZSTD_getErrorName(decompressionResult) );
1081             }
1082             CHECK (decompressionResult != 0, "frame not fully decoded");
1083             CHECK (outBuff.pos != totalTestSize, "decompressed data : wrong size (%u != %u)",
1084                     (U32)outBuff.pos, (U32)totalTestSize);
1085             CHECK (inBuff.pos != cSize, "compressed data should be fully read")
1086             {   U64 const crcDest = XXH64(dstBuffer, totalTestSize, 0);
1087                 if (crcDest!=crcOrig) findDiff(copyBuffer, dstBuffer, totalTestSize);
1088                 CHECK (crcDest!=crcOrig, "decompressed data corrupted");
1089         }   }
1090
1091         /*=====   noisy/erroneous src decompression test   =====*/
1092
1093         /* add some noise */
1094         {   U32 const nbNoiseChunks = (FUZ_rand(&lseed) & 7) + 2;
1095             U32 nn; for (nn=0; nn<nbNoiseChunks; nn++) {
1096                 size_t const randomNoiseSize = FUZ_randomLength(&lseed, maxSampleLog);
1097                 size_t const noiseSize  = MIN((cSize/3) , randomNoiseSize);
1098                 size_t const noiseStart = FUZ_rand(&lseed) % (srcBufferSize - noiseSize);
1099                 size_t const cStart = FUZ_rand(&lseed) % (cSize - noiseSize);
1100                 memcpy(cBuffer+cStart, srcBuffer+noiseStart, noiseSize);
1101         }   }
1102
1103         /* try decompression on noisy data */
1104         CHECK_Z( ZSTD_initDStream(zd_noise) );   /* note : no dictionary */
1105         {   ZSTD_inBuffer  inBuff = { cBuffer, cSize, 0 };
1106             ZSTD_outBuffer outBuff= { dstBuffer, dstBufferSize, 0 };
1107             while (outBuff.pos < dstBufferSize) {
1108                 size_t const randomCSrcSize = FUZ_randomLength(&lseed, maxSampleLog);
1109                 size_t const randomDstSize = FUZ_randomLength(&lseed, maxSampleLog);
1110                 size_t const adjustedDstSize = MIN(dstBufferSize - outBuff.pos, randomDstSize);
1111                 size_t const adjustedCSrcSize = MIN(cSize - inBuff.pos, randomCSrcSize);
1112                 outBuff.size = outBuff.pos + adjustedDstSize;
1113                 inBuff.size  = inBuff.pos + adjustedCSrcSize;
1114                 {   size_t const decompressError = ZSTD_decompressStream(zd, &outBuff, &inBuff);
1115                     if (ZSTD_isError(decompressError)) break;   /* error correctly detected */
1116                     /* No forward progress possible */
1117                     if (outBuff.pos < outBuff.size && inBuff.pos == cSize) break;
1118     }   }   }   }
1119     DISPLAY("\r%u fuzzer tests completed   \n", testNb);
1120
1121 _cleanup:
1122     ZSTD_freeCStream(zc);
1123     ZSTD_freeDStream(zd);
1124     ZSTD_freeDStream(zd_noise);
1125     free(cNoiseBuffer[0]);
1126     free(cNoiseBuffer[1]);
1127     free(cNoiseBuffer[2]);
1128     free(cNoiseBuffer[3]);
1129     free(cNoiseBuffer[4]);
1130     free(copyBuffer);
1131     free(cBuffer);
1132     free(dstBuffer);
1133     return result;
1134
1135 _output_error:
1136     result = 1;
1137     goto _cleanup;
1138 }
1139
1140
1141 /* Multi-threading version of fuzzer Tests */
1142 static int fuzzerTests_MT(U32 seed, U32 nbTests, unsigned startTest, double compressibility, int bigTests)
1143 {
1144     const U32 maxSrcLog = bigTests ? 24 : 22;
1145     static const U32 maxSampleLog = 19;
1146     size_t const srcBufferSize = (size_t)1<<maxSrcLog;
1147     BYTE* cNoiseBuffer[5];
1148     size_t const copyBufferSize= srcBufferSize + (1<<maxSampleLog);
1149     BYTE*  const copyBuffer = (BYTE*)malloc (copyBufferSize);
1150     size_t const cBufferSize   = ZSTD_compressBound(srcBufferSize);
1151     BYTE*  const cBuffer = (BYTE*)malloc (cBufferSize);
1152     size_t const dstBufferSize = srcBufferSize;
1153     BYTE*  const dstBuffer = (BYTE*)malloc (dstBufferSize);
1154     U32 result = 0;
1155     U32 testNb = 0;
1156     U32 coreSeed = seed;
1157     U32 nbThreads = 2;
1158     ZSTDMT_CCtx* zc = ZSTDMT_createCCtx(nbThreads);   /* will be reset sometimes */
1159     ZSTD_DStream* zd = ZSTD_createDStream();   /* will be reset sometimes */
1160     ZSTD_DStream* const zd_noise = ZSTD_createDStream();
1161     UTIL_time_t const startClock = UTIL_getTime();
1162     const BYTE* dict=NULL;   /* can keep same dict on 2 consecutive tests */
1163     size_t dictSize = 0;
1164     U32 oldTestLog = 0;
1165     int const cLevelMax = bigTests ? (U32)ZSTD_maxCLevel()-1 : g_cLevelMax_smallTests;
1166     U32 const nbThreadsMax = bigTests ? 4 : 2;
1167
1168     /* allocations */
1169     cNoiseBuffer[0] = (BYTE*)malloc (srcBufferSize);
1170     cNoiseBuffer[1] = (BYTE*)malloc (srcBufferSize);
1171     cNoiseBuffer[2] = (BYTE*)malloc (srcBufferSize);
1172     cNoiseBuffer[3] = (BYTE*)malloc (srcBufferSize);
1173     cNoiseBuffer[4] = (BYTE*)malloc (srcBufferSize);
1174     CHECK (!cNoiseBuffer[0] || !cNoiseBuffer[1] || !cNoiseBuffer[2] || !cNoiseBuffer[3] || !cNoiseBuffer[4] ||
1175            !copyBuffer || !dstBuffer || !cBuffer || !zc || !zd || !zd_noise ,
1176            "Not enough memory, fuzzer tests cancelled");
1177
1178     /* Create initial samples */
1179     RDG_genBuffer(cNoiseBuffer[0], srcBufferSize, 0.00, 0., coreSeed);    /* pure noise */
1180     RDG_genBuffer(cNoiseBuffer[1], srcBufferSize, 0.05, 0., coreSeed);    /* barely compressible */
1181     RDG_genBuffer(cNoiseBuffer[2], srcBufferSize, compressibility, 0., coreSeed);
1182     RDG_genBuffer(cNoiseBuffer[3], srcBufferSize, 0.95, 0., coreSeed);    /* highly compressible */
1183     RDG_genBuffer(cNoiseBuffer[4], srcBufferSize, 1.00, 0., coreSeed);    /* sparse content */
1184     memset(copyBuffer, 0x65, copyBufferSize);                             /* make copyBuffer considered initialized */
1185     ZSTD_initDStream_usingDict(zd, NULL, 0);  /* ensure at least one init */
1186
1187     /* catch up testNb */
1188     for (testNb=1; testNb < startTest; testNb++)
1189         FUZ_rand(&coreSeed);
1190
1191     /* test loop */
1192     for ( ; (testNb <= nbTests) || (UTIL_clockSpanMicro(startClock) < g_clockTime) ; testNb++ ) {
1193         U32 lseed;
1194         const BYTE* srcBuffer;
1195         size_t totalTestSize, totalGenSize, cSize;
1196         XXH64_state_t xxhState;
1197         U64 crcOrig;
1198         U32 resetAllowed = 1;
1199         size_t maxTestSize;
1200
1201         /* init */
1202         if (testNb < nbTests) {
1203             DISPLAYUPDATE(2, "\r%6u/%6u    ", testNb, nbTests);
1204         } else { DISPLAYUPDATE(2, "\r%6u          ", testNb); }
1205         FUZ_rand(&coreSeed);
1206         lseed = coreSeed ^ prime32;
1207
1208         /* states full reset (deliberately not synchronized) */
1209         /* some issues can only happen when reusing states */
1210         if ((FUZ_rand(&lseed) & 0xFF) == 131) {
1211             nbThreads = (FUZ_rand(&lseed) % nbThreadsMax) + 1;
1212             DISPLAYLEVEL(5, "Creating new context with %u threads \n", nbThreads);
1213             ZSTDMT_freeCCtx(zc);
1214             zc = ZSTDMT_createCCtx(nbThreads);
1215             CHECK(zc==NULL, "ZSTDMT_createCCtx allocation error")
1216             resetAllowed=0;
1217         }
1218         if ((FUZ_rand(&lseed) & 0xFF) == 132) {
1219             ZSTD_freeDStream(zd);
1220             zd = ZSTD_createDStream();
1221             CHECK(zd==NULL, "ZSTDMT_createCCtx allocation error")
1222             ZSTD_initDStream_usingDict(zd, NULL, 0);  /* ensure at least one init */
1223         }
1224
1225         /* srcBuffer selection [0-4] */
1226         {   U32 buffNb = FUZ_rand(&lseed) & 0x7F;
1227             if (buffNb & 7) buffNb=2;   /* most common : compressible (P) */
1228             else {
1229                 buffNb >>= 3;
1230                 if (buffNb & 7) {
1231                     const U32 tnb[2] = { 1, 3 };   /* barely/highly compressible */
1232                     buffNb = tnb[buffNb >> 3];
1233                 } else {
1234                     const U32 tnb[2] = { 0, 4 };   /* not compressible / sparse */
1235                     buffNb = tnb[buffNb >> 3];
1236             }   }
1237             srcBuffer = cNoiseBuffer[buffNb];
1238         }
1239
1240         /* compression init */
1241         if ((FUZ_rand(&lseed)&1) /* at beginning, to keep same nb of rand */
1242             && oldTestLog /* at least one test happened */ && resetAllowed) {
1243             maxTestSize = FUZ_randomLength(&lseed, oldTestLog+2);
1244             if (maxTestSize >= srcBufferSize) maxTestSize = srcBufferSize-1;
1245             {   int const compressionLevel = (FUZ_rand(&lseed) % 5) + 1;
1246                 CHECK_Z( ZSTDMT_initCStream(zc, compressionLevel) );
1247             }
1248         } else {
1249             U32 const testLog = FUZ_rand(&lseed) % maxSrcLog;
1250             U32 const dictLog = FUZ_rand(&lseed) % maxSrcLog;
1251             int const cLevelCandidate = ( FUZ_rand(&lseed)
1252                             % (ZSTD_maxCLevel() - (MAX(testLog, dictLog) / 2)) )
1253                             + 1;
1254             int const cLevelThreadAdjusted = cLevelCandidate - (nbThreads * 2) + 2;  /* reduce cLevel when multiple threads to reduce memory consumption */
1255             int const cLevelMin = MAX(cLevelThreadAdjusted, 1);  /* no negative cLevel yet */
1256             int const cLevel = MIN(cLevelMin, cLevelMax);
1257             maxTestSize = FUZ_rLogLength(&lseed, testLog);
1258             oldTestLog = testLog;
1259             /* random dictionary selection */
1260             dictSize  = ((FUZ_rand(&lseed)&63)==1) ? FUZ_rLogLength(&lseed, dictLog) : 0;
1261             {   size_t const dictStart = FUZ_rand(&lseed) % (srcBufferSize - dictSize);
1262                 dict = srcBuffer + dictStart;
1263             }
1264             {   U64 const pledgedSrcSize = (FUZ_rand(&lseed) & 3) ? ZSTD_CONTENTSIZE_UNKNOWN : maxTestSize;
1265                 ZSTD_parameters params = ZSTD_getParams(cLevel, pledgedSrcSize, dictSize);
1266                 DISPLAYLEVEL(5, "Init with windowLog = %u, pledgedSrcSize = %u, dictSize = %u \n",
1267                     params.cParams.windowLog, (U32)pledgedSrcSize, (U32)dictSize);
1268                 params.fParams.checksumFlag = FUZ_rand(&lseed) & 1;
1269                 params.fParams.noDictIDFlag = FUZ_rand(&lseed) & 1;
1270                 params.fParams.contentSizeFlag = FUZ_rand(&lseed) & 1;
1271                 DISPLAYLEVEL(5, "checksumFlag : %u \n", params.fParams.checksumFlag);
1272                 CHECK_Z( ZSTDMT_setMTCtxParameter(zc, ZSTDMT_p_overlapSectionLog, FUZ_rand(&lseed) % 12) );
1273                 CHECK_Z( ZSTDMT_setMTCtxParameter(zc, ZSTDMT_p_jobSize, FUZ_rand(&lseed) % (2*maxTestSize+1)) );   /* custome job size */
1274                 CHECK_Z( ZSTDMT_initCStream_advanced(zc, dict, dictSize, params, pledgedSrcSize) );
1275         }   }
1276
1277         /* multi-segments compression test */
1278         XXH64_reset(&xxhState, 0);
1279         {   ZSTD_outBuffer outBuff = { cBuffer, cBufferSize, 0 } ;
1280             U32 n;
1281             for (n=0, cSize=0, totalTestSize=0 ; totalTestSize < maxTestSize ; n++) {
1282                 /* compress random chunks into randomly sized dst buffers */
1283                 {   size_t const randomSrcSize = FUZ_randomLength(&lseed, maxSampleLog);
1284                     size_t const srcSize = MIN (maxTestSize-totalTestSize, randomSrcSize);
1285                     size_t const srcStart = FUZ_rand(&lseed) % (srcBufferSize - srcSize);
1286                     size_t const randomDstSize = FUZ_randomLength(&lseed, maxSampleLog);
1287                     size_t const dstBuffSize = MIN(cBufferSize - cSize, randomDstSize);
1288                     ZSTD_inBuffer inBuff = { srcBuffer+srcStart, srcSize, 0 };
1289                     outBuff.size = outBuff.pos + dstBuffSize;
1290
1291                     DISPLAYLEVEL(6, "Sending %u bytes to compress \n", (U32)srcSize);
1292                     CHECK_Z( ZSTDMT_compressStream(zc, &outBuff, &inBuff) );
1293                     DISPLAYLEVEL(6, "%u bytes read by ZSTDMT_compressStream \n", (U32)inBuff.pos);
1294
1295                     XXH64_update(&xxhState, srcBuffer+srcStart, inBuff.pos);
1296                     memcpy(copyBuffer+totalTestSize, srcBuffer+srcStart, inBuff.pos);
1297                     totalTestSize += inBuff.pos;
1298                 }
1299
1300                 /* random flush operation, to mess around */
1301                 if ((FUZ_rand(&lseed) & 15) == 0) {
1302                     size_t const randomDstSize = FUZ_randomLength(&lseed, maxSampleLog);
1303                     size_t const adjustedDstSize = MIN(cBufferSize - cSize, randomDstSize);
1304                     outBuff.size = outBuff.pos + adjustedDstSize;
1305                     DISPLAYLEVEL(5, "Flushing into dst buffer of size %u \n", (U32)adjustedDstSize);
1306                     CHECK_Z( ZSTDMT_flushStream(zc, &outBuff) );
1307             }   }
1308
1309             /* final frame epilogue */
1310             {   size_t remainingToFlush = (size_t)(-1);
1311                 while (remainingToFlush) {
1312                     size_t const randomDstSize = FUZ_randomLength(&lseed, maxSampleLog);
1313                     size_t const adjustedDstSize = MIN(cBufferSize - cSize, randomDstSize);
1314                     outBuff.size = outBuff.pos + adjustedDstSize;
1315                     DISPLAYLEVEL(5, "Ending into dst buffer of size %u \n", (U32)adjustedDstSize);
1316                     remainingToFlush = ZSTDMT_endStream(zc, &outBuff);
1317                     CHECK (ZSTD_isError(remainingToFlush), "ZSTDMT_endStream error : %s", ZSTD_getErrorName(remainingToFlush));
1318                     DISPLAYLEVEL(5, "endStream : remainingToFlush : %u \n", (U32)remainingToFlush);
1319             }   }
1320             crcOrig = XXH64_digest(&xxhState);
1321             cSize = outBuff.pos;
1322             DISPLAYLEVEL(5, "Frame completed : %u bytes \n", (U32)cSize);
1323         }
1324
1325         /* multi - fragments decompression test */
1326         if (!dictSize /* don't reset if dictionary : could be different */ && (FUZ_rand(&lseed) & 1)) {
1327             CHECK_Z( ZSTD_resetDStream(zd) );
1328         } else {
1329             CHECK_Z( ZSTD_initDStream_usingDict(zd, dict, dictSize) );
1330         }
1331         {   size_t decompressionResult = 1;
1332             ZSTD_inBuffer  inBuff = { cBuffer, cSize, 0 };
1333             ZSTD_outBuffer outBuff= { dstBuffer, dstBufferSize, 0 };
1334             for (totalGenSize = 0 ; decompressionResult ; ) {
1335                 size_t const readCSrcSize = FUZ_randomLength(&lseed, maxSampleLog);
1336                 size_t const randomDstSize = FUZ_randomLength(&lseed, maxSampleLog);
1337                 size_t const dstBuffSize = MIN(dstBufferSize - totalGenSize, randomDstSize);
1338                 inBuff.size = inBuff.pos + readCSrcSize;
1339                 outBuff.size = outBuff.pos + dstBuffSize;
1340                 DISPLAYLEVEL(6, "ZSTD_decompressStream input %u bytes \n", (U32)readCSrcSize);
1341                 decompressionResult = ZSTD_decompressStream(zd, &outBuff, &inBuff);
1342                 CHECK (ZSTD_isError(decompressionResult), "decompression error : %s", ZSTD_getErrorName(decompressionResult));
1343                 DISPLAYLEVEL(6, "inBuff.pos = %u \n", (U32)readCSrcSize);
1344             }
1345             CHECK (outBuff.pos != totalTestSize, "decompressed data : wrong size (%u != %u)", (U32)outBuff.pos, (U32)totalTestSize);
1346             CHECK (inBuff.pos != cSize, "compressed data should be fully read (%u != %u)", (U32)inBuff.pos, (U32)cSize);
1347             {   U64 const crcDest = XXH64(dstBuffer, totalTestSize, 0);
1348                 if (crcDest!=crcOrig) findDiff(copyBuffer, dstBuffer, totalTestSize);
1349                 CHECK (crcDest!=crcOrig, "decompressed data corrupted");
1350         }   }
1351
1352         /*=====   noisy/erroneous src decompression test   =====*/
1353
1354         /* add some noise */
1355         {   U32 const nbNoiseChunks = (FUZ_rand(&lseed) & 7) + 2;
1356             U32 nn; for (nn=0; nn<nbNoiseChunks; nn++) {
1357                 size_t const randomNoiseSize = FUZ_randomLength(&lseed, maxSampleLog);
1358                 size_t const noiseSize  = MIN((cSize/3) , randomNoiseSize);
1359                 size_t const noiseStart = FUZ_rand(&lseed) % (srcBufferSize - noiseSize);
1360                 size_t const cStart = FUZ_rand(&lseed) % (cSize - noiseSize);
1361                 memcpy(cBuffer+cStart, srcBuffer+noiseStart, noiseSize);
1362         }   }
1363
1364         /* try decompression on noisy data */
1365         CHECK_Z( ZSTD_initDStream(zd_noise) );   /* note : no dictionary */
1366         {   ZSTD_inBuffer  inBuff = { cBuffer, cSize, 0 };
1367             ZSTD_outBuffer outBuff= { dstBuffer, dstBufferSize, 0 };
1368             while (outBuff.pos < dstBufferSize) {
1369                 size_t const randomCSrcSize = FUZ_randomLength(&lseed, maxSampleLog);
1370                 size_t const randomDstSize = FUZ_randomLength(&lseed, maxSampleLog);
1371                 size_t const adjustedDstSize = MIN(dstBufferSize - outBuff.pos, randomDstSize);
1372                 size_t const adjustedCSrcSize = MIN(cSize - inBuff.pos, randomCSrcSize);
1373                 outBuff.size = outBuff.pos + adjustedDstSize;
1374                 inBuff.size  = inBuff.pos + adjustedCSrcSize;
1375                 {   size_t const decompressError = ZSTD_decompressStream(zd, &outBuff, &inBuff);
1376                     if (ZSTD_isError(decompressError)) break;   /* error correctly detected */
1377                     /* No forward progress possible */
1378                     if (outBuff.pos < outBuff.size && inBuff.pos == cSize) break;
1379     }   }   }   }
1380     DISPLAY("\r%u fuzzer tests completed   \n", testNb);
1381
1382 _cleanup:
1383     ZSTDMT_freeCCtx(zc);
1384     ZSTD_freeDStream(zd);
1385     ZSTD_freeDStream(zd_noise);
1386     free(cNoiseBuffer[0]);
1387     free(cNoiseBuffer[1]);
1388     free(cNoiseBuffer[2]);
1389     free(cNoiseBuffer[3]);
1390     free(cNoiseBuffer[4]);
1391     free(copyBuffer);
1392     free(cBuffer);
1393     free(dstBuffer);
1394     return result;
1395
1396 _output_error:
1397     result = 1;
1398     goto _cleanup;
1399 }
1400
1401 /** If useOpaqueAPI, sets param in cctxParams.
1402  *  Otherwise, sets the param in zc. */
1403 static size_t setCCtxParameter(ZSTD_CCtx* zc, ZSTD_CCtx_params* cctxParams,
1404                                ZSTD_cParameter param, unsigned value,
1405                                U32 useOpaqueAPI)
1406 {
1407     if (useOpaqueAPI) {
1408         return ZSTD_CCtxParam_setParameter(cctxParams, param, value);
1409     } else {
1410         return ZSTD_CCtx_setParameter(zc, param, value);
1411     }
1412 }
1413
1414 /* Tests for ZSTD_compress_generic() API */
1415 static int fuzzerTests_newAPI(U32 seed, U32 nbTests, unsigned startTest, double compressibility, int bigTests, U32 const useOpaqueAPI)
1416 {
1417     U32 const maxSrcLog = bigTests ? 24 : 22;
1418     static const U32 maxSampleLog = 19;
1419     size_t const srcBufferSize = (size_t)1<<maxSrcLog;
1420     BYTE* cNoiseBuffer[5];
1421     size_t const copyBufferSize= srcBufferSize + (1<<maxSampleLog);
1422     BYTE*  const copyBuffer = (BYTE*)malloc (copyBufferSize);
1423     size_t const cBufferSize   = ZSTD_compressBound(srcBufferSize);
1424     BYTE*  const cBuffer = (BYTE*)malloc (cBufferSize);
1425     size_t const dstBufferSize = srcBufferSize;
1426     BYTE*  const dstBuffer = (BYTE*)malloc (dstBufferSize);
1427     U32 result = 0;
1428     U32 testNb = 0;
1429     U32 coreSeed = seed;
1430     ZSTD_CCtx* zc = ZSTD_createCCtx();   /* will be reset sometimes */
1431     ZSTD_DStream* zd = ZSTD_createDStream();   /* will be reset sometimes */
1432     ZSTD_DStream* const zd_noise = ZSTD_createDStream();
1433     UTIL_time_t const startClock = UTIL_getTime();
1434     const BYTE* dict = NULL;   /* can keep same dict on 2 consecutive tests */
1435     size_t dictSize = 0;
1436     U32 oldTestLog = 0;
1437     U32 windowLogMalus = 0;   /* can survive between 2 loops */
1438     U32 const cLevelMax = bigTests ? (U32)ZSTD_maxCLevel()-1 : g_cLevelMax_smallTests;
1439     U32 const nbThreadsMax = bigTests ? 4 : 2;
1440     ZSTD_CCtx_params* cctxParams = ZSTD_createCCtxParams();
1441
1442     /* allocations */
1443     cNoiseBuffer[0] = (BYTE*)malloc (srcBufferSize);
1444     cNoiseBuffer[1] = (BYTE*)malloc (srcBufferSize);
1445     cNoiseBuffer[2] = (BYTE*)malloc (srcBufferSize);
1446     cNoiseBuffer[3] = (BYTE*)malloc (srcBufferSize);
1447     cNoiseBuffer[4] = (BYTE*)malloc (srcBufferSize);
1448     CHECK (!cNoiseBuffer[0] || !cNoiseBuffer[1] || !cNoiseBuffer[2] || !cNoiseBuffer[3] || !cNoiseBuffer[4] ||
1449            !copyBuffer || !dstBuffer || !cBuffer || !zc || !zd || !zd_noise ,
1450            "Not enough memory, fuzzer tests cancelled");
1451
1452     /* Create initial samples */
1453     RDG_genBuffer(cNoiseBuffer[0], srcBufferSize, 0.00, 0., coreSeed);    /* pure noise */
1454     RDG_genBuffer(cNoiseBuffer[1], srcBufferSize, 0.05, 0., coreSeed);    /* barely compressible */
1455     RDG_genBuffer(cNoiseBuffer[2], srcBufferSize, compressibility, 0., coreSeed);
1456     RDG_genBuffer(cNoiseBuffer[3], srcBufferSize, 0.95, 0., coreSeed);    /* highly compressible */
1457     RDG_genBuffer(cNoiseBuffer[4], srcBufferSize, 1.00, 0., coreSeed);    /* sparse content */
1458     memset(copyBuffer, 0x65, copyBufferSize);                             /* make copyBuffer considered initialized */
1459     CHECK_Z( ZSTD_initDStream_usingDict(zd, NULL, 0) );   /* ensure at least one init */
1460
1461     /* catch up testNb */
1462     for (testNb=1; testNb < startTest; testNb++)
1463         FUZ_rand(&coreSeed);
1464
1465     /* test loop */
1466     for ( ; (testNb <= nbTests) || (UTIL_clockSpanMicro(startClock) < g_clockTime) ; testNb++ ) {
1467         U32 lseed;
1468         const BYTE* srcBuffer;
1469         size_t totalTestSize, totalGenSize, cSize;
1470         XXH64_state_t xxhState;
1471         U64 crcOrig;
1472         U32 resetAllowed = 1;
1473         size_t maxTestSize;
1474
1475         /* init */
1476         if (nbTests >= testNb) { DISPLAYUPDATE(2, "\r%6u/%6u    ", testNb, nbTests); }
1477         else { DISPLAYUPDATE(2, "\r%6u          ", testNb); }
1478         FUZ_rand(&coreSeed);
1479         lseed = coreSeed ^ prime32;
1480         DISPLAYLEVEL(5, " ***  Test %u  *** \n", testNb);
1481
1482         /* states full reset (deliberately not synchronized) */
1483         /* some issues can only happen when reusing states */
1484         if ((FUZ_rand(&lseed) & 0xFF) == 131) {
1485             DISPLAYLEVEL(5, "Creating new context \n");
1486             ZSTD_freeCCtx(zc);
1487             zc = ZSTD_createCCtx();
1488             CHECK(zc==NULL, "ZSTD_createCCtx allocation error");
1489             resetAllowed=0;
1490         }
1491         if ((FUZ_rand(&lseed) & 0xFF) == 132) {
1492             ZSTD_freeDStream(zd);
1493             zd = ZSTD_createDStream();
1494             CHECK(zd==NULL, "ZSTD_createDStream allocation error");
1495             ZSTD_initDStream_usingDict(zd, NULL, 0);  /* ensure at least one init */
1496         }
1497
1498         /* srcBuffer selection [0-4] */
1499         {   U32 buffNb = FUZ_rand(&lseed) & 0x7F;
1500             if (buffNb & 7) buffNb=2;   /* most common : compressible (P) */
1501             else {
1502                 buffNb >>= 3;
1503                 if (buffNb & 7) {
1504                     const U32 tnb[2] = { 1, 3 };   /* barely/highly compressible */
1505                     buffNb = tnb[buffNb >> 3];
1506                 } else {
1507                     const U32 tnb[2] = { 0, 4 };   /* not compressible / sparse */
1508                     buffNb = tnb[buffNb >> 3];
1509             }   }
1510             srcBuffer = cNoiseBuffer[buffNb];
1511         }
1512
1513         /* compression init */
1514         CHECK_Z( ZSTD_CCtx_loadDictionary(zc, NULL, 0) );   /* cancel previous dict /*/
1515         if ((FUZ_rand(&lseed)&1) /* at beginning, to keep same nb of rand */
1516             && oldTestLog /* at least one test happened */ && resetAllowed) {
1517             maxTestSize = FUZ_randomLength(&lseed, oldTestLog+2);
1518             if (maxTestSize >= srcBufferSize) maxTestSize = srcBufferSize-1;
1519             {   int const compressionLevel = (FUZ_rand(&lseed) % 5) + 1;
1520                 CHECK_Z (setCCtxParameter(zc, cctxParams, ZSTD_p_compressionLevel, compressionLevel, useOpaqueAPI) );
1521             }
1522         } else {
1523             U32 const testLog = FUZ_rand(&lseed) % maxSrcLog;
1524             U32 const dictLog = FUZ_rand(&lseed) % maxSrcLog;
1525             U32 const cLevelCandidate = (FUZ_rand(&lseed) %
1526                                (ZSTD_maxCLevel() -
1527                                (MAX(testLog, dictLog) / 2))) +
1528                                1;
1529             U32 const cLevel = MIN(cLevelCandidate, cLevelMax);
1530             DISPLAYLEVEL(5, "t%u: base cLevel : %u \n", testNb, cLevel);
1531             maxTestSize = FUZ_rLogLength(&lseed, testLog);
1532             DISPLAYLEVEL(5, "t%u: maxTestSize : %u \n", testNb, (U32)maxTestSize);
1533             oldTestLog = testLog;
1534             /* random dictionary selection */
1535             dictSize  = ((FUZ_rand(&lseed)&63)==1) ? FUZ_rLogLength(&lseed, dictLog) : 0;
1536             {   size_t const dictStart = FUZ_rand(&lseed) % (srcBufferSize - dictSize);
1537                 dict = srcBuffer + dictStart;
1538                 if (!dictSize) dict=NULL;
1539             }
1540             {   U64 const pledgedSrcSize = (FUZ_rand(&lseed) & 3) ? ZSTD_CONTENTSIZE_UNKNOWN : maxTestSize;
1541                 ZSTD_compressionParameters cParams = ZSTD_getCParams(cLevel, pledgedSrcSize, dictSize);
1542                 static const U32 windowLogMax = 24;
1543
1544                 /* mess with compression parameters */
1545                 cParams.windowLog += (FUZ_rand(&lseed) & 3) - 1;
1546                 cParams.windowLog = MIN(windowLogMax, cParams.windowLog);
1547                 cParams.hashLog += (FUZ_rand(&lseed) & 3) - 1;
1548                 cParams.chainLog += (FUZ_rand(&lseed) & 3) - 1;
1549                 cParams.searchLog += (FUZ_rand(&lseed) & 3) - 1;
1550                 cParams.searchLength += (FUZ_rand(&lseed) & 3) - 1;
1551                 cParams.targetLength = (U32)((cParams.targetLength + 1 ) * (0.5 + ((double)(FUZ_rand(&lseed) & 127) / 128)));
1552                 cParams = ZSTD_adjustCParams(cParams, 0, 0);
1553
1554                 if (FUZ_rand(&lseed) & 1) {
1555                     DISPLAYLEVEL(5, "t%u: windowLog : %u \n", testNb, cParams.windowLog);
1556                     CHECK_Z( setCCtxParameter(zc, cctxParams, ZSTD_p_windowLog, cParams.windowLog, useOpaqueAPI) );
1557                     assert(cParams.windowLog >= ZSTD_WINDOWLOG_MIN);   /* guaranteed by ZSTD_adjustCParams() */
1558                     windowLogMalus = (cParams.windowLog - ZSTD_WINDOWLOG_MIN) / 5;
1559                 }
1560                 if (FUZ_rand(&lseed) & 1) {
1561                     DISPLAYLEVEL(5, "t%u: hashLog : %u \n", testNb, cParams.hashLog);
1562                     CHECK_Z( setCCtxParameter(zc, cctxParams, ZSTD_p_hashLog, cParams.hashLog, useOpaqueAPI) );
1563                 }
1564                 if (FUZ_rand(&lseed) & 1) {
1565                     DISPLAYLEVEL(5, "t%u: chainLog : %u \n", testNb, cParams.chainLog);
1566                     CHECK_Z( setCCtxParameter(zc, cctxParams, ZSTD_p_chainLog, cParams.chainLog, useOpaqueAPI) );
1567                 }
1568                 if (FUZ_rand(&lseed) & 1) CHECK_Z( setCCtxParameter(zc, cctxParams, ZSTD_p_searchLog, cParams.searchLog, useOpaqueAPI) );
1569                 if (FUZ_rand(&lseed) & 1) CHECK_Z( setCCtxParameter(zc, cctxParams, ZSTD_p_minMatch, cParams.searchLength, useOpaqueAPI) );
1570                 if (FUZ_rand(&lseed) & 1) CHECK_Z( setCCtxParameter(zc, cctxParams, ZSTD_p_targetLength, cParams.targetLength, useOpaqueAPI) );
1571
1572                 /* mess with long distance matching parameters */
1573                 if (bigTests) {
1574                     if (FUZ_rand(&lseed) & 1) CHECK_Z( setCCtxParameter(zc, cctxParams, ZSTD_p_enableLongDistanceMatching, FUZ_rand(&lseed) & 63, useOpaqueAPI) );
1575                     if (FUZ_rand(&lseed) & 3) CHECK_Z( setCCtxParameter(zc, cctxParams, ZSTD_p_ldmHashLog, FUZ_randomClampedLength(&lseed, ZSTD_HASHLOG_MIN, 23), useOpaqueAPI) );
1576                     if (FUZ_rand(&lseed) & 3) CHECK_Z( setCCtxParameter(zc, cctxParams, ZSTD_p_ldmMinMatch, FUZ_randomClampedLength(&lseed, ZSTD_LDM_MINMATCH_MIN, ZSTD_LDM_MINMATCH_MAX), useOpaqueAPI) );
1577                     if (FUZ_rand(&lseed) & 3) CHECK_Z( setCCtxParameter(zc, cctxParams, ZSTD_p_ldmBucketSizeLog, FUZ_randomClampedLength(&lseed, 0, ZSTD_LDM_BUCKETSIZELOG_MAX), useOpaqueAPI) );
1578                     if (FUZ_rand(&lseed) & 3) CHECK_Z( setCCtxParameter(zc, cctxParams, ZSTD_p_ldmHashEveryLog, FUZ_randomClampedLength(&lseed, 0, ZSTD_WINDOWLOG_MAX - ZSTD_HASHLOG_MIN), useOpaqueAPI) );
1579                 }
1580
1581                 /* mess with frame parameters */
1582                 if (FUZ_rand(&lseed) & 1) CHECK_Z( setCCtxParameter(zc, cctxParams, ZSTD_p_checksumFlag, FUZ_rand(&lseed) & 1, useOpaqueAPI) );
1583                 if (FUZ_rand(&lseed) & 1) CHECK_Z( setCCtxParameter(zc, cctxParams, ZSTD_p_dictIDFlag, FUZ_rand(&lseed) & 1, useOpaqueAPI) );
1584                 if (FUZ_rand(&lseed) & 1) CHECK_Z( setCCtxParameter(zc, cctxParams, ZSTD_p_contentSizeFlag, FUZ_rand(&lseed) & 1, useOpaqueAPI) );
1585                 if (FUZ_rand(&lseed) & 1) {
1586                     DISPLAYLEVEL(5, "t%u: pledgedSrcSize : %u \n", testNb, (U32)pledgedSrcSize);
1587                     CHECK_Z( ZSTD_CCtx_setPledgedSrcSize(zc, pledgedSrcSize) );
1588                 }
1589
1590                 /* multi-threading parameters */
1591                 {   U32 const nbThreadsCandidate = (FUZ_rand(&lseed) & 4) + 1;
1592                     U32 const nbThreadsAdjusted = (windowLogMalus < nbThreadsCandidate) ? nbThreadsCandidate - windowLogMalus : 1;
1593                     U32 const nbThreads = MIN(nbThreadsAdjusted, nbThreadsMax);
1594                     DISPLAYLEVEL(5, "t%u: nbThreads : %u \n", testNb, nbThreads);
1595                     CHECK_Z( setCCtxParameter(zc, cctxParams, ZSTD_p_nbThreads, nbThreads, useOpaqueAPI) );
1596                     if (nbThreads > 1) {
1597                         U32 const jobLog = FUZ_rand(&lseed) % (testLog+1);
1598                         CHECK_Z( setCCtxParameter(zc, cctxParams, ZSTD_p_overlapSizeLog, FUZ_rand(&lseed) % 10, useOpaqueAPI) );
1599                         CHECK_Z( setCCtxParameter(zc, cctxParams, ZSTD_p_jobSize, (U32)FUZ_rLogLength(&lseed, jobLog), useOpaqueAPI) );
1600                     }
1601                 }
1602
1603                 if (FUZ_rand(&lseed) & 1) CHECK_Z( setCCtxParameter(zc, cctxParams, ZSTD_p_forceMaxWindow, FUZ_rand(&lseed) & 1, useOpaqueAPI) );
1604
1605                 /* Apply parameters */
1606                 if (useOpaqueAPI) {
1607                     DISPLAYLEVEL(6," t%u: applying CCtxParams \n", testNb);
1608                     CHECK_Z (ZSTD_CCtx_setParametersUsingCCtxParams(zc, cctxParams) );
1609                 }
1610
1611                 if (FUZ_rand(&lseed) & 1) {
1612                     if (FUZ_rand(&lseed) & 1) {
1613                         CHECK_Z( ZSTD_CCtx_loadDictionary(zc, dict, dictSize) );
1614                     } else {
1615                         CHECK_Z( ZSTD_CCtx_loadDictionary_byReference(zc, dict, dictSize) );
1616                     }
1617                     if (dict && dictSize) {
1618                         /* test that compression parameters are rejected (correctly) after loading a non-NULL dictionary */
1619                         if (useOpaqueAPI) {
1620                             size_t const setError = ZSTD_CCtx_setParametersUsingCCtxParams(zc, cctxParams);
1621                             CHECK(!ZSTD_isError(setError), "ZSTD_CCtx_setParametersUsingCCtxParams should have failed");
1622                         } else {
1623                             size_t const setError = ZSTD_CCtx_setParameter(zc, ZSTD_p_windowLog, cParams.windowLog-1);
1624                             CHECK(!ZSTD_isError(setError), "ZSTD_CCtx_setParameter should have failed");
1625                         }
1626                     }
1627                 } else {
1628                     CHECK_Z( ZSTD_CCtx_refPrefix(zc, dict, dictSize) );
1629                 }
1630         }   }
1631
1632         /* multi-segments compression test */
1633         XXH64_reset(&xxhState, 0);
1634         {   ZSTD_outBuffer outBuff = { cBuffer, cBufferSize, 0 } ;
1635             for (cSize=0, totalTestSize=0 ; (totalTestSize < maxTestSize) ; ) {
1636                 /* compress random chunks into randomly sized dst buffers */
1637                 size_t const randomSrcSize = FUZ_randomLength(&lseed, maxSampleLog);
1638                 size_t const srcSize = MIN(maxTestSize-totalTestSize, randomSrcSize);
1639                 size_t const srcStart = FUZ_rand(&lseed) % (srcBufferSize - srcSize);
1640                 size_t const randomDstSize = FUZ_randomLength(&lseed, maxSampleLog+1);
1641                 size_t const dstBuffSize = MIN(cBufferSize - cSize, randomDstSize);
1642                 ZSTD_EndDirective const flush = (FUZ_rand(&lseed) & 15) ? ZSTD_e_continue : ZSTD_e_flush;
1643                 ZSTD_inBuffer inBuff = { srcBuffer+srcStart, srcSize, 0 };
1644                 outBuff.size = outBuff.pos + dstBuffSize;
1645
1646                 CHECK_Z( ZSTD_compress_generic(zc, &outBuff, &inBuff, flush) );
1647                 DISPLAYLEVEL(6, "t%u: compress consumed %u bytes (total : %u) \n",
1648                     testNb, (U32)inBuff.pos, (U32)(totalTestSize + inBuff.pos));
1649
1650                 XXH64_update(&xxhState, srcBuffer+srcStart, inBuff.pos);
1651                 memcpy(copyBuffer+totalTestSize, srcBuffer+srcStart, inBuff.pos);
1652                 totalTestSize += inBuff.pos;
1653             }
1654
1655             /* final frame epilogue */
1656             {   size_t remainingToFlush = (size_t)(-1);
1657                 while (remainingToFlush) {
1658                     ZSTD_inBuffer inBuff = { NULL, 0, 0 };
1659                     size_t const randomDstSize = FUZ_randomLength(&lseed, maxSampleLog+1);
1660                     size_t const adjustedDstSize = MIN(cBufferSize - cSize, randomDstSize);
1661                     outBuff.size = outBuff.pos + adjustedDstSize;
1662                     DISPLAYLEVEL(6, "End-flush into dst buffer of size %u \n", (U32)adjustedDstSize);
1663                     remainingToFlush = ZSTD_compress_generic(zc, &outBuff, &inBuff, ZSTD_e_end);
1664                     CHECK( ZSTD_isError(remainingToFlush),
1665                           "ZSTD_compress_generic w/ ZSTD_e_end error : %s",
1666                            ZSTD_getErrorName(remainingToFlush) );
1667             }   }
1668             crcOrig = XXH64_digest(&xxhState);
1669             cSize = outBuff.pos;
1670             DISPLAYLEVEL(5, "Frame completed : %u bytes \n", (U32)cSize);
1671         }
1672
1673         /* multi - fragments decompression test */
1674         if (!dictSize /* don't reset if dictionary : could be different */ && (FUZ_rand(&lseed) & 1)) {
1675             DISPLAYLEVEL(5, "resetting DCtx (dict:%08X) \n", (U32)(size_t)dict);
1676             CHECK_Z( ZSTD_resetDStream(zd) );
1677         } else {
1678             DISPLAYLEVEL(5, "using dict of size %u \n", (U32)dictSize);
1679             CHECK_Z( ZSTD_initDStream_usingDict(zd, dict, dictSize) );
1680         }
1681         {   size_t decompressionResult = 1;
1682             ZSTD_inBuffer  inBuff = { cBuffer, cSize, 0 };
1683             ZSTD_outBuffer outBuff= { dstBuffer, dstBufferSize, 0 };
1684             for (totalGenSize = 0 ; decompressionResult ; ) {
1685                 size_t const readCSrcSize = FUZ_randomLength(&lseed, maxSampleLog);
1686                 size_t const randomDstSize = FUZ_randomLength(&lseed, maxSampleLog);
1687                 size_t const dstBuffSize = MIN(dstBufferSize - totalGenSize, randomDstSize);
1688                 inBuff.size = inBuff.pos + readCSrcSize;
1689                 outBuff.size = outBuff.pos + dstBuffSize;
1690                 DISPLAYLEVEL(6, "ZSTD_decompressStream input %u bytes (pos:%u/%u)\n",
1691                             (U32)readCSrcSize, (U32)inBuff.pos, (U32)cSize);
1692                 decompressionResult = ZSTD_decompressStream(zd, &outBuff, &inBuff);
1693                 CHECK (ZSTD_isError(decompressionResult), "decompression error : %s", ZSTD_getErrorName(decompressionResult));
1694                 DISPLAYLEVEL(6, "inBuff.pos = %u \n", (U32)readCSrcSize);
1695             }
1696             CHECK (outBuff.pos != totalTestSize, "decompressed data : wrong size (%u != %u)", (U32)outBuff.pos, (U32)totalTestSize);
1697             CHECK (inBuff.pos != cSize, "compressed data should be fully read (%u != %u)", (U32)inBuff.pos, (U32)cSize);
1698             {   U64 const crcDest = XXH64(dstBuffer, totalTestSize, 0);
1699                 if (crcDest!=crcOrig) findDiff(copyBuffer, dstBuffer, totalTestSize);
1700                 CHECK (crcDest!=crcOrig, "decompressed data corrupted");
1701         }   }
1702
1703         /*=====   noisy/erroneous src decompression test   =====*/
1704
1705         /* add some noise */
1706         {   U32 const nbNoiseChunks = (FUZ_rand(&lseed) & 7) + 2;
1707             U32 nn; for (nn=0; nn<nbNoiseChunks; nn++) {
1708                 size_t const randomNoiseSize = FUZ_randomLength(&lseed, maxSampleLog);
1709                 size_t const noiseSize  = MIN((cSize/3) , randomNoiseSize);
1710                 size_t const noiseStart = FUZ_rand(&lseed) % (srcBufferSize - noiseSize);
1711                 size_t const cStart = FUZ_rand(&lseed) % (cSize - noiseSize);
1712                 memcpy(cBuffer+cStart, srcBuffer+noiseStart, noiseSize);
1713         }   }
1714
1715         /* try decompression on noisy data */
1716         CHECK_Z( ZSTD_initDStream(zd_noise) );   /* note : no dictionary */
1717         {   ZSTD_inBuffer  inBuff = { cBuffer, cSize, 0 };
1718             ZSTD_outBuffer outBuff= { dstBuffer, dstBufferSize, 0 };
1719             while (outBuff.pos < dstBufferSize) {
1720                 size_t const randomCSrcSize = FUZ_randomLength(&lseed, maxSampleLog);
1721                 size_t const randomDstSize = FUZ_randomLength(&lseed, maxSampleLog);
1722                 size_t const adjustedDstSize = MIN(dstBufferSize - outBuff.pos, randomDstSize);
1723                 size_t const adjustedCSrcSize = MIN(cSize - inBuff.pos, randomCSrcSize);
1724                 outBuff.size = outBuff.pos + adjustedDstSize;
1725                 inBuff.size  = inBuff.pos + adjustedCSrcSize;
1726                 {   size_t const decompressError = ZSTD_decompressStream(zd, &outBuff, &inBuff);
1727                     if (ZSTD_isError(decompressError)) break;   /* error correctly detected */
1728                     /* Good so far, but no more progress possible */
1729                     if (outBuff.pos < outBuff.size && inBuff.pos == cSize) break;
1730     }   }   }   }
1731     DISPLAY("\r%u fuzzer tests completed   \n", testNb-1);
1732
1733 _cleanup:
1734     ZSTD_freeCCtx(zc);
1735     ZSTD_freeDStream(zd);
1736     ZSTD_freeDStream(zd_noise);
1737     ZSTD_freeCCtxParams(cctxParams);
1738     free(cNoiseBuffer[0]);
1739     free(cNoiseBuffer[1]);
1740     free(cNoiseBuffer[2]);
1741     free(cNoiseBuffer[3]);
1742     free(cNoiseBuffer[4]);
1743     free(copyBuffer);
1744     free(cBuffer);
1745     free(dstBuffer);
1746     return result;
1747
1748 _output_error:
1749     result = 1;
1750     goto _cleanup;
1751 }
1752
1753 /*-*******************************************************
1754 *  Command line
1755 *********************************************************/
1756 int FUZ_usage(const char* programName)
1757 {
1758     DISPLAY( "Usage :\n");
1759     DISPLAY( "      %s [args]\n", programName);
1760     DISPLAY( "\n");
1761     DISPLAY( "Arguments :\n");
1762     DISPLAY( " -i#    : Nb of tests (default:%u) \n", nbTestsDefault);
1763     DISPLAY( " -s#    : Select seed (default:prompt user)\n");
1764     DISPLAY( " -t#    : Select starting test number (default:0)\n");
1765     DISPLAY( " -P#    : Select compressibility in %% (default:%i%%)\n", FUZ_COMPRESSIBILITY_DEFAULT);
1766     DISPLAY( " -v     : verbose\n");
1767     DISPLAY( " -p     : pause at the end\n");
1768     DISPLAY( " -h     : display help and exit\n");
1769     return 0;
1770 }
1771
1772 typedef enum { simple_api, mt_api, advanced_api } e_api;
1773
1774 int main(int argc, const char** argv)
1775 {
1776     U32 seed = 0;
1777     int seedset = 0;
1778     int nbTests = nbTestsDefault;
1779     int testNb = 0;
1780     int proba = FUZ_COMPRESSIBILITY_DEFAULT;
1781     int result = 0;
1782     int mainPause = 0;
1783     int bigTests = (sizeof(size_t) == 8);
1784     e_api selected_api = simple_api;
1785     const char* const programName = argv[0];
1786     U32 useOpaqueAPI = 0;
1787     int argNb;
1788
1789     /* Check command line */
1790     for(argNb=1; argNb<argc; argNb++) {
1791         const char* argument = argv[argNb];
1792         assert(argument != NULL);
1793
1794         /* Parsing commands. Aggregated commands are allowed */
1795         if (argument[0]=='-') {
1796
1797             if (!strcmp(argument, "--mt")) { selected_api=mt_api; testNb += !testNb; continue; }
1798             if (!strcmp(argument, "--newapi")) { selected_api=advanced_api; testNb += !testNb; continue; }
1799             if (!strcmp(argument, "--opaqueapi")) { selected_api=advanced_api; testNb += !testNb; useOpaqueAPI = 1; continue; }
1800             if (!strcmp(argument, "--no-big-tests")) { bigTests=0; continue; }
1801
1802             argument++;
1803             while (*argument!=0) {
1804                 switch(*argument)
1805                 {
1806                 case 'h':
1807                     return FUZ_usage(programName);
1808
1809                 case 'v':
1810                     argument++;
1811                     g_displayLevel++;
1812                     break;
1813
1814                 case 'q':
1815                     argument++;
1816                     g_displayLevel--;
1817                     break;
1818
1819                 case 'p': /* pause at the end */
1820                     argument++;
1821                     mainPause = 1;
1822                     break;
1823
1824                 case 'i':   /* limit tests by nb of iterations (default) */
1825                     argument++;
1826                     nbTests=0; g_clockTime=0;
1827                     while ((*argument>='0') && (*argument<='9')) {
1828                         nbTests *= 10;
1829                         nbTests += *argument - '0';
1830                         argument++;
1831                     }
1832                     break;
1833
1834                 case 'T':   /* limit tests by time */
1835                     argument++;
1836                     nbTests=0; g_clockTime=0;
1837                     while ((*argument>='0') && (*argument<='9')) {
1838                         g_clockTime *= 10;
1839                         g_clockTime += *argument - '0';
1840                         argument++;
1841                     }
1842                     if (*argument=='m') {    /* -T1m == -T60 */
1843                         g_clockTime *=60, argument++;
1844                         if (*argument=='n') argument++; /* -T1mn == -T60 */
1845                     } else if (*argument=='s') argument++; /* -T10s == -T10 */
1846                     g_clockTime *= SEC_TO_MICRO;
1847                     break;
1848
1849                 case 's':   /* manually select seed */
1850                     argument++;
1851                     seedset=1;
1852                     seed=0;
1853                     while ((*argument>='0') && (*argument<='9')) {
1854                         seed *= 10;
1855                         seed += *argument - '0';
1856                         argument++;
1857                     }
1858                     break;
1859
1860                 case 't':   /* select starting test number */
1861                     argument++;
1862                     testNb=0;
1863                     while ((*argument>='0') && (*argument<='9')) {
1864                         testNb *= 10;
1865                         testNb += *argument - '0';
1866                         argument++;
1867                     }
1868                     break;
1869
1870                 case 'P':   /* compressibility % */
1871                     argument++;
1872                     proba=0;
1873                     while ((*argument>='0') && (*argument<='9')) {
1874                         proba *= 10;
1875                         proba += *argument - '0';
1876                         argument++;
1877                     }
1878                     if (proba<0) proba=0;
1879                     if (proba>100) proba=100;
1880                     break;
1881
1882                 default:
1883                     return FUZ_usage(programName);
1884                 }
1885     }   }   }   /* for(argNb=1; argNb<argc; argNb++) */
1886
1887     /* Get Seed */
1888     DISPLAY("Starting zstream tester (%i-bits, %s)\n", (int)(sizeof(size_t)*8), ZSTD_VERSION_STRING);
1889
1890     if (!seedset) {
1891         time_t const t = time(NULL);
1892         U32 const h = XXH32(&t, sizeof(t), 1);
1893         seed = h % 10000;
1894     }
1895
1896     DISPLAY("Seed = %u\n", seed);
1897     if (proba!=FUZ_COMPRESSIBILITY_DEFAULT) DISPLAY("Compressibility : %i%%\n", proba);
1898
1899     if (nbTests<=0) nbTests=1;
1900
1901     if (testNb==0) {
1902         result = basicUnitTests(0, ((double)proba) / 100);  /* constant seed for predictability */
1903     }
1904
1905     if (!result) {
1906         switch(selected_api)
1907         {
1908         case simple_api :
1909             result = fuzzerTests(seed, nbTests, testNb, ((double)proba) / 100, bigTests);
1910             break;
1911         case mt_api :
1912             result = fuzzerTests_MT(seed, nbTests, testNb, ((double)proba) / 100, bigTests);
1913             break;
1914         case advanced_api :
1915             result = fuzzerTests_newAPI(seed, nbTests, testNb, ((double)proba) / 100, bigTests, useOpaqueAPI);
1916             break;
1917         default :
1918             assert(0);   /* impossible */
1919         }
1920     }
1921
1922     if (mainPause) {
1923         int unused;
1924         DISPLAY("Press Enter \n");
1925         unused = getchar();
1926         (void)unused;
1927     }
1928     return result;
1929 }