]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - tests/fuzzer.c
import zstd 1.4.1
[FreeBSD/FreeBSD.git] / tests / fuzzer.c
1 /*
2  * Copyright (c) 2015-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 : 4204)   /* disable: C4204: non-constant aggregate initializer */
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>
29 #define ZSTD_STATIC_LINKING_ONLY  /* ZSTD_compressContinue, ZSTD_compressBlock */
30 #include "fse.h"
31 #include "zstd.h"         /* ZSTD_VERSION_STRING */
32 #include "zstd_errors.h"  /* ZSTD_getErrorCode */
33 #include "zstdmt_compress.h"
34 #define ZDICT_STATIC_LINKING_ONLY
35 #include "zdict.h"        /* ZDICT_trainFromBuffer */
36 #include "datagen.h"      /* RDG_genBuffer */
37 #include "mem.h"
38 #define XXH_STATIC_LINKING_ONLY   /* XXH64_state_t */
39 #include "xxhash.h"       /* XXH64 */
40 #include "util.h"
41 #include "timefn.h"       /* SEC_TO_MICRO, UTIL_time_t, UTIL_TIME_INITIALIZER, UTIL_clockSpanMicro, UTIL_getTime */
42
43
44 /*-************************************
45 *  Constants
46 **************************************/
47 #define KB *(1U<<10)
48 #define MB *(1U<<20)
49 #define GB *(1U<<30)
50
51 static const int FUZ_compressibility_default = 50;
52 static const int nbTestsDefault = 30000;
53
54
55 /*-************************************
56 *  Display Macros
57 **************************************/
58 #define DISPLAY(...)          fprintf(stderr, __VA_ARGS__)
59 #define DISPLAYLEVEL(l, ...)  if (g_displayLevel>=l) { DISPLAY(__VA_ARGS__); }
60 static U32 g_displayLevel = 2;
61
62 static const U64 g_refreshRate = SEC_TO_MICRO / 6;
63 static UTIL_time_t g_displayClock = UTIL_TIME_INITIALIZER;
64
65 #define DISPLAYUPDATE(l, ...) \
66     if (g_displayLevel>=l) { \
67         if ((UTIL_clockSpanMicro(g_displayClock) > g_refreshRate) || (g_displayLevel>=4)) \
68         { g_displayClock = UTIL_getTime(); DISPLAY(__VA_ARGS__); \
69         if (g_displayLevel>=4) fflush(stderr); } \
70     }
71
72
73 /*-*******************************************************
74 *  Compile time test
75 *********************************************************/
76 #undef MIN
77 #undef MAX
78 /* Declaring the function, to avoid -Wmissing-prototype */
79 void FUZ_bug976(void);
80 void FUZ_bug976(void)
81 {   /* these constants shall not depend on MIN() macro */
82     assert(ZSTD_HASHLOG_MAX < 31);
83     assert(ZSTD_CHAINLOG_MAX < 31);
84 }
85
86
87 /*-*******************************************************
88 *  Internal functions
89 *********************************************************/
90 #define MIN(a,b) ((a)<(b)?(a):(b))
91 #define MAX(a,b) ((a)>(b)?(a):(b))
92
93 #define FUZ_rotl32(x,r) ((x << r) | (x >> (32 - r)))
94 static U32 FUZ_rand(U32* src)
95 {
96     static const U32 prime1 = 2654435761U;
97     static const U32 prime2 = 2246822519U;
98     U32 rand32 = *src;
99     rand32 *= prime1;
100     rand32 += prime2;
101     rand32  = FUZ_rotl32(rand32, 13);
102     *src = rand32;
103     return rand32 >> 5;
104 }
105
106 static U32 FUZ_highbit32(U32 v32)
107 {
108     unsigned nbBits = 0;
109     if (v32==0) return 0;
110     while (v32) v32 >>= 1, nbBits++;
111     return nbBits;
112 }
113
114
115 /*=============================================
116 *   Test macros
117 =============================================*/
118 #define CHECK_Z(f) {                               \
119     size_t const err = f;                          \
120     if (ZSTD_isError(err)) {                       \
121         DISPLAY("Error => %s : %s ",               \
122                 #f, ZSTD_getErrorName(err));       \
123         exit(1);                                   \
124 }   }
125
126 #define CHECK_V(var, fn)  size_t const var = fn; if (ZSTD_isError(var)) goto _output_error
127 #define CHECK(fn)  { CHECK_V(err, fn); }
128 #define CHECKPLUS(var, fn, more)  { CHECK_V(var, fn); more; }
129
130 #define CHECK_OP(op, lhs, rhs) {                                  \
131     if (!((lhs) op (rhs))) {                                      \
132         DISPLAY("Error L%u => FAILED %s %s %s ", __LINE__, #lhs, #op, #rhs);  \
133         goto _output_error;                                       \
134     }                                                             \
135 }
136 #define CHECK_EQ(lhs, rhs) CHECK_OP(==, lhs, rhs)
137 #define CHECK_LT(lhs, rhs) CHECK_OP(<, lhs, rhs)
138
139
140 /*=============================================
141 *   Memory Tests
142 =============================================*/
143 #if defined(__APPLE__) && defined(__MACH__)
144
145 #include <malloc/malloc.h>    /* malloc_size */
146
147 typedef struct {
148     unsigned long long totalMalloc;
149     size_t currentMalloc;
150     size_t peakMalloc;
151     unsigned nbMalloc;
152     unsigned nbFree;
153 } mallocCounter_t;
154
155 static const mallocCounter_t INIT_MALLOC_COUNTER = { 0, 0, 0, 0, 0 };
156
157 static void* FUZ_mallocDebug(void* counter, size_t size)
158 {
159     mallocCounter_t* const mcPtr = (mallocCounter_t*)counter;
160     void* const ptr = malloc(size);
161     if (ptr==NULL) return NULL;
162     DISPLAYLEVEL(4, "allocating %u KB => effectively %u KB \n",
163         (unsigned)(size >> 10), (unsigned)(malloc_size(ptr) >> 10));  /* OS-X specific */
164     mcPtr->totalMalloc += size;
165     mcPtr->currentMalloc += size;
166     if (mcPtr->currentMalloc > mcPtr->peakMalloc)
167         mcPtr->peakMalloc = mcPtr->currentMalloc;
168     mcPtr->nbMalloc += 1;
169     return ptr;
170 }
171
172 static void FUZ_freeDebug(void* counter, void* address)
173 {
174     mallocCounter_t* const mcPtr = (mallocCounter_t*)counter;
175     DISPLAYLEVEL(4, "freeing %u KB \n", (unsigned)(malloc_size(address) >> 10));
176     mcPtr->nbFree += 1;
177     mcPtr->currentMalloc -= malloc_size(address);  /* OS-X specific */
178     free(address);
179 }
180
181 static void FUZ_displayMallocStats(mallocCounter_t count)
182 {
183     DISPLAYLEVEL(3, "peak:%6u KB,  nbMallocs:%2u, total:%6u KB \n",
184         (unsigned)(count.peakMalloc >> 10),
185         count.nbMalloc,
186         (unsigned)(count.totalMalloc >> 10));
187 }
188
189 static int FUZ_mallocTests_internal(unsigned seed, double compressibility, unsigned part,
190                 void* inBuffer, size_t inSize, void* outBuffer, size_t outSize)
191 {
192     /* test only played in verbose mode, as they are long */
193     if (g_displayLevel<3) return 0;
194
195     /* Create compressible noise */
196     if (!inBuffer || !outBuffer) {
197         DISPLAY("Not enough memory, aborting\n");
198         exit(1);
199     }
200     RDG_genBuffer(inBuffer, inSize, compressibility, 0. /*auto*/, seed);
201
202     /* simple compression tests */
203     if (part <= 1)
204     {   int compressionLevel;
205         for (compressionLevel=1; compressionLevel<=6; compressionLevel++) {
206             mallocCounter_t malcount = INIT_MALLOC_COUNTER;
207             ZSTD_customMem const cMem = { FUZ_mallocDebug, FUZ_freeDebug, &malcount };
208             ZSTD_CCtx* const cctx = ZSTD_createCCtx_advanced(cMem);
209             CHECK_Z( ZSTD_compressCCtx(cctx, outBuffer, outSize, inBuffer, inSize, compressionLevel) );
210             ZSTD_freeCCtx(cctx);
211             DISPLAYLEVEL(3, "compressCCtx level %i : ", compressionLevel);
212             FUZ_displayMallocStats(malcount);
213     }   }
214
215     /* streaming compression tests */
216     if (part <= 2)
217     {   int compressionLevel;
218         for (compressionLevel=1; compressionLevel<=6; compressionLevel++) {
219             mallocCounter_t malcount = INIT_MALLOC_COUNTER;
220             ZSTD_customMem const cMem = { FUZ_mallocDebug, FUZ_freeDebug, &malcount };
221             ZSTD_CCtx* const cstream = ZSTD_createCStream_advanced(cMem);
222             ZSTD_outBuffer out = { outBuffer, outSize, 0 };
223             ZSTD_inBuffer in = { inBuffer, inSize, 0 };
224             CHECK_Z( ZSTD_initCStream(cstream, compressionLevel) );
225             CHECK_Z( ZSTD_compressStream(cstream, &out, &in) );
226             CHECK_Z( ZSTD_endStream(cstream, &out) );
227             ZSTD_freeCStream(cstream);
228             DISPLAYLEVEL(3, "compressStream level %i : ", compressionLevel);
229             FUZ_displayMallocStats(malcount);
230     }   }
231
232     /* advanced MT API test */
233     if (part <= 3)
234     {   unsigned nbThreads;
235         for (nbThreads=1; nbThreads<=4; nbThreads++) {
236             int compressionLevel;
237             for (compressionLevel=1; compressionLevel<=6; compressionLevel++) {
238                 mallocCounter_t malcount = INIT_MALLOC_COUNTER;
239                 ZSTD_customMem const cMem = { FUZ_mallocDebug, FUZ_freeDebug, &malcount };
240                 ZSTD_CCtx* const cctx = ZSTD_createCCtx_advanced(cMem);
241                 CHECK_Z( ZSTD_CCtx_setParameter(cctx, ZSTD_c_compressionLevel, compressionLevel) );
242                 CHECK_Z( ZSTD_CCtx_setParameter(cctx, ZSTD_c_nbWorkers, nbThreads) );
243                 CHECK_Z( ZSTD_compress2(cctx, outBuffer, outSize, inBuffer, inSize) );
244                 ZSTD_freeCCtx(cctx);
245                 DISPLAYLEVEL(3, "compress_generic,-T%u,end level %i : ",
246                                 nbThreads, compressionLevel);
247                 FUZ_displayMallocStats(malcount);
248     }   }   }
249
250     /* advanced MT streaming API test */
251     if (part <= 4)
252     {   int nbThreads;
253         for (nbThreads=1; nbThreads<=4; nbThreads++) {
254             int compressionLevel;
255             for (compressionLevel=1; compressionLevel<=6; compressionLevel++) {
256                 mallocCounter_t malcount = INIT_MALLOC_COUNTER;
257                 ZSTD_customMem const cMem = { FUZ_mallocDebug, FUZ_freeDebug, &malcount };
258                 ZSTD_CCtx* const cctx = ZSTD_createCCtx_advanced(cMem);
259                 ZSTD_outBuffer out = { outBuffer, outSize, 0 };
260                 ZSTD_inBuffer in = { inBuffer, inSize, 0 };
261                 CHECK_Z( ZSTD_CCtx_setParameter(cctx, ZSTD_c_compressionLevel, compressionLevel) );
262                 CHECK_Z( ZSTD_CCtx_setParameter(cctx, ZSTD_c_nbWorkers, nbThreads) );
263                 CHECK_Z( ZSTD_compressStream2(cctx, &out, &in, ZSTD_e_continue) );
264                 while ( ZSTD_compressStream2(cctx, &out, &in, ZSTD_e_end) ) {}
265                 ZSTD_freeCCtx(cctx);
266                 DISPLAYLEVEL(3, "compress_generic,-T%i,continue level %i : ",
267                                 nbThreads, compressionLevel);
268                 FUZ_displayMallocStats(malcount);
269     }   }   }
270
271     return 0;
272 }
273
274 static int FUZ_mallocTests(unsigned seed, double compressibility, unsigned part)
275 {
276     size_t const inSize = 64 MB + 16 MB + 4 MB + 1 MB + 256 KB + 64 KB; /* 85.3 MB */
277     size_t const outSize = ZSTD_compressBound(inSize);
278     void* const inBuffer = malloc(inSize);
279     void* const outBuffer = malloc(outSize);
280     int result;
281
282     /* Create compressible noise */
283     if (!inBuffer || !outBuffer) {
284         DISPLAY("Not enough memory, aborting \n");
285         exit(1);
286     }
287
288     result = FUZ_mallocTests_internal(seed, compressibility, part,
289                     inBuffer, inSize, outBuffer, outSize);
290
291     free(inBuffer);
292     free(outBuffer);
293     return result;
294 }
295
296 #else
297
298 static int FUZ_mallocTests(unsigned seed, double compressibility, unsigned part)
299 {
300     (void)seed; (void)compressibility; (void)part;
301     return 0;
302 }
303
304 #endif
305
306 /*=============================================
307 *   Unit tests
308 =============================================*/
309
310 static int basicUnitTests(U32 seed, double compressibility)
311 {
312     size_t const CNBuffSize = 5 MB;
313     void* const CNBuffer = malloc(CNBuffSize);
314     size_t const compressedBufferSize = ZSTD_compressBound(CNBuffSize);
315     void* const compressedBuffer = malloc(compressedBufferSize);
316     void* const decodedBuffer = malloc(CNBuffSize);
317     int testResult = 0;
318     unsigned testNb=0;
319     size_t cSize;
320
321     /* Create compressible noise */
322     if (!CNBuffer || !compressedBuffer || !decodedBuffer) {
323         DISPLAY("Not enough memory, aborting\n");
324         testResult = 1;
325         goto _end;
326     }
327     RDG_genBuffer(CNBuffer, CNBuffSize, compressibility, 0., seed);
328
329     /* Basic tests */
330     DISPLAYLEVEL(3, "test%3u : ZSTD_getErrorName : ", testNb++);
331     {   const char* errorString = ZSTD_getErrorName(0);
332         DISPLAYLEVEL(3, "OK : %s \n", errorString);
333     }
334
335     DISPLAYLEVEL(3, "test%3u : ZSTD_getErrorName with wrong value : ", testNb++);
336     {   const char* errorString = ZSTD_getErrorName(499);
337         DISPLAYLEVEL(3, "OK : %s \n", errorString);
338     }
339
340     DISPLAYLEVEL(3, "test%3u : min compression level : ", testNb++);
341     {   int const mcl = ZSTD_minCLevel();
342         DISPLAYLEVEL(3, "%i (OK) \n", mcl);
343     }
344
345     DISPLAYLEVEL(3, "test%3u : compress %u bytes : ", testNb++, (unsigned)CNBuffSize);
346     {   ZSTD_CCtx* const cctx = ZSTD_createCCtx();
347         if (cctx==NULL) goto _output_error;
348         CHECKPLUS(r, ZSTD_compressCCtx(cctx,
349                             compressedBuffer, compressedBufferSize,
350                             CNBuffer, CNBuffSize, 1),
351                   cSize=r );
352         DISPLAYLEVEL(3, "OK (%u bytes : %.2f%%)\n", (unsigned)cSize, (double)cSize/CNBuffSize*100);
353
354         DISPLAYLEVEL(3, "test%3i : size of cctx for level 1 : ", testNb++);
355         {   size_t const cctxSize = ZSTD_sizeof_CCtx(cctx);
356             DISPLAYLEVEL(3, "%u bytes \n", (unsigned)cctxSize);
357         }
358         ZSTD_freeCCtx(cctx);
359     }
360
361     DISPLAYLEVEL(3, "test%3i : decompress skippable frame -8 size : ", testNb++);
362     {
363        char const skippable8[] = "\x50\x2a\x4d\x18\xf8\xff\xff\xff";
364        size_t const size = ZSTD_decompress(NULL, 0, skippable8, 8);
365        if (!ZSTD_isError(size)) goto _output_error;
366     }
367     DISPLAYLEVEL(3, "OK \n");
368
369
370     DISPLAYLEVEL(3, "test%3i : ZSTD_getFrameContentSize test : ", testNb++);
371     {   unsigned long long const rSize = ZSTD_getFrameContentSize(compressedBuffer, cSize);
372         if (rSize != CNBuffSize) goto _output_error;
373     }
374     DISPLAYLEVEL(3, "OK \n");
375
376     DISPLAYLEVEL(3, "test%3i : ZSTD_findDecompressedSize test : ", testNb++);
377     {   unsigned long long const rSize = ZSTD_findDecompressedSize(compressedBuffer, cSize);
378         if (rSize != CNBuffSize) goto _output_error;
379     }
380     DISPLAYLEVEL(3, "OK \n");
381
382     DISPLAYLEVEL(3, "test%3i : tight ZSTD_decompressBound test : ", testNb++);
383     {
384         unsigned long long bound = ZSTD_decompressBound(compressedBuffer, cSize);
385         if (bound != CNBuffSize) goto _output_error;
386     }
387     DISPLAYLEVEL(3, "OK \n");
388
389     DISPLAYLEVEL(3, "test%3i : ZSTD_decompressBound test with invalid srcSize : ", testNb++);
390     {
391         unsigned long long bound = ZSTD_decompressBound(compressedBuffer, cSize - 1);
392         if (bound != ZSTD_CONTENTSIZE_ERROR) goto _output_error;
393     }
394     DISPLAYLEVEL(3, "OK \n");
395
396     DISPLAYLEVEL(3, "test%3i : decompress %u bytes : ", testNb++, (unsigned)CNBuffSize);
397     { size_t const r = ZSTD_decompress(decodedBuffer, CNBuffSize, compressedBuffer, cSize);
398       if (r != CNBuffSize) goto _output_error; }
399     DISPLAYLEVEL(3, "OK \n");
400
401     DISPLAYLEVEL(3, "test%3i : check decompressed result : ", testNb++);
402     {   size_t u;
403         for (u=0; u<CNBuffSize; u++) {
404             if (((BYTE*)decodedBuffer)[u] != ((BYTE*)CNBuffer)[u]) goto _output_error;;
405     }   }
406     DISPLAYLEVEL(3, "OK \n");
407
408
409     DISPLAYLEVEL(3, "test%3i : decompress with null dict : ", testNb++);
410     {   ZSTD_DCtx* const dctx = ZSTD_createDCtx(); assert(dctx != NULL);
411         {   size_t const r = ZSTD_decompress_usingDict(dctx,
412                                                     decodedBuffer, CNBuffSize,
413                                                     compressedBuffer, cSize,
414                                                     NULL, 0);
415             if (r != CNBuffSize) goto _output_error;
416         }
417         ZSTD_freeDCtx(dctx);
418     }
419     DISPLAYLEVEL(3, "OK \n");
420
421     DISPLAYLEVEL(3, "test%3i : decompress with null DDict : ", testNb++);
422     {   ZSTD_DCtx* const dctx = ZSTD_createDCtx(); assert(dctx != NULL);
423         {   size_t const r = ZSTD_decompress_usingDDict(dctx,
424                                                     decodedBuffer, CNBuffSize,
425                                                     compressedBuffer, cSize,
426                                                     NULL);
427             if (r != CNBuffSize) goto _output_error;
428         }
429         ZSTD_freeDCtx(dctx);
430     }
431     DISPLAYLEVEL(3, "OK \n");
432
433     DISPLAYLEVEL(3, "test%3i : decompress with 1 missing byte : ", testNb++);
434     { size_t const r = ZSTD_decompress(decodedBuffer, CNBuffSize, compressedBuffer, cSize-1);
435       if (!ZSTD_isError(r)) goto _output_error;
436       if (ZSTD_getErrorCode((size_t)r) != ZSTD_error_srcSize_wrong) goto _output_error; }
437     DISPLAYLEVEL(3, "OK \n");
438
439     DISPLAYLEVEL(3, "test%3i : decompress with 1 too much byte : ", testNb++);
440     { size_t const r = ZSTD_decompress(decodedBuffer, CNBuffSize, compressedBuffer, cSize+1);
441       if (!ZSTD_isError(r)) goto _output_error;
442       if (ZSTD_getErrorCode(r) != ZSTD_error_srcSize_wrong) goto _output_error; }
443     DISPLAYLEVEL(3, "OK \n");
444
445     DISPLAYLEVEL(3, "test%3i : decompress too large input : ", testNb++);
446     { size_t const r = ZSTD_decompress(decodedBuffer, CNBuffSize, compressedBuffer, compressedBufferSize);
447       if (!ZSTD_isError(r)) goto _output_error;
448       if (ZSTD_getErrorCode(r) != ZSTD_error_srcSize_wrong) goto _output_error; }
449     DISPLAYLEVEL(3, "OK \n");
450
451     DISPLAYLEVEL(3, "test%3i : ZSTD_decompressBound test with content size missing : ", testNb++);
452     {   /* create compressed buffer with content size missing */
453         ZSTD_CCtx* cctx = ZSTD_createCCtx();
454         CHECK_Z( ZSTD_CCtx_setParameter(cctx, ZSTD_c_contentSizeFlag, 0) );
455         CHECKPLUS(r, ZSTD_compress2(cctx,
456                             compressedBuffer, compressedBufferSize,
457                             CNBuffer, CNBuffSize),
458                   cSize=r );
459         ZSTD_freeCCtx(cctx);
460     }
461     {   /* ensure frame content size is missing */
462         ZSTD_frameHeader zfh;
463         size_t const ret = ZSTD_getFrameHeader(&zfh, compressedBuffer, compressedBufferSize);
464         if (ret != 0 || zfh.frameContentSize !=  ZSTD_CONTENTSIZE_UNKNOWN) goto _output_error;
465     }
466     {   /* ensure CNBuffSize <= decompressBound */
467         unsigned long long const bound = ZSTD_decompressBound(compressedBuffer, compressedBufferSize);
468         if (CNBuffSize > bound) goto _output_error;
469     }
470     DISPLAYLEVEL(3, "OK \n");
471
472     DISPLAYLEVEL(3, "test%3d : check CCtx size after compressing empty input : ", testNb++);
473     {   ZSTD_CCtx* const cctx = ZSTD_createCCtx();
474         size_t const r = ZSTD_compressCCtx(cctx, compressedBuffer, compressedBufferSize, NULL, 0, 19);
475         if (ZSTD_isError(r)) goto _output_error;
476         if (ZSTD_sizeof_CCtx(cctx) > (1U << 20)) goto _output_error;
477         ZSTD_freeCCtx(cctx);
478         cSize = r;
479     }
480     DISPLAYLEVEL(3, "OK \n");
481
482     DISPLAYLEVEL(3, "test%3d : decompress empty frame into NULL : ", testNb++);
483     {   size_t const r = ZSTD_decompress(NULL, 0, compressedBuffer, cSize);
484         if (ZSTD_isError(r)) goto _output_error;
485         if (r != 0) goto _output_error;
486     }
487     {   ZSTD_CCtx* const cctx = ZSTD_createCCtx();
488         ZSTD_outBuffer output;
489         if (cctx==NULL) goto _output_error;
490         output.dst = compressedBuffer;
491         output.size = compressedBufferSize;
492         output.pos = 0;
493         CHECK_Z( ZSTD_initCStream(cctx, 1) );    /* content size unknown */
494         CHECK_Z( ZSTD_flushStream(cctx, &output) );   /* ensure no possibility to "concatenate" and determine the content size */
495         CHECK_Z( ZSTD_endStream(cctx, &output) );
496         ZSTD_freeCCtx(cctx);
497         /* single scan decompression */
498         {   size_t const r = ZSTD_decompress(NULL, 0, compressedBuffer, output.pos);
499             if (ZSTD_isError(r)) goto _output_error;
500             if (r != 0) goto _output_error;
501         }
502         /* streaming decompression */
503         {   ZSTD_DCtx* const dstream = ZSTD_createDStream();
504             ZSTD_inBuffer dinput;
505             ZSTD_outBuffer doutput;
506             size_t ipos;
507             if (dstream==NULL) goto _output_error;
508             dinput.src = compressedBuffer;
509             dinput.size = 0;
510             dinput.pos = 0;
511             doutput.dst = NULL;
512             doutput.size = 0;
513             doutput.pos = 0;
514             CHECK_Z ( ZSTD_initDStream(dstream) );
515             for (ipos=1; ipos<=output.pos; ipos++) {
516                 dinput.size = ipos;
517                 CHECK_Z ( ZSTD_decompressStream(dstream, &doutput, &dinput) );
518             }
519             if (doutput.pos != 0) goto _output_error;
520             ZSTD_freeDStream(dstream);
521         }
522     }
523     DISPLAYLEVEL(3, "OK \n");
524
525     DISPLAYLEVEL(3, "test%3d : re-use CCtx with expanding block size : ", testNb++);
526     {   ZSTD_CCtx* const cctx = ZSTD_createCCtx();
527         ZSTD_parameters const params = ZSTD_getParams(1, ZSTD_CONTENTSIZE_UNKNOWN, 0);
528         assert(params.fParams.contentSizeFlag == 1);  /* block size will be adapted if pledgedSrcSize is enabled */
529         CHECK_Z( ZSTD_compressBegin_advanced(cctx, NULL, 0, params, 1 /*pledgedSrcSize*/) );
530         CHECK_Z( ZSTD_compressEnd(cctx, compressedBuffer, compressedBufferSize, CNBuffer, 1) ); /* creates a block size of 1 */
531
532         CHECK_Z( ZSTD_compressBegin_advanced(cctx, NULL, 0, params, ZSTD_CONTENTSIZE_UNKNOWN) );  /* re-use same parameters */
533         {   size_t const inSize = 2* 128 KB;
534             size_t const outSize = ZSTD_compressBound(inSize);
535             CHECK_Z( ZSTD_compressEnd(cctx, compressedBuffer, outSize, CNBuffer, inSize) );
536             /* will fail if blockSize is not resized */
537         }
538         ZSTD_freeCCtx(cctx);
539     }
540     DISPLAYLEVEL(3, "OK \n");
541
542     DISPLAYLEVEL(3, "test%3d : re-using a CCtx should compress the same : ", testNb++);
543     {   size_t const sampleSize = 30;
544         int i;
545         for (i=0; i<20; i++)
546             ((char*)CNBuffer)[i] = (char)i;   /* ensure no match during initial section */
547         memcpy((char*)CNBuffer + 20, CNBuffer, 10);   /* create one match, starting from beginning of sample, which is the difficult case (see #1241) */
548         for (i=1; i<=19; i++) {
549             ZSTD_CCtx* const cctx = ZSTD_createCCtx();
550             size_t size1, size2;
551             DISPLAYLEVEL(5, "l%i ", i);
552             size1 = ZSTD_compressCCtx(cctx, compressedBuffer, compressedBufferSize, CNBuffer, sampleSize, i);
553             CHECK_Z(size1);
554
555             size2 = ZSTD_compressCCtx(cctx, compressedBuffer, compressedBufferSize, CNBuffer, sampleSize, i);
556             CHECK_Z(size2);
557             CHECK_EQ(size1, size2);
558
559             CHECK_Z( ZSTD_CCtx_setParameter(cctx, ZSTD_c_compressionLevel, i) );
560             size2 = ZSTD_compress2(cctx, compressedBuffer, compressedBufferSize, CNBuffer, sampleSize);
561             CHECK_Z(size2);
562             CHECK_EQ(size1, size2);
563
564             size2 = ZSTD_compress2(cctx, compressedBuffer, ZSTD_compressBound(sampleSize) - 1, CNBuffer, sampleSize);  /* force streaming, as output buffer is not large enough to guarantee success */
565             CHECK_Z(size2);
566             CHECK_EQ(size1, size2);
567
568             {   ZSTD_inBuffer inb;
569                 ZSTD_outBuffer outb;
570                 inb.src = CNBuffer;
571                 inb.pos = 0;
572                 inb.size = sampleSize;
573                 outb.dst = compressedBuffer;
574                 outb.pos = 0;
575                 outb.size = ZSTD_compressBound(sampleSize) - 1;  /* force streaming, as output buffer is not large enough to guarantee success */
576                 CHECK_Z( ZSTD_compressStream2(cctx, &outb, &inb, ZSTD_e_end) );
577                 assert(inb.pos == inb.size);
578                 CHECK_EQ(size1, outb.pos);
579             }
580
581             ZSTD_freeCCtx(cctx);
582         }
583     }
584     DISPLAYLEVEL(3, "OK \n");
585
586     DISPLAYLEVEL(3, "test%3d : btultra2 & 1st block : ", testNb++);
587     {   size_t const sampleSize = 1024;
588         ZSTD_CCtx* const cctx = ZSTD_createCCtx();
589         ZSTD_inBuffer inb;
590         ZSTD_outBuffer outb;
591         inb.src = CNBuffer;
592         inb.pos = 0;
593         inb.size = 0;
594         outb.dst = compressedBuffer;
595         outb.pos = 0;
596         outb.size = compressedBufferSize;
597         CHECK_Z( ZSTD_CCtx_setParameter(cctx, ZSTD_c_compressionLevel, ZSTD_maxCLevel()) );
598
599         inb.size = sampleSize;   /* start with something, so that context is already used */
600         CHECK_Z( ZSTD_compressStream2(cctx, &outb, &inb, ZSTD_e_end) );   /* will break internal assert if stats_init is not disabled */
601         assert(inb.pos == inb.size);
602         outb.pos = 0;     /* cancel output */
603
604         CHECK_Z( ZSTD_CCtx_setPledgedSrcSize(cctx, sampleSize) );
605         inb.size = 4;   /* too small size : compression will be skipped */
606         inb.pos = 0;
607         CHECK_Z( ZSTD_compressStream2(cctx, &outb, &inb, ZSTD_e_flush) );
608         assert(inb.pos == inb.size);
609
610         inb.size += 5;   /* too small size : compression will be skipped */
611         CHECK_Z( ZSTD_compressStream2(cctx, &outb, &inb, ZSTD_e_flush) );
612         assert(inb.pos == inb.size);
613
614         inb.size += 11;   /* small enough to attempt compression */
615         CHECK_Z( ZSTD_compressStream2(cctx, &outb, &inb, ZSTD_e_flush) );
616         assert(inb.pos == inb.size);
617
618         assert(inb.pos < sampleSize);
619         inb.size = sampleSize;   /* large enough to trigger stats_init, but no longer at beginning */
620         CHECK_Z( ZSTD_compressStream2(cctx, &outb, &inb, ZSTD_e_end) );   /* will break internal assert if stats_init is not disabled */
621         assert(inb.pos == inb.size);
622         ZSTD_freeCCtx(cctx);
623     }
624     DISPLAYLEVEL(3, "OK \n");
625
626     DISPLAYLEVEL(3, "test%3d : ZSTD_CCtx_getParameter() : ", testNb++);
627     {   ZSTD_CCtx* const cctx = ZSTD_createCCtx();
628         ZSTD_outBuffer out = {NULL, 0, 0};
629         ZSTD_inBuffer in = {NULL, 0, 0};
630         int value;
631
632         CHECK_Z(ZSTD_CCtx_getParameter(cctx, ZSTD_c_compressionLevel, &value));
633         CHECK_EQ(value, 3);
634         CHECK_Z(ZSTD_CCtx_getParameter(cctx, ZSTD_c_hashLog, &value));
635         CHECK_EQ(value, 0);
636         CHECK_Z(ZSTD_CCtx_setParameter(cctx, ZSTD_c_hashLog, ZSTD_HASHLOG_MIN));
637         CHECK_Z(ZSTD_CCtx_getParameter(cctx, ZSTD_c_compressionLevel, &value));
638         CHECK_EQ(value, 3);
639         CHECK_Z(ZSTD_CCtx_getParameter(cctx, ZSTD_c_hashLog, &value));
640         CHECK_EQ(value, ZSTD_HASHLOG_MIN);
641         CHECK_Z(ZSTD_CCtx_setParameter(cctx, ZSTD_c_compressionLevel, 7));
642         CHECK_Z(ZSTD_CCtx_getParameter(cctx, ZSTD_c_compressionLevel, &value));
643         CHECK_EQ(value, 7);
644         CHECK_Z(ZSTD_CCtx_getParameter(cctx, ZSTD_c_hashLog, &value));
645         CHECK_EQ(value, ZSTD_HASHLOG_MIN);
646         /* Start a compression job */
647         ZSTD_compressStream2(cctx, &out, &in, ZSTD_e_continue);
648         CHECK_Z(ZSTD_CCtx_getParameter(cctx, ZSTD_c_compressionLevel, &value));
649         CHECK_EQ(value, 7);
650         CHECK_Z(ZSTD_CCtx_getParameter(cctx, ZSTD_c_hashLog, &value));
651         CHECK_EQ(value, ZSTD_HASHLOG_MIN);
652         /* Reset the CCtx */
653         ZSTD_CCtx_reset(cctx, ZSTD_reset_session_only);
654         CHECK_Z(ZSTD_CCtx_getParameter(cctx, ZSTD_c_compressionLevel, &value));
655         CHECK_EQ(value, 7);
656         CHECK_Z(ZSTD_CCtx_getParameter(cctx, ZSTD_c_hashLog, &value));
657         CHECK_EQ(value, ZSTD_HASHLOG_MIN);
658         /* Reset the parameters */
659         ZSTD_CCtx_reset(cctx, ZSTD_reset_parameters);
660         CHECK_Z(ZSTD_CCtx_getParameter(cctx, ZSTD_c_compressionLevel, &value));
661         CHECK_EQ(value, 3);
662         CHECK_Z(ZSTD_CCtx_getParameter(cctx, ZSTD_c_hashLog, &value));
663         CHECK_EQ(value, 0);
664
665         ZSTD_freeCCtx(cctx);
666     }
667     DISPLAYLEVEL(3, "OK \n");
668
669     /* this test is really too long, and should be made faster */
670     DISPLAYLEVEL(3, "test%3d : overflow protection with large windowLog : ", testNb++);
671     {   ZSTD_CCtx* const cctx = ZSTD_createCCtx();
672         ZSTD_parameters params = ZSTD_getParams(-999, ZSTD_CONTENTSIZE_UNKNOWN, 0);
673         size_t const nbCompressions = ((1U << 31) / CNBuffSize) + 2;   /* ensure U32 overflow protection is triggered */
674         size_t cnb;
675         assert(cctx != NULL);
676         params.fParams.contentSizeFlag = 0;
677         params.cParams.windowLog = ZSTD_WINDOWLOG_MAX;
678         for (cnb = 0; cnb < nbCompressions; ++cnb) {
679             DISPLAYLEVEL(6, "run %zu / %zu \n", cnb, nbCompressions);
680             CHECK_Z( ZSTD_compressBegin_advanced(cctx, NULL, 0, params, ZSTD_CONTENTSIZE_UNKNOWN) );  /* re-use same parameters */
681             CHECK_Z( ZSTD_compressEnd(cctx, compressedBuffer, compressedBufferSize, CNBuffer, CNBuffSize) );
682         }
683         ZSTD_freeCCtx(cctx);
684     }
685     DISPLAYLEVEL(3, "OK \n");
686
687     DISPLAYLEVEL(3, "test%3d : size down context : ", testNb++);
688     {   ZSTD_CCtx* const largeCCtx = ZSTD_createCCtx();
689         assert(largeCCtx != NULL);
690         CHECK_Z( ZSTD_compressBegin(largeCCtx, 19) );   /* streaming implies ZSTD_CONTENTSIZE_UNKNOWN, which maximizes memory usage */
691         CHECK_Z( ZSTD_compressEnd(largeCCtx, compressedBuffer, compressedBufferSize, CNBuffer, 1) );
692         {   size_t const largeCCtxSize = ZSTD_sizeof_CCtx(largeCCtx);   /* size of context must be measured after compression */
693             {   ZSTD_CCtx* const smallCCtx = ZSTD_createCCtx();
694                 assert(smallCCtx != NULL);
695                 CHECK_Z(ZSTD_compressCCtx(smallCCtx, compressedBuffer, compressedBufferSize, CNBuffer, 1, 1));
696                 {   size_t const smallCCtxSize = ZSTD_sizeof_CCtx(smallCCtx);
697                     DISPLAYLEVEL(5, "(large) %zuKB > 32*%zuKB (small) : ",
698                                 largeCCtxSize>>10, smallCCtxSize>>10);
699                     assert(largeCCtxSize > 32* smallCCtxSize);  /* note : "too large" definition is handled within zstd_compress.c .
700                                                                  * make this test case extreme, so that it doesn't depend on a possibly fluctuating definition */
701                 }
702                 ZSTD_freeCCtx(smallCCtx);
703             }
704             {   U32 const maxNbAttempts = 1100;   /* nb of usages before triggering size down is handled within zstd_compress.c.
705                                                    * currently defined as 128x, but could be adjusted in the future.
706                                                    * make this test long enough so that it's not too much tied to the current definition within zstd_compress.c */
707                 unsigned u;
708                 for (u=0; u<maxNbAttempts; u++) {
709                     CHECK_Z(ZSTD_compressCCtx(largeCCtx, compressedBuffer, compressedBufferSize, CNBuffer, 1, 1));
710                     if (ZSTD_sizeof_CCtx(largeCCtx) < largeCCtxSize) break;   /* sized down */
711                 }
712                 DISPLAYLEVEL(5, "size down after %u attempts : ", u);
713                 if (u==maxNbAttempts) goto _output_error;   /* no sizedown happened */
714             }
715         }
716         ZSTD_freeCCtx(largeCCtx);
717     }
718     DISPLAYLEVEL(3, "OK \n");
719
720     /* Static CCtx tests */
721 #define STATIC_CCTX_LEVEL 3
722     DISPLAYLEVEL(3, "test%3i : create static CCtx for level %u :", testNb++, STATIC_CCTX_LEVEL);
723     {   size_t const staticCCtxSize = ZSTD_estimateCStreamSize(STATIC_CCTX_LEVEL);
724         void* const staticCCtxBuffer = malloc(staticCCtxSize);
725         size_t const staticDCtxSize = ZSTD_estimateDCtxSize();
726         void* const staticDCtxBuffer = malloc(staticDCtxSize);
727         if (staticCCtxBuffer==NULL || staticDCtxBuffer==NULL) {
728             free(staticCCtxBuffer);
729             free(staticDCtxBuffer);
730             DISPLAY("Not enough memory, aborting\n");
731             testResult = 1;
732             goto _end;
733         }
734         {   ZSTD_CCtx* staticCCtx = ZSTD_initStaticCCtx(staticCCtxBuffer, staticCCtxSize);
735             ZSTD_DCtx* staticDCtx = ZSTD_initStaticDCtx(staticDCtxBuffer, staticDCtxSize);
736             if ((staticCCtx==NULL) || (staticDCtx==NULL)) goto _output_error;
737             DISPLAYLEVEL(3, "OK \n");
738
739             DISPLAYLEVEL(3, "test%3i : init CCtx for level %u : ", testNb++, STATIC_CCTX_LEVEL);
740             { size_t const r = ZSTD_compressBegin(staticCCtx, STATIC_CCTX_LEVEL);
741               if (ZSTD_isError(r)) goto _output_error; }
742             DISPLAYLEVEL(3, "OK \n");
743
744             DISPLAYLEVEL(3, "test%3i : simple compression test with static CCtx : ", testNb++);
745             CHECKPLUS(r, ZSTD_compressCCtx(staticCCtx,
746                             compressedBuffer, compressedBufferSize,
747                             CNBuffer, CNBuffSize, STATIC_CCTX_LEVEL),
748                       cSize=r );
749             DISPLAYLEVEL(3, "OK (%u bytes : %.2f%%)\n",
750                             (unsigned)cSize, (double)cSize/CNBuffSize*100);
751
752             DISPLAYLEVEL(3, "test%3i : simple decompression test with static DCtx : ", testNb++);
753             { size_t const r = ZSTD_decompressDCtx(staticDCtx,
754                                                 decodedBuffer, CNBuffSize,
755                                                 compressedBuffer, cSize);
756               if (r != CNBuffSize) goto _output_error; }
757             DISPLAYLEVEL(3, "OK \n");
758
759             DISPLAYLEVEL(3, "test%3i : check decompressed result : ", testNb++);
760             {   size_t u;
761                 for (u=0; u<CNBuffSize; u++) {
762                     if (((BYTE*)decodedBuffer)[u] != ((BYTE*)CNBuffer)[u])
763                         goto _output_error;;
764             }   }
765             DISPLAYLEVEL(3, "OK \n");
766
767             DISPLAYLEVEL(3, "test%3i : init CCtx for too large level (must fail) : ", testNb++);
768             { size_t const r = ZSTD_compressBegin(staticCCtx, ZSTD_maxCLevel());
769               if (!ZSTD_isError(r)) goto _output_error; }
770             DISPLAYLEVEL(3, "OK \n");
771
772             DISPLAYLEVEL(3, "test%3i : init CCtx for small level %u (should work again) : ", testNb++, 1);
773             CHECK( ZSTD_compressBegin(staticCCtx, 1) );
774             DISPLAYLEVEL(3, "OK \n");
775
776             DISPLAYLEVEL(3, "test%3i : init CStream for small level %u : ", testNb++, 1);
777             CHECK( ZSTD_initCStream(staticCCtx, 1) );
778             DISPLAYLEVEL(3, "OK \n");
779
780             DISPLAYLEVEL(3, "test%3i : init CStream with dictionary (should fail) : ", testNb++);
781             { size_t const r = ZSTD_initCStream_usingDict(staticCCtx, CNBuffer, 64 KB, 1);
782               if (!ZSTD_isError(r)) goto _output_error; }
783             DISPLAYLEVEL(3, "OK \n");
784
785             DISPLAYLEVEL(3, "test%3i : init DStream (should fail) : ", testNb++);
786             { size_t const r = ZSTD_initDStream(staticDCtx);
787               if (ZSTD_isError(r)) goto _output_error; }
788             {   ZSTD_outBuffer output = { decodedBuffer, CNBuffSize, 0 };
789                 ZSTD_inBuffer input = { compressedBuffer, ZSTD_FRAMEHEADERSIZE_MAX+1, 0 };
790                 size_t const r = ZSTD_decompressStream(staticDCtx, &output, &input);
791                 if (!ZSTD_isError(r)) goto _output_error;
792             }
793             DISPLAYLEVEL(3, "OK \n");
794         }
795         free(staticCCtxBuffer);
796         free(staticDCtxBuffer);
797     }
798
799     DISPLAYLEVEL(3, "test%3i : Static negative levels : ", testNb++);
800     {   size_t const cctxSizeN1 = ZSTD_estimateCCtxSize(-1);
801         size_t const cctxSizeP1 = ZSTD_estimateCCtxSize(1);
802         size_t const cstreamSizeN1 = ZSTD_estimateCStreamSize(-1);
803         size_t const cstreamSizeP1 = ZSTD_estimateCStreamSize(1);
804
805         if (!(0 < cctxSizeN1 && cctxSizeN1 <= cctxSizeP1)) goto _output_error;
806         if (!(0 < cstreamSizeN1 && cstreamSizeN1 <= cstreamSizeP1)) goto _output_error;
807     }
808     DISPLAYLEVEL(3, "OK \n");
809
810
811     /* ZSTDMT simple MT compression test */
812     DISPLAYLEVEL(3, "test%3i : create ZSTDMT CCtx : ", testNb++);
813     {   ZSTDMT_CCtx* mtctx = ZSTDMT_createCCtx(2);
814         if (mtctx==NULL) {
815             DISPLAY("mtctx : mot enough memory, aborting \n");
816             testResult = 1;
817             goto _end;
818         }
819         DISPLAYLEVEL(3, "OK \n");
820
821         DISPLAYLEVEL(3, "test%3u : compress %u bytes with 2 threads : ", testNb++, (unsigned)CNBuffSize);
822         CHECKPLUS(r, ZSTDMT_compressCCtx(mtctx,
823                                 compressedBuffer, compressedBufferSize,
824                                 CNBuffer, CNBuffSize,
825                                 1),
826                   cSize=r );
827         DISPLAYLEVEL(3, "OK (%u bytes : %.2f%%)\n", (unsigned)cSize, (double)cSize/CNBuffSize*100);
828
829         DISPLAYLEVEL(3, "test%3i : decompressed size test : ", testNb++);
830         {   unsigned long long const rSize = ZSTD_getFrameContentSize(compressedBuffer, cSize);
831             if (rSize != CNBuffSize)  {
832                 DISPLAY("ZSTD_getFrameContentSize incorrect : %u != %u \n", (unsigned)rSize, (unsigned)CNBuffSize);
833                 goto _output_error;
834         }   }
835         DISPLAYLEVEL(3, "OK \n");
836
837         DISPLAYLEVEL(3, "test%3i : decompress %u bytes : ", testNb++, (unsigned)CNBuffSize);
838         { size_t const r = ZSTD_decompress(decodedBuffer, CNBuffSize, compressedBuffer, cSize);
839           if (r != CNBuffSize) goto _output_error; }
840         DISPLAYLEVEL(3, "OK \n");
841
842         DISPLAYLEVEL(3, "test%3i : check decompressed result : ", testNb++);
843         {   size_t u;
844             for (u=0; u<CNBuffSize; u++) {
845                 if (((BYTE*)decodedBuffer)[u] != ((BYTE*)CNBuffer)[u]) goto _output_error;;
846         }   }
847         DISPLAYLEVEL(3, "OK \n");
848
849         DISPLAYLEVEL(3, "test%3i : compress -T2 with checksum : ", testNb++);
850         {   ZSTD_parameters params = ZSTD_getParams(1, CNBuffSize, 0);
851             params.fParams.checksumFlag = 1;
852             params.fParams.contentSizeFlag = 1;
853             CHECKPLUS(r, ZSTDMT_compress_advanced(mtctx,
854                                     compressedBuffer, compressedBufferSize,
855                                     CNBuffer, CNBuffSize,
856                                     NULL, params, 3 /*overlapRLog*/),
857                       cSize=r );
858         }
859         DISPLAYLEVEL(3, "OK (%u bytes : %.2f%%)\n", (unsigned)cSize, (double)cSize/CNBuffSize*100);
860
861         DISPLAYLEVEL(3, "test%3i : decompress %u bytes : ", testNb++, (unsigned)CNBuffSize);
862         { size_t const r = ZSTD_decompress(decodedBuffer, CNBuffSize, compressedBuffer, cSize);
863           if (r != CNBuffSize) goto _output_error; }
864         DISPLAYLEVEL(3, "OK \n");
865
866         ZSTDMT_freeCCtx(mtctx);
867     }
868
869     DISPLAYLEVEL(3, "test%3i : compress -T2 with/without literals compression : ", testNb++)
870     {   ZSTD_CCtx* cctx = ZSTD_createCCtx();
871         size_t cSize1, cSize2;
872         CHECK( ZSTD_CCtx_setParameter(cctx, ZSTD_c_compressionLevel, 1) );
873         CHECK( ZSTD_CCtx_setParameter(cctx, ZSTD_c_nbWorkers, 2) );
874         cSize1 = ZSTD_compress2(cctx, compressedBuffer, compressedBufferSize, CNBuffer, CNBuffSize);
875         CHECK(cSize1);
876         CHECK( ZSTD_CCtx_setParameter(cctx, ZSTD_c_literalCompressionMode, ZSTD_lcm_uncompressed) );
877         cSize2 = ZSTD_compress2(cctx, compressedBuffer, compressedBufferSize, CNBuffer, CNBuffSize);
878         CHECK(cSize2);
879         CHECK_LT(cSize1, cSize2);
880         ZSTD_freeCCtx(cctx);
881     }
882     DISPLAYLEVEL(3, "OK \n");
883
884     DISPLAYLEVEL(3, "test%3i : Multithreaded ZSTD_compress2() with rsyncable : ", testNb++)
885     {   ZSTD_CCtx* cctx = ZSTD_createCCtx();
886         /* Set rsyncable and don't give the ZSTD_compressBound(CNBuffSize) so
887          * ZSTDMT is forced to not take the shortcut.
888          */
889         CHECK( ZSTD_CCtx_setParameter(cctx, ZSTD_c_compressionLevel, 1) );
890         CHECK( ZSTD_CCtx_setParameter(cctx, ZSTD_c_nbWorkers, 1) );
891         CHECK( ZSTD_CCtx_setParameter(cctx, ZSTD_c_rsyncable, 1) );
892         CHECK( ZSTD_compress2(cctx, compressedBuffer, compressedBufferSize - 1, CNBuffer, CNBuffSize) );
893         ZSTD_freeCCtx(cctx);
894     }
895     DISPLAYLEVEL(3, "OK \n");
896
897     DISPLAYLEVEL(3, "test%3i : setting multithreaded parameters : ", testNb++)
898     {   ZSTD_CCtx_params* params = ZSTD_createCCtxParams();
899         int value;
900         /* Check that the overlap log and job size are unset. */
901         CHECK( ZSTD_CCtxParams_getParameter(params, ZSTD_c_overlapLog, &value) );
902         CHECK_EQ(value, 0);
903         CHECK( ZSTD_CCtxParams_getParameter(params, ZSTD_c_jobSize, &value) );
904         CHECK_EQ(value, 0);
905         /* Set and check the overlap log and job size. */
906         CHECK( ZSTD_CCtxParams_setParameter(params, ZSTD_c_overlapLog, 5) );
907         CHECK( ZSTD_CCtxParams_setParameter(params, ZSTD_c_jobSize, 2 MB) );
908         CHECK( ZSTD_CCtxParams_getParameter(params, ZSTD_c_overlapLog, &value) );
909         CHECK_EQ(value, 5);
910         CHECK( ZSTD_CCtxParams_getParameter(params, ZSTD_c_jobSize, &value) );
911         CHECK_EQ(value, 2 MB);
912         /* Set the number of workers and check the overlap log and job size. */
913         CHECK( ZSTD_CCtxParams_setParameter(params, ZSTD_c_nbWorkers, 2) );
914         CHECK( ZSTD_CCtxParams_getParameter(params, ZSTD_c_overlapLog, &value) );
915         CHECK_EQ(value, 5);
916         CHECK( ZSTD_CCtxParams_getParameter(params, ZSTD_c_jobSize, &value) );
917         CHECK_EQ(value, 2 MB);
918         ZSTD_freeCCtxParams(params);
919
920     }
921     DISPLAYLEVEL(3, "OK \n");
922
923     /* Simple API multiframe test */
924     DISPLAYLEVEL(3, "test%3i : compress multiple frames : ", testNb++);
925     {   size_t off = 0;
926         int i;
927         int const segs = 4;
928         /* only use the first half so we don't push against size limit of compressedBuffer */
929         size_t const segSize = (CNBuffSize / 2) / segs;
930         for (i = 0; i < segs; i++) {
931             CHECK_V(r, ZSTD_compress(
932                             (BYTE *)compressedBuffer + off, CNBuffSize - off,
933                             (BYTE *)CNBuffer + segSize * i,
934                             segSize, 5));
935             off += r;
936             if (i == segs/2) {
937                 /* insert skippable frame */
938                 const U32 skipLen = 129 KB;
939                 MEM_writeLE32((BYTE*)compressedBuffer + off, ZSTD_MAGIC_SKIPPABLE_START);
940                 MEM_writeLE32((BYTE*)compressedBuffer + off + 4, skipLen);
941                 off += skipLen + ZSTD_SKIPPABLEHEADERSIZE;
942             }
943         }
944         cSize = off;
945     }
946     DISPLAYLEVEL(3, "OK \n");
947
948     DISPLAYLEVEL(3, "test%3i : get decompressed size of multiple frames : ", testNb++);
949     {   unsigned long long const r = ZSTD_findDecompressedSize(compressedBuffer, cSize);
950         if (r != CNBuffSize / 2) goto _output_error; }
951     DISPLAYLEVEL(3, "OK \n");
952
953     DISPLAYLEVEL(3, "test%3i : get tight decompressed bound of multiple frames : ", testNb++);
954     {   unsigned long long const bound = ZSTD_decompressBound(compressedBuffer, cSize);
955         if (bound != CNBuffSize / 2) goto _output_error; }
956     DISPLAYLEVEL(3, "OK \n");
957
958     DISPLAYLEVEL(3, "test%3i : decompress multiple frames : ", testNb++);
959     {   CHECK_V(r, ZSTD_decompress(decodedBuffer, CNBuffSize, compressedBuffer, cSize));
960         if (r != CNBuffSize / 2) goto _output_error; }
961     DISPLAYLEVEL(3, "OK \n");
962
963     DISPLAYLEVEL(3, "test%3i : check decompressed result : ", testNb++);
964     if (memcmp(decodedBuffer, CNBuffer, CNBuffSize / 2) != 0) goto _output_error;
965     DISPLAYLEVEL(3, "OK \n");
966
967     /* Dictionary and CCtx Duplication tests */
968     {   ZSTD_CCtx* const ctxOrig = ZSTD_createCCtx();
969         ZSTD_CCtx* const ctxDuplicated = ZSTD_createCCtx();
970         ZSTD_DCtx* const dctx = ZSTD_createDCtx();
971         static const size_t dictSize = 551;
972         assert(dctx != NULL); assert(ctxOrig != NULL); assert(ctxDuplicated != NULL);
973
974         DISPLAYLEVEL(3, "test%3i : copy context too soon : ", testNb++);
975         { size_t const copyResult = ZSTD_copyCCtx(ctxDuplicated, ctxOrig, 0);
976           if (!ZSTD_isError(copyResult)) goto _output_error; }   /* error must be detected */
977         DISPLAYLEVEL(3, "OK \n");
978
979         DISPLAYLEVEL(3, "test%3i : load dictionary into context : ", testNb++);
980         CHECK( ZSTD_compressBegin_usingDict(ctxOrig, CNBuffer, dictSize, 2) );
981         CHECK( ZSTD_copyCCtx(ctxDuplicated, ctxOrig, 0) ); /* Begin_usingDict implies unknown srcSize, so match that */
982         DISPLAYLEVEL(3, "OK \n");
983
984         DISPLAYLEVEL(3, "test%3i : compress with flat dictionary : ", testNb++);
985         cSize = 0;
986         CHECKPLUS(r, ZSTD_compressEnd(ctxOrig, compressedBuffer, compressedBufferSize,
987                                            (const char*)CNBuffer + dictSize, CNBuffSize - dictSize),
988                   cSize += r);
989         DISPLAYLEVEL(3, "OK (%u bytes : %.2f%%)\n", (unsigned)cSize, (double)cSize/CNBuffSize*100);
990
991         DISPLAYLEVEL(3, "test%3i : frame built with flat dictionary should be decompressible : ", testNb++);
992         CHECKPLUS(r, ZSTD_decompress_usingDict(dctx,
993                                        decodedBuffer, CNBuffSize,
994                                        compressedBuffer, cSize,
995                                        CNBuffer, dictSize),
996                   if (r != CNBuffSize - dictSize) goto _output_error);
997         DISPLAYLEVEL(3, "OK \n");
998
999         DISPLAYLEVEL(3, "test%3i : compress with duplicated context : ", testNb++);
1000         {   size_t const cSizeOrig = cSize;
1001             cSize = 0;
1002             CHECKPLUS(r, ZSTD_compressEnd(ctxDuplicated, compressedBuffer, compressedBufferSize,
1003                                                (const char*)CNBuffer + dictSize, CNBuffSize - dictSize),
1004                       cSize += r);
1005             if (cSize != cSizeOrig) goto _output_error;   /* should be identical ==> same size */
1006         }
1007         DISPLAYLEVEL(3, "OK (%u bytes : %.2f%%)\n", (unsigned)cSize, (double)cSize/CNBuffSize*100);
1008
1009         DISPLAYLEVEL(3, "test%3i : frame built with duplicated context should be decompressible : ", testNb++);
1010         CHECKPLUS(r, ZSTD_decompress_usingDict(dctx,
1011                                            decodedBuffer, CNBuffSize,
1012                                            compressedBuffer, cSize,
1013                                            CNBuffer, dictSize),
1014                   if (r != CNBuffSize - dictSize) goto _output_error);
1015         DISPLAYLEVEL(3, "OK \n");
1016
1017         DISPLAYLEVEL(3, "test%3i : decompress with DDict : ", testNb++);
1018         {   ZSTD_DDict* const ddict = ZSTD_createDDict(CNBuffer, dictSize);
1019             size_t const r = ZSTD_decompress_usingDDict(dctx, decodedBuffer, CNBuffSize, compressedBuffer, cSize, ddict);
1020             if (r != CNBuffSize - dictSize) goto _output_error;
1021             DISPLAYLEVEL(3, "OK (size of DDict : %u) \n", (unsigned)ZSTD_sizeof_DDict(ddict));
1022             ZSTD_freeDDict(ddict);
1023         }
1024
1025         DISPLAYLEVEL(3, "test%3i : decompress with static DDict : ", testNb++);
1026         {   size_t const ddictBufferSize = ZSTD_estimateDDictSize(dictSize, ZSTD_dlm_byCopy);
1027             void* ddictBuffer = malloc(ddictBufferSize);
1028             if (ddictBuffer == NULL) goto _output_error;
1029             {   const ZSTD_DDict* const ddict = ZSTD_initStaticDDict(ddictBuffer, ddictBufferSize, CNBuffer, dictSize, ZSTD_dlm_byCopy, ZSTD_dct_auto);
1030                 size_t const r = ZSTD_decompress_usingDDict(dctx, decodedBuffer, CNBuffSize, compressedBuffer, cSize, ddict);
1031                 if (r != CNBuffSize - dictSize) goto _output_error;
1032             }
1033             free(ddictBuffer);
1034             DISPLAYLEVEL(3, "OK (size of static DDict : %u) \n", (unsigned)ddictBufferSize);
1035         }
1036
1037         DISPLAYLEVEL(3, "test%3i : check content size on duplicated context : ", testNb++);
1038         {   size_t const testSize = CNBuffSize / 3;
1039             {   ZSTD_parameters p = ZSTD_getParams(2, testSize, dictSize);
1040                 p.fParams.contentSizeFlag = 1;
1041                 CHECK( ZSTD_compressBegin_advanced(ctxOrig, CNBuffer, dictSize, p, testSize-1) );
1042             }
1043             CHECK( ZSTD_copyCCtx(ctxDuplicated, ctxOrig, testSize) );
1044
1045             CHECKPLUS(r, ZSTD_compressEnd(ctxDuplicated, compressedBuffer, ZSTD_compressBound(testSize),
1046                                           (const char*)CNBuffer + dictSize, testSize),
1047                       cSize = r);
1048             {   ZSTD_frameHeader zfh;
1049                 if (ZSTD_getFrameHeader(&zfh, compressedBuffer, cSize)) goto _output_error;
1050                 if ((zfh.frameContentSize != testSize) && (zfh.frameContentSize != 0)) goto _output_error;
1051         }   }
1052         DISPLAYLEVEL(3, "OK \n");
1053
1054         ZSTD_freeCCtx(ctxOrig);
1055         ZSTD_freeCCtx(ctxDuplicated);
1056         ZSTD_freeDCtx(dctx);
1057     }
1058
1059     /* Dictionary and dictBuilder tests */
1060     {   ZSTD_CCtx* const cctx = ZSTD_createCCtx();
1061         size_t const dictBufferCapacity = 16 KB;
1062         void* const dictBuffer = malloc(dictBufferCapacity);
1063         size_t const totalSampleSize = 1 MB;
1064         size_t const sampleUnitSize = 8 KB;
1065         U32 const nbSamples = (U32)(totalSampleSize / sampleUnitSize);
1066         size_t* const samplesSizes = (size_t*) malloc(nbSamples * sizeof(size_t));
1067         size_t dictSize;
1068         U32 dictID;
1069
1070         if (dictBuffer==NULL || samplesSizes==NULL) {
1071             free(dictBuffer);
1072             free(samplesSizes);
1073             goto _output_error;
1074         }
1075
1076         DISPLAYLEVEL(3, "test%3i : dictBuilder on cyclic data : ", testNb++);
1077         assert(compressedBufferSize >= totalSampleSize);
1078         { U32 u; for (u=0; u<totalSampleSize; u++) ((BYTE*)decodedBuffer)[u] = (BYTE)u; }
1079         { U32 u; for (u=0; u<nbSamples; u++) samplesSizes[u] = sampleUnitSize; }
1080         {   size_t const sDictSize = ZDICT_trainFromBuffer(dictBuffer, dictBufferCapacity,
1081                                          decodedBuffer, samplesSizes, nbSamples);
1082             if (ZDICT_isError(sDictSize)) goto _output_error;
1083             DISPLAYLEVEL(3, "OK, created dictionary of size %u \n", (unsigned)sDictSize);
1084         }
1085
1086         DISPLAYLEVEL(3, "test%3i : dictBuilder : ", testNb++);
1087         { U32 u; for (u=0; u<nbSamples; u++) samplesSizes[u] = sampleUnitSize; }
1088         dictSize = ZDICT_trainFromBuffer(dictBuffer, dictBufferCapacity,
1089                                          CNBuffer, samplesSizes, nbSamples);
1090         if (ZDICT_isError(dictSize)) goto _output_error;
1091         DISPLAYLEVEL(3, "OK, created dictionary of size %u \n", (unsigned)dictSize);
1092
1093         DISPLAYLEVEL(3, "test%3i : Multithreaded COVER dictBuilder : ", testNb++);
1094         { U32 u; for (u=0; u<nbSamples; u++) samplesSizes[u] = sampleUnitSize; }
1095         {   ZDICT_cover_params_t coverParams;
1096             memset(&coverParams, 0, sizeof(coverParams));
1097             coverParams.steps = 8;
1098             coverParams.nbThreads = 4;
1099             dictSize = ZDICT_optimizeTrainFromBuffer_cover(
1100                 dictBuffer, dictBufferCapacity,
1101                 CNBuffer, samplesSizes, nbSamples/8,  /* less samples for faster tests */
1102                 &coverParams);
1103             if (ZDICT_isError(dictSize)) goto _output_error;
1104         }
1105         DISPLAYLEVEL(3, "OK, created dictionary of size %u \n", (unsigned)dictSize);
1106
1107         DISPLAYLEVEL(3, "test%3i : COVER dictBuilder with shrinkDict: ", testNb++);
1108         { U32 u; for (u=0; u<nbSamples; u++) samplesSizes[u] = sampleUnitSize; }
1109         {   ZDICT_cover_params_t coverParams;
1110             memset(&coverParams, 0, sizeof(coverParams));
1111             coverParams.steps = 8;
1112             coverParams.nbThreads = 4;
1113             coverParams.shrinkDict = 1;
1114             coverParams.shrinkDictMaxRegression = 1;
1115             dictSize = ZDICT_optimizeTrainFromBuffer_cover(
1116                 dictBuffer, dictBufferCapacity,
1117                 CNBuffer, samplesSizes, nbSamples/8,  /* less samples for faster tests */
1118                 &coverParams);
1119             if (ZDICT_isError(dictSize)) goto _output_error;
1120         }
1121         DISPLAYLEVEL(3, "OK, created dictionary of size %u \n", (unsigned)dictSize);
1122
1123         DISPLAYLEVEL(3, "test%3i : Multithreaded FASTCOVER dictBuilder : ", testNb++);
1124         { U32 u; for (u=0; u<nbSamples; u++) samplesSizes[u] = sampleUnitSize; }
1125         {   ZDICT_fastCover_params_t fastCoverParams;
1126             memset(&fastCoverParams, 0, sizeof(fastCoverParams));
1127             fastCoverParams.steps = 8;
1128             fastCoverParams.nbThreads = 4;
1129             dictSize = ZDICT_optimizeTrainFromBuffer_fastCover(
1130                 dictBuffer, dictBufferCapacity,
1131                 CNBuffer, samplesSizes, nbSamples,
1132                 &fastCoverParams);
1133             if (ZDICT_isError(dictSize)) goto _output_error;
1134         }
1135         DISPLAYLEVEL(3, "OK, created dictionary of size %u \n", (unsigned)dictSize);
1136
1137         DISPLAYLEVEL(3, "test%3i : FASTCOVER dictBuilder with shrinkDict: ", testNb++);
1138         { U32 u; for (u=0; u<nbSamples; u++) samplesSizes[u] = sampleUnitSize; }
1139         {   ZDICT_fastCover_params_t fastCoverParams;
1140             memset(&fastCoverParams, 0, sizeof(fastCoverParams));
1141             fastCoverParams.steps = 8;
1142             fastCoverParams.nbThreads = 4;
1143             fastCoverParams.shrinkDict = 1;
1144             fastCoverParams.shrinkDictMaxRegression = 1;
1145             dictSize = ZDICT_optimizeTrainFromBuffer_fastCover(
1146                 dictBuffer, dictBufferCapacity,
1147                 CNBuffer, samplesSizes, nbSamples,
1148                 &fastCoverParams);
1149             if (ZDICT_isError(dictSize)) goto _output_error;
1150         }
1151         DISPLAYLEVEL(3, "OK, created dictionary of size %u \n", (unsigned)dictSize);
1152
1153         DISPLAYLEVEL(3, "test%3i : check dictID : ", testNb++);
1154         dictID = ZDICT_getDictID(dictBuffer, dictSize);
1155         if (dictID==0) goto _output_error;
1156         DISPLAYLEVEL(3, "OK : %u \n", (unsigned)dictID);
1157
1158         DISPLAYLEVEL(3, "test%3i : compress with dictionary : ", testNb++);
1159         cSize = ZSTD_compress_usingDict(cctx, compressedBuffer, compressedBufferSize,
1160                                         CNBuffer, CNBuffSize,
1161                                         dictBuffer, dictSize, 4);
1162         if (ZSTD_isError(cSize)) goto _output_error;
1163         DISPLAYLEVEL(3, "OK (%u bytes : %.2f%%)\n", (unsigned)cSize, (double)cSize/CNBuffSize*100);
1164
1165         DISPLAYLEVEL(3, "test%3i : retrieve dictID from dictionary : ", testNb++);
1166         {   U32 const did = ZSTD_getDictID_fromDict(dictBuffer, dictSize);
1167             if (did != dictID) goto _output_error;   /* non-conformant (content-only) dictionary */
1168         }
1169         DISPLAYLEVEL(3, "OK \n");
1170
1171         DISPLAYLEVEL(3, "test%3i : retrieve dictID from frame : ", testNb++);
1172         {   U32 const did = ZSTD_getDictID_fromFrame(compressedBuffer, cSize);
1173             if (did != dictID) goto _output_error;   /* non-conformant (content-only) dictionary */
1174         }
1175         DISPLAYLEVEL(3, "OK \n");
1176
1177         DISPLAYLEVEL(3, "test%3i : frame built with dictionary should be decompressible : ", testNb++);
1178         {   ZSTD_DCtx* const dctx = ZSTD_createDCtx(); assert(dctx != NULL);
1179             CHECKPLUS(r, ZSTD_decompress_usingDict(dctx,
1180                                            decodedBuffer, CNBuffSize,
1181                                            compressedBuffer, cSize,
1182                                            dictBuffer, dictSize),
1183                       if (r != CNBuffSize) goto _output_error);
1184             ZSTD_freeDCtx(dctx);
1185         }
1186         DISPLAYLEVEL(3, "OK \n");
1187
1188         DISPLAYLEVEL(3, "test%3i : estimate CDict size : ", testNb++);
1189         {   ZSTD_compressionParameters const cParams = ZSTD_getCParams(1, CNBuffSize, dictSize);
1190             size_t const estimatedSize = ZSTD_estimateCDictSize_advanced(dictSize, cParams, ZSTD_dlm_byRef);
1191             DISPLAYLEVEL(3, "OK : %u \n", (unsigned)estimatedSize);
1192         }
1193
1194         DISPLAYLEVEL(3, "test%3i : compress with CDict ", testNb++);
1195         {   ZSTD_compressionParameters const cParams = ZSTD_getCParams(1, CNBuffSize, dictSize);
1196             ZSTD_CDict* const cdict = ZSTD_createCDict_advanced(dictBuffer, dictSize,
1197                                             ZSTD_dlm_byRef, ZSTD_dct_auto,
1198                                             cParams, ZSTD_defaultCMem);
1199             assert(cdict != NULL);
1200             DISPLAYLEVEL(3, "(size : %u) : ", (unsigned)ZSTD_sizeof_CDict(cdict));
1201             cSize = ZSTD_compress_usingCDict(cctx, compressedBuffer, compressedBufferSize,
1202                                                  CNBuffer, CNBuffSize, cdict);
1203             ZSTD_freeCDict(cdict);
1204             if (ZSTD_isError(cSize)) goto _output_error;
1205         }
1206         DISPLAYLEVEL(3, "OK (%u bytes : %.2f%%)\n", (unsigned)cSize, (double)cSize/CNBuffSize*100);
1207
1208         DISPLAYLEVEL(3, "test%3i : retrieve dictID from frame : ", testNb++);
1209         {   U32 const did = ZSTD_getDictID_fromFrame(compressedBuffer, cSize);
1210             if (did != dictID) goto _output_error;   /* non-conformant (content-only) dictionary */
1211         }
1212         DISPLAYLEVEL(3, "OK \n");
1213
1214         DISPLAYLEVEL(3, "test%3i : frame built with dictionary should be decompressible : ", testNb++);
1215         {   ZSTD_DCtx* const dctx = ZSTD_createDCtx(); assert(dctx != NULL);
1216             CHECKPLUS(r, ZSTD_decompress_usingDict(dctx,
1217                                            decodedBuffer, CNBuffSize,
1218                                            compressedBuffer, cSize,
1219                                            dictBuffer, dictSize),
1220                       if (r != CNBuffSize) goto _output_error);
1221             ZSTD_freeDCtx(dctx);
1222         }
1223         DISPLAYLEVEL(3, "OK \n");
1224
1225         DISPLAYLEVEL(3, "test%3i : compress with static CDict : ", testNb++);
1226         {   int const maxLevel = ZSTD_maxCLevel();
1227             int level;
1228             for (level = 1; level <= maxLevel; ++level) {
1229                 ZSTD_compressionParameters const cParams = ZSTD_getCParams(level, CNBuffSize, dictSize);
1230                 size_t const cdictSize = ZSTD_estimateCDictSize_advanced(dictSize, cParams, ZSTD_dlm_byCopy);
1231                 void* const cdictBuffer = malloc(cdictSize);
1232                 if (cdictBuffer==NULL) goto _output_error;
1233                 {   const ZSTD_CDict* const cdict = ZSTD_initStaticCDict(
1234                                                 cdictBuffer, cdictSize,
1235                                                 dictBuffer, dictSize,
1236                                                 ZSTD_dlm_byCopy, ZSTD_dct_auto,
1237                                                 cParams);
1238                     if (cdict == NULL) {
1239                         DISPLAY("ZSTD_initStaticCDict failed ");
1240                         goto _output_error;
1241                     }
1242                     cSize = ZSTD_compress_usingCDict(cctx,
1243                                     compressedBuffer, compressedBufferSize,
1244                                     CNBuffer, MIN(10 KB, CNBuffSize), cdict);
1245                     if (ZSTD_isError(cSize)) {
1246                         DISPLAY("ZSTD_compress_usingCDict failed ");
1247                         goto _output_error;
1248                 }   }
1249                 free(cdictBuffer);
1250         }   }
1251         DISPLAYLEVEL(3, "OK (%u bytes : %.2f%%)\n", (unsigned)cSize, (double)cSize/CNBuffSize*100);
1252
1253         DISPLAYLEVEL(3, "test%3i : ZSTD_compress_usingCDict_advanced, no contentSize, no dictID : ", testNb++);
1254         {   ZSTD_frameParameters const fParams = { 0 /* frameSize */, 1 /* checksum */, 1 /* noDictID*/ };
1255             ZSTD_compressionParameters const cParams = ZSTD_getCParams(1, CNBuffSize, dictSize);
1256             ZSTD_CDict* const cdict = ZSTD_createCDict_advanced(dictBuffer, dictSize, ZSTD_dlm_byRef, ZSTD_dct_auto, cParams, ZSTD_defaultCMem);
1257             assert(cdict != NULL);
1258             cSize = ZSTD_compress_usingCDict_advanced(cctx,
1259                                                       compressedBuffer, compressedBufferSize,
1260                                                       CNBuffer, CNBuffSize,
1261                                                       cdict, fParams);
1262             ZSTD_freeCDict(cdict);
1263             if (ZSTD_isError(cSize)) goto _output_error;
1264         }
1265         DISPLAYLEVEL(3, "OK (%u bytes : %.2f%%)\n", (unsigned)cSize, (double)cSize/CNBuffSize*100);
1266
1267         DISPLAYLEVEL(3, "test%3i : try retrieving contentSize from frame : ", testNb++);
1268         {   U64 const contentSize = ZSTD_getFrameContentSize(compressedBuffer, cSize);
1269             if (contentSize != ZSTD_CONTENTSIZE_UNKNOWN) goto _output_error;
1270         }
1271         DISPLAYLEVEL(3, "OK (unknown)\n");
1272
1273         DISPLAYLEVEL(3, "test%3i : frame built without dictID should be decompressible : ", testNb++);
1274         {   ZSTD_DCtx* const dctx = ZSTD_createDCtx();
1275             assert(dctx != NULL);
1276             CHECKPLUS(r, ZSTD_decompress_usingDict(dctx,
1277                                            decodedBuffer, CNBuffSize,
1278                                            compressedBuffer, cSize,
1279                                            dictBuffer, dictSize),
1280                       if (r != CNBuffSize) goto _output_error);
1281             ZSTD_freeDCtx(dctx);
1282         }
1283         DISPLAYLEVEL(3, "OK \n");
1284
1285         DISPLAYLEVEL(3, "test%3i : ZSTD_compress_advanced, no dictID : ", testNb++);
1286         {   ZSTD_parameters p = ZSTD_getParams(3, CNBuffSize, dictSize);
1287             p.fParams.noDictIDFlag = 1;
1288             cSize = ZSTD_compress_advanced(cctx, compressedBuffer, compressedBufferSize,
1289                                            CNBuffer, CNBuffSize,
1290                                            dictBuffer, dictSize, p);
1291             if (ZSTD_isError(cSize)) goto _output_error;
1292         }
1293         DISPLAYLEVEL(3, "OK (%u bytes : %.2f%%)\n", (unsigned)cSize, (double)cSize/CNBuffSize*100);
1294
1295         DISPLAYLEVEL(3, "test%3i : frame built without dictID should be decompressible : ", testNb++);
1296         {   ZSTD_DCtx* const dctx = ZSTD_createDCtx(); assert(dctx != NULL);
1297             CHECKPLUS(r, ZSTD_decompress_usingDict(dctx,
1298                                            decodedBuffer, CNBuffSize,
1299                                            compressedBuffer, cSize,
1300                                            dictBuffer, dictSize),
1301                       if (r != CNBuffSize) goto _output_error);
1302             ZSTD_freeDCtx(dctx);
1303         }
1304         DISPLAYLEVEL(3, "OK \n");
1305
1306         DISPLAYLEVEL(3, "test%3i : dictionary containing only header should return error : ", testNb++);
1307         {   ZSTD_DCtx* const dctx = ZSTD_createDCtx();
1308             assert(dctx != NULL);
1309             {   const size_t ret = ZSTD_decompress_usingDict(
1310                     dctx, decodedBuffer, CNBuffSize, compressedBuffer, cSize,
1311                     "\x37\xa4\x30\xec\x11\x22\x33\x44", 8);
1312                 if (ZSTD_getErrorCode(ret) != ZSTD_error_dictionary_corrupted)
1313                     goto _output_error;
1314             }
1315             ZSTD_freeDCtx(dctx);
1316         }
1317         DISPLAYLEVEL(3, "OK \n");
1318
1319         DISPLAYLEVEL(3, "test%3i : Building cdict w/ ZSTD_dm_fullDict on a good dictionary : ", testNb++);
1320         {   ZSTD_compressionParameters const cParams = ZSTD_getCParams(1, CNBuffSize, dictSize);
1321             ZSTD_CDict* const cdict = ZSTD_createCDict_advanced(dictBuffer, dictSize, ZSTD_dlm_byRef, ZSTD_dct_fullDict, cParams, ZSTD_defaultCMem);
1322             if (cdict==NULL) goto _output_error;
1323             ZSTD_freeCDict(cdict);
1324         }
1325         DISPLAYLEVEL(3, "OK \n");
1326
1327         DISPLAYLEVEL(3, "test%3i : Building cdict w/ ZSTD_dm_fullDict on a rawContent (must fail) : ", testNb++);
1328         {   ZSTD_compressionParameters const cParams = ZSTD_getCParams(1, CNBuffSize, dictSize);
1329             ZSTD_CDict* const cdict = ZSTD_createCDict_advanced((const char*)dictBuffer+1, dictSize-1, ZSTD_dlm_byRef, ZSTD_dct_fullDict, cParams, ZSTD_defaultCMem);
1330             if (cdict!=NULL) goto _output_error;
1331             ZSTD_freeCDict(cdict);
1332         }
1333         DISPLAYLEVEL(3, "OK \n");
1334
1335         DISPLAYLEVEL(3, "test%3i : Loading rawContent starting with dict header w/ ZSTD_dm_auto should fail : ", testNb++);
1336         {
1337             size_t ret;
1338             MEM_writeLE32((char*)dictBuffer+2, ZSTD_MAGIC_DICTIONARY);
1339             /* Either operation is allowed to fail, but one must fail. */
1340             ret = ZSTD_CCtx_loadDictionary_advanced(
1341                     cctx, (const char*)dictBuffer+2, dictSize-2, ZSTD_dlm_byRef, ZSTD_dct_auto);
1342             if (!ZSTD_isError(ret)) {
1343                 ret = ZSTD_compress2(cctx, compressedBuffer, compressedBufferSize, CNBuffer, MIN(CNBuffSize, 100));
1344                 if (!ZSTD_isError(ret)) goto _output_error;
1345             }
1346         }
1347         DISPLAYLEVEL(3, "OK \n");
1348
1349         DISPLAYLEVEL(3, "test%3i : Loading rawContent starting with dict header w/ ZSTD_dm_rawContent should pass : ", testNb++);
1350         {
1351             size_t ret;
1352             MEM_writeLE32((char*)dictBuffer+2, ZSTD_MAGIC_DICTIONARY);
1353             ret = ZSTD_CCtx_loadDictionary_advanced(
1354                     cctx, (const char*)dictBuffer+2, dictSize-2, ZSTD_dlm_byRef, ZSTD_dct_rawContent);
1355             if (ZSTD_isError(ret)) goto _output_error;
1356             ret = ZSTD_compress2(cctx, compressedBuffer, compressedBufferSize, CNBuffer, MIN(CNBuffSize, 100));
1357             if (ZSTD_isError(ret)) goto _output_error;
1358         }
1359         DISPLAYLEVEL(3, "OK \n");
1360
1361         DISPLAYLEVEL(3, "test%3i : ZSTD_CCtx_refCDict() then set parameters : ", testNb++);
1362         {   ZSTD_CDict* const cdict = ZSTD_createCDict(CNBuffer, dictSize, 1);
1363             CHECK_Z( ZSTD_CCtx_setParameter(cctx, ZSTD_c_compressionLevel, 1) );
1364             CHECK_Z( ZSTD_CCtx_setParameter(cctx, ZSTD_c_hashLog, 12 ));
1365             CHECK_Z( ZSTD_CCtx_refCDict(cctx, cdict) );
1366             CHECK_Z( ZSTD_CCtx_setParameter(cctx, ZSTD_c_compressionLevel, 1) );
1367             CHECK_Z( ZSTD_CCtx_setParameter(cctx, ZSTD_c_hashLog, 12 ));
1368             ZSTD_freeCDict(cdict);
1369         }
1370         DISPLAYLEVEL(3, "OK \n");
1371
1372         DISPLAYLEVEL(3, "test%3i : Loading dictionary before setting parameters is the same as loading after : ", testNb++);
1373         {
1374             size_t size1, size2;
1375             ZSTD_CCtx_reset(cctx, ZSTD_reset_session_and_parameters);
1376             CHECK_Z( ZSTD_CCtx_setParameter(cctx, ZSTD_c_compressionLevel, 7) );
1377             CHECK_Z( ZSTD_CCtx_loadDictionary(cctx, CNBuffer, MIN(CNBuffSize, 10 KB)) );
1378             size1 = ZSTD_compress2(cctx, compressedBuffer, compressedBufferSize, CNBuffer, MIN(CNBuffSize, 100 KB));
1379             if (ZSTD_isError(size1)) goto _output_error;
1380
1381             ZSTD_CCtx_reset(cctx, ZSTD_reset_session_and_parameters);
1382             CHECK_Z( ZSTD_CCtx_loadDictionary(cctx, CNBuffer, MIN(CNBuffSize, 10 KB)) );
1383             CHECK_Z( ZSTD_CCtx_setParameter(cctx, ZSTD_c_compressionLevel, 7) );
1384             size2 = ZSTD_compress2(cctx, compressedBuffer, compressedBufferSize, CNBuffer, MIN(CNBuffSize, 100 KB));
1385             if (ZSTD_isError(size2)) goto _output_error;
1386
1387             if (size1 != size2) goto _output_error;
1388         }
1389         DISPLAYLEVEL(3, "OK \n");
1390
1391         DISPLAYLEVEL(3, "test%3i : Loading a dictionary clears the prefix : ", testNb++);
1392         {
1393             CHECK_Z( ZSTD_CCtx_refPrefix(cctx, (const char*)dictBuffer, dictSize) );
1394             CHECK_Z( ZSTD_CCtx_loadDictionary(cctx, (const char*)dictBuffer, dictSize) );
1395             CHECK_Z( ZSTD_compress2(cctx, compressedBuffer, compressedBufferSize, CNBuffer, MIN(CNBuffSize, 100)) );
1396         }
1397         DISPLAYLEVEL(3, "OK \n");
1398
1399         DISPLAYLEVEL(3, "test%3i : Loading a dictionary clears the cdict : ", testNb++);
1400         {
1401             ZSTD_CDict* const cdict = ZSTD_createCDict(dictBuffer, dictSize, 1);
1402             CHECK_Z( ZSTD_CCtx_refCDict(cctx, cdict) );
1403             CHECK_Z( ZSTD_CCtx_loadDictionary(cctx, (const char*)dictBuffer, dictSize) );
1404             CHECK_Z( ZSTD_compress2(cctx, compressedBuffer, compressedBufferSize, CNBuffer, MIN(CNBuffSize, 100)) );
1405             ZSTD_freeCDict(cdict);
1406         }
1407         DISPLAYLEVEL(3, "OK \n");
1408
1409         DISPLAYLEVEL(3, "test%3i : Loading a cdict clears the prefix : ", testNb++);
1410         {
1411             ZSTD_CDict* const cdict = ZSTD_createCDict(dictBuffer, dictSize, 1);
1412             CHECK_Z( ZSTD_CCtx_refPrefix(cctx, (const char*)dictBuffer, dictSize) );
1413             CHECK_Z( ZSTD_CCtx_refCDict(cctx, cdict) );
1414             CHECK_Z( ZSTD_compress2(cctx, compressedBuffer, compressedBufferSize, CNBuffer, MIN(CNBuffSize, 100)) );
1415             ZSTD_freeCDict(cdict);
1416         }
1417         DISPLAYLEVEL(3, "OK \n");
1418
1419         DISPLAYLEVEL(3, "test%3i : Loading a cdict clears the dictionary : ", testNb++);
1420         {
1421             ZSTD_CDict* const cdict = ZSTD_createCDict(dictBuffer, dictSize, 1);
1422             CHECK_Z( ZSTD_CCtx_loadDictionary(cctx, (const char*)dictBuffer, dictSize) );
1423             CHECK_Z( ZSTD_CCtx_refCDict(cctx, cdict) );
1424             CHECK_Z( ZSTD_compress2(cctx, compressedBuffer, compressedBufferSize, CNBuffer, MIN(CNBuffSize, 100)) );
1425             ZSTD_freeCDict(cdict);
1426         }
1427         DISPLAYLEVEL(3, "OK \n");
1428
1429         DISPLAYLEVEL(3, "test%3i : Loading a prefix clears the dictionary : ", testNb++);
1430         {
1431             CHECK_Z( ZSTD_CCtx_loadDictionary(cctx, (const char*)dictBuffer, dictSize) );
1432             CHECK_Z( ZSTD_CCtx_refPrefix(cctx, (const char*)dictBuffer, dictSize) );
1433             CHECK_Z( ZSTD_compress2(cctx, compressedBuffer, compressedBufferSize, CNBuffer, MIN(CNBuffSize, 100)) );
1434         }
1435         DISPLAYLEVEL(3, "OK \n");
1436
1437         DISPLAYLEVEL(3, "test%3i : Loading a prefix clears the cdict : ", testNb++);
1438         {
1439             ZSTD_CDict* const cdict = ZSTD_createCDict(dictBuffer, dictSize, 1);
1440             CHECK_Z( ZSTD_CCtx_refCDict(cctx, cdict) );
1441             CHECK_Z( ZSTD_CCtx_refPrefix(cctx, (const char*)dictBuffer, dictSize) );
1442             CHECK_Z( ZSTD_compress2(cctx, compressedBuffer, compressedBufferSize, CNBuffer, MIN(CNBuffSize, 100)) );
1443             ZSTD_freeCDict(cdict);
1444         }
1445         DISPLAYLEVEL(3, "OK \n");
1446
1447         DISPLAYLEVEL(3, "test%3i : Loaded dictionary persists across reset session : ", testNb++);
1448         {
1449             size_t size1, size2;
1450             ZSTD_CCtx_reset(cctx, ZSTD_reset_session_and_parameters);
1451             CHECK_Z( ZSTD_CCtx_loadDictionary(cctx, CNBuffer, MIN(CNBuffSize, 10 KB)) );
1452             size1 = ZSTD_compress2(cctx, compressedBuffer, compressedBufferSize, CNBuffer, MIN(CNBuffSize, 100 KB));
1453             if (ZSTD_isError(size1)) goto _output_error;
1454
1455             ZSTD_CCtx_reset(cctx, ZSTD_reset_session_only);
1456             size2 = ZSTD_compress2(cctx, compressedBuffer, compressedBufferSize, CNBuffer, MIN(CNBuffSize, 100 KB));
1457             if (ZSTD_isError(size2)) goto _output_error;
1458
1459             if (size1 != size2) goto _output_error;
1460         }
1461         DISPLAYLEVEL(3, "OK \n");
1462
1463         DISPLAYLEVEL(3, "test%3i : Loaded dictionary is cleared after resetting parameters : ", testNb++);
1464         {
1465             size_t size1, size2;
1466             ZSTD_CCtx_reset(cctx, ZSTD_reset_session_and_parameters);
1467             CHECK_Z( ZSTD_CCtx_loadDictionary(cctx, CNBuffer, MIN(CNBuffSize, 10 KB)) );
1468             size1 = ZSTD_compress2(cctx, compressedBuffer, compressedBufferSize, CNBuffer, MIN(CNBuffSize, 100 KB));
1469             if (ZSTD_isError(size1)) goto _output_error;
1470
1471             ZSTD_CCtx_reset(cctx, ZSTD_reset_session_and_parameters);
1472             size2 = ZSTD_compress2(cctx, compressedBuffer, compressedBufferSize, CNBuffer, MIN(CNBuffSize, 100 KB));
1473             if (ZSTD_isError(size2)) goto _output_error;
1474
1475             if (size1 == size2) goto _output_error;
1476         }
1477         DISPLAYLEVEL(3, "OK \n");
1478
1479         ZSTD_CCtx_reset(cctx, ZSTD_reset_session_and_parameters);
1480         CHECK_Z( ZSTD_CCtx_loadDictionary(cctx, dictBuffer, dictSize) );
1481         cSize = ZSTD_compress2(cctx, compressedBuffer, compressedBufferSize, CNBuffer, MIN(CNBuffSize, 100 KB));
1482         CHECK_Z(cSize);
1483         DISPLAYLEVEL(3, "test%3i : ZSTD_decompressDCtx() with dictionary : ", testNb++);
1484         {
1485             ZSTD_DCtx* dctx = ZSTD_createDCtx();
1486             size_t ret;
1487             /* We should fail to decompress without a dictionary. */
1488             ZSTD_DCtx_reset(dctx, ZSTD_reset_session_and_parameters);
1489             ret = ZSTD_decompressDCtx(dctx, decodedBuffer, CNBuffSize, compressedBuffer, cSize);
1490             if (!ZSTD_isError(ret)) goto _output_error;
1491             /* We should succeed to decompress with the dictionary. */
1492             ZSTD_DCtx_reset(dctx, ZSTD_reset_session_and_parameters);
1493             CHECK_Z( ZSTD_DCtx_loadDictionary(dctx, dictBuffer, dictSize) );
1494             CHECK_Z( ZSTD_decompressDCtx(dctx, decodedBuffer, CNBuffSize, compressedBuffer, cSize) );
1495             /* The dictionary should presist across calls. */
1496             CHECK_Z( ZSTD_decompressDCtx(dctx, decodedBuffer, CNBuffSize, compressedBuffer, cSize) );
1497             /* When we reset the context the dictionary is cleared. */
1498             ZSTD_DCtx_reset(dctx, ZSTD_reset_session_and_parameters);
1499             ret = ZSTD_decompressDCtx(dctx, decodedBuffer, CNBuffSize, compressedBuffer, cSize);
1500             if (!ZSTD_isError(ret)) goto _output_error;
1501             ZSTD_freeDCtx(dctx);
1502         }
1503         DISPLAYLEVEL(3, "OK \n");
1504
1505         DISPLAYLEVEL(3, "test%3i : ZSTD_decompressDCtx() with ddict : ", testNb++);
1506         {
1507             ZSTD_DCtx* dctx = ZSTD_createDCtx();
1508             ZSTD_DDict* ddict = ZSTD_createDDict(dictBuffer, dictSize);
1509             size_t ret;
1510             /* We should succeed to decompress with the ddict. */
1511             ZSTD_DCtx_reset(dctx, ZSTD_reset_session_and_parameters);
1512             CHECK_Z( ZSTD_DCtx_refDDict(dctx, ddict) );
1513             CHECK_Z( ZSTD_decompressDCtx(dctx, decodedBuffer, CNBuffSize, compressedBuffer, cSize) );
1514             /* The ddict should presist across calls. */
1515             CHECK_Z( ZSTD_decompressDCtx(dctx, decodedBuffer, CNBuffSize, compressedBuffer, cSize) );
1516             /* When we reset the context the ddict is cleared. */
1517             ZSTD_DCtx_reset(dctx, ZSTD_reset_session_and_parameters);
1518             ret = ZSTD_decompressDCtx(dctx, decodedBuffer, CNBuffSize, compressedBuffer, cSize);
1519             if (!ZSTD_isError(ret)) goto _output_error;
1520             ZSTD_freeDCtx(dctx);
1521             ZSTD_freeDDict(ddict);
1522         }
1523         DISPLAYLEVEL(3, "OK \n");
1524
1525         DISPLAYLEVEL(3, "test%3i : ZSTD_decompressDCtx() with prefix : ", testNb++);
1526         {
1527             ZSTD_DCtx* dctx = ZSTD_createDCtx();
1528             size_t ret;
1529             /* We should succeed to decompress with the prefix. */
1530             ZSTD_DCtx_reset(dctx, ZSTD_reset_session_and_parameters);
1531             CHECK_Z( ZSTD_DCtx_refPrefix_advanced(dctx, dictBuffer, dictSize, ZSTD_dct_auto) );
1532             CHECK_Z( ZSTD_decompressDCtx(dctx, decodedBuffer, CNBuffSize, compressedBuffer, cSize) );
1533             /* The prefix should be cleared after the first compression. */
1534             ret = ZSTD_decompressDCtx(dctx, decodedBuffer, CNBuffSize, compressedBuffer, cSize);
1535             if (!ZSTD_isError(ret)) goto _output_error;
1536             ZSTD_freeDCtx(dctx);
1537         }
1538         DISPLAYLEVEL(3, "OK \n");
1539
1540         DISPLAYLEVEL(3, "test%3i : Dictionary with non-default repcodes : ", testNb++);
1541         { U32 u; for (u=0; u<nbSamples; u++) samplesSizes[u] = sampleUnitSize; }
1542         dictSize = ZDICT_trainFromBuffer(dictBuffer, dictSize,
1543                                          CNBuffer, samplesSizes, nbSamples);
1544         if (ZDICT_isError(dictSize)) goto _output_error;
1545         /* Set all the repcodes to non-default */
1546         {
1547             BYTE* dictPtr = (BYTE*)dictBuffer;
1548             BYTE* dictLimit = dictPtr + dictSize - 12;
1549             /* Find the repcodes */
1550             while (dictPtr < dictLimit &&
1551                    (MEM_readLE32(dictPtr) != 1 || MEM_readLE32(dictPtr + 4) != 4 ||
1552                     MEM_readLE32(dictPtr + 8) != 8)) {
1553                 ++dictPtr;
1554             }
1555             if (dictPtr >= dictLimit) goto _output_error;
1556             MEM_writeLE32(dictPtr + 0, 10);
1557             MEM_writeLE32(dictPtr + 4, 10);
1558             MEM_writeLE32(dictPtr + 8, 10);
1559             /* Set the last 8 bytes to 'x' */
1560             memset((BYTE*)dictBuffer + dictSize - 8, 'x', 8);
1561         }
1562         /* The optimal parser checks all the repcodes.
1563          * Make sure at least one is a match >= targetLength so that it is
1564          * immediately chosen. This will make sure that the compressor and
1565          * decompressor agree on at least one of the repcodes.
1566          */
1567         {   size_t dSize;
1568             BYTE data[1024];
1569             ZSTD_DCtx* const dctx = ZSTD_createDCtx();
1570             ZSTD_compressionParameters const cParams = ZSTD_getCParams(19, CNBuffSize, dictSize);
1571             ZSTD_CDict* const cdict = ZSTD_createCDict_advanced(dictBuffer, dictSize,
1572                                             ZSTD_dlm_byRef, ZSTD_dct_auto,
1573                                             cParams, ZSTD_defaultCMem);
1574             assert(dctx != NULL); assert(cdict != NULL);
1575             memset(data, 'x', sizeof(data));
1576             cSize = ZSTD_compress_usingCDict(cctx, compressedBuffer, compressedBufferSize,
1577                                              data, sizeof(data), cdict);
1578             ZSTD_freeCDict(cdict);
1579             if (ZSTD_isError(cSize)) { DISPLAYLEVEL(5, "Compression error %s : ", ZSTD_getErrorName(cSize)); goto _output_error; }
1580             dSize = ZSTD_decompress_usingDict(dctx, decodedBuffer, sizeof(data), compressedBuffer, cSize, dictBuffer, dictSize);
1581             if (ZSTD_isError(dSize)) { DISPLAYLEVEL(5, "Decompression error %s : ", ZSTD_getErrorName(dSize)); goto _output_error; }
1582             if (memcmp(data, decodedBuffer, sizeof(data))) { DISPLAYLEVEL(5, "Data corruption : "); goto _output_error; }
1583             ZSTD_freeDCtx(dctx);
1584         }
1585         DISPLAYLEVEL(3, "OK \n");
1586
1587         ZSTD_freeCCtx(cctx);
1588         free(dictBuffer);
1589         free(samplesSizes);
1590     }
1591
1592     /* COVER dictionary builder tests */
1593     {   ZSTD_CCtx* const cctx = ZSTD_createCCtx();
1594         size_t dictSize = 16 KB;
1595         size_t optDictSize = dictSize;
1596         void* dictBuffer = malloc(dictSize);
1597         size_t const totalSampleSize = 1 MB;
1598         size_t const sampleUnitSize = 8 KB;
1599         U32 const nbSamples = (U32)(totalSampleSize / sampleUnitSize);
1600         size_t* const samplesSizes = (size_t*) malloc(nbSamples * sizeof(size_t));
1601         ZDICT_cover_params_t params;
1602         U32 dictID;
1603
1604         if (dictBuffer==NULL || samplesSizes==NULL) {
1605             free(dictBuffer);
1606             free(samplesSizes);
1607             goto _output_error;
1608         }
1609
1610         DISPLAYLEVEL(3, "test%3i : ZDICT_trainFromBuffer_cover : ", testNb++);
1611         { U32 u; for (u=0; u<nbSamples; u++) samplesSizes[u] = sampleUnitSize; }
1612         memset(&params, 0, sizeof(params));
1613         params.d = 1 + (FUZ_rand(&seed) % 16);
1614         params.k = params.d + (FUZ_rand(&seed) % 256);
1615         dictSize = ZDICT_trainFromBuffer_cover(dictBuffer, dictSize,
1616                                                CNBuffer, samplesSizes, nbSamples,
1617                                                params);
1618         if (ZDICT_isError(dictSize)) goto _output_error;
1619         DISPLAYLEVEL(3, "OK, created dictionary of size %u \n", (unsigned)dictSize);
1620
1621         DISPLAYLEVEL(3, "test%3i : check dictID : ", testNb++);
1622         dictID = ZDICT_getDictID(dictBuffer, dictSize);
1623         if (dictID==0) goto _output_error;
1624         DISPLAYLEVEL(3, "OK : %u \n", (unsigned)dictID);
1625
1626         DISPLAYLEVEL(3, "test%3i : ZDICT_optimizeTrainFromBuffer_cover : ", testNb++);
1627         memset(&params, 0, sizeof(params));
1628         params.steps = 4;
1629         optDictSize = ZDICT_optimizeTrainFromBuffer_cover(dictBuffer, optDictSize,
1630                                                           CNBuffer, samplesSizes,
1631                                                           nbSamples / 4, &params);
1632         if (ZDICT_isError(optDictSize)) goto _output_error;
1633         DISPLAYLEVEL(3, "OK, created dictionary of size %u \n", (unsigned)optDictSize);
1634
1635         DISPLAYLEVEL(3, "test%3i : check dictID : ", testNb++);
1636         dictID = ZDICT_getDictID(dictBuffer, optDictSize);
1637         if (dictID==0) goto _output_error;
1638         DISPLAYLEVEL(3, "OK : %u \n", (unsigned)dictID);
1639
1640         ZSTD_freeCCtx(cctx);
1641         free(dictBuffer);
1642         free(samplesSizes);
1643     }
1644
1645     /* Decompression defense tests */
1646     DISPLAYLEVEL(3, "test%3i : Check input length for magic number : ", testNb++);
1647     { size_t const r = ZSTD_decompress(decodedBuffer, CNBuffSize, CNBuffer, 3);   /* too small input */
1648       if (!ZSTD_isError(r)) goto _output_error;
1649       if (ZSTD_getErrorCode(r) != ZSTD_error_srcSize_wrong) goto _output_error; }
1650     DISPLAYLEVEL(3, "OK \n");
1651
1652     DISPLAYLEVEL(3, "test%3i : Check magic Number : ", testNb++);
1653     ((char*)(CNBuffer))[0] = 1;
1654     { size_t const r = ZSTD_decompress(decodedBuffer, CNBuffSize, CNBuffer, 4);
1655       if (!ZSTD_isError(r)) goto _output_error; }
1656     DISPLAYLEVEL(3, "OK \n");
1657
1658     /* content size verification test */
1659     DISPLAYLEVEL(3, "test%3i : Content size verification : ", testNb++);
1660     {   ZSTD_CCtx* const cctx = ZSTD_createCCtx();
1661         size_t const srcSize = 5000;
1662         size_t const wrongSrcSize = (srcSize + 1000);
1663         ZSTD_parameters params = ZSTD_getParams(1, wrongSrcSize, 0);
1664         params.fParams.contentSizeFlag = 1;
1665         CHECK( ZSTD_compressBegin_advanced(cctx, NULL, 0, params, wrongSrcSize) );
1666         {   size_t const result = ZSTD_compressEnd(cctx, decodedBuffer, CNBuffSize, CNBuffer, srcSize);
1667             if (!ZSTD_isError(result)) goto _output_error;
1668             if (ZSTD_getErrorCode(result) != ZSTD_error_srcSize_wrong) goto _output_error;
1669             DISPLAYLEVEL(3, "OK : %s \n", ZSTD_getErrorName(result));
1670         }
1671         ZSTD_freeCCtx(cctx);
1672     }
1673
1674     /* negative compression level test : ensure simple API and advanced API produce same result */
1675     DISPLAYLEVEL(3, "test%3i : negative compression level : ", testNb++);
1676     {   ZSTD_CCtx* const cctx = ZSTD_createCCtx();
1677         size_t const srcSize = CNBuffSize / 5;
1678         int const compressionLevel = -1;
1679
1680         assert(cctx != NULL);
1681         {   ZSTD_parameters const params = ZSTD_getParams(compressionLevel, srcSize, 0);
1682             size_t const cSize_1pass = ZSTD_compress_advanced(cctx,
1683                                         compressedBuffer, compressedBufferSize,
1684                                         CNBuffer, srcSize,
1685                                         NULL, 0,
1686                                         params);
1687             if (ZSTD_isError(cSize_1pass)) goto _output_error;
1688
1689             CHECK( ZSTD_CCtx_setParameter(cctx, ZSTD_c_compressionLevel, compressionLevel) );
1690             {   size_t const compressionResult = ZSTD_compress2(cctx,
1691                                     compressedBuffer, compressedBufferSize,
1692                                     CNBuffer, srcSize);
1693                 DISPLAYLEVEL(5, "simple=%zu vs %zu=advanced : ", cSize_1pass, compressionResult);
1694                 if (ZSTD_isError(compressionResult)) goto _output_error;
1695                 if (compressionResult != cSize_1pass) goto _output_error;
1696         }   }
1697         ZSTD_freeCCtx(cctx);
1698     }
1699     DISPLAYLEVEL(3, "OK \n");
1700
1701     /* parameters order test */
1702     {   size_t const inputSize = CNBuffSize / 2;
1703         U64 xxh64;
1704
1705         {   ZSTD_CCtx* const cctx = ZSTD_createCCtx();
1706             DISPLAYLEVEL(3, "test%3i : parameters in order : ", testNb++);
1707             assert(cctx != NULL);
1708             CHECK( ZSTD_CCtx_setParameter(cctx, ZSTD_c_compressionLevel, 2) );
1709             CHECK( ZSTD_CCtx_setParameter(cctx, ZSTD_c_enableLongDistanceMatching, 1) );
1710             CHECK( ZSTD_CCtx_setParameter(cctx, ZSTD_c_windowLog, 18) );
1711             {   size_t const compressedSize = ZSTD_compress2(cctx,
1712                                 compressedBuffer, ZSTD_compressBound(inputSize),
1713                                 CNBuffer, inputSize);
1714                 CHECK(compressedSize);
1715                 cSize = compressedSize;
1716                 xxh64 = XXH64(compressedBuffer, compressedSize, 0);
1717             }
1718             DISPLAYLEVEL(3, "OK (compress : %u -> %u bytes)\n", (unsigned)inputSize, (unsigned)cSize);
1719             ZSTD_freeCCtx(cctx);
1720         }
1721
1722         {   ZSTD_CCtx* cctx = ZSTD_createCCtx();
1723             DISPLAYLEVEL(3, "test%3i : parameters disordered : ", testNb++);
1724             CHECK( ZSTD_CCtx_setParameter(cctx, ZSTD_c_windowLog, 18) );
1725             CHECK( ZSTD_CCtx_setParameter(cctx, ZSTD_c_enableLongDistanceMatching, 1) );
1726             CHECK( ZSTD_CCtx_setParameter(cctx, ZSTD_c_compressionLevel, 2) );
1727             {   size_t const result = ZSTD_compress2(cctx,
1728                                 compressedBuffer, ZSTD_compressBound(inputSize),
1729                                 CNBuffer, inputSize);
1730                 CHECK(result);
1731                 if (result != cSize) goto _output_error;   /* must result in same compressed result, hence same size */
1732                 if (XXH64(compressedBuffer, result, 0) != xxh64) goto _output_error;  /* must result in exactly same content, hence same hash */
1733                 DISPLAYLEVEL(3, "OK (compress : %u -> %u bytes)\n", (unsigned)inputSize, (unsigned)result);
1734             }
1735             ZSTD_freeCCtx(cctx);
1736         }
1737     }
1738
1739     /* advanced parameters for decompression */
1740     {   ZSTD_DCtx* const dctx = ZSTD_createDCtx();
1741         assert(dctx != NULL);
1742
1743         DISPLAYLEVEL(3, "test%3i : get dParameter bounds ", testNb++);
1744         {   ZSTD_bounds const bounds = ZSTD_dParam_getBounds(ZSTD_d_windowLogMax);
1745             CHECK(bounds.error);
1746         }
1747         DISPLAYLEVEL(3, "OK \n");
1748
1749         DISPLAYLEVEL(3, "test%3i : wrong dParameter : ", testNb++);
1750         {   size_t const sr = ZSTD_DCtx_setParameter(dctx, (ZSTD_dParameter)999999, 0);
1751             if (!ZSTD_isError(sr)) goto _output_error;
1752         }
1753         {   ZSTD_bounds const bounds = ZSTD_dParam_getBounds((ZSTD_dParameter)999998);
1754             if (!ZSTD_isError(bounds.error)) goto _output_error;
1755         }
1756         DISPLAYLEVEL(3, "OK \n");
1757
1758         DISPLAYLEVEL(3, "test%3i : out of bound dParameter : ", testNb++);
1759         {   size_t const sr = ZSTD_DCtx_setParameter(dctx, ZSTD_d_windowLogMax, 9999);
1760             if (!ZSTD_isError(sr)) goto _output_error;
1761         }
1762         {   size_t const sr = ZSTD_DCtx_setParameter(dctx, ZSTD_d_format, (ZSTD_format_e)888);
1763             if (!ZSTD_isError(sr)) goto _output_error;
1764         }
1765         DISPLAYLEVEL(3, "OK \n");
1766
1767         ZSTD_freeDCtx(dctx);
1768     }
1769
1770
1771     /* custom formats tests */
1772     {   ZSTD_CCtx* const cctx = ZSTD_createCCtx();
1773         ZSTD_DCtx* const dctx = ZSTD_createDCtx();
1774         size_t const inputSize = CNBuffSize / 2;   /* won't cause pb with small dict size */
1775         assert(dctx != NULL); assert(cctx != NULL);
1776
1777         /* basic block compression */
1778         DISPLAYLEVEL(3, "test%3i : magic-less format test : ", testNb++);
1779         CHECK( ZSTD_CCtx_setParameter(cctx, ZSTD_c_format, ZSTD_f_zstd1_magicless) );
1780         {   ZSTD_inBuffer in = { CNBuffer, inputSize, 0 };
1781             ZSTD_outBuffer out = { compressedBuffer, ZSTD_compressBound(inputSize), 0 };
1782             size_t const result = ZSTD_compressStream2(cctx, &out, &in, ZSTD_e_end);
1783             if (result != 0) goto _output_error;
1784             if (in.pos != in.size) goto _output_error;
1785             cSize = out.pos;
1786         }
1787         DISPLAYLEVEL(3, "OK (compress : %u -> %u bytes)\n", (unsigned)inputSize, (unsigned)cSize);
1788
1789         DISPLAYLEVEL(3, "test%3i : decompress normally (should fail) : ", testNb++);
1790         {   size_t const decodeResult = ZSTD_decompressDCtx(dctx, decodedBuffer, CNBuffSize, compressedBuffer, cSize);
1791             if (ZSTD_getErrorCode(decodeResult) != ZSTD_error_prefix_unknown) goto _output_error;
1792             DISPLAYLEVEL(3, "OK : %s \n", ZSTD_getErrorName(decodeResult));
1793         }
1794
1795         DISPLAYLEVEL(3, "test%3i : decompress of magic-less frame : ", testNb++);
1796         ZSTD_DCtx_reset(dctx, ZSTD_reset_session_and_parameters);
1797         CHECK( ZSTD_DCtx_setParameter(dctx, ZSTD_d_format, ZSTD_f_zstd1_magicless) );
1798         {   ZSTD_frameHeader zfh;
1799             size_t const zfhrt = ZSTD_getFrameHeader_advanced(&zfh, compressedBuffer, cSize, ZSTD_f_zstd1_magicless);
1800             if (zfhrt != 0) goto _output_error;
1801         }
1802         /* one shot */
1803         {   size_t const result = ZSTD_decompressDCtx(dctx, decodedBuffer, CNBuffSize, compressedBuffer, cSize);
1804             if (result != inputSize) goto _output_error;
1805             DISPLAYLEVEL(3, "one-shot OK, ");
1806         }
1807         /* streaming */
1808         {   ZSTD_inBuffer in = { compressedBuffer, cSize, 0 };
1809             ZSTD_outBuffer out = { decodedBuffer, CNBuffSize, 0 };
1810             size_t const result = ZSTD_decompressStream(dctx, &out, &in);
1811             if (result != 0) goto _output_error;
1812             if (in.pos != in.size) goto _output_error;
1813             if (out.pos != inputSize) goto _output_error;
1814             DISPLAYLEVEL(3, "streaming OK : regenerated %u bytes \n", (unsigned)out.pos);
1815         }
1816
1817         ZSTD_freeCCtx(cctx);
1818         ZSTD_freeDCtx(dctx);
1819     }
1820
1821     /* block API tests */
1822     {   ZSTD_CCtx* const cctx = ZSTD_createCCtx();
1823         ZSTD_DCtx* const dctx = ZSTD_createDCtx();
1824         static const size_t dictSize = 65 KB;
1825         static const size_t blockSize = 100 KB;   /* won't cause pb with small dict size */
1826         size_t cSize2;
1827         assert(cctx != NULL); assert(dctx != NULL);
1828
1829         /* basic block compression */
1830         DISPLAYLEVEL(3, "test%3i : Block compression test : ", testNb++);
1831         CHECK( ZSTD_compressBegin(cctx, 5) );
1832         CHECK( ZSTD_getBlockSize(cctx) >= blockSize);
1833         cSize = ZSTD_compressBlock(cctx, compressedBuffer, ZSTD_compressBound(blockSize), CNBuffer, blockSize);
1834         if (ZSTD_isError(cSize)) goto _output_error;
1835         DISPLAYLEVEL(3, "OK \n");
1836
1837         DISPLAYLEVEL(3, "test%3i : Block decompression test : ", testNb++);
1838         CHECK( ZSTD_decompressBegin(dctx) );
1839         { CHECK_V(r, ZSTD_decompressBlock(dctx, decodedBuffer, CNBuffSize, compressedBuffer, cSize) );
1840           if (r != blockSize) goto _output_error; }
1841         DISPLAYLEVEL(3, "OK \n");
1842
1843         /* very long stream of block compression */
1844         DISPLAYLEVEL(3, "test%3i : Huge block streaming compression test : ", testNb++);
1845         CHECK( ZSTD_compressBegin(cctx, -199) );  /* we just want to quickly overflow internal U32 index */
1846         CHECK( ZSTD_getBlockSize(cctx) >= blockSize);
1847         {   U64 const toCompress = 5000000000ULL;   /* > 4 GB */
1848             U64 compressed = 0;
1849             while (compressed < toCompress) {
1850                 size_t const blockCSize = ZSTD_compressBlock(cctx, compressedBuffer, ZSTD_compressBound(blockSize), CNBuffer, blockSize);
1851                 assert(blockCSize != 0);
1852                 if (ZSTD_isError(blockCSize)) goto _output_error;
1853                 compressed += blockCSize;
1854             }
1855         }
1856         DISPLAYLEVEL(3, "OK \n");
1857
1858         /* dictionary block compression */
1859         DISPLAYLEVEL(3, "test%3i : Dictionary Block compression test : ", testNb++);
1860         CHECK( ZSTD_compressBegin_usingDict(cctx, CNBuffer, dictSize, 5) );
1861         cSize = ZSTD_compressBlock(cctx, compressedBuffer, ZSTD_compressBound(blockSize), (char*)CNBuffer+dictSize, blockSize);
1862         if (ZSTD_isError(cSize)) goto _output_error;
1863         cSize2 = ZSTD_compressBlock(cctx, (char*)compressedBuffer+cSize, ZSTD_compressBound(blockSize), (char*)CNBuffer+dictSize+blockSize, blockSize);
1864         if (ZSTD_isError(cSize2)) goto _output_error;
1865         memcpy((char*)compressedBuffer+cSize, (char*)CNBuffer+dictSize+blockSize, blockSize);   /* fake non-compressed block */
1866         cSize2 = ZSTD_compressBlock(cctx, (char*)compressedBuffer+cSize+blockSize, ZSTD_compressBound(blockSize),
1867                                           (char*)CNBuffer+dictSize+2*blockSize, blockSize);
1868         if (ZSTD_isError(cSize2)) goto _output_error;
1869         DISPLAYLEVEL(3, "OK \n");
1870
1871         DISPLAYLEVEL(3, "test%3i : Dictionary Block decompression test : ", testNb++);
1872         CHECK( ZSTD_decompressBegin_usingDict(dctx, CNBuffer, dictSize) );
1873         { CHECK_V( r, ZSTD_decompressBlock(dctx, decodedBuffer, CNBuffSize, compressedBuffer, cSize) );
1874           if (r != blockSize) goto _output_error; }
1875         ZSTD_insertBlock(dctx, (char*)decodedBuffer+blockSize, blockSize);   /* insert non-compressed block into dctx history */
1876         { CHECK_V( r, ZSTD_decompressBlock(dctx, (char*)decodedBuffer+2*blockSize, CNBuffSize, (char*)compressedBuffer+cSize+blockSize, cSize2) );
1877           if (r != blockSize) goto _output_error; }
1878         DISPLAYLEVEL(3, "OK \n");
1879
1880         DISPLAYLEVEL(3, "test%3i : Block compression with CDict : ", testNb++);
1881         {   ZSTD_CDict* const cdict = ZSTD_createCDict(CNBuffer, dictSize, 3);
1882             if (cdict==NULL) goto _output_error;
1883             CHECK( ZSTD_compressBegin_usingCDict(cctx, cdict) );
1884             CHECK( ZSTD_compressBlock(cctx, compressedBuffer, ZSTD_compressBound(blockSize), (char*)CNBuffer+dictSize, blockSize) );
1885             ZSTD_freeCDict(cdict);
1886         }
1887         DISPLAYLEVEL(3, "OK \n");
1888
1889         ZSTD_freeCCtx(cctx);
1890         ZSTD_freeDCtx(dctx);
1891     }
1892
1893     /* long rle test */
1894     {   size_t sampleSize = 0;
1895         DISPLAYLEVEL(3, "test%3i : Long RLE test : ", testNb++);
1896         RDG_genBuffer(CNBuffer, sampleSize, compressibility, 0., seed+1);
1897         memset((char*)CNBuffer+sampleSize, 'B', 256 KB - 1);
1898         sampleSize += 256 KB - 1;
1899         RDG_genBuffer((char*)CNBuffer+sampleSize, 96 KB, compressibility, 0., seed+2);
1900         sampleSize += 96 KB;
1901         cSize = ZSTD_compress(compressedBuffer, ZSTD_compressBound(sampleSize), CNBuffer, sampleSize, 1);
1902         if (ZSTD_isError(cSize)) goto _output_error;
1903         { CHECK_V(regenSize, ZSTD_decompress(decodedBuffer, sampleSize, compressedBuffer, cSize));
1904           if (regenSize!=sampleSize) goto _output_error; }
1905         DISPLAYLEVEL(3, "OK \n");
1906     }
1907
1908     /* All zeroes test (test bug #137) */
1909     #define ZEROESLENGTH 100
1910     DISPLAYLEVEL(3, "test%3i : compress %u zeroes : ", testNb++, ZEROESLENGTH);
1911     memset(CNBuffer, 0, ZEROESLENGTH);
1912     { CHECK_V(r, ZSTD_compress(compressedBuffer, ZSTD_compressBound(ZEROESLENGTH), CNBuffer, ZEROESLENGTH, 1) );
1913       cSize = r; }
1914     DISPLAYLEVEL(3, "OK (%u bytes : %.2f%%)\n", (unsigned)cSize, (double)cSize/ZEROESLENGTH*100);
1915
1916     DISPLAYLEVEL(3, "test%3i : decompress %u zeroes : ", testNb++, ZEROESLENGTH);
1917     { CHECK_V(r, ZSTD_decompress(decodedBuffer, ZEROESLENGTH, compressedBuffer, cSize) );
1918       if (r != ZEROESLENGTH) goto _output_error; }
1919     DISPLAYLEVEL(3, "OK \n");
1920
1921     /* nbSeq limit test */
1922     #define _3BYTESTESTLENGTH 131000
1923     #define NB3BYTESSEQLOG   9
1924     #define NB3BYTESSEQ     (1 << NB3BYTESSEQLOG)
1925     #define NB3BYTESSEQMASK (NB3BYTESSEQ-1)
1926     /* creates a buffer full of 3-bytes sequences */
1927     {   BYTE _3BytesSeqs[NB3BYTESSEQ][3];
1928         U32 rSeed = 1;
1929
1930         /* create batch of 3-bytes sequences */
1931         {   int i;
1932             for (i=0; i < NB3BYTESSEQ; i++) {
1933                 _3BytesSeqs[i][0] = (BYTE)(FUZ_rand(&rSeed) & 255);
1934                 _3BytesSeqs[i][1] = (BYTE)(FUZ_rand(&rSeed) & 255);
1935                 _3BytesSeqs[i][2] = (BYTE)(FUZ_rand(&rSeed) & 255);
1936         }   }
1937
1938         /* randomly fills CNBuffer with prepared 3-bytes sequences */
1939         {   int i;
1940             for (i=0; i < _3BYTESTESTLENGTH; i += 3) {   /* note : CNBuffer size > _3BYTESTESTLENGTH+3 */
1941                 U32 const id = FUZ_rand(&rSeed) & NB3BYTESSEQMASK;
1942                 ((BYTE*)CNBuffer)[i+0] = _3BytesSeqs[id][0];
1943                 ((BYTE*)CNBuffer)[i+1] = _3BytesSeqs[id][1];
1944                 ((BYTE*)CNBuffer)[i+2] = _3BytesSeqs[id][2];
1945     }   }   }
1946     DISPLAYLEVEL(3, "test%3i : growing nbSeq : ", testNb++);
1947     {   ZSTD_CCtx* const cctx = ZSTD_createCCtx();
1948         size_t const maxNbSeq = _3BYTESTESTLENGTH / 3;
1949         size_t const bound = ZSTD_compressBound(_3BYTESTESTLENGTH);
1950         size_t nbSeq = 1;
1951         while (nbSeq <= maxNbSeq) {
1952           CHECK(ZSTD_compressCCtx(cctx, compressedBuffer, bound, CNBuffer, nbSeq * 3, 19));
1953           /* Check every sequence for the first 100, then skip more rapidly. */
1954           if (nbSeq < 100) {
1955             ++nbSeq;
1956           } else {
1957             nbSeq += (nbSeq >> 2);
1958           }
1959         }
1960         ZSTD_freeCCtx(cctx);
1961     }
1962     DISPLAYLEVEL(3, "OK \n");
1963
1964     DISPLAYLEVEL(3, "test%3i : compress lots 3-bytes sequences : ", testNb++);
1965     { CHECK_V(r, ZSTD_compress(compressedBuffer, ZSTD_compressBound(_3BYTESTESTLENGTH),
1966                                  CNBuffer, _3BYTESTESTLENGTH, 19) );
1967       cSize = r; }
1968     DISPLAYLEVEL(3, "OK (%u bytes : %.2f%%)\n", (unsigned)cSize, (double)cSize/_3BYTESTESTLENGTH*100);
1969
1970     DISPLAYLEVEL(3, "test%3i : decompress lots 3-bytes sequence : ", testNb++);
1971     { CHECK_V(r, ZSTD_decompress(decodedBuffer, _3BYTESTESTLENGTH, compressedBuffer, cSize) );
1972       if (r != _3BYTESTESTLENGTH) goto _output_error; }
1973     DISPLAYLEVEL(3, "OK \n");
1974
1975
1976     DISPLAYLEVEL(3, "test%3i : growing literals buffer : ", testNb++);
1977     RDG_genBuffer(CNBuffer, CNBuffSize, 0.0, 0.1, seed);
1978     {   ZSTD_CCtx* const cctx = ZSTD_createCCtx();
1979         size_t const bound = ZSTD_compressBound(CNBuffSize);
1980         size_t size = 1;
1981         while (size <= CNBuffSize) {
1982           CHECK(ZSTD_compressCCtx(cctx, compressedBuffer, bound, CNBuffer, size, 3));
1983           /* Check every size for the first 100, then skip more rapidly. */
1984           if (size < 100) {
1985             ++size;
1986           } else {
1987             size += (size >> 2);
1988           }
1989         }
1990         ZSTD_freeCCtx(cctx);
1991     }
1992     DISPLAYLEVEL(3, "OK \n");
1993
1994     DISPLAYLEVEL(3, "test%3i : incompressible data and ill suited dictionary : ", testNb++);
1995     {   /* Train a dictionary on low characters */
1996         size_t dictSize = 16 KB;
1997         void* const dictBuffer = malloc(dictSize);
1998         size_t const totalSampleSize = 1 MB;
1999         size_t const sampleUnitSize = 8 KB;
2000         U32 const nbSamples = (U32)(totalSampleSize / sampleUnitSize);
2001         size_t* const samplesSizes = (size_t*) malloc(nbSamples * sizeof(size_t));
2002         if (!dictBuffer || !samplesSizes) goto _output_error;
2003         { U32 u; for (u=0; u<nbSamples; u++) samplesSizes[u] = sampleUnitSize; }
2004         dictSize = ZDICT_trainFromBuffer(dictBuffer, dictSize, CNBuffer, samplesSizes, nbSamples);
2005         if (ZDICT_isError(dictSize)) goto _output_error;
2006         /* Reverse the characters to make the dictionary ill suited */
2007         {   U32 u;
2008             for (u = 0; u < CNBuffSize; ++u) {
2009               ((BYTE*)CNBuffer)[u] = 255 - ((BYTE*)CNBuffer)[u];
2010             }
2011         }
2012         {   /* Compress the data */
2013             size_t const inputSize = 500;
2014             size_t const outputSize = ZSTD_compressBound(inputSize);
2015             void* const outputBuffer = malloc(outputSize);
2016             ZSTD_CCtx* const cctx = ZSTD_createCCtx();
2017             if (!outputBuffer || !cctx) goto _output_error;
2018             CHECK(ZSTD_compress_usingDict(cctx, outputBuffer, outputSize, CNBuffer, inputSize, dictBuffer, dictSize, 1));
2019             free(outputBuffer);
2020             ZSTD_freeCCtx(cctx);
2021         }
2022
2023         free(dictBuffer);
2024         free(samplesSizes);
2025     }
2026     DISPLAYLEVEL(3, "OK \n");
2027
2028
2029     /* findFrameCompressedSize on skippable frames */
2030     DISPLAYLEVEL(3, "test%3i : frame compressed size of skippable frame : ", testNb++);
2031     {   const char* frame = "\x50\x2a\x4d\x18\x05\x0\x0\0abcde";
2032         size_t const frameSrcSize = 13;
2033         if (ZSTD_findFrameCompressedSize(frame, frameSrcSize) != frameSrcSize) goto _output_error; }
2034     DISPLAYLEVEL(3, "OK \n");
2035
2036     /* error string tests */
2037     DISPLAYLEVEL(3, "test%3i : testing ZSTD error code strings : ", testNb++);
2038     if (strcmp("No error detected", ZSTD_getErrorName((ZSTD_ErrorCode)(0-ZSTD_error_no_error))) != 0) goto _output_error;
2039     if (strcmp("No error detected", ZSTD_getErrorString(ZSTD_error_no_error)) != 0) goto _output_error;
2040     if (strcmp("Unspecified error code", ZSTD_getErrorString((ZSTD_ErrorCode)(0-ZSTD_error_GENERIC))) != 0) goto _output_error;
2041     if (strcmp("Error (generic)", ZSTD_getErrorName((size_t)0-ZSTD_error_GENERIC)) != 0) goto _output_error;
2042     if (strcmp("Error (generic)", ZSTD_getErrorString(ZSTD_error_GENERIC)) != 0) goto _output_error;
2043     if (strcmp("No error detected", ZSTD_getErrorName(ZSTD_error_GENERIC)) != 0) goto _output_error;
2044     DISPLAYLEVEL(3, "OK \n");
2045
2046     DISPLAYLEVEL(3, "test%3i : testing ZSTD dictionary sizes : ", testNb++);
2047     RDG_genBuffer(CNBuffer, CNBuffSize, compressibility, 0., seed);
2048     {
2049         size_t const size = MIN(128 KB, CNBuffSize);
2050         ZSTD_CCtx* const cctx = ZSTD_createCCtx();
2051         ZSTD_CDict* const lgCDict = ZSTD_createCDict(CNBuffer, size, 1);
2052         ZSTD_CDict* const smCDict = ZSTD_createCDict(CNBuffer, 1 KB, 1);
2053         ZSTD_frameHeader lgHeader;
2054         ZSTD_frameHeader smHeader;
2055
2056         CHECK_Z(ZSTD_compress_usingCDict(cctx, compressedBuffer, compressedBufferSize, CNBuffer, size, lgCDict));
2057         CHECK_Z(ZSTD_getFrameHeader(&lgHeader, compressedBuffer, compressedBufferSize));
2058         CHECK_Z(ZSTD_compress_usingCDict(cctx, compressedBuffer, compressedBufferSize, CNBuffer, size, smCDict));
2059         CHECK_Z(ZSTD_getFrameHeader(&smHeader, compressedBuffer, compressedBufferSize));
2060
2061         if (lgHeader.windowSize != smHeader.windowSize) goto _output_error;
2062
2063         ZSTD_freeCDict(smCDict);
2064         ZSTD_freeCDict(lgCDict);
2065         ZSTD_freeCCtx(cctx);
2066     }
2067     DISPLAYLEVEL(3, "OK \n");
2068
2069     DISPLAYLEVEL(3, "test%3i : testing FSE_normalizeCount() PR#1255: ", testNb++);
2070     {
2071         short norm[32];
2072         unsigned count[32];
2073         unsigned const tableLog = 5;
2074         size_t const nbSeq = 32;
2075         unsigned const maxSymbolValue = 31;
2076         size_t i;
2077
2078         for (i = 0; i < 32; ++i)
2079             count[i] = 1;
2080         /* Calling FSE_normalizeCount() on a uniform distribution should not
2081          * cause a division by zero.
2082          */
2083         FSE_normalizeCount(norm, tableLog, count, nbSeq, maxSymbolValue);
2084     }
2085     DISPLAYLEVEL(3, "OK \n");
2086
2087 _end:
2088     free(CNBuffer);
2089     free(compressedBuffer);
2090     free(decodedBuffer);
2091     return testResult;
2092
2093 _output_error:
2094     testResult = 1;
2095     DISPLAY("Error detected in Unit tests ! \n");
2096     goto _end;
2097 }
2098
2099
2100 static size_t findDiff(const void* buf1, const void* buf2, size_t max)
2101 {
2102     const BYTE* b1 = (const BYTE*)buf1;
2103     const BYTE* b2 = (const BYTE*)buf2;
2104     size_t u;
2105     for (u=0; u<max; u++) {
2106         if (b1[u] != b2[u]) break;
2107     }
2108     return u;
2109 }
2110
2111
2112 static ZSTD_parameters FUZ_makeParams(ZSTD_compressionParameters cParams, ZSTD_frameParameters fParams)
2113 {
2114     ZSTD_parameters params;
2115     params.cParams = cParams;
2116     params.fParams = fParams;
2117     return params;
2118 }
2119
2120 static size_t FUZ_rLogLength(U32* seed, U32 logLength)
2121 {
2122     size_t const lengthMask = ((size_t)1 << logLength) - 1;
2123     return (lengthMask+1) + (FUZ_rand(seed) & lengthMask);
2124 }
2125
2126 static size_t FUZ_randomLength(U32* seed, U32 maxLog)
2127 {
2128     U32 const logLength = FUZ_rand(seed) % maxLog;
2129     return FUZ_rLogLength(seed, logLength);
2130 }
2131
2132 #undef CHECK
2133 #define CHECK(cond, ...) {                                    \
2134     if (cond) {                                               \
2135         DISPLAY("Error => ");                                 \
2136         DISPLAY(__VA_ARGS__);                                 \
2137         DISPLAY(" (seed %u, test nb %u)  \n", (unsigned)seed, testNb);  \
2138         goto _output_error;                                   \
2139 }   }
2140
2141 #undef CHECK_Z
2142 #define CHECK_Z(f) {                                          \
2143     size_t const err = f;                                     \
2144     if (ZSTD_isError(err)) {                                  \
2145         DISPLAY("Error => %s : %s ",                          \
2146                 #f, ZSTD_getErrorName(err));                  \
2147         DISPLAY(" (seed %u, test nb %u)  \n", (unsigned)seed, testNb);  \
2148         goto _output_error;                                   \
2149 }   }
2150
2151
2152 static int fuzzerTests(U32 seed, unsigned nbTests, unsigned startTest, U32 const maxDurationS, double compressibility, int bigTests)
2153 {
2154     static const U32 maxSrcLog = 23;
2155     static const U32 maxSampleLog = 22;
2156     size_t const srcBufferSize = (size_t)1<<maxSrcLog;
2157     size_t const dstBufferSize = (size_t)1<<maxSampleLog;
2158     size_t const cBufferSize   = ZSTD_compressBound(dstBufferSize);
2159     BYTE* cNoiseBuffer[5];
2160     BYTE* const cBuffer = (BYTE*) malloc (cBufferSize);
2161     BYTE* const dstBuffer = (BYTE*) malloc (dstBufferSize);
2162     BYTE* const mirrorBuffer = (BYTE*) malloc (dstBufferSize);
2163     ZSTD_CCtx* const refCtx = ZSTD_createCCtx();
2164     ZSTD_CCtx* const ctx = ZSTD_createCCtx();
2165     ZSTD_DCtx* const dctx = ZSTD_createDCtx();
2166     U32 result = 0;
2167     unsigned testNb = 0;
2168     U32 coreSeed = seed;
2169     UTIL_time_t const startClock = UTIL_getTime();
2170     U64 const maxClockSpan = maxDurationS * SEC_TO_MICRO;
2171     int const cLevelLimiter = bigTests ? 3 : 2;
2172
2173     /* allocation */
2174     cNoiseBuffer[0] = (BYTE*)malloc (srcBufferSize);
2175     cNoiseBuffer[1] = (BYTE*)malloc (srcBufferSize);
2176     cNoiseBuffer[2] = (BYTE*)malloc (srcBufferSize);
2177     cNoiseBuffer[3] = (BYTE*)malloc (srcBufferSize);
2178     cNoiseBuffer[4] = (BYTE*)malloc (srcBufferSize);
2179     CHECK (!cNoiseBuffer[0] || !cNoiseBuffer[1] || !cNoiseBuffer[2] || !cNoiseBuffer[3] || !cNoiseBuffer[4]
2180            || !dstBuffer || !mirrorBuffer || !cBuffer || !refCtx || !ctx || !dctx,
2181            "Not enough memory, fuzzer tests cancelled");
2182
2183     /* Create initial samples */
2184     RDG_genBuffer(cNoiseBuffer[0], srcBufferSize, 0.00, 0., coreSeed);    /* pure noise */
2185     RDG_genBuffer(cNoiseBuffer[1], srcBufferSize, 0.05, 0., coreSeed);    /* barely compressible */
2186     RDG_genBuffer(cNoiseBuffer[2], srcBufferSize, compressibility, 0., coreSeed);
2187     RDG_genBuffer(cNoiseBuffer[3], srcBufferSize, 0.95, 0., coreSeed);    /* highly compressible */
2188     RDG_genBuffer(cNoiseBuffer[4], srcBufferSize, 1.00, 0., coreSeed);    /* sparse content */
2189
2190     /* catch up testNb */
2191     for (testNb=1; testNb < startTest; testNb++) FUZ_rand(&coreSeed);
2192
2193     /* main test loop */
2194     for ( ; (testNb <= nbTests) || (UTIL_clockSpanMicro(startClock) < maxClockSpan); testNb++ ) {
2195         BYTE* srcBuffer;   /* jumping pointer */
2196         U32 lseed;
2197         size_t sampleSize, maxTestSize, totalTestSize;
2198         size_t cSize, totalCSize, totalGenSize;
2199         U64 crcOrig;
2200         BYTE* sampleBuffer;
2201         const BYTE* dict;
2202         size_t dictSize;
2203
2204         /* notification */
2205         if (nbTests >= testNb) { DISPLAYUPDATE(2, "\r%6u/%6u    ", testNb, nbTests); }
2206         else { DISPLAYUPDATE(2, "\r%6u          ", testNb); }
2207
2208         FUZ_rand(&coreSeed);
2209         { U32 const prime1 = 2654435761U; lseed = coreSeed ^ prime1; }
2210
2211         /* srcBuffer selection [0-4] */
2212         {   U32 buffNb = FUZ_rand(&lseed) & 0x7F;
2213             if (buffNb & 7) buffNb=2;   /* most common : compressible (P) */
2214             else {
2215                 buffNb >>= 3;
2216                 if (buffNb & 7) {
2217                     const U32 tnb[2] = { 1, 3 };   /* barely/highly compressible */
2218                     buffNb = tnb[buffNb >> 3];
2219                 } else {
2220                     const U32 tnb[2] = { 0, 4 };   /* not compressible / sparse */
2221                     buffNb = tnb[buffNb >> 3];
2222             }   }
2223             srcBuffer = cNoiseBuffer[buffNb];
2224         }
2225
2226         /* select src segment */
2227         sampleSize = FUZ_randomLength(&lseed, maxSampleLog);
2228
2229         /* create sample buffer (to catch read error with valgrind & sanitizers)  */
2230         sampleBuffer = (BYTE*)malloc(sampleSize);
2231         CHECK(sampleBuffer==NULL, "not enough memory for sample buffer");
2232         { size_t const sampleStart = FUZ_rand(&lseed) % (srcBufferSize - sampleSize);
2233           memcpy(sampleBuffer, srcBuffer + sampleStart, sampleSize); }
2234         crcOrig = XXH64(sampleBuffer, sampleSize, 0);
2235
2236         /* compression tests */
2237         {   int const cLevelPositive =
2238                     ( FUZ_rand(&lseed) %
2239                      (ZSTD_maxCLevel() - (FUZ_highbit32((U32)sampleSize) / cLevelLimiter)) )
2240                     + 1;
2241             int const cLevel = ((FUZ_rand(&lseed) & 15) == 3) ?
2242                              - (int)((FUZ_rand(&lseed) & 7) + 1) :   /* test negative cLevel */
2243                              cLevelPositive;
2244             DISPLAYLEVEL(5, "fuzzer t%u: Simple compression test (level %i) \n", testNb, cLevel);
2245             cSize = ZSTD_compressCCtx(ctx, cBuffer, cBufferSize, sampleBuffer, sampleSize, cLevel);
2246             CHECK(ZSTD_isError(cSize), "ZSTD_compressCCtx failed : %s", ZSTD_getErrorName(cSize));
2247
2248             /* compression failure test : too small dest buffer */
2249             assert(cSize > 3);
2250             {   const size_t missing = (FUZ_rand(&lseed) % (cSize-2)) + 1;
2251                 const size_t tooSmallSize = cSize - missing;
2252                 const unsigned endMark = 0x4DC2B1A9;
2253                 memcpy(dstBuffer+tooSmallSize, &endMark, sizeof(endMark));
2254                 DISPLAYLEVEL(5, "fuzzer t%u: compress into too small buffer of size %u (missing %u bytes) \n",
2255                             testNb, (unsigned)tooSmallSize, (unsigned)missing);
2256                 { size_t const errorCode = ZSTD_compressCCtx(ctx, dstBuffer, tooSmallSize, sampleBuffer, sampleSize, cLevel);
2257                   CHECK(!ZSTD_isError(errorCode), "ZSTD_compressCCtx should have failed ! (buffer too small : %u < %u)", (unsigned)tooSmallSize, (unsigned)cSize); }
2258                 { unsigned endCheck; memcpy(&endCheck, dstBuffer+tooSmallSize, sizeof(endCheck));
2259                   CHECK(endCheck != endMark, "ZSTD_compressCCtx : dst buffer overflow  (check.%08X != %08X.mark)", endCheck, endMark); }
2260         }   }
2261
2262         /* frame header decompression test */
2263         {   ZSTD_frameHeader zfh;
2264             CHECK_Z( ZSTD_getFrameHeader(&zfh, cBuffer, cSize) );
2265             CHECK(zfh.frameContentSize != sampleSize, "Frame content size incorrect");
2266         }
2267
2268         /* Decompressed size test */
2269         {   unsigned long long const rSize = ZSTD_findDecompressedSize(cBuffer, cSize);
2270             CHECK(rSize != sampleSize, "decompressed size incorrect");
2271         }
2272
2273         /* successful decompression test */
2274         DISPLAYLEVEL(5, "fuzzer t%u: simple decompression test \n", testNb);
2275         {   size_t const margin = (FUZ_rand(&lseed) & 1) ? 0 : (FUZ_rand(&lseed) & 31) + 1;
2276             size_t const dSize = ZSTD_decompress(dstBuffer, sampleSize + margin, cBuffer, cSize);
2277             CHECK(dSize != sampleSize, "ZSTD_decompress failed (%s) (srcSize : %u ; cSize : %u)", ZSTD_getErrorName(dSize), (unsigned)sampleSize, (unsigned)cSize);
2278             {   U64 const crcDest = XXH64(dstBuffer, sampleSize, 0);
2279                 CHECK(crcOrig != crcDest, "decompression result corrupted (pos %u / %u)", (unsigned)findDiff(sampleBuffer, dstBuffer, sampleSize), (unsigned)sampleSize);
2280         }   }
2281
2282         free(sampleBuffer);   /* no longer useful after this point */
2283
2284         /* truncated src decompression test */
2285         DISPLAYLEVEL(5, "fuzzer t%u: decompression of truncated source \n", testNb);
2286         {   size_t const missing = (FUZ_rand(&lseed) % (cSize-2)) + 1;   /* no problem, as cSize > 4 (frameHeaderSizer) */
2287             size_t const tooSmallSize = cSize - missing;
2288             void* cBufferTooSmall = malloc(tooSmallSize);   /* valgrind will catch read overflows */
2289             CHECK(cBufferTooSmall == NULL, "not enough memory !");
2290             memcpy(cBufferTooSmall, cBuffer, tooSmallSize);
2291             { size_t const errorCode = ZSTD_decompress(dstBuffer, dstBufferSize, cBufferTooSmall, tooSmallSize);
2292               CHECK(!ZSTD_isError(errorCode), "ZSTD_decompress should have failed ! (truncated src buffer)"); }
2293             free(cBufferTooSmall);
2294         }
2295
2296         /* too small dst decompression test */
2297         DISPLAYLEVEL(5, "fuzzer t%u: decompress into too small dst buffer \n", testNb);
2298         if (sampleSize > 3) {
2299             size_t const missing = (FUZ_rand(&lseed) % (sampleSize-2)) + 1;   /* no problem, as cSize > 4 (frameHeaderSizer) */
2300             size_t const tooSmallSize = sampleSize - missing;
2301             static const BYTE token = 0xA9;
2302             dstBuffer[tooSmallSize] = token;
2303             { size_t const errorCode = ZSTD_decompress(dstBuffer, tooSmallSize, cBuffer, cSize);
2304               CHECK(!ZSTD_isError(errorCode), "ZSTD_decompress should have failed : %u > %u (dst buffer too small)", (unsigned)errorCode, (unsigned)tooSmallSize); }
2305             CHECK(dstBuffer[tooSmallSize] != token, "ZSTD_decompress : dst buffer overflow");
2306         }
2307
2308         /* noisy src decompression test */
2309         if (cSize > 6) {
2310             /* insert noise into src */
2311             {   U32 const maxNbBits = FUZ_highbit32((U32)(cSize-4));
2312                 size_t pos = 4;   /* preserve magic number (too easy to detect) */
2313                 for (;;) {
2314                     /* keep some original src */
2315                     {   U32 const nbBits = FUZ_rand(&lseed) % maxNbBits;
2316                         size_t const mask = (1<<nbBits) - 1;
2317                         size_t const skipLength = FUZ_rand(&lseed) & mask;
2318                         pos += skipLength;
2319                     }
2320                     if (pos >= cSize) break;
2321                     /* add noise */
2322                     {   U32 const nbBitsCodes = FUZ_rand(&lseed) % maxNbBits;
2323                         U32 const nbBits = nbBitsCodes ? nbBitsCodes-1 : 0;
2324                         size_t const mask = (1<<nbBits) - 1;
2325                         size_t const rNoiseLength = (FUZ_rand(&lseed) & mask) + 1;
2326                         size_t const noiseLength = MIN(rNoiseLength, cSize-pos);
2327                         size_t const noiseStart = FUZ_rand(&lseed) % (srcBufferSize - noiseLength);
2328                         memcpy(cBuffer + pos, srcBuffer + noiseStart, noiseLength);
2329                         pos += noiseLength;
2330             }   }   }
2331
2332             /* decompress noisy source */
2333             DISPLAYLEVEL(5, "fuzzer t%u: decompress noisy source \n", testNb);
2334             {   U32 const endMark = 0xA9B1C3D6;
2335                 memcpy(dstBuffer+sampleSize, &endMark, 4);
2336                 {   size_t const decompressResult = ZSTD_decompress(dstBuffer, sampleSize, cBuffer, cSize);
2337                     /* result *may* be an unlikely success, but even then, it must strictly respect dst buffer boundaries */
2338                     CHECK((!ZSTD_isError(decompressResult)) && (decompressResult>sampleSize),
2339                           "ZSTD_decompress on noisy src : result is too large : %u > %u (dst buffer)", (unsigned)decompressResult, (unsigned)sampleSize);
2340                 }
2341                 {   U32 endCheck; memcpy(&endCheck, dstBuffer+sampleSize, 4);
2342                     CHECK(endMark!=endCheck, "ZSTD_decompress on noisy src : dst buffer overflow");
2343         }   }   }   /* noisy src decompression test */
2344
2345         /*=====   Bufferless streaming compression test, scattered segments and dictionary   =====*/
2346         DISPLAYLEVEL(5, "fuzzer t%u: Bufferless streaming compression test \n", testNb);
2347         {   U32 const testLog = FUZ_rand(&lseed) % maxSrcLog;
2348             U32 const dictLog = FUZ_rand(&lseed) % maxSrcLog;
2349             int const cLevel = (FUZ_rand(&lseed) %
2350                                 (ZSTD_maxCLevel() -
2351                                  (MAX(testLog, dictLog) / cLevelLimiter))) +
2352                                1;
2353             maxTestSize = FUZ_rLogLength(&lseed, testLog);
2354             if (maxTestSize >= dstBufferSize) maxTestSize = dstBufferSize-1;
2355
2356             dictSize = FUZ_rLogLength(&lseed, dictLog);   /* needed also for decompression */
2357             dict = srcBuffer + (FUZ_rand(&lseed) % (srcBufferSize - dictSize));
2358
2359             DISPLAYLEVEL(6, "fuzzer t%u: Compressing up to <=%u bytes at level %i with dictionary size %u \n",
2360                             testNb, (unsigned)maxTestSize, cLevel, (unsigned)dictSize);
2361
2362             if (FUZ_rand(&lseed) & 0xF) {
2363                 CHECK_Z ( ZSTD_compressBegin_usingDict(refCtx, dict, dictSize, cLevel) );
2364             } else {
2365                 ZSTD_compressionParameters const cPar = ZSTD_getCParams(cLevel, ZSTD_CONTENTSIZE_UNKNOWN, dictSize);
2366                 ZSTD_frameParameters const fPar = { FUZ_rand(&lseed)&1 /* contentSizeFlag */,
2367                                                     !(FUZ_rand(&lseed)&3) /* contentChecksumFlag*/,
2368                                                     0 /*NodictID*/ };   /* note : since dictionary is fake, dictIDflag has no impact */
2369                 ZSTD_parameters const p = FUZ_makeParams(cPar, fPar);
2370                 CHECK_Z ( ZSTD_compressBegin_advanced(refCtx, dict, dictSize, p, 0) );
2371             }
2372             CHECK_Z( ZSTD_copyCCtx(ctx, refCtx, 0) );
2373         }
2374
2375         {   U32 const nbChunks = (FUZ_rand(&lseed) & 127) + 2;
2376             U32 n;
2377             XXH64_state_t xxhState;
2378             XXH64_reset(&xxhState, 0);
2379             for (totalTestSize=0, cSize=0, n=0 ; n<nbChunks ; n++) {
2380                 size_t const segmentSize = FUZ_randomLength(&lseed, maxSampleLog);
2381                 size_t const segmentStart = FUZ_rand(&lseed) % (srcBufferSize - segmentSize);
2382
2383                 if (cBufferSize-cSize < ZSTD_compressBound(segmentSize)) break;   /* avoid invalid dstBufferTooSmall */
2384                 if (totalTestSize+segmentSize > maxTestSize) break;
2385
2386                 {   size_t const compressResult = ZSTD_compressContinue(ctx, cBuffer+cSize, cBufferSize-cSize, srcBuffer+segmentStart, segmentSize);
2387                     CHECK (ZSTD_isError(compressResult), "multi-segments compression error : %s", ZSTD_getErrorName(compressResult));
2388                     cSize += compressResult;
2389                 }
2390                 XXH64_update(&xxhState, srcBuffer+segmentStart, segmentSize);
2391                 memcpy(mirrorBuffer + totalTestSize, srcBuffer+segmentStart, segmentSize);
2392                 totalTestSize += segmentSize;
2393             }
2394
2395             {   size_t const flushResult = ZSTD_compressEnd(ctx, cBuffer+cSize, cBufferSize-cSize, NULL, 0);
2396                 CHECK (ZSTD_isError(flushResult), "multi-segments epilogue error : %s", ZSTD_getErrorName(flushResult));
2397                 cSize += flushResult;
2398             }
2399             crcOrig = XXH64_digest(&xxhState);
2400         }
2401
2402         /* streaming decompression test */
2403         DISPLAYLEVEL(5, "fuzzer t%u: Bufferless streaming decompression test \n", testNb);
2404         /* ensure memory requirement is good enough (should always be true) */
2405         {   ZSTD_frameHeader zfh;
2406             CHECK( ZSTD_getFrameHeader(&zfh, cBuffer, ZSTD_FRAMEHEADERSIZE_MAX),
2407                   "ZSTD_getFrameHeader(): error retrieving frame information");
2408             {   size_t const roundBuffSize = ZSTD_decodingBufferSize_min(zfh.windowSize, zfh.frameContentSize);
2409                 CHECK_Z(roundBuffSize);
2410                 CHECK((roundBuffSize > totalTestSize) && (zfh.frameContentSize!=ZSTD_CONTENTSIZE_UNKNOWN),
2411                       "ZSTD_decodingBufferSize_min() requires more memory (%u) than necessary (%u)",
2412                       (unsigned)roundBuffSize, (unsigned)totalTestSize );
2413         }   }
2414         if (dictSize<8) dictSize=0, dict=NULL;   /* disable dictionary */
2415         CHECK_Z( ZSTD_decompressBegin_usingDict(dctx, dict, dictSize) );
2416         totalCSize = 0;
2417         totalGenSize = 0;
2418         while (totalCSize < cSize) {
2419             size_t const inSize = ZSTD_nextSrcSizeToDecompress(dctx);
2420             size_t const genSize = ZSTD_decompressContinue(dctx, dstBuffer+totalGenSize, dstBufferSize-totalGenSize, cBuffer+totalCSize, inSize);
2421             CHECK (ZSTD_isError(genSize), "ZSTD_decompressContinue error : %s", ZSTD_getErrorName(genSize));
2422             totalGenSize += genSize;
2423             totalCSize += inSize;
2424         }
2425         CHECK (ZSTD_nextSrcSizeToDecompress(dctx) != 0, "frame not fully decoded");
2426         CHECK (totalGenSize != totalTestSize, "streaming decompressed data : wrong size")
2427         CHECK (totalCSize != cSize, "compressed data should be fully read")
2428         {   U64 const crcDest = XXH64(dstBuffer, totalTestSize, 0);
2429             CHECK(crcOrig != crcDest, "streaming decompressed data corrupted (pos %u / %u)",
2430                 (unsigned)findDiff(mirrorBuffer, dstBuffer, totalTestSize), (unsigned)totalTestSize);
2431         }
2432     }   /* for ( ; (testNb <= nbTests) */
2433     DISPLAY("\r%u fuzzer tests completed   \n", testNb-1);
2434
2435 _cleanup:
2436     ZSTD_freeCCtx(refCtx);
2437     ZSTD_freeCCtx(ctx);
2438     ZSTD_freeDCtx(dctx);
2439     free(cNoiseBuffer[0]);
2440     free(cNoiseBuffer[1]);
2441     free(cNoiseBuffer[2]);
2442     free(cNoiseBuffer[3]);
2443     free(cNoiseBuffer[4]);
2444     free(cBuffer);
2445     free(dstBuffer);
2446     free(mirrorBuffer);
2447     return result;
2448
2449 _output_error:
2450     result = 1;
2451     goto _cleanup;
2452 }
2453
2454
2455 /*_*******************************************************
2456 *  Command line
2457 *********************************************************/
2458 static int FUZ_usage(const char* programName)
2459 {
2460     DISPLAY( "Usage :\n");
2461     DISPLAY( "      %s [args]\n", programName);
2462     DISPLAY( "\n");
2463     DISPLAY( "Arguments :\n");
2464     DISPLAY( " -i#    : Nb of tests (default:%i) \n", nbTestsDefault);
2465     DISPLAY( " -s#    : Select seed (default:prompt user)\n");
2466     DISPLAY( " -t#    : Select starting test number (default:0)\n");
2467     DISPLAY( " -P#    : Select compressibility in %% (default:%i%%)\n", FUZ_compressibility_default);
2468     DISPLAY( " -v     : verbose\n");
2469     DISPLAY( " -p     : pause at the end\n");
2470     DISPLAY( " -h     : display help and exit\n");
2471     return 0;
2472 }
2473
2474 /*! readU32FromChar() :
2475     @return : unsigned integer value read from input in `char` format
2476     allows and interprets K, KB, KiB, M, MB and MiB suffix.
2477     Will also modify `*stringPtr`, advancing it to position where it stopped reading.
2478     Note : function result can overflow if digit string > MAX_UINT */
2479 static unsigned readU32FromChar(const char** stringPtr)
2480 {
2481     unsigned result = 0;
2482     while ((**stringPtr >='0') && (**stringPtr <='9'))
2483         result *= 10, result += **stringPtr - '0', (*stringPtr)++ ;
2484     if ((**stringPtr=='K') || (**stringPtr=='M')) {
2485         result <<= 10;
2486         if (**stringPtr=='M') result <<= 10;
2487         (*stringPtr)++ ;
2488         if (**stringPtr=='i') (*stringPtr)++;
2489         if (**stringPtr=='B') (*stringPtr)++;
2490     }
2491     return result;
2492 }
2493
2494 /** longCommandWArg() :
2495  *  check if *stringPtr is the same as longCommand.
2496  *  If yes, @return 1 and advances *stringPtr to the position which immediately follows longCommand.
2497  *  @return 0 and doesn't modify *stringPtr otherwise.
2498  */
2499 static int longCommandWArg(const char** stringPtr, const char* longCommand)
2500 {
2501     size_t const comSize = strlen(longCommand);
2502     int const result = !strncmp(*stringPtr, longCommand, comSize);
2503     if (result) *stringPtr += comSize;
2504     return result;
2505 }
2506
2507 int main(int argc, const char** argv)
2508 {
2509     U32 seed = 0;
2510     int seedset = 0;
2511     int argNb;
2512     int nbTests = nbTestsDefault;
2513     int testNb = 0;
2514     int proba = FUZ_compressibility_default;
2515     int result = 0;
2516     U32 mainPause = 0;
2517     U32 maxDuration = 0;
2518     int bigTests = 1;
2519     U32 memTestsOnly = 0;
2520     const char* const programName = argv[0];
2521
2522     /* Check command line */
2523     for (argNb=1; argNb<argc; argNb++) {
2524         const char* argument = argv[argNb];
2525         if(!argument) continue;   /* Protection if argument empty */
2526
2527         /* Handle commands. Aggregated commands are allowed */
2528         if (argument[0]=='-') {
2529
2530             if (longCommandWArg(&argument, "--memtest=")) { memTestsOnly = readU32FromChar(&argument); continue; }
2531
2532             if (!strcmp(argument, "--memtest")) { memTestsOnly=1; continue; }
2533             if (!strcmp(argument, "--no-big-tests")) { bigTests=0; continue; }
2534
2535             argument++;
2536             while (*argument!=0) {
2537                 switch(*argument)
2538                 {
2539                 case 'h':
2540                     return FUZ_usage(programName);
2541
2542                 case 'v':
2543                     argument++;
2544                     g_displayLevel++;
2545                     break;
2546
2547                 case 'q':
2548                     argument++;
2549                     g_displayLevel--;
2550                     break;
2551
2552                 case 'p': /* pause at the end */
2553                     argument++;
2554                     mainPause = 1;
2555                     break;
2556
2557                 case 'i':
2558                     argument++; maxDuration = 0;
2559                     nbTests = (int)readU32FromChar(&argument);
2560                     break;
2561
2562                 case 'T':
2563                     argument++;
2564                     nbTests = 0;
2565                     maxDuration = readU32FromChar(&argument);
2566                     if (*argument=='s') argument++;   /* seconds */
2567                     if (*argument=='m') maxDuration *= 60, argument++;   /* minutes */
2568                     if (*argument=='n') argument++;
2569                     break;
2570
2571                 case 's':
2572                     argument++;
2573                     seedset = 1;
2574                     seed = readU32FromChar(&argument);
2575                     break;
2576
2577                 case 't':
2578                     argument++;
2579                     testNb = (int)readU32FromChar(&argument);
2580                     break;
2581
2582                 case 'P':   /* compressibility % */
2583                     argument++;
2584                     proba = (int)readU32FromChar(&argument);
2585                     if (proba>100) proba = 100;
2586                     break;
2587
2588                 default:
2589                     return (FUZ_usage(programName), 1);
2590     }   }   }   }   /* for (argNb=1; argNb<argc; argNb++) */
2591
2592     /* Get Seed */
2593     DISPLAY("Starting zstd tester (%i-bits, %s)\n", (int)(sizeof(size_t)*8), ZSTD_VERSION_STRING);
2594
2595     if (!seedset) {
2596         time_t const t = time(NULL);
2597         U32 const h = XXH32(&t, sizeof(t), 1);
2598         seed = h % 10000;
2599     }
2600
2601     DISPLAY("Seed = %u\n", (unsigned)seed);
2602     if (proba!=FUZ_compressibility_default) DISPLAY("Compressibility : %i%%\n", proba);
2603
2604     if (memTestsOnly) {
2605         g_displayLevel = MAX(3, g_displayLevel);
2606         return FUZ_mallocTests(seed, ((double)proba) / 100, memTestsOnly);
2607     }
2608
2609     if (nbTests < testNb) nbTests = testNb;
2610
2611     if (testNb==0)
2612         result = basicUnitTests(0, ((double)proba) / 100);  /* constant seed for predictability */
2613     if (!result)
2614         result = fuzzerTests(seed, nbTests, testNb, maxDuration, ((double)proba) / 100, bigTests);
2615     if (mainPause) {
2616         int unused;
2617         DISPLAY("Press Enter \n");
2618         unused = getchar();
2619         (void)unused;
2620     }
2621     return result;
2622 }