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