]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - tests/fuzzer.c
Import zstd 1.3.1
[FreeBSD/FreeBSD.git] / tests / fuzzer.c
1 /*
2  * Copyright (c) 2016-present, Yann Collet, Facebook, Inc.
3  * All rights reserved.
4  *
5  * This source code is licensed under both the BSD-style license (found in the
6  * LICENSE file in the root directory of this source tree) and the GPLv2 (found
7  * in the COPYING file in the root directory of this source tree).
8  */
9
10
11 /*-************************************
12 *  Compiler specific
13 **************************************/
14 #ifdef _MSC_VER    /* Visual Studio */
15 #  define _CRT_SECURE_NO_WARNINGS   /* fgets */
16 #  pragma warning(disable : 4127)   /* disable: C4127: conditional expression is constant */
17 #  pragma warning(disable : 4204)   /* disable: C4204: non-constant aggregate initializer */
18 #endif
19
20
21 /*-************************************
22 *  Includes
23 **************************************/
24 #include <stdlib.h>       /* free */
25 #include <stdio.h>        /* fgets, sscanf */
26 #include <string.h>       /* strcmp */
27 #include <time.h>         /* clock_t */
28 #define ZSTD_STATIC_LINKING_ONLY  /* ZSTD_compressContinue, ZSTD_compressBlock */
29 #include "zstd.h"         /* ZSTD_VERSION_STRING */
30 #include "zstd_errors.h"  /* ZSTD_getErrorCode */
31 #include "zstdmt_compress.h"
32 #define ZDICT_STATIC_LINKING_ONLY
33 #include "zdict.h"        /* ZDICT_trainFromBuffer */
34 #include "datagen.h"      /* RDG_genBuffer */
35 #include "mem.h"
36 #define XXH_STATIC_LINKING_ONLY
37 #include "xxhash.h"       /* XXH64 */
38
39
40 /*-************************************
41 *  Constants
42 **************************************/
43 #define KB *(1U<<10)
44 #define MB *(1U<<20)
45 #define GB *(1U<<30)
46
47 static const U32 FUZ_compressibility_default = 50;
48 static const U32 nbTestsDefault = 30000;
49
50
51 /*-************************************
52 *  Display Macros
53 **************************************/
54 #define DISPLAY(...)          fprintf(stdout, __VA_ARGS__)
55 #define DISPLAYLEVEL(l, ...)  if (g_displayLevel>=l) { DISPLAY(__VA_ARGS__); }
56 static U32 g_displayLevel = 2;
57
58 #define DISPLAYUPDATE(l, ...) if (g_displayLevel>=l) { \
59             if ((FUZ_clockSpan(g_displayClock) > g_refreshRate) || (g_displayLevel>=4)) \
60             { g_displayClock = clock(); DISPLAY(__VA_ARGS__); \
61             if (g_displayLevel>=4) fflush(stdout); } }
62 static const clock_t g_refreshRate = CLOCKS_PER_SEC / 6;
63 static clock_t g_displayClock = 0;
64
65
66 /*-*******************************************************
67 *  Fuzzer functions
68 *********************************************************/
69 #define MIN(a,b) ((a)<(b)?(a):(b))
70 #define MAX(a,b) ((a)>(b)?(a):(b))
71
72 static clock_t FUZ_clockSpan(clock_t cStart)
73 {
74     return clock() - cStart;   /* works even when overflow; max span ~ 30mn */
75 }
76
77 #define FUZ_rotl32(x,r) ((x << r) | (x >> (32 - r)))
78 static unsigned FUZ_rand(unsigned* src)
79 {
80     static const U32 prime1 = 2654435761U;
81     static const U32 prime2 = 2246822519U;
82     U32 rand32 = *src;
83     rand32 *= prime1;
84     rand32 += prime2;
85     rand32  = FUZ_rotl32(rand32, 13);
86     *src = rand32;
87     return rand32 >> 5;
88 }
89
90 static unsigned FUZ_highbit32(U32 v32)
91 {
92     unsigned nbBits = 0;
93     if (v32==0) return 0;
94     while (v32) v32 >>= 1, nbBits++;
95     return nbBits;
96 }
97
98
99 /*=============================================
100 *   Memory Tests
101 =============================================*/
102 #if defined(__APPLE__) && defined(__MACH__)
103
104 #include <malloc/malloc.h>    /* malloc_size */
105
106 typedef struct {
107     unsigned long long totalMalloc;
108     size_t currentMalloc;
109     size_t peakMalloc;
110     unsigned nbMalloc;
111     unsigned nbFree;
112 } mallocCounter_t;
113
114 static const mallocCounter_t INIT_MALLOC_COUNTER = { 0, 0, 0, 0, 0 };
115
116 static void* FUZ_mallocDebug(void* counter, size_t size)
117 {
118     mallocCounter_t* const mcPtr = (mallocCounter_t*)counter;
119     void* const ptr = malloc(size);
120     if (ptr==NULL) return NULL;
121     DISPLAYLEVEL(4, "allocating %u KB => effectively %u KB \n",
122         (U32)(size >> 10), (U32)(malloc_size(ptr) >> 10));  /* OS-X specific */
123     mcPtr->totalMalloc += size;
124     mcPtr->currentMalloc += size;
125     if (mcPtr->currentMalloc > mcPtr->peakMalloc)
126         mcPtr->peakMalloc = mcPtr->currentMalloc;
127     mcPtr->nbMalloc += 1;
128     return ptr;
129 }
130
131 static void FUZ_freeDebug(void* counter, void* address)
132 {
133     mallocCounter_t* const mcPtr = (mallocCounter_t*)counter;
134     DISPLAYLEVEL(4, "freeing %u KB \n", (U32)(malloc_size(address) >> 10));
135     mcPtr->nbFree += 1;
136     mcPtr->currentMalloc -= malloc_size(address);  /* OS-X specific */
137     free(address);
138 }
139
140 static void FUZ_displayMallocStats(mallocCounter_t count)
141 {
142     DISPLAYLEVEL(3, "peak:%6u KB,  nbMallocs:%2u, total:%6u KB \n",
143         (U32)(count.peakMalloc >> 10),
144         count.nbMalloc,
145         (U32)(count.totalMalloc >> 10));
146 }
147
148 #define CHECK_Z(f) {                               \
149     size_t const err = f;                          \
150     if (ZSTD_isError(err)) {                       \
151         DISPLAY("Error => %s : %s ",               \
152                 #f, ZSTD_getErrorName(err));       \
153         exit(1);                                   \
154 }   }
155
156 static int FUZ_mallocTests(unsigned seed, double compressibility, unsigned part)
157 {
158     size_t const inSize = 64 MB + 16 MB + 4 MB + 1 MB + 256 KB + 64 KB; /* 85.3 MB */
159     size_t const outSize = ZSTD_compressBound(inSize);
160     void* const inBuffer = malloc(inSize);
161     void* const outBuffer = malloc(outSize);
162
163     /* test only played in verbose mode, as they are long */
164     if (g_displayLevel<3) return 0;
165
166     /* Create compressible noise */
167     if (!inBuffer || !outBuffer) {
168         DISPLAY("Not enough memory, aborting\n");
169         exit(1);
170     }
171     RDG_genBuffer(inBuffer, inSize, compressibility, 0. /*auto*/, seed);
172
173     /* simple compression tests */
174     if (part <= 1)
175     {   int compressionLevel;
176         for (compressionLevel=1; compressionLevel<=6; compressionLevel++) {
177             mallocCounter_t malcount = INIT_MALLOC_COUNTER;
178             ZSTD_customMem const cMem = { FUZ_mallocDebug, FUZ_freeDebug, &malcount };
179             ZSTD_CCtx* const cctx = ZSTD_createCCtx_advanced(cMem);
180             CHECK_Z( ZSTD_compressCCtx(cctx, outBuffer, outSize, inBuffer, inSize, compressionLevel) );
181             ZSTD_freeCCtx(cctx);
182             DISPLAYLEVEL(3, "compressCCtx level %i : ", compressionLevel);
183             FUZ_displayMallocStats(malcount);
184     }   }
185
186     /* streaming compression tests */
187     if (part <= 2)
188     {   int compressionLevel;
189         for (compressionLevel=1; compressionLevel<=6; compressionLevel++) {
190             mallocCounter_t malcount = INIT_MALLOC_COUNTER;
191             ZSTD_customMem const cMem = { FUZ_mallocDebug, FUZ_freeDebug, &malcount };
192             ZSTD_CCtx* const cstream = ZSTD_createCStream_advanced(cMem);
193             ZSTD_outBuffer out = { outBuffer, outSize, 0 };
194             ZSTD_inBuffer in = { inBuffer, inSize, 0 };
195             CHECK_Z( ZSTD_initCStream(cstream, compressionLevel) );
196             CHECK_Z( ZSTD_compressStream(cstream, &out, &in) );
197             CHECK_Z( ZSTD_endStream(cstream, &out) );
198             ZSTD_freeCStream(cstream);
199             DISPLAYLEVEL(3, "compressStream level %i : ", compressionLevel);
200             FUZ_displayMallocStats(malcount);
201     }   }
202
203     /* advanced MT API test */
204     if (part <= 3)
205     {   U32 nbThreads;
206         for (nbThreads=1; nbThreads<=4; nbThreads++) {
207             int compressionLevel;
208             for (compressionLevel=1; compressionLevel<=6; compressionLevel++) {
209                 mallocCounter_t malcount = INIT_MALLOC_COUNTER;
210                 ZSTD_customMem const cMem = { FUZ_mallocDebug, FUZ_freeDebug, &malcount };
211                 ZSTD_CCtx* const cctx = ZSTD_createCCtx_advanced(cMem);
212                 ZSTD_outBuffer out = { outBuffer, outSize, 0 };
213                 ZSTD_inBuffer in = { inBuffer, inSize, 0 };
214                 CHECK_Z( ZSTD_CCtx_setParameter(cctx, ZSTD_p_compressionLevel, (U32)compressionLevel) );
215                 CHECK_Z( ZSTD_CCtx_setParameter(cctx, ZSTD_p_nbThreads, nbThreads) );
216                 while ( ZSTD_compress_generic(cctx, &out, &in, ZSTD_e_end) ) {}
217                 ZSTD_freeCCtx(cctx);
218                 DISPLAYLEVEL(3, "compress_generic,-T%u,end level %i : ",
219                                 nbThreads, compressionLevel);
220                 FUZ_displayMallocStats(malcount);
221     }   }   }
222
223     /* advanced MT streaming API test */
224     if (part <= 4)
225     {   U32 nbThreads;
226         for (nbThreads=1; nbThreads<=4; nbThreads++) {
227             int compressionLevel;
228             for (compressionLevel=1; compressionLevel<=6; compressionLevel++) {
229                 mallocCounter_t malcount = INIT_MALLOC_COUNTER;
230                 ZSTD_customMem const cMem = { FUZ_mallocDebug, FUZ_freeDebug, &malcount };
231                 ZSTD_CCtx* const cctx = ZSTD_createCCtx_advanced(cMem);
232                 ZSTD_outBuffer out = { outBuffer, outSize, 0 };
233                 ZSTD_inBuffer in = { inBuffer, inSize, 0 };
234                 CHECK_Z( ZSTD_CCtx_setParameter(cctx, ZSTD_p_compressionLevel, (U32)compressionLevel) );
235                 CHECK_Z( ZSTD_CCtx_setParameter(cctx, ZSTD_p_nbThreads, nbThreads) );
236                 CHECK_Z( ZSTD_compress_generic(cctx, &out, &in, ZSTD_e_continue) );
237                 while ( ZSTD_compress_generic(cctx, &out, &in, ZSTD_e_end) ) {}
238                 ZSTD_freeCCtx(cctx);
239                 DISPLAYLEVEL(3, "compress_generic,-T%u,continue level %i : ",
240                                 nbThreads, compressionLevel);
241                 FUZ_displayMallocStats(malcount);
242     }   }   }
243
244     return 0;
245 }
246
247 #else
248
249 static int FUZ_mallocTests(unsigned seed, double compressibility, unsigned part)
250 {
251     (void)seed; (void)compressibility; (void)part;
252     return 0;
253 }
254
255 #endif
256
257 /*=============================================
258 *   Unit tests
259 =============================================*/
260
261 #define CHECK_V(var, fn)  size_t const var = fn; if (ZSTD_isError(var)) goto _output_error
262 #define CHECK(fn)  { CHECK_V(err, fn); }
263 #define CHECKPLUS(var, fn, more)  { CHECK_V(var, fn); more; }
264
265 static int basicUnitTests(U32 seed, double compressibility)
266 {
267     size_t const CNBuffSize = 5 MB;
268     void* const CNBuffer = malloc(CNBuffSize);
269     size_t const compressedBufferSize = ZSTD_compressBound(CNBuffSize);
270     void* const compressedBuffer = malloc(compressedBufferSize);
271     void* const decodedBuffer = malloc(CNBuffSize);
272     ZSTD_DCtx* dctx = ZSTD_createDCtx();
273     int testResult = 0;
274     U32 testNb=0;
275     size_t cSize;
276
277     /* Create compressible noise */
278     if (!CNBuffer || !compressedBuffer || !decodedBuffer) {
279         DISPLAY("Not enough memory, aborting\n");
280         testResult = 1;
281         goto _end;
282     }
283     RDG_genBuffer(CNBuffer, CNBuffSize, compressibility, 0., seed);
284
285     /* Basic tests */
286     DISPLAYLEVEL(4, "test%3i : ZSTD_getErrorName : ", testNb++);
287     {   const char* errorString = ZSTD_getErrorName(0);
288         DISPLAYLEVEL(4, "OK : %s \n", errorString);
289     }
290
291     DISPLAYLEVEL(4, "test%3i : ZSTD_getErrorName with wrong value : ", testNb++);
292     {   const char* errorString = ZSTD_getErrorName(499);
293         DISPLAYLEVEL(4, "OK : %s \n", errorString);
294     }
295
296
297     DISPLAYLEVEL(4, "test%3i : compress %u bytes : ", testNb++, (U32)CNBuffSize);
298     {   ZSTD_CCtx* cctx = ZSTD_createCCtx();
299         if (cctx==NULL) goto _output_error;
300         CHECKPLUS(r, ZSTD_compressCCtx(cctx,
301                             compressedBuffer, compressedBufferSize,
302                             CNBuffer, CNBuffSize, 1),
303                   cSize=r );
304         DISPLAYLEVEL(4, "OK (%u bytes : %.2f%%)\n", (U32)cSize, (double)cSize/CNBuffSize*100);
305
306         DISPLAYLEVEL(4, "test%3i : size of cctx for level 1 : ", testNb++);
307         {   size_t const cctxSize = ZSTD_sizeof_CCtx(cctx);
308             DISPLAYLEVEL(4, "%u bytes \n", (U32)cctxSize);
309         }
310         ZSTD_freeCCtx(cctx);
311     }
312
313
314     DISPLAYLEVEL(4, "test%3i : ZSTD_getFrameContentSize test : ", testNb++);
315     {   unsigned long long const rSize = ZSTD_getFrameContentSize(compressedBuffer, cSize);
316         if (rSize != CNBuffSize) goto _output_error;
317     }
318     DISPLAYLEVEL(4, "OK \n");
319
320     DISPLAYLEVEL(4, "test%3i : ZSTD_findDecompressedSize test : ", testNb++);
321     {   unsigned long long const rSize = ZSTD_findDecompressedSize(compressedBuffer, cSize);
322         if (rSize != CNBuffSize) goto _output_error;
323     }
324     DISPLAYLEVEL(4, "OK \n");
325
326     DISPLAYLEVEL(4, "test%3i : decompress %u bytes : ", testNb++, (U32)CNBuffSize);
327     { size_t const r = ZSTD_decompress(decodedBuffer, CNBuffSize, compressedBuffer, cSize);
328       if (r != CNBuffSize) goto _output_error; }
329     DISPLAYLEVEL(4, "OK \n");
330
331     DISPLAYLEVEL(4, "test%3i : check decompressed result : ", testNb++);
332     {   size_t u;
333         for (u=0; u<CNBuffSize; u++) {
334             if (((BYTE*)decodedBuffer)[u] != ((BYTE*)CNBuffer)[u]) goto _output_error;;
335     }   }
336     DISPLAYLEVEL(4, "OK \n");
337
338
339     DISPLAYLEVEL(4, "test%3i : decompress with null dict : ", testNb++);
340     { size_t const r = ZSTD_decompress_usingDict(dctx, decodedBuffer, CNBuffSize, compressedBuffer, cSize, NULL, 0);
341       if (r != CNBuffSize) goto _output_error; }
342     DISPLAYLEVEL(4, "OK \n");
343
344     DISPLAYLEVEL(4, "test%3i : decompress with null DDict : ", testNb++);
345     { size_t const r = ZSTD_decompress_usingDDict(dctx, decodedBuffer, CNBuffSize, compressedBuffer, cSize, NULL);
346       if (r != CNBuffSize) goto _output_error; }
347     DISPLAYLEVEL(4, "OK \n");
348
349     DISPLAYLEVEL(4, "test%3i : decompress with 1 missing byte : ", testNb++);
350     { size_t const r = ZSTD_decompress(decodedBuffer, CNBuffSize, compressedBuffer, cSize-1);
351       if (!ZSTD_isError(r)) goto _output_error;
352       if (ZSTD_getErrorCode((size_t)r) != ZSTD_error_srcSize_wrong) goto _output_error; }
353     DISPLAYLEVEL(4, "OK \n");
354
355     DISPLAYLEVEL(4, "test%3i : decompress with 1 too much byte : ", testNb++);
356     { size_t const r = ZSTD_decompress(decodedBuffer, CNBuffSize, compressedBuffer, cSize+1);
357       if (!ZSTD_isError(r)) goto _output_error;
358       if (ZSTD_getErrorCode(r) != ZSTD_error_srcSize_wrong) goto _output_error; }
359     DISPLAYLEVEL(4, "OK \n");
360
361
362     /* Static CCtx tests */
363 #define STATIC_CCTX_LEVEL 3
364     DISPLAYLEVEL(4, "test%3i : create static CCtx for level %u :", testNb++, STATIC_CCTX_LEVEL);
365     {   size_t const staticCCtxSize = ZSTD_estimateCStreamSize(STATIC_CCTX_LEVEL);
366         void* const staticCCtxBuffer = malloc(staticCCtxSize);
367         size_t const staticDCtxSize = ZSTD_estimateDCtxSize();
368         void* const staticDCtxBuffer = malloc(staticDCtxSize);
369         if (staticCCtxBuffer==NULL || staticDCtxBuffer==NULL) {
370             free(staticCCtxBuffer);
371             free(staticDCtxBuffer);
372             DISPLAY("Not enough memory, aborting\n");
373             testResult = 1;
374             goto _end;
375         }
376         {   ZSTD_CCtx* staticCCtx = ZSTD_initStaticCCtx(staticCCtxBuffer, staticCCtxSize);
377             ZSTD_DCtx* staticDCtx = ZSTD_initStaticDCtx(staticDCtxBuffer, staticDCtxSize);
378             if ((staticCCtx==NULL) || (staticDCtx==NULL)) goto _output_error;
379             DISPLAYLEVEL(4, "OK \n");
380
381             DISPLAYLEVEL(4, "test%3i : init CCtx for level %u : ", testNb++, STATIC_CCTX_LEVEL);
382             { size_t const r = ZSTD_compressBegin(staticCCtx, STATIC_CCTX_LEVEL);
383               if (ZSTD_isError(r)) goto _output_error; }
384             DISPLAYLEVEL(4, "OK \n");
385
386             DISPLAYLEVEL(4, "test%3i : simple compression test with static CCtx : ", testNb++);
387             CHECKPLUS(r, ZSTD_compressCCtx(staticCCtx,
388                             compressedBuffer, compressedBufferSize,
389                             CNBuffer, CNBuffSize, STATIC_CCTX_LEVEL),
390                       cSize=r );
391             DISPLAYLEVEL(4, "OK (%u bytes : %.2f%%)\n",
392                             (U32)cSize, (double)cSize/CNBuffSize*100);
393
394             DISPLAYLEVEL(4, "test%3i : simple decompression test with static DCtx : ", testNb++);
395             { size_t const r = ZSTD_decompressDCtx(staticDCtx,
396                                                 decodedBuffer, CNBuffSize,
397                                                 compressedBuffer, cSize);
398               if (r != CNBuffSize) goto _output_error; }
399             DISPLAYLEVEL(4, "OK \n");
400
401             DISPLAYLEVEL(4, "test%3i : check decompressed result : ", testNb++);
402             {   size_t u;
403                 for (u=0; u<CNBuffSize; u++) {
404                     if (((BYTE*)decodedBuffer)[u] != ((BYTE*)CNBuffer)[u])
405                         goto _output_error;;
406             }   }
407             DISPLAYLEVEL(4, "OK \n");
408
409             DISPLAYLEVEL(4, "test%3i : init CCtx for too large level (must fail) : ", testNb++);
410             { size_t const r = ZSTD_compressBegin(staticCCtx, ZSTD_maxCLevel());
411               if (!ZSTD_isError(r)) goto _output_error; }
412             DISPLAYLEVEL(4, "OK \n");
413
414             DISPLAYLEVEL(4, "test%3i : init CCtx for small level %u (should work again) : ", testNb++, 1);
415             { size_t const r = ZSTD_compressBegin(staticCCtx, 1);
416               if (ZSTD_isError(r)) goto _output_error; }
417             DISPLAYLEVEL(4, "OK \n");
418
419             DISPLAYLEVEL(4, "test%3i : init CStream for small level %u : ", testNb++, 1);
420             { size_t const r = ZSTD_initCStream(staticCCtx, 1);
421               if (ZSTD_isError(r)) goto _output_error; }
422             DISPLAYLEVEL(4, "OK \n");
423
424             DISPLAYLEVEL(4, "test%3i : init CStream with dictionary (should fail) : ", testNb++);
425             { size_t const r = ZSTD_initCStream_usingDict(staticCCtx, CNBuffer, 64 KB, 1);
426               if (!ZSTD_isError(r)) goto _output_error; }
427             DISPLAYLEVEL(4, "OK \n");
428
429             DISPLAYLEVEL(4, "test%3i : init DStream (should fail) : ", testNb++);
430             { size_t const r = ZSTD_initDStream(staticDCtx);
431               if (ZSTD_isError(r)) goto _output_error; }
432             {   ZSTD_outBuffer output = { decodedBuffer, CNBuffSize, 0 };
433                 ZSTD_inBuffer input = { compressedBuffer, ZSTD_FRAMEHEADERSIZE_MAX+1, 0 };
434                 size_t const r = ZSTD_decompressStream(staticDCtx, &output, &input);
435                 if (!ZSTD_isError(r)) goto _output_error;
436             }
437             DISPLAYLEVEL(4, "OK \n");
438         }
439         free(staticCCtxBuffer);
440         free(staticDCtxBuffer);
441     }
442
443
444
445     /* ZSTDMT simple MT compression test */
446     DISPLAYLEVEL(4, "test%3i : create ZSTDMT CCtx : ", testNb++);
447     {   ZSTDMT_CCtx* mtctx = ZSTDMT_createCCtx(2);
448         if (mtctx==NULL) {
449             DISPLAY("mtctx : mot enough memory, aborting \n");
450             testResult = 1;
451             goto _end;
452         }
453         DISPLAYLEVEL(4, "OK \n");
454
455         DISPLAYLEVEL(4, "test%3i : compress %u bytes with 2 threads : ", testNb++, (U32)CNBuffSize);
456         CHECKPLUS(r, ZSTDMT_compressCCtx(mtctx,
457                                 compressedBuffer, compressedBufferSize,
458                                 CNBuffer, CNBuffSize,
459                                 1),
460                   cSize=r );
461         DISPLAYLEVEL(4, "OK (%u bytes : %.2f%%)\n", (U32)cSize, (double)cSize/CNBuffSize*100);
462
463         DISPLAYLEVEL(4, "test%3i : decompressed size test : ", testNb++);
464         {   unsigned long long const rSize = ZSTD_getFrameContentSize(compressedBuffer, cSize);
465             if (rSize != CNBuffSize)  {
466                 DISPLAY("ZSTD_getFrameContentSize incorrect : %u != %u \n", (U32)rSize, (U32)CNBuffSize);
467                 goto _output_error;
468         }   }
469         DISPLAYLEVEL(4, "OK \n");
470
471         DISPLAYLEVEL(4, "test%3i : decompress %u bytes : ", testNb++, (U32)CNBuffSize);
472         { size_t const r = ZSTD_decompress(decodedBuffer, CNBuffSize, compressedBuffer, cSize);
473           if (r != CNBuffSize) goto _output_error; }
474         DISPLAYLEVEL(4, "OK \n");
475
476         DISPLAYLEVEL(4, "test%3i : check decompressed result : ", testNb++);
477         {   size_t u;
478             for (u=0; u<CNBuffSize; u++) {
479                 if (((BYTE*)decodedBuffer)[u] != ((BYTE*)CNBuffer)[u]) goto _output_error;;
480         }   }
481         DISPLAYLEVEL(4, "OK \n");
482
483         DISPLAYLEVEL(4, "test%3i : compress -T2 with checksum : ", testNb++);
484         {   ZSTD_parameters params = ZSTD_getParams(1, CNBuffSize, 0);
485             params.fParams.checksumFlag = 1;
486             params.fParams.contentSizeFlag = 1;
487             CHECKPLUS(r, ZSTDMT_compress_advanced(mtctx,
488                                     compressedBuffer, compressedBufferSize,
489                                     CNBuffer, CNBuffSize,
490                                     NULL, params, 3 /*overlapRLog*/),
491                       cSize=r );
492         }
493         DISPLAYLEVEL(4, "OK (%u bytes : %.2f%%)\n", (U32)cSize, (double)cSize/CNBuffSize*100);
494
495         DISPLAYLEVEL(4, "test%3i : decompress %u bytes : ", testNb++, (U32)CNBuffSize);
496         { size_t const r = ZSTD_decompress(decodedBuffer, CNBuffSize, compressedBuffer, cSize);
497           if (r != CNBuffSize) goto _output_error; }
498         DISPLAYLEVEL(4, "OK \n");
499
500         ZSTDMT_freeCCtx(mtctx);
501     }
502
503
504     /* Simple API multiframe test */
505     DISPLAYLEVEL(4, "test%3i : compress multiple frames : ", testNb++);
506     {   size_t off = 0;
507         int i;
508         int const segs = 4;
509         /* only use the first half so we don't push against size limit of compressedBuffer */
510         size_t const segSize = (CNBuffSize / 2) / segs;
511         for (i = 0; i < segs; i++) {
512             CHECK_V(r,
513                     ZSTD_compress(
514                             (BYTE *)compressedBuffer + off, CNBuffSize - off,
515                             (BYTE *)CNBuffer + segSize * i,
516                             segSize, 5));
517             off += r;
518             if (i == segs/2) {
519                 /* insert skippable frame */
520                 const U32 skipLen = 128 KB;
521                 MEM_writeLE32((BYTE*)compressedBuffer + off, ZSTD_MAGIC_SKIPPABLE_START);
522                 MEM_writeLE32((BYTE*)compressedBuffer + off + 4, skipLen);
523                 off += skipLen + ZSTD_skippableHeaderSize;
524             }
525         }
526         cSize = off;
527     }
528     DISPLAYLEVEL(4, "OK \n");
529
530     DISPLAYLEVEL(4, "test%3i : get decompressed size of multiple frames : ", testNb++);
531     {   unsigned long long const r = ZSTD_findDecompressedSize(compressedBuffer, cSize);
532         if (r != CNBuffSize / 2) goto _output_error; }
533     DISPLAYLEVEL(4, "OK \n");
534
535     DISPLAYLEVEL(4, "test%3i : decompress multiple frames : ", testNb++);
536     {   CHECK_V(r, ZSTD_decompress(decodedBuffer, CNBuffSize, compressedBuffer, cSize));
537         if (r != CNBuffSize / 2) goto _output_error; }
538     DISPLAYLEVEL(4, "OK \n");
539
540     DISPLAYLEVEL(4, "test%3i : check decompressed result : ", testNb++);
541     if (memcmp(decodedBuffer, CNBuffer, CNBuffSize / 2) != 0) goto _output_error;
542     DISPLAYLEVEL(4, "OK \n");
543
544     /* Dictionary and CCtx Duplication tests */
545     {   ZSTD_CCtx* const ctxOrig = ZSTD_createCCtx();
546         ZSTD_CCtx* const ctxDuplicated = ZSTD_createCCtx();
547         static const size_t dictSize = 551;
548
549         DISPLAYLEVEL(4, "test%3i : copy context too soon : ", testNb++);
550         { size_t const copyResult = ZSTD_copyCCtx(ctxDuplicated, ctxOrig, 0);
551           if (!ZSTD_isError(copyResult)) goto _output_error; }   /* error must be detected */
552         DISPLAYLEVEL(4, "OK \n");
553
554         DISPLAYLEVEL(4, "test%3i : load dictionary into context : ", testNb++);
555         CHECK( ZSTD_compressBegin_usingDict(ctxOrig, CNBuffer, dictSize, 2) );
556         CHECK( ZSTD_copyCCtx(ctxDuplicated, ctxOrig, 0) ); /* Begin_usingDict implies unknown srcSize, so match that */
557         DISPLAYLEVEL(4, "OK \n");
558
559         DISPLAYLEVEL(4, "test%3i : compress with flat dictionary : ", testNb++);
560         cSize = 0;
561         CHECKPLUS(r, ZSTD_compressEnd(ctxOrig, compressedBuffer, compressedBufferSize,
562                                            (const char*)CNBuffer + dictSize, CNBuffSize - dictSize),
563                   cSize += r);
564         DISPLAYLEVEL(4, "OK (%u bytes : %.2f%%)\n", (U32)cSize, (double)cSize/CNBuffSize*100);
565
566         DISPLAYLEVEL(4, "test%3i : frame built with flat dictionary should be decompressible : ", testNb++);
567         CHECKPLUS(r, ZSTD_decompress_usingDict(dctx,
568                                        decodedBuffer, CNBuffSize,
569                                        compressedBuffer, cSize,
570                                        CNBuffer, dictSize),
571                   if (r != CNBuffSize - dictSize) goto _output_error);
572         DISPLAYLEVEL(4, "OK \n");
573
574         DISPLAYLEVEL(4, "test%3i : compress with duplicated context : ", testNb++);
575         {   size_t const cSizeOrig = cSize;
576             cSize = 0;
577             CHECKPLUS(r, ZSTD_compressEnd(ctxDuplicated, compressedBuffer, compressedBufferSize,
578                                                (const char*)CNBuffer + dictSize, CNBuffSize - dictSize),
579                       cSize += r);
580             if (cSize != cSizeOrig) goto _output_error;   /* should be identical ==> same size */
581         }
582         DISPLAYLEVEL(4, "OK (%u bytes : %.2f%%)\n", (U32)cSize, (double)cSize/CNBuffSize*100);
583
584         DISPLAYLEVEL(4, "test%3i : frame built with duplicated context should be decompressible : ", testNb++);
585         CHECKPLUS(r, ZSTD_decompress_usingDict(dctx,
586                                            decodedBuffer, CNBuffSize,
587                                            compressedBuffer, cSize,
588                                            CNBuffer, dictSize),
589                   if (r != CNBuffSize - dictSize) goto _output_error);
590         DISPLAYLEVEL(4, "OK \n");
591
592         DISPLAYLEVEL(4, "test%3i : decompress with DDict : ", testNb++);
593         {   ZSTD_DDict* const ddict = ZSTD_createDDict(CNBuffer, dictSize);
594             size_t const r = ZSTD_decompress_usingDDict(dctx, decodedBuffer, CNBuffSize, compressedBuffer, cSize, ddict);
595             if (r != CNBuffSize - dictSize) goto _output_error;
596             DISPLAYLEVEL(4, "OK (size of DDict : %u) \n", (U32)ZSTD_sizeof_DDict(ddict));
597             ZSTD_freeDDict(ddict);
598         }
599
600         DISPLAYLEVEL(4, "test%3i : decompress with static DDict : ", testNb++);
601         {   size_t const ddictBufferSize = ZSTD_estimateDDictSize(dictSize, 0);
602             void* ddictBuffer = malloc(ddictBufferSize);
603             if (ddictBuffer == NULL) goto _output_error;
604             {   ZSTD_DDict* const ddict = ZSTD_initStaticDDict(ddictBuffer, ddictBufferSize, CNBuffer, dictSize, 0);
605                 size_t const r = ZSTD_decompress_usingDDict(dctx, decodedBuffer, CNBuffSize, compressedBuffer, cSize, ddict);
606                 if (r != CNBuffSize - dictSize) goto _output_error;
607             }
608             free(ddictBuffer);
609             DISPLAYLEVEL(4, "OK (size of static DDict : %u) \n", (U32)ddictBufferSize);
610         }
611
612         DISPLAYLEVEL(4, "test%3i : check content size on duplicated context : ", testNb++);
613         {   size_t const testSize = CNBuffSize / 3;
614             {   ZSTD_parameters p = ZSTD_getParams(2, testSize, dictSize);
615                 p.fParams.contentSizeFlag = 1;
616                 CHECK( ZSTD_compressBegin_advanced(ctxOrig, CNBuffer, dictSize, p, testSize-1) );
617             }
618             CHECK( ZSTD_copyCCtx(ctxDuplicated, ctxOrig, testSize) );
619
620             CHECKPLUS(r, ZSTD_compressEnd(ctxDuplicated, compressedBuffer, ZSTD_compressBound(testSize),
621                                           (const char*)CNBuffer + dictSize, testSize),
622                       cSize = r);
623             {   ZSTD_frameHeader zfh;
624                 if (ZSTD_getFrameHeader(&zfh, compressedBuffer, cSize)) goto _output_error;
625                 if ((zfh.frameContentSize != testSize) && (zfh.frameContentSize != 0)) goto _output_error;
626         }   }
627         DISPLAYLEVEL(4, "OK \n");
628
629         ZSTD_freeCCtx(ctxOrig);
630         ZSTD_freeCCtx(ctxDuplicated);
631     }
632
633     /* Dictionary and dictBuilder tests */
634     {   ZSTD_CCtx* const cctx = ZSTD_createCCtx();
635         size_t dictSize = 16 KB;
636         void* dictBuffer = malloc(dictSize);
637         size_t const totalSampleSize = 1 MB;
638         size_t const sampleUnitSize = 8 KB;
639         U32 const nbSamples = (U32)(totalSampleSize / sampleUnitSize);
640         size_t* const samplesSizes = (size_t*) malloc(nbSamples * sizeof(size_t));
641         U32 dictID;
642
643         if (dictBuffer==NULL || samplesSizes==NULL) {
644             free(dictBuffer);
645             free(samplesSizes);
646             goto _output_error;
647         }
648
649         DISPLAYLEVEL(4, "test%3i : dictBuilder : ", testNb++);
650         { U32 u; for (u=0; u<nbSamples; u++) samplesSizes[u] = sampleUnitSize; }
651         dictSize = ZDICT_trainFromBuffer(dictBuffer, dictSize,
652                                          CNBuffer, samplesSizes, nbSamples);
653         if (ZDICT_isError(dictSize)) goto _output_error;
654         DISPLAYLEVEL(4, "OK, created dictionary of size %u \n", (U32)dictSize);
655
656         DISPLAYLEVEL(4, "test%3i : check dictID : ", testNb++);
657         dictID = ZDICT_getDictID(dictBuffer, dictSize);
658         if (dictID==0) goto _output_error;
659         DISPLAYLEVEL(4, "OK : %u \n", dictID);
660
661         DISPLAYLEVEL(4, "test%3i : compress with dictionary : ", testNb++);
662         cSize = ZSTD_compress_usingDict(cctx, compressedBuffer, compressedBufferSize,
663                                         CNBuffer, CNBuffSize,
664                                         dictBuffer, dictSize, 4);
665         if (ZSTD_isError(cSize)) goto _output_error;
666         DISPLAYLEVEL(4, "OK (%u bytes : %.2f%%)\n", (U32)cSize, (double)cSize/CNBuffSize*100);
667
668         DISPLAYLEVEL(4, "test%3i : retrieve dictID from dictionary : ", testNb++);
669         {   U32 const did = ZSTD_getDictID_fromDict(dictBuffer, dictSize);
670             if (did != dictID) goto _output_error;   /* non-conformant (content-only) dictionary */
671         }
672         DISPLAYLEVEL(4, "OK \n");
673
674         DISPLAYLEVEL(4, "test%3i : retrieve dictID from frame : ", testNb++);
675         {   U32 const did = ZSTD_getDictID_fromFrame(compressedBuffer, cSize);
676             if (did != dictID) goto _output_error;   /* non-conformant (content-only) dictionary */
677         }
678         DISPLAYLEVEL(4, "OK \n");
679
680         DISPLAYLEVEL(4, "test%3i : frame built with dictionary should be decompressible : ", testNb++);
681         CHECKPLUS(r, ZSTD_decompress_usingDict(dctx,
682                                        decodedBuffer, CNBuffSize,
683                                        compressedBuffer, cSize,
684                                        dictBuffer, dictSize),
685                   if (r != CNBuffSize) goto _output_error);
686         DISPLAYLEVEL(4, "OK \n");
687
688         DISPLAYLEVEL(4, "test%3i : estimate CDict size : ", testNb++);
689         {   ZSTD_compressionParameters const cParams = ZSTD_getCParams(1, CNBuffSize, dictSize);
690             size_t const estimatedSize = ZSTD_estimateCDictSize_advanced(dictSize, cParams, 1 /*byReference*/);
691             DISPLAYLEVEL(4, "OK : %u \n", (U32)estimatedSize);
692         }
693
694         DISPLAYLEVEL(4, "test%3i : compress with CDict ", testNb++);
695         {   ZSTD_compressionParameters const cParams = ZSTD_getCParams(1, CNBuffSize, dictSize);
696             ZSTD_CDict* const cdict = ZSTD_createCDict_advanced(dictBuffer, dictSize,
697                                             1 /* byReference */, ZSTD_dm_auto,
698                                             cParams, ZSTD_defaultCMem);
699             DISPLAYLEVEL(4, "(size : %u) : ", (U32)ZSTD_sizeof_CDict(cdict));
700             cSize = ZSTD_compress_usingCDict(cctx, compressedBuffer, compressedBufferSize,
701                                                  CNBuffer, CNBuffSize, cdict);
702             ZSTD_freeCDict(cdict);
703             if (ZSTD_isError(cSize)) goto _output_error;
704         }
705         DISPLAYLEVEL(4, "OK (%u bytes : %.2f%%)\n", (U32)cSize, (double)cSize/CNBuffSize*100);
706
707         DISPLAYLEVEL(4, "test%3i : retrieve dictID from frame : ", testNb++);
708         {   U32 const did = ZSTD_getDictID_fromFrame(compressedBuffer, cSize);
709             if (did != dictID) goto _output_error;   /* non-conformant (content-only) dictionary */
710         }
711         DISPLAYLEVEL(4, "OK \n");
712
713         DISPLAYLEVEL(4, "test%3i : frame built with dictionary should be decompressible : ", testNb++);
714         CHECKPLUS(r, ZSTD_decompress_usingDict(dctx,
715                                        decodedBuffer, CNBuffSize,
716                                        compressedBuffer, cSize,
717                                        dictBuffer, dictSize),
718                   if (r != CNBuffSize) goto _output_error);
719         DISPLAYLEVEL(4, "OK \n");
720
721         DISPLAYLEVEL(4, "test%3i : compress with static CDict : ", testNb++);
722         {   ZSTD_compressionParameters const cParams = ZSTD_getCParams(1, CNBuffSize, dictSize);
723             size_t const cdictSize = ZSTD_estimateCDictSize_advanced(dictSize, cParams, 0);
724             void* const cdictBuffer = malloc(cdictSize);
725             if (cdictBuffer==NULL) goto _output_error;
726             {   ZSTD_CDict* const cdict = ZSTD_initStaticCDict(cdictBuffer, cdictSize,
727                                             dictBuffer, dictSize,
728                                             0 /* by Reference */, ZSTD_dm_auto,
729                                             cParams);
730                 if (cdict == NULL) {
731                     DISPLAY("ZSTD_initStaticCDict failed ");
732                     goto _output_error;
733                 }
734                 cSize = ZSTD_compress_usingCDict(cctx,
735                                 compressedBuffer, compressedBufferSize,
736                                 CNBuffer, CNBuffSize, cdict);
737                 if (ZSTD_isError(cSize)) {
738                     DISPLAY("ZSTD_compress_usingCDict failed ");
739                     goto _output_error;
740             }   }
741             free(cdictBuffer);
742         }
743         DISPLAYLEVEL(4, "OK (%u bytes : %.2f%%)\n", (U32)cSize, (double)cSize/CNBuffSize*100);
744
745         DISPLAYLEVEL(4, "test%3i : ZSTD_compress_usingCDict_advanced, no contentSize, no dictID : ", testNb++);
746         {   ZSTD_frameParameters const fParams = { 0 /* frameSize */, 1 /* checksum */, 1 /* noDictID*/ };
747             ZSTD_compressionParameters const cParams = ZSTD_getCParams(1, CNBuffSize, dictSize);
748             ZSTD_CDict* const cdict = ZSTD_createCDict_advanced(dictBuffer, dictSize, 1 /*byRef*/, ZSTD_dm_auto, cParams, ZSTD_defaultCMem);
749             cSize = ZSTD_compress_usingCDict_advanced(cctx, compressedBuffer, compressedBufferSize,
750                                                  CNBuffer, CNBuffSize, cdict, fParams);
751             ZSTD_freeCDict(cdict);
752             if (ZSTD_isError(cSize)) goto _output_error;
753         }
754         DISPLAYLEVEL(4, "OK (%u bytes : %.2f%%)\n", (U32)cSize, (double)cSize/CNBuffSize*100);
755
756         DISPLAYLEVEL(4, "test%3i : try retrieving contentSize from frame : ", testNb++);
757         {   U64 const contentSize = ZSTD_getFrameContentSize(compressedBuffer, cSize);
758             if (contentSize != ZSTD_CONTENTSIZE_UNKNOWN) goto _output_error;
759         }
760         DISPLAYLEVEL(4, "OK (unknown)\n");
761
762         DISPLAYLEVEL(4, "test%3i : frame built without dictID should be decompressible : ", testNb++);
763         CHECKPLUS(r, ZSTD_decompress_usingDict(dctx,
764                                        decodedBuffer, CNBuffSize,
765                                        compressedBuffer, cSize,
766                                        dictBuffer, dictSize),
767                   if (r != CNBuffSize) goto _output_error);
768         DISPLAYLEVEL(4, "OK \n");
769
770         DISPLAYLEVEL(4, "test%3i : ZSTD_compress_advanced, no dictID : ", testNb++);
771         {   ZSTD_parameters p = ZSTD_getParams(3, CNBuffSize, dictSize);
772             p.fParams.noDictIDFlag = 1;
773             cSize = ZSTD_compress_advanced(cctx, compressedBuffer, compressedBufferSize,
774                                            CNBuffer, CNBuffSize,
775                                            dictBuffer, dictSize, p);
776             if (ZSTD_isError(cSize)) goto _output_error;
777         }
778         DISPLAYLEVEL(4, "OK (%u bytes : %.2f%%)\n", (U32)cSize, (double)cSize/CNBuffSize*100);
779
780         DISPLAYLEVEL(4, "test%3i : frame built without dictID should be decompressible : ", testNb++);
781         CHECKPLUS(r, ZSTD_decompress_usingDict(dctx,
782                                        decodedBuffer, CNBuffSize,
783                                        compressedBuffer, cSize,
784                                        dictBuffer, dictSize),
785                   if (r != CNBuffSize) goto _output_error);
786         DISPLAYLEVEL(4, "OK \n");
787
788         DISPLAYLEVEL(4, "test%3i : dictionary containing only header should return error : ", testNb++);
789         {
790           const size_t ret = ZSTD_decompress_usingDict(
791               dctx, decodedBuffer, CNBuffSize, compressedBuffer, cSize,
792               "\x37\xa4\x30\xec\x11\x22\x33\x44", 8);
793           if (ZSTD_getErrorCode(ret) != ZSTD_error_dictionary_corrupted) goto _output_error;
794         }
795         DISPLAYLEVEL(4, "OK \n");
796
797         DISPLAYLEVEL(4, "test%3i : Building cdict w/ ZSTD_dm_fullDict on a good dictionary : ", testNb++);
798         {   ZSTD_compressionParameters const cParams = ZSTD_getCParams(1, CNBuffSize, dictSize);
799             ZSTD_CDict* const cdict = ZSTD_createCDict_advanced(dictBuffer, dictSize, 1 /*byRef*/, ZSTD_dm_fullDict, cParams, ZSTD_defaultCMem);
800             if (cdict==NULL) goto _output_error;
801             ZSTD_freeCDict(cdict);
802         }
803         DISPLAYLEVEL(4, "OK \n");
804
805         DISPLAYLEVEL(4, "test%3i : Building cdict w/ ZSTD_dm_fullDict on a rawContent (must fail) : ", testNb++);
806         {   ZSTD_compressionParameters const cParams = ZSTD_getCParams(1, CNBuffSize, dictSize);
807             ZSTD_CDict* const cdict = ZSTD_createCDict_advanced((const char*)dictBuffer+1, dictSize-1, 1 /*byRef*/, ZSTD_dm_fullDict, cParams, ZSTD_defaultCMem);
808             if (cdict!=NULL) goto _output_error;
809             ZSTD_freeCDict(cdict);
810         }
811         DISPLAYLEVEL(4, "OK \n");
812
813         ZSTD_freeCCtx(cctx);
814         free(dictBuffer);
815         free(samplesSizes);
816     }
817
818     /* COVER dictionary builder tests */
819     {   ZSTD_CCtx* const cctx = ZSTD_createCCtx();
820         size_t dictSize = 16 KB;
821         size_t optDictSize = dictSize;
822         void* dictBuffer = malloc(dictSize);
823         size_t const totalSampleSize = 1 MB;
824         size_t const sampleUnitSize = 8 KB;
825         U32 const nbSamples = (U32)(totalSampleSize / sampleUnitSize);
826         size_t* const samplesSizes = (size_t*) malloc(nbSamples * sizeof(size_t));
827         ZDICT_cover_params_t params;
828         U32 dictID;
829
830         if (dictBuffer==NULL || samplesSizes==NULL) {
831             free(dictBuffer);
832             free(samplesSizes);
833             goto _output_error;
834         }
835
836         DISPLAYLEVEL(4, "test%3i : ZDICT_trainFromBuffer_cover : ", testNb++);
837         { U32 u; for (u=0; u<nbSamples; u++) samplesSizes[u] = sampleUnitSize; }
838         memset(&params, 0, sizeof(params));
839         params.d = 1 + (FUZ_rand(&seed) % 16);
840         params.k = params.d + (FUZ_rand(&seed) % 256);
841         dictSize = ZDICT_trainFromBuffer_cover(dictBuffer, dictSize,
842                                                CNBuffer, samplesSizes, nbSamples,
843                                                params);
844         if (ZDICT_isError(dictSize)) goto _output_error;
845         DISPLAYLEVEL(4, "OK, created dictionary of size %u \n", (U32)dictSize);
846
847         DISPLAYLEVEL(4, "test%3i : check dictID : ", testNb++);
848         dictID = ZDICT_getDictID(dictBuffer, dictSize);
849         if (dictID==0) goto _output_error;
850         DISPLAYLEVEL(4, "OK : %u \n", dictID);
851
852         DISPLAYLEVEL(4, "test%3i : ZDICT_optimizeTrainFromBuffer_cover : ", testNb++);
853         memset(&params, 0, sizeof(params));
854         params.steps = 4;
855         optDictSize = ZDICT_optimizeTrainFromBuffer_cover(dictBuffer, optDictSize,
856                                                           CNBuffer, samplesSizes,
857                                                           nbSamples / 4, &params);
858         if (ZDICT_isError(optDictSize)) goto _output_error;
859         DISPLAYLEVEL(4, "OK, created dictionary of size %u \n", (U32)optDictSize);
860
861         DISPLAYLEVEL(4, "test%3i : check dictID : ", testNb++);
862         dictID = ZDICT_getDictID(dictBuffer, optDictSize);
863         if (dictID==0) goto _output_error;
864         DISPLAYLEVEL(4, "OK : %u \n", dictID);
865
866         ZSTD_freeCCtx(cctx);
867         free(dictBuffer);
868         free(samplesSizes);
869     }
870
871     /* Decompression defense tests */
872     DISPLAYLEVEL(4, "test%3i : Check input length for magic number : ", testNb++);
873     { size_t const r = ZSTD_decompress(decodedBuffer, CNBuffSize, CNBuffer, 3);   /* too small input */
874       if (!ZSTD_isError(r)) goto _output_error;
875       if (ZSTD_getErrorCode(r) != ZSTD_error_srcSize_wrong) goto _output_error; }
876     DISPLAYLEVEL(4, "OK \n");
877
878     DISPLAYLEVEL(4, "test%3i : Check magic Number : ", testNb++);
879     ((char*)(CNBuffer))[0] = 1;
880     { size_t const r = ZSTD_decompress(decodedBuffer, CNBuffSize, CNBuffer, 4);
881       if (!ZSTD_isError(r)) goto _output_error; }
882     DISPLAYLEVEL(4, "OK \n");
883
884     /* content size verification test */
885     DISPLAYLEVEL(4, "test%3i : Content size verification : ", testNb++);
886     {   ZSTD_CCtx* const cctx = ZSTD_createCCtx();
887         size_t const srcSize = 5000;
888         size_t const wrongSrcSize = (srcSize + 1000);
889         ZSTD_parameters params = ZSTD_getParams(1, wrongSrcSize, 0);
890         params.fParams.contentSizeFlag = 1;
891         CHECK( ZSTD_compressBegin_advanced(cctx, NULL, 0, params, wrongSrcSize) );
892         {   size_t const result = ZSTD_compressEnd(cctx, decodedBuffer, CNBuffSize, CNBuffer, srcSize);
893             if (!ZSTD_isError(result)) goto _output_error;
894             if (ZSTD_getErrorCode(result) != ZSTD_error_srcSize_wrong) goto _output_error;
895             DISPLAYLEVEL(4, "OK : %s \n", ZSTD_getErrorName(result));
896         }
897         ZSTD_freeCCtx(cctx);
898     }
899
900     /* block API tests */
901     {   ZSTD_CCtx* const cctx = ZSTD_createCCtx();
902         static const size_t dictSize = 65 KB;
903         static const size_t blockSize = 100 KB;   /* won't cause pb with small dict size */
904         size_t cSize2;
905
906         /* basic block compression */
907         DISPLAYLEVEL(4, "test%3i : Block compression test : ", testNb++);
908         CHECK( ZSTD_compressBegin(cctx, 5) );
909         CHECK( ZSTD_getBlockSize(cctx) >= blockSize);
910         cSize = ZSTD_compressBlock(cctx, compressedBuffer, ZSTD_compressBound(blockSize), CNBuffer, blockSize);
911         if (ZSTD_isError(cSize)) goto _output_error;
912         DISPLAYLEVEL(4, "OK \n");
913
914         DISPLAYLEVEL(4, "test%3i : Block decompression test : ", testNb++);
915         CHECK( ZSTD_decompressBegin(dctx) );
916         { CHECK_V(r, ZSTD_decompressBlock(dctx, decodedBuffer, CNBuffSize, compressedBuffer, cSize) );
917           if (r != blockSize) goto _output_error; }
918         DISPLAYLEVEL(4, "OK \n");
919
920         /* dictionary block compression */
921         DISPLAYLEVEL(4, "test%3i : Dictionary Block compression test : ", testNb++);
922         CHECK( ZSTD_compressBegin_usingDict(cctx, CNBuffer, dictSize, 5) );
923         cSize = ZSTD_compressBlock(cctx, compressedBuffer, ZSTD_compressBound(blockSize), (char*)CNBuffer+dictSize, blockSize);
924         if (ZSTD_isError(cSize)) goto _output_error;
925         cSize2 = ZSTD_compressBlock(cctx, (char*)compressedBuffer+cSize, ZSTD_compressBound(blockSize), (char*)CNBuffer+dictSize+blockSize, blockSize);
926         if (ZSTD_isError(cSize2)) goto _output_error;
927         memcpy((char*)compressedBuffer+cSize, (char*)CNBuffer+dictSize+blockSize, blockSize);   /* fake non-compressed block */
928         cSize2 = ZSTD_compressBlock(cctx, (char*)compressedBuffer+cSize+blockSize, ZSTD_compressBound(blockSize),
929                                           (char*)CNBuffer+dictSize+2*blockSize, blockSize);
930         if (ZSTD_isError(cSize2)) goto _output_error;
931         DISPLAYLEVEL(4, "OK \n");
932
933         DISPLAYLEVEL(4, "test%3i : Dictionary Block decompression test : ", testNb++);
934         CHECK( ZSTD_decompressBegin_usingDict(dctx, CNBuffer, dictSize) );
935         { CHECK_V( r, ZSTD_decompressBlock(dctx, decodedBuffer, CNBuffSize, compressedBuffer, cSize) );
936           if (r != blockSize) goto _output_error; }
937         ZSTD_insertBlock(dctx, (char*)decodedBuffer+blockSize, blockSize);   /* insert non-compressed block into dctx history */
938         { CHECK_V( r, ZSTD_decompressBlock(dctx, (char*)decodedBuffer+2*blockSize, CNBuffSize, (char*)compressedBuffer+cSize+blockSize, cSize2) );
939           if (r != blockSize) goto _output_error; }
940         DISPLAYLEVEL(4, "OK \n");
941
942         ZSTD_freeCCtx(cctx);
943         ZSTD_freeDCtx(dctx);
944     }
945
946     /* long rle test */
947     {   size_t sampleSize = 0;
948         DISPLAYLEVEL(4, "test%3i : Long RLE test : ", testNb++);
949         RDG_genBuffer(CNBuffer, sampleSize, compressibility, 0., seed+1);
950         memset((char*)CNBuffer+sampleSize, 'B', 256 KB - 1);
951         sampleSize += 256 KB - 1;
952         RDG_genBuffer((char*)CNBuffer+sampleSize, 96 KB, compressibility, 0., seed+2);
953         sampleSize += 96 KB;
954         cSize = ZSTD_compress(compressedBuffer, ZSTD_compressBound(sampleSize), CNBuffer, sampleSize, 1);
955         if (ZSTD_isError(cSize)) goto _output_error;
956         { CHECK_V(regenSize, ZSTD_decompress(decodedBuffer, sampleSize, compressedBuffer, cSize));
957           if (regenSize!=sampleSize) goto _output_error; }
958         DISPLAYLEVEL(4, "OK \n");
959     }
960
961     /* All zeroes test (test bug #137) */
962     #define ZEROESLENGTH 100
963     DISPLAYLEVEL(4, "test%3i : compress %u zeroes : ", testNb++, ZEROESLENGTH);
964     memset(CNBuffer, 0, ZEROESLENGTH);
965     { CHECK_V(r, ZSTD_compress(compressedBuffer, ZSTD_compressBound(ZEROESLENGTH), CNBuffer, ZEROESLENGTH, 1) );
966       cSize = r; }
967     DISPLAYLEVEL(4, "OK (%u bytes : %.2f%%)\n", (U32)cSize, (double)cSize/ZEROESLENGTH*100);
968
969     DISPLAYLEVEL(4, "test%3i : decompress %u zeroes : ", testNb++, ZEROESLENGTH);
970     { CHECK_V(r, ZSTD_decompress(decodedBuffer, ZEROESLENGTH, compressedBuffer, cSize) );
971       if (r != ZEROESLENGTH) goto _output_error; }
972     DISPLAYLEVEL(4, "OK \n");
973
974     /* nbSeq limit test */
975     #define _3BYTESTESTLENGTH 131000
976     #define NB3BYTESSEQLOG   9
977     #define NB3BYTESSEQ     (1 << NB3BYTESSEQLOG)
978     #define NB3BYTESSEQMASK (NB3BYTESSEQ-1)
979     /* creates a buffer full of 3-bytes sequences */
980     {   BYTE _3BytesSeqs[NB3BYTESSEQ][3];
981         U32 rSeed = 1;
982
983         /* create batch of 3-bytes sequences */
984         {   int i;
985             for (i=0; i < NB3BYTESSEQ; i++) {
986                 _3BytesSeqs[i][0] = (BYTE)(FUZ_rand(&rSeed) & 255);
987                 _3BytesSeqs[i][1] = (BYTE)(FUZ_rand(&rSeed) & 255);
988                 _3BytesSeqs[i][2] = (BYTE)(FUZ_rand(&rSeed) & 255);
989         }   }
990
991         /* randomly fills CNBuffer with prepared 3-bytes sequences */
992         {   int i;
993             for (i=0; i < _3BYTESTESTLENGTH; i += 3) {   /* note : CNBuffer size > _3BYTESTESTLENGTH+3 */
994                 U32 const id = FUZ_rand(&rSeed) & NB3BYTESSEQMASK;
995                 ((BYTE*)CNBuffer)[i+0] = _3BytesSeqs[id][0];
996                 ((BYTE*)CNBuffer)[i+1] = _3BytesSeqs[id][1];
997                 ((BYTE*)CNBuffer)[i+2] = _3BytesSeqs[id][2];
998     }   }   }
999     DISPLAYLEVEL(4, "test%3i : compress lots 3-bytes sequences : ", testNb++);
1000     { CHECK_V(r, ZSTD_compress(compressedBuffer, ZSTD_compressBound(_3BYTESTESTLENGTH),
1001                                  CNBuffer, _3BYTESTESTLENGTH, 19) );
1002       cSize = r; }
1003     DISPLAYLEVEL(4, "OK (%u bytes : %.2f%%)\n", (U32)cSize, (double)cSize/_3BYTESTESTLENGTH*100);
1004
1005     DISPLAYLEVEL(4, "test%3i : decompress lots 3-bytes sequence : ", testNb++);
1006     { CHECK_V(r, ZSTD_decompress(decodedBuffer, _3BYTESTESTLENGTH, compressedBuffer, cSize) );
1007       if (r != _3BYTESTESTLENGTH) goto _output_error; }
1008     DISPLAYLEVEL(4, "OK \n");
1009
1010     DISPLAYLEVEL(4, "test%3i : incompressible data and ill suited dictionary : ", testNb++);
1011     RDG_genBuffer(CNBuffer, CNBuffSize, 0.0, 0.1, seed);
1012     {   /* Train a dictionary on low characters */
1013         size_t dictSize = 16 KB;
1014         void* const dictBuffer = malloc(dictSize);
1015         size_t const totalSampleSize = 1 MB;
1016         size_t const sampleUnitSize = 8 KB;
1017         U32 const nbSamples = (U32)(totalSampleSize / sampleUnitSize);
1018         size_t* const samplesSizes = (size_t*) malloc(nbSamples * sizeof(size_t));
1019         if (!dictBuffer || !samplesSizes) goto _output_error;
1020         { U32 u; for (u=0; u<nbSamples; u++) samplesSizes[u] = sampleUnitSize; }
1021         dictSize = ZDICT_trainFromBuffer(dictBuffer, dictSize, CNBuffer, samplesSizes, nbSamples);
1022         if (ZDICT_isError(dictSize)) goto _output_error;
1023         /* Reverse the characters to make the dictionary ill suited */
1024         {   U32 u;
1025             for (u = 0; u < CNBuffSize; ++u) {
1026               ((BYTE*)CNBuffer)[u] = 255 - ((BYTE*)CNBuffer)[u];
1027             }
1028         }
1029         {   /* Compress the data */
1030             size_t const inputSize = 500;
1031             size_t const outputSize = ZSTD_compressBound(inputSize);
1032             void* const outputBuffer = malloc(outputSize);
1033             ZSTD_CCtx* const cctx = ZSTD_createCCtx();
1034             if (!outputBuffer || !cctx) goto _output_error;
1035             CHECK(ZSTD_compress_usingDict(cctx, outputBuffer, outputSize, CNBuffer, inputSize, dictBuffer, dictSize, 1));
1036             free(outputBuffer);
1037             ZSTD_freeCCtx(cctx);
1038         }
1039
1040         free(dictBuffer);
1041         free(samplesSizes);
1042     }
1043     DISPLAYLEVEL(4, "OK \n");
1044
1045
1046     /* findFrameCompressedSize on skippable frames */
1047     DISPLAYLEVEL(4, "test%3i : frame compressed size of skippable frame : ", testNb++);
1048     {   const char* frame = "\x50\x2a\x4d\x18\x05\x0\x0\0abcde";
1049         size_t const frameSrcSize = 13;
1050         if (ZSTD_findFrameCompressedSize(frame, frameSrcSize) != frameSrcSize) goto _output_error; }
1051     DISPLAYLEVEL(4, "OK \n");
1052
1053     /* error string tests */
1054     DISPLAYLEVEL(4, "test%3i : testing ZSTD error code strings : ", testNb++);
1055     if (strcmp("No error detected", ZSTD_getErrorName((ZSTD_ErrorCode)(0-ZSTD_error_no_error))) != 0) goto _output_error;
1056     if (strcmp("No error detected", ZSTD_getErrorString(ZSTD_error_no_error)) != 0) goto _output_error;
1057     if (strcmp("Unspecified error code", ZSTD_getErrorString((ZSTD_ErrorCode)(0-ZSTD_error_GENERIC))) != 0) goto _output_error;
1058     if (strcmp("Error (generic)", ZSTD_getErrorName((size_t)0-ZSTD_error_GENERIC)) != 0) goto _output_error;
1059     if (strcmp("Error (generic)", ZSTD_getErrorString(ZSTD_error_GENERIC)) != 0) goto _output_error;
1060     if (strcmp("No error detected", ZSTD_getErrorName(ZSTD_error_GENERIC)) != 0) goto _output_error;
1061     DISPLAYLEVEL(4, "OK \n");
1062
1063 _end:
1064     free(CNBuffer);
1065     free(compressedBuffer);
1066     free(decodedBuffer);
1067     return testResult;
1068
1069 _output_error:
1070     testResult = 1;
1071     DISPLAY("Error detected in Unit tests ! \n");
1072     goto _end;
1073 }
1074
1075
1076 static size_t findDiff(const void* buf1, const void* buf2, size_t max)
1077 {
1078     const BYTE* b1 = (const BYTE*)buf1;
1079     const BYTE* b2 = (const BYTE*)buf2;
1080     size_t u;
1081     for (u=0; u<max; u++) {
1082         if (b1[u] != b2[u]) break;
1083     }
1084     return u;
1085 }
1086
1087
1088 static ZSTD_parameters FUZ_makeParams(ZSTD_compressionParameters cParams, ZSTD_frameParameters fParams)
1089 {
1090     ZSTD_parameters params;
1091     params.cParams = cParams;
1092     params.fParams = fParams;
1093     return params;
1094 }
1095
1096 static size_t FUZ_rLogLength(U32* seed, U32 logLength)
1097 {
1098     size_t const lengthMask = ((size_t)1 << logLength) - 1;
1099     return (lengthMask+1) + (FUZ_rand(seed) & lengthMask);
1100 }
1101
1102 static size_t FUZ_randomLength(U32* seed, U32 maxLog)
1103 {
1104     U32 const logLength = FUZ_rand(seed) % maxLog;
1105     return FUZ_rLogLength(seed, logLength);
1106 }
1107
1108 #undef CHECK
1109 #define CHECK(cond, ...) {                                    \
1110     if (cond) {                                               \
1111         DISPLAY("Error => ");                                 \
1112         DISPLAY(__VA_ARGS__);                                 \
1113         DISPLAY(" (seed %u, test nb %u)  \n", seed, testNb);  \
1114         goto _output_error;                                   \
1115 }   }
1116
1117 #undef CHECK_Z
1118 #define CHECK_Z(f) {                                          \
1119     size_t const err = f;                                     \
1120     if (ZSTD_isError(err)) {                                  \
1121         DISPLAY("Error => %s : %s ",                          \
1122                 #f, ZSTD_getErrorName(err));                  \
1123         DISPLAY(" (seed %u, test nb %u)  \n", seed, testNb);  \
1124         goto _output_error;                                   \
1125 }   }
1126
1127
1128 static int fuzzerTests(U32 seed, U32 nbTests, unsigned startTest, U32 const maxDurationS, double compressibility, int bigTests)
1129 {
1130     static const U32 maxSrcLog = 23;
1131     static const U32 maxSampleLog = 22;
1132     size_t const srcBufferSize = (size_t)1<<maxSrcLog;
1133     size_t const dstBufferSize = (size_t)1<<maxSampleLog;
1134     size_t const cBufferSize   = ZSTD_compressBound(dstBufferSize);
1135     BYTE* cNoiseBuffer[5];
1136     BYTE* srcBuffer;   /* jumping pointer */
1137     BYTE* const cBuffer = (BYTE*) malloc (cBufferSize);
1138     BYTE* const dstBuffer = (BYTE*) malloc (dstBufferSize);
1139     BYTE* const mirrorBuffer = (BYTE*) malloc (dstBufferSize);
1140     ZSTD_CCtx* const refCtx = ZSTD_createCCtx();
1141     ZSTD_CCtx* const ctx = ZSTD_createCCtx();
1142     ZSTD_DCtx* const dctx = ZSTD_createDCtx();
1143     U32 result = 0;
1144     U32 testNb = 0;
1145     U32 coreSeed = seed, lseed = 0;
1146     clock_t const startClock = clock();
1147     clock_t const maxClockSpan = maxDurationS * CLOCKS_PER_SEC;
1148     int const cLevelLimiter = bigTests ? 3 : 2;
1149
1150     /* allocation */
1151     cNoiseBuffer[0] = (BYTE*)malloc (srcBufferSize);
1152     cNoiseBuffer[1] = (BYTE*)malloc (srcBufferSize);
1153     cNoiseBuffer[2] = (BYTE*)malloc (srcBufferSize);
1154     cNoiseBuffer[3] = (BYTE*)malloc (srcBufferSize);
1155     cNoiseBuffer[4] = (BYTE*)malloc (srcBufferSize);
1156     CHECK (!cNoiseBuffer[0] || !cNoiseBuffer[1] || !cNoiseBuffer[2] || !cNoiseBuffer[3] || !cNoiseBuffer[4]
1157            || !dstBuffer || !mirrorBuffer || !cBuffer || !refCtx || !ctx || !dctx,
1158            "Not enough memory, fuzzer tests cancelled");
1159
1160     /* Create initial samples */
1161     RDG_genBuffer(cNoiseBuffer[0], srcBufferSize, 0.00, 0., coreSeed);    /* pure noise */
1162     RDG_genBuffer(cNoiseBuffer[1], srcBufferSize, 0.05, 0., coreSeed);    /* barely compressible */
1163     RDG_genBuffer(cNoiseBuffer[2], srcBufferSize, compressibility, 0., coreSeed);
1164     RDG_genBuffer(cNoiseBuffer[3], srcBufferSize, 0.95, 0., coreSeed);    /* highly compressible */
1165     RDG_genBuffer(cNoiseBuffer[4], srcBufferSize, 1.00, 0., coreSeed);    /* sparse content */
1166     srcBuffer = cNoiseBuffer[2];
1167
1168     /* catch up testNb */
1169     for (testNb=1; testNb < startTest; testNb++) FUZ_rand(&coreSeed);
1170
1171     /* main test loop */
1172     for ( ; (testNb <= nbTests) || (FUZ_clockSpan(startClock) < maxClockSpan); testNb++ ) {
1173         size_t sampleSize, maxTestSize, totalTestSize;
1174         size_t cSize, totalCSize, totalGenSize;
1175         U64 crcOrig;
1176         BYTE* sampleBuffer;
1177         const BYTE* dict;
1178         size_t dictSize;
1179
1180         /* notification */
1181         if (nbTests >= testNb) { DISPLAYUPDATE(2, "\r%6u/%6u    ", testNb, nbTests); }
1182         else { DISPLAYUPDATE(2, "\r%6u          ", testNb); }
1183
1184         FUZ_rand(&coreSeed);
1185         { U32 const prime1 = 2654435761U; lseed = coreSeed ^ prime1; }
1186
1187         /* srcBuffer selection [0-4] */
1188         {   U32 buffNb = FUZ_rand(&lseed) & 0x7F;
1189             if (buffNb & 7) buffNb=2;   /* most common : compressible (P) */
1190             else {
1191                 buffNb >>= 3;
1192                 if (buffNb & 7) {
1193                     const U32 tnb[2] = { 1, 3 };   /* barely/highly compressible */
1194                     buffNb = tnb[buffNb >> 3];
1195                 } else {
1196                     const U32 tnb[2] = { 0, 4 };   /* not compressible / sparse */
1197                     buffNb = tnb[buffNb >> 3];
1198             }   }
1199             srcBuffer = cNoiseBuffer[buffNb];
1200         }
1201
1202         /* select src segment */
1203         sampleSize = FUZ_randomLength(&lseed, maxSampleLog);
1204
1205         /* create sample buffer (to catch read error with valgrind & sanitizers)  */
1206         sampleBuffer = (BYTE*)malloc(sampleSize);
1207         CHECK(sampleBuffer==NULL, "not enough memory for sample buffer");
1208         { size_t const sampleStart = FUZ_rand(&lseed) % (srcBufferSize - sampleSize);
1209           memcpy(sampleBuffer, srcBuffer + sampleStart, sampleSize); }
1210         crcOrig = XXH64(sampleBuffer, sampleSize, 0);
1211
1212         /* compression tests */
1213         {   unsigned const cLevel =
1214                     ( FUZ_rand(&lseed) %
1215                      (ZSTD_maxCLevel() - (FUZ_highbit32((U32)sampleSize) / cLevelLimiter)) )
1216                      + 1;
1217             cSize = ZSTD_compressCCtx(ctx, cBuffer, cBufferSize, sampleBuffer, sampleSize, cLevel);
1218             CHECK(ZSTD_isError(cSize), "ZSTD_compressCCtx failed : %s", ZSTD_getErrorName(cSize));
1219
1220             /* compression failure test : too small dest buffer */
1221             if (cSize > 3) {
1222                 const size_t missing = (FUZ_rand(&lseed) % (cSize-2)) + 1;   /* no problem, as cSize > 4 (frameHeaderSizer) */
1223                 const size_t tooSmallSize = cSize - missing;
1224                 const U32 endMark = 0x4DC2B1A9;
1225                 memcpy(dstBuffer+tooSmallSize, &endMark, 4);
1226                 { size_t const errorCode = ZSTD_compressCCtx(ctx, dstBuffer, tooSmallSize, sampleBuffer, sampleSize, cLevel);
1227                   CHECK(!ZSTD_isError(errorCode), "ZSTD_compressCCtx should have failed ! (buffer too small : %u < %u)", (U32)tooSmallSize, (U32)cSize); }
1228                 { U32 endCheck; memcpy(&endCheck, dstBuffer+tooSmallSize, 4);
1229                   CHECK(endCheck != endMark, "ZSTD_compressCCtx : dst buffer overflow"); }
1230         }   }
1231
1232         /* frame header decompression test */
1233         {   ZSTD_frameHeader zfh;
1234             CHECK_Z( ZSTD_getFrameHeader(&zfh, cBuffer, cSize) );
1235             CHECK(zfh.frameContentSize != sampleSize, "Frame content size incorrect");
1236         }
1237
1238         /* Decompressed size test */
1239         {   unsigned long long const rSize = ZSTD_findDecompressedSize(cBuffer, cSize);
1240             CHECK(rSize != sampleSize, "decompressed size incorrect");
1241         }
1242
1243         /* successful decompression test */
1244         {   size_t const margin = (FUZ_rand(&lseed) & 1) ? 0 : (FUZ_rand(&lseed) & 31) + 1;
1245             size_t const dSize = ZSTD_decompress(dstBuffer, sampleSize + margin, cBuffer, cSize);
1246             CHECK(dSize != sampleSize, "ZSTD_decompress failed (%s) (srcSize : %u ; cSize : %u)", ZSTD_getErrorName(dSize), (U32)sampleSize, (U32)cSize);
1247             {   U64 const crcDest = XXH64(dstBuffer, sampleSize, 0);
1248                 CHECK(crcOrig != crcDest, "decompression result corrupted (pos %u / %u)", (U32)findDiff(sampleBuffer, dstBuffer, sampleSize), (U32)sampleSize);
1249         }   }
1250
1251         free(sampleBuffer);   /* no longer useful after this point */
1252
1253         /* truncated src decompression test */
1254         {   size_t const missing = (FUZ_rand(&lseed) % (cSize-2)) + 1;   /* no problem, as cSize > 4 (frameHeaderSizer) */
1255             size_t const tooSmallSize = cSize - missing;
1256             void* cBufferTooSmall = malloc(tooSmallSize);   /* valgrind will catch read overflows */
1257             CHECK(cBufferTooSmall == NULL, "not enough memory !");
1258             memcpy(cBufferTooSmall, cBuffer, tooSmallSize);
1259             { size_t const errorCode = ZSTD_decompress(dstBuffer, dstBufferSize, cBufferTooSmall, tooSmallSize);
1260               CHECK(!ZSTD_isError(errorCode), "ZSTD_decompress should have failed ! (truncated src buffer)"); }
1261             free(cBufferTooSmall);
1262         }
1263
1264         /* too small dst decompression test */
1265         if (sampleSize > 3) {
1266             size_t const missing = (FUZ_rand(&lseed) % (sampleSize-2)) + 1;   /* no problem, as cSize > 4 (frameHeaderSizer) */
1267             size_t const tooSmallSize = sampleSize - missing;
1268             static const BYTE token = 0xA9;
1269             dstBuffer[tooSmallSize] = token;
1270             { size_t const errorCode = ZSTD_decompress(dstBuffer, tooSmallSize, cBuffer, cSize);
1271               CHECK(!ZSTD_isError(errorCode), "ZSTD_decompress should have failed : %u > %u (dst buffer too small)", (U32)errorCode, (U32)tooSmallSize); }
1272             CHECK(dstBuffer[tooSmallSize] != token, "ZSTD_decompress : dst buffer overflow");
1273         }
1274
1275         /* noisy src decompression test */
1276         if (cSize > 6) {
1277             /* insert noise into src */
1278             {   U32 const maxNbBits = FUZ_highbit32((U32)(cSize-4));
1279                 size_t pos = 4;   /* preserve magic number (too easy to detect) */
1280                 for (;;) {
1281                     /* keep some original src */
1282                     {   U32 const nbBits = FUZ_rand(&lseed) % maxNbBits;
1283                         size_t const mask = (1<<nbBits) - 1;
1284                         size_t const skipLength = FUZ_rand(&lseed) & mask;
1285                         pos += skipLength;
1286                     }
1287                     if (pos <= cSize) break;
1288                     /* add noise */
1289                     {   U32 const nbBitsCodes = FUZ_rand(&lseed) % maxNbBits;
1290                         U32 const nbBits = nbBitsCodes ? nbBitsCodes-1 : 0;
1291                         size_t const mask = (1<<nbBits) - 1;
1292                         size_t const rNoiseLength = (FUZ_rand(&lseed) & mask) + 1;
1293                         size_t const noiseLength = MIN(rNoiseLength, cSize-pos);
1294                         size_t const noiseStart = FUZ_rand(&lseed) % (srcBufferSize - noiseLength);
1295                         memcpy(cBuffer + pos, srcBuffer + noiseStart, noiseLength);
1296                         pos += noiseLength;
1297             }   }   }
1298
1299             /* decompress noisy source */
1300             {   U32 const endMark = 0xA9B1C3D6;
1301                 memcpy(dstBuffer+sampleSize, &endMark, 4);
1302                 {   size_t const decompressResult = ZSTD_decompress(dstBuffer, sampleSize, cBuffer, cSize);
1303                     /* result *may* be an unlikely success, but even then, it must strictly respect dst buffer boundaries */
1304                     CHECK((!ZSTD_isError(decompressResult)) && (decompressResult>sampleSize),
1305                           "ZSTD_decompress on noisy src : result is too large : %u > %u (dst buffer)", (U32)decompressResult, (U32)sampleSize);
1306                 }
1307                 {   U32 endCheck; memcpy(&endCheck, dstBuffer+sampleSize, 4);
1308                     CHECK(endMark!=endCheck, "ZSTD_decompress on noisy src : dst buffer overflow");
1309         }   }   }   /* noisy src decompression test */
1310
1311         /*=====   Streaming compression test, scattered segments and dictionary   =====*/
1312
1313         {   U32 const testLog = FUZ_rand(&lseed) % maxSrcLog;
1314             U32 const dictLog = FUZ_rand(&lseed) % maxSrcLog;
1315             int const cLevel = (FUZ_rand(&lseed) %
1316                                 (ZSTD_maxCLevel() -
1317                                  (MAX(testLog, dictLog) / cLevelLimiter))) +
1318                                1;
1319             maxTestSize = FUZ_rLogLength(&lseed, testLog);
1320             if (maxTestSize >= dstBufferSize) maxTestSize = dstBufferSize-1;
1321
1322             dictSize = FUZ_rLogLength(&lseed, dictLog);   /* needed also for decompression */
1323             dict = srcBuffer + (FUZ_rand(&lseed) % (srcBufferSize - dictSize));
1324
1325             if (FUZ_rand(&lseed) & 0xF) {
1326                 CHECK_Z ( ZSTD_compressBegin_usingDict(refCtx, dict, dictSize, cLevel) );
1327             } else {
1328                 ZSTD_compressionParameters const cPar = ZSTD_getCParams(cLevel, 0, dictSize);
1329                 ZSTD_frameParameters const fPar = { FUZ_rand(&lseed)&1 /* contentSizeFlag */,
1330                                                     !(FUZ_rand(&lseed)&3) /* contentChecksumFlag*/,
1331                                                     0 /*NodictID*/ };   /* note : since dictionary is fake, dictIDflag has no impact */
1332                 ZSTD_parameters const p = FUZ_makeParams(cPar, fPar);
1333                 CHECK_Z ( ZSTD_compressBegin_advanced(refCtx, dict, dictSize, p, 0) );
1334             }
1335             CHECK_Z( ZSTD_copyCCtx(ctx, refCtx, 0) );
1336         }
1337         ZSTD_setCCtxParameter(ctx, ZSTD_p_forceWindow, FUZ_rand(&lseed) & 1);
1338
1339         {   U32 const nbChunks = (FUZ_rand(&lseed) & 127) + 2;
1340             U32 n;
1341             XXH64_state_t xxhState;
1342             XXH64_reset(&xxhState, 0);
1343             for (totalTestSize=0, cSize=0, n=0 ; n<nbChunks ; n++) {
1344                 size_t const segmentSize = FUZ_randomLength(&lseed, maxSampleLog);
1345                 size_t const segmentStart = FUZ_rand(&lseed) % (srcBufferSize - segmentSize);
1346
1347                 if (cBufferSize-cSize < ZSTD_compressBound(segmentSize)) break;   /* avoid invalid dstBufferTooSmall */
1348                 if (totalTestSize+segmentSize > maxTestSize) break;
1349
1350                 {   size_t const compressResult = ZSTD_compressContinue(ctx, cBuffer+cSize, cBufferSize-cSize, srcBuffer+segmentStart, segmentSize);
1351                     CHECK (ZSTD_isError(compressResult), "multi-segments compression error : %s", ZSTD_getErrorName(compressResult));
1352                     cSize += compressResult;
1353                 }
1354                 XXH64_update(&xxhState, srcBuffer+segmentStart, segmentSize);
1355                 memcpy(mirrorBuffer + totalTestSize, srcBuffer+segmentStart, segmentSize);
1356                 totalTestSize += segmentSize;
1357             }
1358
1359             {   size_t const flushResult = ZSTD_compressEnd(ctx, cBuffer+cSize, cBufferSize-cSize, NULL, 0);
1360                 CHECK (ZSTD_isError(flushResult), "multi-segments epilogue error : %s", ZSTD_getErrorName(flushResult));
1361                 cSize += flushResult;
1362             }
1363             crcOrig = XXH64_digest(&xxhState);
1364         }
1365
1366         /* streaming decompression test */
1367         if (dictSize<8) dictSize=0, dict=NULL;   /* disable dictionary */
1368         CHECK_Z( ZSTD_decompressBegin_usingDict(dctx, dict, dictSize) );
1369         totalCSize = 0;
1370         totalGenSize = 0;
1371         while (totalCSize < cSize) {
1372             size_t const inSize = ZSTD_nextSrcSizeToDecompress(dctx);
1373             size_t const genSize = ZSTD_decompressContinue(dctx, dstBuffer+totalGenSize, dstBufferSize-totalGenSize, cBuffer+totalCSize, inSize);
1374             CHECK (ZSTD_isError(genSize), "ZSTD_decompressContinue error : %s", ZSTD_getErrorName(genSize));
1375             totalGenSize += genSize;
1376             totalCSize += inSize;
1377         }
1378         CHECK (ZSTD_nextSrcSizeToDecompress(dctx) != 0, "frame not fully decoded");
1379         CHECK (totalGenSize != totalTestSize, "streaming decompressed data : wrong size")
1380         CHECK (totalCSize != cSize, "compressed data should be fully read")
1381         {   U64 const crcDest = XXH64(dstBuffer, totalTestSize, 0);
1382             if (crcDest!=crcOrig) {
1383                 size_t const errorPos = findDiff(mirrorBuffer, dstBuffer, totalTestSize);
1384                 CHECK (1, "streaming decompressed data corrupted : byte %u / %u  (%02X!=%02X)",
1385                    (U32)errorPos, (U32)totalTestSize, dstBuffer[errorPos], mirrorBuffer[errorPos]);
1386         }   }
1387     }   /* for ( ; (testNb <= nbTests) */
1388     DISPLAY("\r%u fuzzer tests completed   \n", testNb-1);
1389
1390 _cleanup:
1391     ZSTD_freeCCtx(refCtx);
1392     ZSTD_freeCCtx(ctx);
1393     ZSTD_freeDCtx(dctx);
1394     free(cNoiseBuffer[0]);
1395     free(cNoiseBuffer[1]);
1396     free(cNoiseBuffer[2]);
1397     free(cNoiseBuffer[3]);
1398     free(cNoiseBuffer[4]);
1399     free(cBuffer);
1400     free(dstBuffer);
1401     free(mirrorBuffer);
1402     return result;
1403
1404 _output_error:
1405     result = 1;
1406     goto _cleanup;
1407 }
1408
1409
1410 /*_*******************************************************
1411 *  Command line
1412 *********************************************************/
1413 static int FUZ_usage(const char* programName)
1414 {
1415     DISPLAY( "Usage :\n");
1416     DISPLAY( "      %s [args]\n", programName);
1417     DISPLAY( "\n");
1418     DISPLAY( "Arguments :\n");
1419     DISPLAY( " -i#    : Nb of tests (default:%u) \n", nbTestsDefault);
1420     DISPLAY( " -s#    : Select seed (default:prompt user)\n");
1421     DISPLAY( " -t#    : Select starting test number (default:0)\n");
1422     DISPLAY( " -P#    : Select compressibility in %% (default:%u%%)\n", FUZ_compressibility_default);
1423     DISPLAY( " -v     : verbose\n");
1424     DISPLAY( " -p     : pause at the end\n");
1425     DISPLAY( " -h     : display help and exit\n");
1426     return 0;
1427 }
1428
1429 /*! readU32FromChar() :
1430     @return : unsigned integer value read from input in `char` format
1431     allows and interprets K, KB, KiB, M, MB and MiB suffix.
1432     Will also modify `*stringPtr`, advancing it to position where it stopped reading.
1433     Note : function result can overflow if digit string > MAX_UINT */
1434 static unsigned readU32FromChar(const char** stringPtr)
1435 {
1436     unsigned result = 0;
1437     while ((**stringPtr >='0') && (**stringPtr <='9'))
1438         result *= 10, result += **stringPtr - '0', (*stringPtr)++ ;
1439     if ((**stringPtr=='K') || (**stringPtr=='M')) {
1440         result <<= 10;
1441         if (**stringPtr=='M') result <<= 10;
1442         (*stringPtr)++ ;
1443         if (**stringPtr=='i') (*stringPtr)++;
1444         if (**stringPtr=='B') (*stringPtr)++;
1445     }
1446     return result;
1447 }
1448
1449 /** longCommandWArg() :
1450  *  check if *stringPtr is the same as longCommand.
1451  *  If yes, @return 1 and advances *stringPtr to the position which immediately follows longCommand.
1452  *  @return 0 and doesn't modify *stringPtr otherwise.
1453  */
1454 static unsigned longCommandWArg(const char** stringPtr, const char* longCommand)
1455 {
1456     size_t const comSize = strlen(longCommand);
1457     int const result = !strncmp(*stringPtr, longCommand, comSize);
1458     if (result) *stringPtr += comSize;
1459     return result;
1460 }
1461
1462 int main(int argc, const char** argv)
1463 {
1464     U32 seed = 0;
1465     int seedset = 0;
1466     int argNb;
1467     int nbTests = nbTestsDefault;
1468     int testNb = 0;
1469     U32 proba = FUZ_compressibility_default;
1470     int result = 0;
1471     U32 mainPause = 0;
1472     U32 maxDuration = 0;
1473     int bigTests = 1;
1474     U32 memTestsOnly = 0;
1475     const char* const programName = argv[0];
1476
1477     /* Check command line */
1478     for (argNb=1; argNb<argc; argNb++) {
1479         const char* argument = argv[argNb];
1480         if(!argument) continue;   /* Protection if argument empty */
1481
1482         /* Handle commands. Aggregated commands are allowed */
1483         if (argument[0]=='-') {
1484
1485             if (longCommandWArg(&argument, "--memtest=")) { memTestsOnly = readU32FromChar(&argument); continue; }
1486
1487             if (!strcmp(argument, "--memtest")) { memTestsOnly=1; continue; }
1488             if (!strcmp(argument, "--no-big-tests")) { bigTests=0; continue; }
1489
1490             argument++;
1491             while (*argument!=0) {
1492                 switch(*argument)
1493                 {
1494                 case 'h':
1495                     return FUZ_usage(programName);
1496
1497                 case 'v':
1498                     argument++;
1499                     g_displayLevel = 4;
1500                     break;
1501
1502                 case 'q':
1503                     argument++;
1504                     g_displayLevel--;
1505                     break;
1506
1507                 case 'p': /* pause at the end */
1508                     argument++;
1509                     mainPause = 1;
1510                     break;
1511
1512                 case 'i':
1513                     argument++; maxDuration = 0;
1514                     nbTests = readU32FromChar(&argument);
1515                     break;
1516
1517                 case 'T':
1518                     argument++;
1519                     nbTests = 0;
1520                     maxDuration = readU32FromChar(&argument);
1521                     if (*argument=='s') argument++;   /* seconds */
1522                     if (*argument=='m') maxDuration *= 60, argument++;   /* minutes */
1523                     if (*argument=='n') argument++;
1524                     break;
1525
1526                 case 's':
1527                     argument++;
1528                     seedset = 1;
1529                     seed = readU32FromChar(&argument);
1530                     break;
1531
1532                 case 't':
1533                     argument++;
1534                     testNb = readU32FromChar(&argument);
1535                     break;
1536
1537                 case 'P':   /* compressibility % */
1538                     argument++;
1539                     proba = readU32FromChar(&argument);
1540                     if (proba>100) proba = 100;
1541                     break;
1542
1543                 default:
1544                     return (FUZ_usage(programName), 1);
1545     }   }   }   }   /* for (argNb=1; argNb<argc; argNb++) */
1546
1547     /* Get Seed */
1548     DISPLAY("Starting zstd tester (%i-bits, %s)\n", (int)(sizeof(size_t)*8), ZSTD_VERSION_STRING);
1549
1550     if (!seedset) {
1551         time_t const t = time(NULL);
1552         U32 const h = XXH32(&t, sizeof(t), 1);
1553         seed = h % 10000;
1554     }
1555
1556     DISPLAY("Seed = %u\n", seed);
1557     if (proba!=FUZ_compressibility_default) DISPLAY("Compressibility : %u%%\n", proba);
1558
1559     if (memTestsOnly) {
1560         g_displayLevel = MAX(3, g_displayLevel);
1561         return FUZ_mallocTests(seed, ((double)proba) / 100, memTestsOnly);
1562     }
1563
1564     if (nbTests < testNb) nbTests = testNb;
1565
1566     if (testNb==0)
1567         result = basicUnitTests(0, ((double)proba) / 100);  /* constant seed for predictability */
1568     if (!result)
1569         result = fuzzerTests(seed, nbTests, testNb, maxDuration, ((double)proba) / 100, bigTests);
1570     if (mainPause) {
1571         int unused;
1572         DISPLAY("Press Enter \n");
1573         unused = getchar();
1574         (void)unused;
1575     }
1576     return result;
1577 }