]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - sys/contrib/zstd/tests/fuzzer.c
libfdt: Update to 1.4.6, switch to using libfdt for overlay support
[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 <time.h>         /* clock_t */
29 #define ZSTD_STATIC_LINKING_ONLY  /* ZSTD_compressContinue, ZSTD_compressBlock */
30 #include "zstd.h"         /* ZSTD_VERSION_STRING */
31 #include "zstd_errors.h"  /* ZSTD_getErrorCode */
32 #include "zstdmt_compress.h"
33 #define ZDICT_STATIC_LINKING_ONLY
34 #include "zdict.h"        /* ZDICT_trainFromBuffer */
35 #include "datagen.h"      /* RDG_genBuffer */
36 #include "mem.h"
37 #define XXH_STATIC_LINKING_ONLY
38 #include "xxhash.h"       /* XXH64 */
39
40
41 /*-************************************
42 *  Constants
43 **************************************/
44 #define KB *(1U<<10)
45 #define MB *(1U<<20)
46 #define GB *(1U<<30)
47
48 static const U32 FUZ_compressibility_default = 50;
49 static const U32 nbTestsDefault = 30000;
50
51
52 /*-************************************
53 *  Display Macros
54 **************************************/
55 #define DISPLAY(...)          fprintf(stdout, __VA_ARGS__)
56 #define DISPLAYLEVEL(l, ...)  if (g_displayLevel>=l) { DISPLAY(__VA_ARGS__); }
57 static U32 g_displayLevel = 2;
58
59 #define DISPLAYUPDATE(l, ...) if (g_displayLevel>=l) { \
60             if ((FUZ_clockSpan(g_displayClock) > g_refreshRate) || (g_displayLevel>=4)) \
61             { g_displayClock = clock(); DISPLAY(__VA_ARGS__); \
62             if (g_displayLevel>=4) fflush(stdout); } }
63 static const clock_t g_refreshRate = CLOCKS_PER_SEC / 6;
64 static clock_t g_displayClock = 0;
65
66
67 /*-*******************************************************
68 *  Fuzzer functions
69 *********************************************************/
70 #define MIN(a,b) ((a)<(b)?(a):(b))
71 #define MAX(a,b) ((a)>(b)?(a):(b))
72
73 static clock_t FUZ_clockSpan(clock_t cStart)
74 {
75     return clock() - cStart;   /* works even when overflow; max span ~ 30mn */
76 }
77
78 #define FUZ_rotl32(x,r) ((x << r) | (x >> (32 - r)))
79 static unsigned FUZ_rand(unsigned* src)
80 {
81     static const U32 prime1 = 2654435761U;
82     static const U32 prime2 = 2246822519U;
83     U32 rand32 = *src;
84     rand32 *= prime1;
85     rand32 += prime2;
86     rand32  = FUZ_rotl32(rand32, 13);
87     *src = rand32;
88     return rand32 >> 5;
89 }
90
91 static unsigned FUZ_highbit32(U32 v32)
92 {
93     unsigned nbBits = 0;
94     if (v32==0) return 0;
95     while (v32) v32 >>= 1, nbBits++;
96     return nbBits;
97 }
98
99
100 /*=============================================
101 *   Memory Tests
102 =============================================*/
103 #if defined(__APPLE__) && defined(__MACH__)
104
105 #include <malloc/malloc.h>    /* malloc_size */
106
107 typedef struct {
108     unsigned long long totalMalloc;
109     size_t currentMalloc;
110     size_t peakMalloc;
111     unsigned nbMalloc;
112     unsigned nbFree;
113 } mallocCounter_t;
114
115 static const mallocCounter_t INIT_MALLOC_COUNTER = { 0, 0, 0, 0, 0 };
116
117 static void* FUZ_mallocDebug(void* counter, size_t size)
118 {
119     mallocCounter_t* const mcPtr = (mallocCounter_t*)counter;
120     void* const ptr = malloc(size);
121     if (ptr==NULL) return NULL;
122     DISPLAYLEVEL(4, "allocating %u KB => effectively %u KB \n",
123         (U32)(size >> 10), (U32)(malloc_size(ptr) >> 10));  /* OS-X specific */
124     mcPtr->totalMalloc += size;
125     mcPtr->currentMalloc += size;
126     if (mcPtr->currentMalloc > mcPtr->peakMalloc)
127         mcPtr->peakMalloc = mcPtr->currentMalloc;
128     mcPtr->nbMalloc += 1;
129     return ptr;
130 }
131
132 static void FUZ_freeDebug(void* counter, void* address)
133 {
134     mallocCounter_t* const mcPtr = (mallocCounter_t*)counter;
135     DISPLAYLEVEL(4, "freeing %u KB \n", (U32)(malloc_size(address) >> 10));
136     mcPtr->nbFree += 1;
137     mcPtr->currentMalloc -= malloc_size(address);  /* OS-X specific */
138     free(address);
139 }
140
141 static void FUZ_displayMallocStats(mallocCounter_t count)
142 {
143     DISPLAYLEVEL(3, "peak:%6u KB,  nbMallocs:%2u, total:%6u KB \n",
144         (U32)(count.peakMalloc >> 10),
145         count.nbMalloc,
146         (U32)(count.totalMalloc >> 10));
147 }
148
149 #define CHECK_Z(f) {                               \
150     size_t const err = f;                          \
151     if (ZSTD_isError(err)) {                       \
152         DISPLAY("Error => %s : %s ",               \
153                 #f, ZSTD_getErrorName(err));       \
154         exit(1);                                   \
155 }   }
156
157 static int FUZ_mallocTests(unsigned seed, double compressibility, unsigned part)
158 {
159     size_t const inSize = 64 MB + 16 MB + 4 MB + 1 MB + 256 KB + 64 KB; /* 85.3 MB */
160     size_t const outSize = ZSTD_compressBound(inSize);
161     void* const inBuffer = malloc(inSize);
162     void* const outBuffer = malloc(outSize);
163
164     /* test only played in verbose mode, as they are long */
165     if (g_displayLevel<3) return 0;
166
167     /* Create compressible noise */
168     if (!inBuffer || !outBuffer) {
169         DISPLAY("Not enough memory, aborting\n");
170         exit(1);
171     }
172     RDG_genBuffer(inBuffer, inSize, compressibility, 0. /*auto*/, seed);
173
174     /* simple compression tests */
175     if (part <= 1)
176     {   int compressionLevel;
177         for (compressionLevel=1; compressionLevel<=6; compressionLevel++) {
178             mallocCounter_t malcount = INIT_MALLOC_COUNTER;
179             ZSTD_customMem const cMem = { FUZ_mallocDebug, FUZ_freeDebug, &malcount };
180             ZSTD_CCtx* const cctx = ZSTD_createCCtx_advanced(cMem);
181             CHECK_Z( ZSTD_compressCCtx(cctx, outBuffer, outSize, inBuffer, inSize, compressionLevel) );
182             ZSTD_freeCCtx(cctx);
183             DISPLAYLEVEL(3, "compressCCtx level %i : ", compressionLevel);
184             FUZ_displayMallocStats(malcount);
185     }   }
186
187     /* streaming compression tests */
188     if (part <= 2)
189     {   int compressionLevel;
190         for (compressionLevel=1; compressionLevel<=6; compressionLevel++) {
191             mallocCounter_t malcount = INIT_MALLOC_COUNTER;
192             ZSTD_customMem const cMem = { FUZ_mallocDebug, FUZ_freeDebug, &malcount };
193             ZSTD_CCtx* const cstream = ZSTD_createCStream_advanced(cMem);
194             ZSTD_outBuffer out = { outBuffer, outSize, 0 };
195             ZSTD_inBuffer in = { inBuffer, inSize, 0 };
196             CHECK_Z( ZSTD_initCStream(cstream, compressionLevel) );
197             CHECK_Z( ZSTD_compressStream(cstream, &out, &in) );
198             CHECK_Z( ZSTD_endStream(cstream, &out) );
199             ZSTD_freeCStream(cstream);
200             DISPLAYLEVEL(3, "compressStream level %i : ", compressionLevel);
201             FUZ_displayMallocStats(malcount);
202     }   }
203
204     /* advanced MT API test */
205     if (part <= 3)
206     {   U32 nbThreads;
207         for (nbThreads=1; nbThreads<=4; nbThreads++) {
208             int compressionLevel;
209             for (compressionLevel=1; compressionLevel<=6; compressionLevel++) {
210                 mallocCounter_t malcount = INIT_MALLOC_COUNTER;
211                 ZSTD_customMem const cMem = { FUZ_mallocDebug, FUZ_freeDebug, &malcount };
212                 ZSTD_CCtx* const cctx = ZSTD_createCCtx_advanced(cMem);
213                 ZSTD_outBuffer out = { outBuffer, outSize, 0 };
214                 ZSTD_inBuffer in = { inBuffer, inSize, 0 };
215                 CHECK_Z( ZSTD_CCtx_setParameter(cctx, ZSTD_p_compressionLevel, (U32)compressionLevel) );
216                 CHECK_Z( ZSTD_CCtx_setParameter(cctx, ZSTD_p_nbThreads, nbThreads) );
217                 while ( ZSTD_compress_generic(cctx, &out, &in, ZSTD_e_end) ) {}
218                 ZSTD_freeCCtx(cctx);
219                 DISPLAYLEVEL(3, "compress_generic,-T%u,end level %i : ",
220                                 nbThreads, compressionLevel);
221                 FUZ_displayMallocStats(malcount);
222     }   }   }
223
224     /* advanced MT streaming API test */
225     if (part <= 4)
226     {   U32 nbThreads;
227         for (nbThreads=1; nbThreads<=4; nbThreads++) {
228             int compressionLevel;
229             for (compressionLevel=1; compressionLevel<=6; compressionLevel++) {
230                 mallocCounter_t malcount = INIT_MALLOC_COUNTER;
231                 ZSTD_customMem const cMem = { FUZ_mallocDebug, FUZ_freeDebug, &malcount };
232                 ZSTD_CCtx* const cctx = ZSTD_createCCtx_advanced(cMem);
233                 ZSTD_outBuffer out = { outBuffer, outSize, 0 };
234                 ZSTD_inBuffer in = { inBuffer, inSize, 0 };
235                 CHECK_Z( ZSTD_CCtx_setParameter(cctx, ZSTD_p_compressionLevel, (U32)compressionLevel) );
236                 CHECK_Z( ZSTD_CCtx_setParameter(cctx, ZSTD_p_nbThreads, nbThreads) );
237                 CHECK_Z( ZSTD_compress_generic(cctx, &out, &in, ZSTD_e_continue) );
238                 while ( ZSTD_compress_generic(cctx, &out, &in, ZSTD_e_end) ) {}
239                 ZSTD_freeCCtx(cctx);
240                 DISPLAYLEVEL(3, "compress_generic,-T%u,continue level %i : ",
241                                 nbThreads, compressionLevel);
242                 FUZ_displayMallocStats(malcount);
243     }   }   }
244
245     return 0;
246 }
247
248 #else
249
250 static int FUZ_mallocTests(unsigned seed, double compressibility, unsigned part)
251 {
252     (void)seed; (void)compressibility; (void)part;
253     return 0;
254 }
255
256 #endif
257
258 /*=============================================
259 *   Unit tests
260 =============================================*/
261
262 #define CHECK_V(var, fn)  size_t const var = fn; if (ZSTD_isError(var)) goto _output_error
263 #define CHECK(fn)  { CHECK_V(err, fn); }
264 #define CHECKPLUS(var, fn, more)  { CHECK_V(var, fn); more; }
265
266 static int basicUnitTests(U32 seed, double compressibility)
267 {
268     size_t const CNBuffSize = 5 MB;
269     void* const CNBuffer = malloc(CNBuffSize);
270     size_t const compressedBufferSize = ZSTD_compressBound(CNBuffSize);
271     void* const compressedBuffer = malloc(compressedBufferSize);
272     void* const decodedBuffer = malloc(CNBuffSize);
273     ZSTD_DCtx* dctx = ZSTD_createDCtx();
274     int testResult = 0;
275     U32 testNb=0;
276     size_t cSize;
277
278     /* Create compressible noise */
279     if (!CNBuffer || !compressedBuffer || !decodedBuffer) {
280         DISPLAY("Not enough memory, aborting\n");
281         testResult = 1;
282         goto _end;
283     }
284     RDG_genBuffer(CNBuffer, CNBuffSize, compressibility, 0., seed);
285
286     /* Basic tests */
287     DISPLAYLEVEL(4, "test%3i : ZSTD_getErrorName : ", testNb++);
288     {   const char* errorString = ZSTD_getErrorName(0);
289         DISPLAYLEVEL(4, "OK : %s \n", errorString);
290     }
291
292     DISPLAYLEVEL(4, "test%3i : ZSTD_getErrorName with wrong value : ", testNb++);
293     {   const char* errorString = ZSTD_getErrorName(499);
294         DISPLAYLEVEL(4, "OK : %s \n", errorString);
295     }
296
297
298     DISPLAYLEVEL(4, "test%3i : compress %u bytes : ", testNb++, (U32)CNBuffSize);
299     {   ZSTD_CCtx* cctx = ZSTD_createCCtx();
300         if (cctx==NULL) goto _output_error;
301         CHECKPLUS(r, ZSTD_compressCCtx(cctx,
302                             compressedBuffer, compressedBufferSize,
303                             CNBuffer, CNBuffSize, 1),
304                   cSize=r );
305         DISPLAYLEVEL(4, "OK (%u bytes : %.2f%%)\n", (U32)cSize, (double)cSize/CNBuffSize*100);
306
307         DISPLAYLEVEL(4, "test%3i : size of cctx for level 1 : ", testNb++);
308         {   size_t const cctxSize = ZSTD_sizeof_CCtx(cctx);
309             DISPLAYLEVEL(4, "%u bytes \n", (U32)cctxSize);
310         }
311         ZSTD_freeCCtx(cctx);
312     }
313
314
315     DISPLAYLEVEL(4, "test%3i : ZSTD_getFrameContentSize test : ", testNb++);
316     {   unsigned long long const rSize = ZSTD_getFrameContentSize(compressedBuffer, cSize);
317         if (rSize != CNBuffSize) goto _output_error;
318     }
319     DISPLAYLEVEL(4, "OK \n");
320
321     DISPLAYLEVEL(4, "test%3i : ZSTD_findDecompressedSize test : ", testNb++);
322     {   unsigned long long const rSize = ZSTD_findDecompressedSize(compressedBuffer, cSize);
323         if (rSize != CNBuffSize) goto _output_error;
324     }
325     DISPLAYLEVEL(4, "OK \n");
326
327     DISPLAYLEVEL(4, "test%3i : decompress %u bytes : ", testNb++, (U32)CNBuffSize);
328     { size_t const r = ZSTD_decompress(decodedBuffer, CNBuffSize, compressedBuffer, cSize);
329       if (r != CNBuffSize) goto _output_error; }
330     DISPLAYLEVEL(4, "OK \n");
331
332     DISPLAYLEVEL(4, "test%3i : check decompressed result : ", testNb++);
333     {   size_t u;
334         for (u=0; u<CNBuffSize; u++) {
335             if (((BYTE*)decodedBuffer)[u] != ((BYTE*)CNBuffer)[u]) goto _output_error;;
336     }   }
337     DISPLAYLEVEL(4, "OK \n");
338
339
340     DISPLAYLEVEL(4, "test%3i : decompress with null dict : ", testNb++);
341     { size_t const r = ZSTD_decompress_usingDict(dctx, decodedBuffer, CNBuffSize, compressedBuffer, cSize, NULL, 0);
342       if (r != CNBuffSize) goto _output_error; }
343     DISPLAYLEVEL(4, "OK \n");
344
345     DISPLAYLEVEL(4, "test%3i : decompress with null DDict : ", testNb++);
346     { size_t const r = ZSTD_decompress_usingDDict(dctx, decodedBuffer, CNBuffSize, compressedBuffer, cSize, NULL);
347       if (r != CNBuffSize) goto _output_error; }
348     DISPLAYLEVEL(4, "OK \n");
349
350     DISPLAYLEVEL(4, "test%3i : decompress with 1 missing byte : ", testNb++);
351     { size_t const r = ZSTD_decompress(decodedBuffer, CNBuffSize, compressedBuffer, cSize-1);
352       if (!ZSTD_isError(r)) goto _output_error;
353       if (ZSTD_getErrorCode((size_t)r) != ZSTD_error_srcSize_wrong) goto _output_error; }
354     DISPLAYLEVEL(4, "OK \n");
355
356     DISPLAYLEVEL(4, "test%3i : decompress with 1 too much byte : ", testNb++);
357     { size_t const r = ZSTD_decompress(decodedBuffer, CNBuffSize, compressedBuffer, cSize+1);
358       if (!ZSTD_isError(r)) goto _output_error;
359       if (ZSTD_getErrorCode(r) != ZSTD_error_srcSize_wrong) goto _output_error; }
360     DISPLAYLEVEL(4, "OK \n");
361
362
363     /* Static CCtx tests */
364 #define STATIC_CCTX_LEVEL 3
365     DISPLAYLEVEL(4, "test%3i : create static CCtx for level %u :", testNb++, STATIC_CCTX_LEVEL);
366     {   size_t const staticCCtxSize = ZSTD_estimateCStreamSize(STATIC_CCTX_LEVEL);
367         void* const staticCCtxBuffer = malloc(staticCCtxSize);
368         size_t const staticDCtxSize = ZSTD_estimateDCtxSize();
369         void* const staticDCtxBuffer = malloc(staticDCtxSize);
370         if (staticCCtxBuffer==NULL || staticDCtxBuffer==NULL) {
371             free(staticCCtxBuffer);
372             free(staticDCtxBuffer);
373             DISPLAY("Not enough memory, aborting\n");
374             testResult = 1;
375             goto _end;
376         }
377         {   ZSTD_CCtx* staticCCtx = ZSTD_initStaticCCtx(staticCCtxBuffer, staticCCtxSize);
378             ZSTD_DCtx* staticDCtx = ZSTD_initStaticDCtx(staticDCtxBuffer, staticDCtxSize);
379             if ((staticCCtx==NULL) || (staticDCtx==NULL)) goto _output_error;
380             DISPLAYLEVEL(4, "OK \n");
381
382             DISPLAYLEVEL(4, "test%3i : init CCtx for level %u : ", testNb++, STATIC_CCTX_LEVEL);
383             { size_t const r = ZSTD_compressBegin(staticCCtx, STATIC_CCTX_LEVEL);
384               if (ZSTD_isError(r)) goto _output_error; }
385             DISPLAYLEVEL(4, "OK \n");
386
387             DISPLAYLEVEL(4, "test%3i : simple compression test with static CCtx : ", testNb++);
388             CHECKPLUS(r, ZSTD_compressCCtx(staticCCtx,
389                             compressedBuffer, compressedBufferSize,
390                             CNBuffer, CNBuffSize, STATIC_CCTX_LEVEL),
391                       cSize=r );
392             DISPLAYLEVEL(4, "OK (%u bytes : %.2f%%)\n",
393                             (U32)cSize, (double)cSize/CNBuffSize*100);
394
395             DISPLAYLEVEL(4, "test%3i : simple decompression test with static DCtx : ", testNb++);
396             { size_t const r = ZSTD_decompressDCtx(staticDCtx,
397                                                 decodedBuffer, CNBuffSize,
398                                                 compressedBuffer, cSize);
399               if (r != CNBuffSize) goto _output_error; }
400             DISPLAYLEVEL(4, "OK \n");
401
402             DISPLAYLEVEL(4, "test%3i : check decompressed result : ", testNb++);
403             {   size_t u;
404                 for (u=0; u<CNBuffSize; u++) {
405                     if (((BYTE*)decodedBuffer)[u] != ((BYTE*)CNBuffer)[u])
406                         goto _output_error;;
407             }   }
408             DISPLAYLEVEL(4, "OK \n");
409
410             DISPLAYLEVEL(4, "test%3i : init CCtx for too large level (must fail) : ", testNb++);
411             { size_t const r = ZSTD_compressBegin(staticCCtx, ZSTD_maxCLevel());
412               if (!ZSTD_isError(r)) goto _output_error; }
413             DISPLAYLEVEL(4, "OK \n");
414
415             DISPLAYLEVEL(4, "test%3i : init CCtx for small level %u (should work again) : ", testNb++, 1);
416             { size_t const r = ZSTD_compressBegin(staticCCtx, 1);
417               if (ZSTD_isError(r)) goto _output_error; }
418             DISPLAYLEVEL(4, "OK \n");
419
420             DISPLAYLEVEL(4, "test%3i : init CStream for small level %u : ", testNb++, 1);
421             { size_t const r = ZSTD_initCStream(staticCCtx, 1);
422               if (ZSTD_isError(r)) goto _output_error; }
423             DISPLAYLEVEL(4, "OK \n");
424
425             DISPLAYLEVEL(4, "test%3i : init CStream with dictionary (should fail) : ", testNb++);
426             { size_t const r = ZSTD_initCStream_usingDict(staticCCtx, CNBuffer, 64 KB, 1);
427               if (!ZSTD_isError(r)) goto _output_error; }
428             DISPLAYLEVEL(4, "OK \n");
429
430             DISPLAYLEVEL(4, "test%3i : init DStream (should fail) : ", testNb++);
431             { size_t const r = ZSTD_initDStream(staticDCtx);
432               if (ZSTD_isError(r)) goto _output_error; }
433             {   ZSTD_outBuffer output = { decodedBuffer, CNBuffSize, 0 };
434                 ZSTD_inBuffer input = { compressedBuffer, ZSTD_FRAMEHEADERSIZE_MAX+1, 0 };
435                 size_t const r = ZSTD_decompressStream(staticDCtx, &output, &input);
436                 if (!ZSTD_isError(r)) goto _output_error;
437             }
438             DISPLAYLEVEL(4, "OK \n");
439         }
440         free(staticCCtxBuffer);
441         free(staticDCtxBuffer);
442     }
443
444
445
446     /* ZSTDMT simple MT compression test */
447     DISPLAYLEVEL(4, "test%3i : create ZSTDMT CCtx : ", testNb++);
448     {   ZSTDMT_CCtx* mtctx = ZSTDMT_createCCtx(2);
449         if (mtctx==NULL) {
450             DISPLAY("mtctx : mot enough memory, aborting \n");
451             testResult = 1;
452             goto _end;
453         }
454         DISPLAYLEVEL(4, "OK \n");
455
456         DISPLAYLEVEL(4, "test%3i : compress %u bytes with 2 threads : ", testNb++, (U32)CNBuffSize);
457         CHECKPLUS(r, ZSTDMT_compressCCtx(mtctx,
458                                 compressedBuffer, compressedBufferSize,
459                                 CNBuffer, CNBuffSize,
460                                 1),
461                   cSize=r );
462         DISPLAYLEVEL(4, "OK (%u bytes : %.2f%%)\n", (U32)cSize, (double)cSize/CNBuffSize*100);
463
464         DISPLAYLEVEL(4, "test%3i : decompressed size test : ", testNb++);
465         {   unsigned long long const rSize = ZSTD_getFrameContentSize(compressedBuffer, cSize);
466             if (rSize != CNBuffSize)  {
467                 DISPLAY("ZSTD_getFrameContentSize incorrect : %u != %u \n", (U32)rSize, (U32)CNBuffSize);
468                 goto _output_error;
469         }   }
470         DISPLAYLEVEL(4, "OK \n");
471
472         DISPLAYLEVEL(4, "test%3i : decompress %u bytes : ", testNb++, (U32)CNBuffSize);
473         { size_t const r = ZSTD_decompress(decodedBuffer, CNBuffSize, compressedBuffer, cSize);
474           if (r != CNBuffSize) goto _output_error; }
475         DISPLAYLEVEL(4, "OK \n");
476
477         DISPLAYLEVEL(4, "test%3i : check decompressed result : ", testNb++);
478         {   size_t u;
479             for (u=0; u<CNBuffSize; u++) {
480                 if (((BYTE*)decodedBuffer)[u] != ((BYTE*)CNBuffer)[u]) goto _output_error;;
481         }   }
482         DISPLAYLEVEL(4, "OK \n");
483
484         DISPLAYLEVEL(4, "test%3i : compress -T2 with checksum : ", testNb++);
485         {   ZSTD_parameters params = ZSTD_getParams(1, CNBuffSize, 0);
486             params.fParams.checksumFlag = 1;
487             params.fParams.contentSizeFlag = 1;
488             CHECKPLUS(r, ZSTDMT_compress_advanced(mtctx,
489                                     compressedBuffer, compressedBufferSize,
490                                     CNBuffer, CNBuffSize,
491                                     NULL, params, 3 /*overlapRLog*/),
492                       cSize=r );
493         }
494         DISPLAYLEVEL(4, "OK (%u bytes : %.2f%%)\n", (U32)cSize, (double)cSize/CNBuffSize*100);
495
496         DISPLAYLEVEL(4, "test%3i : decompress %u bytes : ", testNb++, (U32)CNBuffSize);
497         { size_t const r = ZSTD_decompress(decodedBuffer, CNBuffSize, compressedBuffer, cSize);
498           if (r != CNBuffSize) goto _output_error; }
499         DISPLAYLEVEL(4, "OK \n");
500
501         ZSTDMT_freeCCtx(mtctx);
502     }
503
504
505     /* Simple API multiframe test */
506     DISPLAYLEVEL(4, "test%3i : compress multiple frames : ", testNb++);
507     {   size_t off = 0;
508         int i;
509         int const segs = 4;
510         /* only use the first half so we don't push against size limit of compressedBuffer */
511         size_t const segSize = (CNBuffSize / 2) / segs;
512         for (i = 0; i < segs; i++) {
513             CHECK_V(r, 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, ZSTD_dlm_byCopy);
602             void* ddictBuffer = malloc(ddictBufferSize);
603             if (ddictBuffer == NULL) goto _output_error;
604             {   ZSTD_DDict* const ddict = ZSTD_initStaticDDict(ddictBuffer, ddictBufferSize, CNBuffer, dictSize, ZSTD_dlm_byCopy);
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, ZSTD_dlm_byRef);
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                                             ZSTD_dlm_byRef, 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, ZSTD_dlm_byCopy);
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                                             ZSTD_dlm_byCopy, 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, ZSTD_dlm_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, ZSTD_dlm_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, ZSTD_dlm_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         DISPLAYLEVEL(4, "test%3i : Loading rawContent starting with dict header w/ ZSTD_dm_auto should fail : ", testNb++);
814         {
815             size_t ret;
816             MEM_writeLE32((char*)dictBuffer+2, ZSTD_MAGIC_DICTIONARY);
817             ret = ZSTD_CCtx_loadDictionary_advanced(
818                     cctx, (const char*)dictBuffer+2, dictSize-2, ZSTD_dlm_byRef, ZSTD_dm_auto);
819             if (!ZSTD_isError(ret)) goto _output_error;
820         }
821         DISPLAYLEVEL(4, "OK \n");
822
823         DISPLAYLEVEL(4, "test%3i : Loading rawContent starting with dict header w/ ZSTD_dm_rawContent should pass : ", testNb++);
824         {
825             size_t ret;
826             MEM_writeLE32((char*)dictBuffer+2, ZSTD_MAGIC_DICTIONARY);
827             ret = ZSTD_CCtx_loadDictionary_advanced(
828                     cctx, (const char*)dictBuffer+2, dictSize-2, ZSTD_dlm_byRef, ZSTD_dm_rawContent);
829             if (ZSTD_isError(ret)) goto _output_error;
830         }
831         DISPLAYLEVEL(4, "OK \n");
832
833         ZSTD_freeCCtx(cctx);
834         free(dictBuffer);
835         free(samplesSizes);
836     }
837
838     /* COVER dictionary builder tests */
839     {   ZSTD_CCtx* const cctx = ZSTD_createCCtx();
840         size_t dictSize = 16 KB;
841         size_t optDictSize = dictSize;
842         void* dictBuffer = malloc(dictSize);
843         size_t const totalSampleSize = 1 MB;
844         size_t const sampleUnitSize = 8 KB;
845         U32 const nbSamples = (U32)(totalSampleSize / sampleUnitSize);
846         size_t* const samplesSizes = (size_t*) malloc(nbSamples * sizeof(size_t));
847         ZDICT_cover_params_t params;
848         U32 dictID;
849
850         if (dictBuffer==NULL || samplesSizes==NULL) {
851             free(dictBuffer);
852             free(samplesSizes);
853             goto _output_error;
854         }
855
856         DISPLAYLEVEL(4, "test%3i : ZDICT_trainFromBuffer_cover : ", testNb++);
857         { U32 u; for (u=0; u<nbSamples; u++) samplesSizes[u] = sampleUnitSize; }
858         memset(&params, 0, sizeof(params));
859         params.d = 1 + (FUZ_rand(&seed) % 16);
860         params.k = params.d + (FUZ_rand(&seed) % 256);
861         dictSize = ZDICT_trainFromBuffer_cover(dictBuffer, dictSize,
862                                                CNBuffer, samplesSizes, nbSamples,
863                                                params);
864         if (ZDICT_isError(dictSize)) goto _output_error;
865         DISPLAYLEVEL(4, "OK, created dictionary of size %u \n", (U32)dictSize);
866
867         DISPLAYLEVEL(4, "test%3i : check dictID : ", testNb++);
868         dictID = ZDICT_getDictID(dictBuffer, dictSize);
869         if (dictID==0) goto _output_error;
870         DISPLAYLEVEL(4, "OK : %u \n", dictID);
871
872         DISPLAYLEVEL(4, "test%3i : ZDICT_optimizeTrainFromBuffer_cover : ", testNb++);
873         memset(&params, 0, sizeof(params));
874         params.steps = 4;
875         optDictSize = ZDICT_optimizeTrainFromBuffer_cover(dictBuffer, optDictSize,
876                                                           CNBuffer, samplesSizes,
877                                                           nbSamples / 4, &params);
878         if (ZDICT_isError(optDictSize)) goto _output_error;
879         DISPLAYLEVEL(4, "OK, created dictionary of size %u \n", (U32)optDictSize);
880
881         DISPLAYLEVEL(4, "test%3i : check dictID : ", testNb++);
882         dictID = ZDICT_getDictID(dictBuffer, optDictSize);
883         if (dictID==0) goto _output_error;
884         DISPLAYLEVEL(4, "OK : %u \n", dictID);
885
886         ZSTD_freeCCtx(cctx);
887         free(dictBuffer);
888         free(samplesSizes);
889     }
890
891     /* Decompression defense tests */
892     DISPLAYLEVEL(4, "test%3i : Check input length for magic number : ", testNb++);
893     { size_t const r = ZSTD_decompress(decodedBuffer, CNBuffSize, CNBuffer, 3);   /* too small input */
894       if (!ZSTD_isError(r)) goto _output_error;
895       if (ZSTD_getErrorCode(r) != ZSTD_error_srcSize_wrong) goto _output_error; }
896     DISPLAYLEVEL(4, "OK \n");
897
898     DISPLAYLEVEL(4, "test%3i : Check magic Number : ", testNb++);
899     ((char*)(CNBuffer))[0] = 1;
900     { size_t const r = ZSTD_decompress(decodedBuffer, CNBuffSize, CNBuffer, 4);
901       if (!ZSTD_isError(r)) goto _output_error; }
902     DISPLAYLEVEL(4, "OK \n");
903
904     /* content size verification test */
905     DISPLAYLEVEL(4, "test%3i : Content size verification : ", testNb++);
906     {   ZSTD_CCtx* const cctx = ZSTD_createCCtx();
907         size_t const srcSize = 5000;
908         size_t const wrongSrcSize = (srcSize + 1000);
909         ZSTD_parameters params = ZSTD_getParams(1, wrongSrcSize, 0);
910         params.fParams.contentSizeFlag = 1;
911         CHECK( ZSTD_compressBegin_advanced(cctx, NULL, 0, params, wrongSrcSize) );
912         {   size_t const result = ZSTD_compressEnd(cctx, decodedBuffer, CNBuffSize, CNBuffer, srcSize);
913             if (!ZSTD_isError(result)) goto _output_error;
914             if (ZSTD_getErrorCode(result) != ZSTD_error_srcSize_wrong) goto _output_error;
915             DISPLAYLEVEL(4, "OK : %s \n", ZSTD_getErrorName(result));
916         }
917         ZSTD_freeCCtx(cctx);
918     }
919
920     /* custom formats tests */
921     {   ZSTD_CCtx* const cctx = ZSTD_createCCtx();
922         size_t const inputSize = CNBuffSize / 2;   /* won't cause pb with small dict size */
923
924         /* basic block compression */
925         DISPLAYLEVEL(4, "test%3i : magic-less format test : ", testNb++);
926         CHECK( ZSTD_CCtx_setParameter(cctx, ZSTD_p_format, ZSTD_f_zstd1_magicless) );
927         {   ZSTD_inBuffer in = { CNBuffer, inputSize, 0 };
928             ZSTD_outBuffer out = { compressedBuffer, ZSTD_compressBound(inputSize), 0 };
929             size_t const result = ZSTD_compress_generic(cctx, &out, &in, ZSTD_e_end);
930             if (result != 0) goto _output_error;
931             if (in.pos != in.size) goto _output_error;
932             cSize = out.pos;
933         }
934         DISPLAYLEVEL(4, "OK (compress : %u -> %u bytes)\n", (U32)inputSize, (U32)cSize);
935
936         DISPLAYLEVEL(4, "test%3i : decompress normally (should fail) : ", testNb++);
937         {   size_t const decodeResult = ZSTD_decompressDCtx(dctx, decodedBuffer, CNBuffSize, compressedBuffer, cSize);
938             if (ZSTD_getErrorCode(decodeResult) != ZSTD_error_prefix_unknown) goto _output_error;
939             DISPLAYLEVEL(4, "OK : %s \n", ZSTD_getErrorName(decodeResult));
940         }
941
942         DISPLAYLEVEL(4, "test%3i : decompress with magic-less instruction : ", testNb++);
943         ZSTD_DCtx_reset(dctx);
944         CHECK( ZSTD_DCtx_setFormat(dctx, ZSTD_f_zstd1_magicless) );
945         {   ZSTD_inBuffer in = { compressedBuffer, cSize, 0 };
946             ZSTD_outBuffer out = { decodedBuffer, CNBuffSize, 0 };
947             size_t const result = ZSTD_decompress_generic(dctx, &out, &in);
948             if (result != 0) goto _output_error;
949             if (in.pos != in.size) goto _output_error;
950             if (out.pos != inputSize) goto _output_error;
951             DISPLAYLEVEL(4, "OK : regenerated %u bytes \n", (U32)out.pos);
952         }
953
954         ZSTD_freeCCtx(cctx);
955     }
956
957     /* block API tests */
958     {   ZSTD_CCtx* const cctx = ZSTD_createCCtx();
959         static const size_t dictSize = 65 KB;
960         static const size_t blockSize = 100 KB;   /* won't cause pb with small dict size */
961         size_t cSize2;
962
963         /* basic block compression */
964         DISPLAYLEVEL(4, "test%3i : Block compression test : ", testNb++);
965         CHECK( ZSTD_compressBegin(cctx, 5) );
966         CHECK( ZSTD_getBlockSize(cctx) >= blockSize);
967         cSize = ZSTD_compressBlock(cctx, compressedBuffer, ZSTD_compressBound(blockSize), CNBuffer, blockSize);
968         if (ZSTD_isError(cSize)) goto _output_error;
969         DISPLAYLEVEL(4, "OK \n");
970
971         DISPLAYLEVEL(4, "test%3i : Block decompression test : ", testNb++);
972         CHECK( ZSTD_decompressBegin(dctx) );
973         { CHECK_V(r, ZSTD_decompressBlock(dctx, decodedBuffer, CNBuffSize, compressedBuffer, cSize) );
974           if (r != blockSize) goto _output_error; }
975         DISPLAYLEVEL(4, "OK \n");
976
977         /* dictionary block compression */
978         DISPLAYLEVEL(4, "test%3i : Dictionary Block compression test : ", testNb++);
979         CHECK( ZSTD_compressBegin_usingDict(cctx, CNBuffer, dictSize, 5) );
980         cSize = ZSTD_compressBlock(cctx, compressedBuffer, ZSTD_compressBound(blockSize), (char*)CNBuffer+dictSize, blockSize);
981         if (ZSTD_isError(cSize)) goto _output_error;
982         cSize2 = ZSTD_compressBlock(cctx, (char*)compressedBuffer+cSize, ZSTD_compressBound(blockSize), (char*)CNBuffer+dictSize+blockSize, blockSize);
983         if (ZSTD_isError(cSize2)) goto _output_error;
984         memcpy((char*)compressedBuffer+cSize, (char*)CNBuffer+dictSize+blockSize, blockSize);   /* fake non-compressed block */
985         cSize2 = ZSTD_compressBlock(cctx, (char*)compressedBuffer+cSize+blockSize, ZSTD_compressBound(blockSize),
986                                           (char*)CNBuffer+dictSize+2*blockSize, blockSize);
987         if (ZSTD_isError(cSize2)) goto _output_error;
988         DISPLAYLEVEL(4, "OK \n");
989
990         DISPLAYLEVEL(4, "test%3i : Dictionary Block decompression test : ", testNb++);
991         CHECK( ZSTD_decompressBegin_usingDict(dctx, CNBuffer, dictSize) );
992         { CHECK_V( r, ZSTD_decompressBlock(dctx, decodedBuffer, CNBuffSize, compressedBuffer, cSize) );
993           if (r != blockSize) goto _output_error; }
994         ZSTD_insertBlock(dctx, (char*)decodedBuffer+blockSize, blockSize);   /* insert non-compressed block into dctx history */
995         { CHECK_V( r, ZSTD_decompressBlock(dctx, (char*)decodedBuffer+2*blockSize, CNBuffSize, (char*)compressedBuffer+cSize+blockSize, cSize2) );
996           if (r != blockSize) goto _output_error; }
997         DISPLAYLEVEL(4, "OK \n");
998
999         ZSTD_freeCCtx(cctx);
1000     }
1001     ZSTD_freeDCtx(dctx);
1002
1003     /* long rle test */
1004     {   size_t sampleSize = 0;
1005         DISPLAYLEVEL(4, "test%3i : Long RLE test : ", testNb++);
1006         RDG_genBuffer(CNBuffer, sampleSize, compressibility, 0., seed+1);
1007         memset((char*)CNBuffer+sampleSize, 'B', 256 KB - 1);
1008         sampleSize += 256 KB - 1;
1009         RDG_genBuffer((char*)CNBuffer+sampleSize, 96 KB, compressibility, 0., seed+2);
1010         sampleSize += 96 KB;
1011         cSize = ZSTD_compress(compressedBuffer, ZSTD_compressBound(sampleSize), CNBuffer, sampleSize, 1);
1012         if (ZSTD_isError(cSize)) goto _output_error;
1013         { CHECK_V(regenSize, ZSTD_decompress(decodedBuffer, sampleSize, compressedBuffer, cSize));
1014           if (regenSize!=sampleSize) goto _output_error; }
1015         DISPLAYLEVEL(4, "OK \n");
1016     }
1017
1018     /* All zeroes test (test bug #137) */
1019     #define ZEROESLENGTH 100
1020     DISPLAYLEVEL(4, "test%3i : compress %u zeroes : ", testNb++, ZEROESLENGTH);
1021     memset(CNBuffer, 0, ZEROESLENGTH);
1022     { CHECK_V(r, ZSTD_compress(compressedBuffer, ZSTD_compressBound(ZEROESLENGTH), CNBuffer, ZEROESLENGTH, 1) );
1023       cSize = r; }
1024     DISPLAYLEVEL(4, "OK (%u bytes : %.2f%%)\n", (U32)cSize, (double)cSize/ZEROESLENGTH*100);
1025
1026     DISPLAYLEVEL(4, "test%3i : decompress %u zeroes : ", testNb++, ZEROESLENGTH);
1027     { CHECK_V(r, ZSTD_decompress(decodedBuffer, ZEROESLENGTH, compressedBuffer, cSize) );
1028       if (r != ZEROESLENGTH) goto _output_error; }
1029     DISPLAYLEVEL(4, "OK \n");
1030
1031     /* nbSeq limit test */
1032     #define _3BYTESTESTLENGTH 131000
1033     #define NB3BYTESSEQLOG   9
1034     #define NB3BYTESSEQ     (1 << NB3BYTESSEQLOG)
1035     #define NB3BYTESSEQMASK (NB3BYTESSEQ-1)
1036     /* creates a buffer full of 3-bytes sequences */
1037     {   BYTE _3BytesSeqs[NB3BYTESSEQ][3];
1038         U32 rSeed = 1;
1039
1040         /* create batch of 3-bytes sequences */
1041         {   int i;
1042             for (i=0; i < NB3BYTESSEQ; i++) {
1043                 _3BytesSeqs[i][0] = (BYTE)(FUZ_rand(&rSeed) & 255);
1044                 _3BytesSeqs[i][1] = (BYTE)(FUZ_rand(&rSeed) & 255);
1045                 _3BytesSeqs[i][2] = (BYTE)(FUZ_rand(&rSeed) & 255);
1046         }   }
1047
1048         /* randomly fills CNBuffer with prepared 3-bytes sequences */
1049         {   int i;
1050             for (i=0; i < _3BYTESTESTLENGTH; i += 3) {   /* note : CNBuffer size > _3BYTESTESTLENGTH+3 */
1051                 U32 const id = FUZ_rand(&rSeed) & NB3BYTESSEQMASK;
1052                 ((BYTE*)CNBuffer)[i+0] = _3BytesSeqs[id][0];
1053                 ((BYTE*)CNBuffer)[i+1] = _3BytesSeqs[id][1];
1054                 ((BYTE*)CNBuffer)[i+2] = _3BytesSeqs[id][2];
1055     }   }   }
1056     DISPLAYLEVEL(4, "test%3i : compress lots 3-bytes sequences : ", testNb++);
1057     { CHECK_V(r, ZSTD_compress(compressedBuffer, ZSTD_compressBound(_3BYTESTESTLENGTH),
1058                                  CNBuffer, _3BYTESTESTLENGTH, 19) );
1059       cSize = r; }
1060     DISPLAYLEVEL(4, "OK (%u bytes : %.2f%%)\n", (U32)cSize, (double)cSize/_3BYTESTESTLENGTH*100);
1061
1062     DISPLAYLEVEL(4, "test%3i : decompress lots 3-bytes sequence : ", testNb++);
1063     { CHECK_V(r, ZSTD_decompress(decodedBuffer, _3BYTESTESTLENGTH, compressedBuffer, cSize) );
1064       if (r != _3BYTESTESTLENGTH) goto _output_error; }
1065     DISPLAYLEVEL(4, "OK \n");
1066
1067     DISPLAYLEVEL(4, "test%3i : incompressible data and ill suited dictionary : ", testNb++);
1068     RDG_genBuffer(CNBuffer, CNBuffSize, 0.0, 0.1, seed);
1069     {   /* Train a dictionary on low characters */
1070         size_t dictSize = 16 KB;
1071         void* const dictBuffer = malloc(dictSize);
1072         size_t const totalSampleSize = 1 MB;
1073         size_t const sampleUnitSize = 8 KB;
1074         U32 const nbSamples = (U32)(totalSampleSize / sampleUnitSize);
1075         size_t* const samplesSizes = (size_t*) malloc(nbSamples * sizeof(size_t));
1076         if (!dictBuffer || !samplesSizes) goto _output_error;
1077         { U32 u; for (u=0; u<nbSamples; u++) samplesSizes[u] = sampleUnitSize; }
1078         dictSize = ZDICT_trainFromBuffer(dictBuffer, dictSize, CNBuffer, samplesSizes, nbSamples);
1079         if (ZDICT_isError(dictSize)) goto _output_error;
1080         /* Reverse the characters to make the dictionary ill suited */
1081         {   U32 u;
1082             for (u = 0; u < CNBuffSize; ++u) {
1083               ((BYTE*)CNBuffer)[u] = 255 - ((BYTE*)CNBuffer)[u];
1084             }
1085         }
1086         {   /* Compress the data */
1087             size_t const inputSize = 500;
1088             size_t const outputSize = ZSTD_compressBound(inputSize);
1089             void* const outputBuffer = malloc(outputSize);
1090             ZSTD_CCtx* const cctx = ZSTD_createCCtx();
1091             if (!outputBuffer || !cctx) goto _output_error;
1092             CHECK(ZSTD_compress_usingDict(cctx, outputBuffer, outputSize, CNBuffer, inputSize, dictBuffer, dictSize, 1));
1093             free(outputBuffer);
1094             ZSTD_freeCCtx(cctx);
1095         }
1096
1097         free(dictBuffer);
1098         free(samplesSizes);
1099     }
1100     DISPLAYLEVEL(4, "OK \n");
1101
1102
1103     /* findFrameCompressedSize on skippable frames */
1104     DISPLAYLEVEL(4, "test%3i : frame compressed size of skippable frame : ", testNb++);
1105     {   const char* frame = "\x50\x2a\x4d\x18\x05\x0\x0\0abcde";
1106         size_t const frameSrcSize = 13;
1107         if (ZSTD_findFrameCompressedSize(frame, frameSrcSize) != frameSrcSize) goto _output_error; }
1108     DISPLAYLEVEL(4, "OK \n");
1109
1110     /* error string tests */
1111     DISPLAYLEVEL(4, "test%3i : testing ZSTD error code strings : ", testNb++);
1112     if (strcmp("No error detected", ZSTD_getErrorName((ZSTD_ErrorCode)(0-ZSTD_error_no_error))) != 0) goto _output_error;
1113     if (strcmp("No error detected", ZSTD_getErrorString(ZSTD_error_no_error)) != 0) goto _output_error;
1114     if (strcmp("Unspecified error code", ZSTD_getErrorString((ZSTD_ErrorCode)(0-ZSTD_error_GENERIC))) != 0) goto _output_error;
1115     if (strcmp("Error (generic)", ZSTD_getErrorName((size_t)0-ZSTD_error_GENERIC)) != 0) goto _output_error;
1116     if (strcmp("Error (generic)", ZSTD_getErrorString(ZSTD_error_GENERIC)) != 0) goto _output_error;
1117     if (strcmp("No error detected", ZSTD_getErrorName(ZSTD_error_GENERIC)) != 0) goto _output_error;
1118     DISPLAYLEVEL(4, "OK \n");
1119
1120 _end:
1121     free(CNBuffer);
1122     free(compressedBuffer);
1123     free(decodedBuffer);
1124     return testResult;
1125
1126 _output_error:
1127     testResult = 1;
1128     DISPLAY("Error detected in Unit tests ! \n");
1129     goto _end;
1130 }
1131
1132
1133 static size_t findDiff(const void* buf1, const void* buf2, size_t max)
1134 {
1135     const BYTE* b1 = (const BYTE*)buf1;
1136     const BYTE* b2 = (const BYTE*)buf2;
1137     size_t u;
1138     for (u=0; u<max; u++) {
1139         if (b1[u] != b2[u]) break;
1140     }
1141     return u;
1142 }
1143
1144
1145 static ZSTD_parameters FUZ_makeParams(ZSTD_compressionParameters cParams, ZSTD_frameParameters fParams)
1146 {
1147     ZSTD_parameters params;
1148     params.cParams = cParams;
1149     params.fParams = fParams;
1150     return params;
1151 }
1152
1153 static size_t FUZ_rLogLength(U32* seed, U32 logLength)
1154 {
1155     size_t const lengthMask = ((size_t)1 << logLength) - 1;
1156     return (lengthMask+1) + (FUZ_rand(seed) & lengthMask);
1157 }
1158
1159 static size_t FUZ_randomLength(U32* seed, U32 maxLog)
1160 {
1161     U32 const logLength = FUZ_rand(seed) % maxLog;
1162     return FUZ_rLogLength(seed, logLength);
1163 }
1164
1165 #undef CHECK
1166 #define CHECK(cond, ...) {                                    \
1167     if (cond) {                                               \
1168         DISPLAY("Error => ");                                 \
1169         DISPLAY(__VA_ARGS__);                                 \
1170         DISPLAY(" (seed %u, test nb %u)  \n", seed, testNb);  \
1171         goto _output_error;                                   \
1172 }   }
1173
1174 #undef CHECK_Z
1175 #define CHECK_Z(f) {                                          \
1176     size_t const err = f;                                     \
1177     if (ZSTD_isError(err)) {                                  \
1178         DISPLAY("Error => %s : %s ",                          \
1179                 #f, ZSTD_getErrorName(err));                  \
1180         DISPLAY(" (seed %u, test nb %u)  \n", seed, testNb);  \
1181         goto _output_error;                                   \
1182 }   }
1183
1184
1185 static int fuzzerTests(U32 seed, U32 nbTests, unsigned startTest, U32 const maxDurationS, double compressibility, int bigTests)
1186 {
1187     static const U32 maxSrcLog = 23;
1188     static const U32 maxSampleLog = 22;
1189     size_t const srcBufferSize = (size_t)1<<maxSrcLog;
1190     size_t const dstBufferSize = (size_t)1<<maxSampleLog;
1191     size_t const cBufferSize   = ZSTD_compressBound(dstBufferSize);
1192     BYTE* cNoiseBuffer[5];
1193     BYTE* srcBuffer;   /* jumping pointer */
1194     BYTE* const cBuffer = (BYTE*) malloc (cBufferSize);
1195     BYTE* const dstBuffer = (BYTE*) malloc (dstBufferSize);
1196     BYTE* const mirrorBuffer = (BYTE*) malloc (dstBufferSize);
1197     ZSTD_CCtx* const refCtx = ZSTD_createCCtx();
1198     ZSTD_CCtx* const ctx = ZSTD_createCCtx();
1199     ZSTD_DCtx* const dctx = ZSTD_createDCtx();
1200     U32 result = 0;
1201     U32 testNb = 0;
1202     U32 coreSeed = seed, lseed = 0;
1203     clock_t const startClock = clock();
1204     clock_t const maxClockSpan = maxDurationS * CLOCKS_PER_SEC;
1205     int const cLevelLimiter = bigTests ? 3 : 2;
1206
1207     /* allocation */
1208     cNoiseBuffer[0] = (BYTE*)malloc (srcBufferSize);
1209     cNoiseBuffer[1] = (BYTE*)malloc (srcBufferSize);
1210     cNoiseBuffer[2] = (BYTE*)malloc (srcBufferSize);
1211     cNoiseBuffer[3] = (BYTE*)malloc (srcBufferSize);
1212     cNoiseBuffer[4] = (BYTE*)malloc (srcBufferSize);
1213     CHECK (!cNoiseBuffer[0] || !cNoiseBuffer[1] || !cNoiseBuffer[2] || !cNoiseBuffer[3] || !cNoiseBuffer[4]
1214            || !dstBuffer || !mirrorBuffer || !cBuffer || !refCtx || !ctx || !dctx,
1215            "Not enough memory, fuzzer tests cancelled");
1216
1217     /* Create initial samples */
1218     RDG_genBuffer(cNoiseBuffer[0], srcBufferSize, 0.00, 0., coreSeed);    /* pure noise */
1219     RDG_genBuffer(cNoiseBuffer[1], srcBufferSize, 0.05, 0., coreSeed);    /* barely compressible */
1220     RDG_genBuffer(cNoiseBuffer[2], srcBufferSize, compressibility, 0., coreSeed);
1221     RDG_genBuffer(cNoiseBuffer[3], srcBufferSize, 0.95, 0., coreSeed);    /* highly compressible */
1222     RDG_genBuffer(cNoiseBuffer[4], srcBufferSize, 1.00, 0., coreSeed);    /* sparse content */
1223     srcBuffer = cNoiseBuffer[2];
1224
1225     /* catch up testNb */
1226     for (testNb=1; testNb < startTest; testNb++) FUZ_rand(&coreSeed);
1227
1228     /* main test loop */
1229     for ( ; (testNb <= nbTests) || (FUZ_clockSpan(startClock) < maxClockSpan); testNb++ ) {
1230         size_t sampleSize, maxTestSize, totalTestSize;
1231         size_t cSize, totalCSize, totalGenSize;
1232         U64 crcOrig;
1233         BYTE* sampleBuffer;
1234         const BYTE* dict;
1235         size_t dictSize;
1236
1237         /* notification */
1238         if (nbTests >= testNb) { DISPLAYUPDATE(2, "\r%6u/%6u    ", testNb, nbTests); }
1239         else { DISPLAYUPDATE(2, "\r%6u          ", testNb); }
1240
1241         FUZ_rand(&coreSeed);
1242         { U32 const prime1 = 2654435761U; lseed = coreSeed ^ prime1; }
1243
1244         /* srcBuffer selection [0-4] */
1245         {   U32 buffNb = FUZ_rand(&lseed) & 0x7F;
1246             if (buffNb & 7) buffNb=2;   /* most common : compressible (P) */
1247             else {
1248                 buffNb >>= 3;
1249                 if (buffNb & 7) {
1250                     const U32 tnb[2] = { 1, 3 };   /* barely/highly compressible */
1251                     buffNb = tnb[buffNb >> 3];
1252                 } else {
1253                     const U32 tnb[2] = { 0, 4 };   /* not compressible / sparse */
1254                     buffNb = tnb[buffNb >> 3];
1255             }   }
1256             srcBuffer = cNoiseBuffer[buffNb];
1257         }
1258
1259         /* select src segment */
1260         sampleSize = FUZ_randomLength(&lseed, maxSampleLog);
1261
1262         /* create sample buffer (to catch read error with valgrind & sanitizers)  */
1263         sampleBuffer = (BYTE*)malloc(sampleSize);
1264         CHECK(sampleBuffer==NULL, "not enough memory for sample buffer");
1265         { size_t const sampleStart = FUZ_rand(&lseed) % (srcBufferSize - sampleSize);
1266           memcpy(sampleBuffer, srcBuffer + sampleStart, sampleSize); }
1267         crcOrig = XXH64(sampleBuffer, sampleSize, 0);
1268
1269         /* compression tests */
1270         {   unsigned const cLevel =
1271                     ( FUZ_rand(&lseed) %
1272                      (ZSTD_maxCLevel() - (FUZ_highbit32((U32)sampleSize) / cLevelLimiter)) )
1273                      + 1;
1274             cSize = ZSTD_compressCCtx(ctx, cBuffer, cBufferSize, sampleBuffer, sampleSize, cLevel);
1275             CHECK(ZSTD_isError(cSize), "ZSTD_compressCCtx failed : %s", ZSTD_getErrorName(cSize));
1276
1277             /* compression failure test : too small dest buffer */
1278             if (cSize > 3) {
1279                 const size_t missing = (FUZ_rand(&lseed) % (cSize-2)) + 1;   /* no problem, as cSize > 4 (frameHeaderSizer) */
1280                 const size_t tooSmallSize = cSize - missing;
1281                 const U32 endMark = 0x4DC2B1A9;
1282                 memcpy(dstBuffer+tooSmallSize, &endMark, 4);
1283                 { size_t const errorCode = ZSTD_compressCCtx(ctx, dstBuffer, tooSmallSize, sampleBuffer, sampleSize, cLevel);
1284                   CHECK(!ZSTD_isError(errorCode), "ZSTD_compressCCtx should have failed ! (buffer too small : %u < %u)", (U32)tooSmallSize, (U32)cSize); }
1285                 { U32 endCheck; memcpy(&endCheck, dstBuffer+tooSmallSize, 4);
1286                   CHECK(endCheck != endMark, "ZSTD_compressCCtx : dst buffer overflow"); }
1287         }   }
1288
1289         /* frame header decompression test */
1290         {   ZSTD_frameHeader zfh;
1291             CHECK_Z( ZSTD_getFrameHeader(&zfh, cBuffer, cSize) );
1292             CHECK(zfh.frameContentSize != sampleSize, "Frame content size incorrect");
1293         }
1294
1295         /* Decompressed size test */
1296         {   unsigned long long const rSize = ZSTD_findDecompressedSize(cBuffer, cSize);
1297             CHECK(rSize != sampleSize, "decompressed size incorrect");
1298         }
1299
1300         /* successful decompression test */
1301         {   size_t const margin = (FUZ_rand(&lseed) & 1) ? 0 : (FUZ_rand(&lseed) & 31) + 1;
1302             size_t const dSize = ZSTD_decompress(dstBuffer, sampleSize + margin, cBuffer, cSize);
1303             CHECK(dSize != sampleSize, "ZSTD_decompress failed (%s) (srcSize : %u ; cSize : %u)", ZSTD_getErrorName(dSize), (U32)sampleSize, (U32)cSize);
1304             {   U64 const crcDest = XXH64(dstBuffer, sampleSize, 0);
1305                 CHECK(crcOrig != crcDest, "decompression result corrupted (pos %u / %u)", (U32)findDiff(sampleBuffer, dstBuffer, sampleSize), (U32)sampleSize);
1306         }   }
1307
1308         free(sampleBuffer);   /* no longer useful after this point */
1309
1310         /* truncated src decompression test */
1311         {   size_t const missing = (FUZ_rand(&lseed) % (cSize-2)) + 1;   /* no problem, as cSize > 4 (frameHeaderSizer) */
1312             size_t const tooSmallSize = cSize - missing;
1313             void* cBufferTooSmall = malloc(tooSmallSize);   /* valgrind will catch read overflows */
1314             CHECK(cBufferTooSmall == NULL, "not enough memory !");
1315             memcpy(cBufferTooSmall, cBuffer, tooSmallSize);
1316             { size_t const errorCode = ZSTD_decompress(dstBuffer, dstBufferSize, cBufferTooSmall, tooSmallSize);
1317               CHECK(!ZSTD_isError(errorCode), "ZSTD_decompress should have failed ! (truncated src buffer)"); }
1318             free(cBufferTooSmall);
1319         }
1320
1321         /* too small dst decompression test */
1322         if (sampleSize > 3) {
1323             size_t const missing = (FUZ_rand(&lseed) % (sampleSize-2)) + 1;   /* no problem, as cSize > 4 (frameHeaderSizer) */
1324             size_t const tooSmallSize = sampleSize - missing;
1325             static const BYTE token = 0xA9;
1326             dstBuffer[tooSmallSize] = token;
1327             { size_t const errorCode = ZSTD_decompress(dstBuffer, tooSmallSize, cBuffer, cSize);
1328               CHECK(!ZSTD_isError(errorCode), "ZSTD_decompress should have failed : %u > %u (dst buffer too small)", (U32)errorCode, (U32)tooSmallSize); }
1329             CHECK(dstBuffer[tooSmallSize] != token, "ZSTD_decompress : dst buffer overflow");
1330         }
1331
1332         /* noisy src decompression test */
1333         if (cSize > 6) {
1334             /* insert noise into src */
1335             {   U32 const maxNbBits = FUZ_highbit32((U32)(cSize-4));
1336                 size_t pos = 4;   /* preserve magic number (too easy to detect) */
1337                 for (;;) {
1338                     /* keep some original src */
1339                     {   U32 const nbBits = FUZ_rand(&lseed) % maxNbBits;
1340                         size_t const mask = (1<<nbBits) - 1;
1341                         size_t const skipLength = FUZ_rand(&lseed) & mask;
1342                         pos += skipLength;
1343                     }
1344                     if (pos <= cSize) break;
1345                     /* add noise */
1346                     {   U32 const nbBitsCodes = FUZ_rand(&lseed) % maxNbBits;
1347                         U32 const nbBits = nbBitsCodes ? nbBitsCodes-1 : 0;
1348                         size_t const mask = (1<<nbBits) - 1;
1349                         size_t const rNoiseLength = (FUZ_rand(&lseed) & mask) + 1;
1350                         size_t const noiseLength = MIN(rNoiseLength, cSize-pos);
1351                         size_t const noiseStart = FUZ_rand(&lseed) % (srcBufferSize - noiseLength);
1352                         memcpy(cBuffer + pos, srcBuffer + noiseStart, noiseLength);
1353                         pos += noiseLength;
1354             }   }   }
1355
1356             /* decompress noisy source */
1357             {   U32 const endMark = 0xA9B1C3D6;
1358                 memcpy(dstBuffer+sampleSize, &endMark, 4);
1359                 {   size_t const decompressResult = ZSTD_decompress(dstBuffer, sampleSize, cBuffer, cSize);
1360                     /* result *may* be an unlikely success, but even then, it must strictly respect dst buffer boundaries */
1361                     CHECK((!ZSTD_isError(decompressResult)) && (decompressResult>sampleSize),
1362                           "ZSTD_decompress on noisy src : result is too large : %u > %u (dst buffer)", (U32)decompressResult, (U32)sampleSize);
1363                 }
1364                 {   U32 endCheck; memcpy(&endCheck, dstBuffer+sampleSize, 4);
1365                     CHECK(endMark!=endCheck, "ZSTD_decompress on noisy src : dst buffer overflow");
1366         }   }   }   /* noisy src decompression test */
1367
1368         /*=====   Streaming compression test, scattered segments and dictionary   =====*/
1369
1370         {   U32 const testLog = FUZ_rand(&lseed) % maxSrcLog;
1371             U32 const dictLog = FUZ_rand(&lseed) % maxSrcLog;
1372             int const cLevel = (FUZ_rand(&lseed) %
1373                                 (ZSTD_maxCLevel() -
1374                                  (MAX(testLog, dictLog) / cLevelLimiter))) +
1375                                1;
1376             maxTestSize = FUZ_rLogLength(&lseed, testLog);
1377             if (maxTestSize >= dstBufferSize) maxTestSize = dstBufferSize-1;
1378
1379             dictSize = FUZ_rLogLength(&lseed, dictLog);   /* needed also for decompression */
1380             dict = srcBuffer + (FUZ_rand(&lseed) % (srcBufferSize - dictSize));
1381
1382             if (FUZ_rand(&lseed) & 0xF) {
1383                 CHECK_Z ( ZSTD_compressBegin_usingDict(refCtx, dict, dictSize, cLevel) );
1384             } else {
1385                 ZSTD_compressionParameters const cPar = ZSTD_getCParams(cLevel, 0, dictSize);
1386                 ZSTD_frameParameters const fPar = { FUZ_rand(&lseed)&1 /* contentSizeFlag */,
1387                                                     !(FUZ_rand(&lseed)&3) /* contentChecksumFlag*/,
1388                                                     0 /*NodictID*/ };   /* note : since dictionary is fake, dictIDflag has no impact */
1389                 ZSTD_parameters const p = FUZ_makeParams(cPar, fPar);
1390                 CHECK_Z ( ZSTD_compressBegin_advanced(refCtx, dict, dictSize, p, 0) );
1391             }
1392             CHECK_Z( ZSTD_copyCCtx(ctx, refCtx, 0) );
1393         }
1394
1395         {   U32 const nbChunks = (FUZ_rand(&lseed) & 127) + 2;
1396             U32 n;
1397             XXH64_state_t xxhState;
1398             XXH64_reset(&xxhState, 0);
1399             for (totalTestSize=0, cSize=0, n=0 ; n<nbChunks ; n++) {
1400                 size_t const segmentSize = FUZ_randomLength(&lseed, maxSampleLog);
1401                 size_t const segmentStart = FUZ_rand(&lseed) % (srcBufferSize - segmentSize);
1402
1403                 if (cBufferSize-cSize < ZSTD_compressBound(segmentSize)) break;   /* avoid invalid dstBufferTooSmall */
1404                 if (totalTestSize+segmentSize > maxTestSize) break;
1405
1406                 {   size_t const compressResult = ZSTD_compressContinue(ctx, cBuffer+cSize, cBufferSize-cSize, srcBuffer+segmentStart, segmentSize);
1407                     CHECK (ZSTD_isError(compressResult), "multi-segments compression error : %s", ZSTD_getErrorName(compressResult));
1408                     cSize += compressResult;
1409                 }
1410                 XXH64_update(&xxhState, srcBuffer+segmentStart, segmentSize);
1411                 memcpy(mirrorBuffer + totalTestSize, srcBuffer+segmentStart, segmentSize);
1412                 totalTestSize += segmentSize;
1413             }
1414
1415             {   size_t const flushResult = ZSTD_compressEnd(ctx, cBuffer+cSize, cBufferSize-cSize, NULL, 0);
1416                 CHECK (ZSTD_isError(flushResult), "multi-segments epilogue error : %s", ZSTD_getErrorName(flushResult));
1417                 cSize += flushResult;
1418             }
1419             crcOrig = XXH64_digest(&xxhState);
1420         }
1421
1422         /* streaming decompression test */
1423         /* ensure memory requirement is good enough (should always be true) */
1424         {   ZSTD_frameHeader zfh;
1425             CHECK( ZSTD_getFrameHeader(&zfh, cBuffer, ZSTD_frameHeaderSize_max),
1426                   "ZSTD_getFrameHeader(): error retrieving frame information");
1427             {   size_t const roundBuffSize = ZSTD_decodingBufferSize_min(zfh.windowSize, zfh.frameContentSize);
1428                 CHECK_Z(roundBuffSize);
1429                 CHECK((roundBuffSize > totalTestSize) && (zfh.frameContentSize!=ZSTD_CONTENTSIZE_UNKNOWN),
1430                       "ZSTD_decodingBufferSize_min() requires more memory (%u) than necessary (%u)",
1431                       (U32)roundBuffSize, (U32)totalTestSize );
1432         }   }
1433         if (dictSize<8) dictSize=0, dict=NULL;   /* disable dictionary */
1434         CHECK_Z( ZSTD_decompressBegin_usingDict(dctx, dict, dictSize) );
1435         totalCSize = 0;
1436         totalGenSize = 0;
1437         while (totalCSize < cSize) {
1438             size_t const inSize = ZSTD_nextSrcSizeToDecompress(dctx);
1439             size_t const genSize = ZSTD_decompressContinue(dctx, dstBuffer+totalGenSize, dstBufferSize-totalGenSize, cBuffer+totalCSize, inSize);
1440             CHECK (ZSTD_isError(genSize), "ZSTD_decompressContinue error : %s", ZSTD_getErrorName(genSize));
1441             totalGenSize += genSize;
1442             totalCSize += inSize;
1443         }
1444         CHECK (ZSTD_nextSrcSizeToDecompress(dctx) != 0, "frame not fully decoded");
1445         CHECK (totalGenSize != totalTestSize, "streaming decompressed data : wrong size")
1446         CHECK (totalCSize != cSize, "compressed data should be fully read")
1447         {   U64 const crcDest = XXH64(dstBuffer, totalTestSize, 0);
1448             if (crcDest!=crcOrig) {
1449                 size_t const errorPos = findDiff(mirrorBuffer, dstBuffer, totalTestSize);
1450                 CHECK (1, "streaming decompressed data corrupted : byte %u / %u  (%02X!=%02X)",
1451                    (U32)errorPos, (U32)totalTestSize, dstBuffer[errorPos], mirrorBuffer[errorPos]);
1452         }   }
1453     }   /* for ( ; (testNb <= nbTests) */
1454     DISPLAY("\r%u fuzzer tests completed   \n", testNb-1);
1455
1456 _cleanup:
1457     ZSTD_freeCCtx(refCtx);
1458     ZSTD_freeCCtx(ctx);
1459     ZSTD_freeDCtx(dctx);
1460     free(cNoiseBuffer[0]);
1461     free(cNoiseBuffer[1]);
1462     free(cNoiseBuffer[2]);
1463     free(cNoiseBuffer[3]);
1464     free(cNoiseBuffer[4]);
1465     free(cBuffer);
1466     free(dstBuffer);
1467     free(mirrorBuffer);
1468     return result;
1469
1470 _output_error:
1471     result = 1;
1472     goto _cleanup;
1473 }
1474
1475
1476 /*_*******************************************************
1477 *  Command line
1478 *********************************************************/
1479 static int FUZ_usage(const char* programName)
1480 {
1481     DISPLAY( "Usage :\n");
1482     DISPLAY( "      %s [args]\n", programName);
1483     DISPLAY( "\n");
1484     DISPLAY( "Arguments :\n");
1485     DISPLAY( " -i#    : Nb of tests (default:%u) \n", nbTestsDefault);
1486     DISPLAY( " -s#    : Select seed (default:prompt user)\n");
1487     DISPLAY( " -t#    : Select starting test number (default:0)\n");
1488     DISPLAY( " -P#    : Select compressibility in %% (default:%u%%)\n", FUZ_compressibility_default);
1489     DISPLAY( " -v     : verbose\n");
1490     DISPLAY( " -p     : pause at the end\n");
1491     DISPLAY( " -h     : display help and exit\n");
1492     return 0;
1493 }
1494
1495 /*! readU32FromChar() :
1496     @return : unsigned integer value read from input in `char` format
1497     allows and interprets K, KB, KiB, M, MB and MiB suffix.
1498     Will also modify `*stringPtr`, advancing it to position where it stopped reading.
1499     Note : function result can overflow if digit string > MAX_UINT */
1500 static unsigned readU32FromChar(const char** stringPtr)
1501 {
1502     unsigned result = 0;
1503     while ((**stringPtr >='0') && (**stringPtr <='9'))
1504         result *= 10, result += **stringPtr - '0', (*stringPtr)++ ;
1505     if ((**stringPtr=='K') || (**stringPtr=='M')) {
1506         result <<= 10;
1507         if (**stringPtr=='M') result <<= 10;
1508         (*stringPtr)++ ;
1509         if (**stringPtr=='i') (*stringPtr)++;
1510         if (**stringPtr=='B') (*stringPtr)++;
1511     }
1512     return result;
1513 }
1514
1515 /** longCommandWArg() :
1516  *  check if *stringPtr is the same as longCommand.
1517  *  If yes, @return 1 and advances *stringPtr to the position which immediately follows longCommand.
1518  *  @return 0 and doesn't modify *stringPtr otherwise.
1519  */
1520 static unsigned longCommandWArg(const char** stringPtr, const char* longCommand)
1521 {
1522     size_t const comSize = strlen(longCommand);
1523     int const result = !strncmp(*stringPtr, longCommand, comSize);
1524     if (result) *stringPtr += comSize;
1525     return result;
1526 }
1527
1528 int main(int argc, const char** argv)
1529 {
1530     U32 seed = 0;
1531     int seedset = 0;
1532     int argNb;
1533     int nbTests = nbTestsDefault;
1534     int testNb = 0;
1535     U32 proba = FUZ_compressibility_default;
1536     int result = 0;
1537     U32 mainPause = 0;
1538     U32 maxDuration = 0;
1539     int bigTests = 1;
1540     U32 memTestsOnly = 0;
1541     const char* const programName = argv[0];
1542
1543     /* Check command line */
1544     for (argNb=1; argNb<argc; argNb++) {
1545         const char* argument = argv[argNb];
1546         if(!argument) continue;   /* Protection if argument empty */
1547
1548         /* Handle commands. Aggregated commands are allowed */
1549         if (argument[0]=='-') {
1550
1551             if (longCommandWArg(&argument, "--memtest=")) { memTestsOnly = readU32FromChar(&argument); continue; }
1552
1553             if (!strcmp(argument, "--memtest")) { memTestsOnly=1; continue; }
1554             if (!strcmp(argument, "--no-big-tests")) { bigTests=0; continue; }
1555
1556             argument++;
1557             while (*argument!=0) {
1558                 switch(*argument)
1559                 {
1560                 case 'h':
1561                     return FUZ_usage(programName);
1562
1563                 case 'v':
1564                     argument++;
1565                     g_displayLevel = 4;
1566                     break;
1567
1568                 case 'q':
1569                     argument++;
1570                     g_displayLevel--;
1571                     break;
1572
1573                 case 'p': /* pause at the end */
1574                     argument++;
1575                     mainPause = 1;
1576                     break;
1577
1578                 case 'i':
1579                     argument++; maxDuration = 0;
1580                     nbTests = readU32FromChar(&argument);
1581                     break;
1582
1583                 case 'T':
1584                     argument++;
1585                     nbTests = 0;
1586                     maxDuration = readU32FromChar(&argument);
1587                     if (*argument=='s') argument++;   /* seconds */
1588                     if (*argument=='m') maxDuration *= 60, argument++;   /* minutes */
1589                     if (*argument=='n') argument++;
1590                     break;
1591
1592                 case 's':
1593                     argument++;
1594                     seedset = 1;
1595                     seed = readU32FromChar(&argument);
1596                     break;
1597
1598                 case 't':
1599                     argument++;
1600                     testNb = readU32FromChar(&argument);
1601                     break;
1602
1603                 case 'P':   /* compressibility % */
1604                     argument++;
1605                     proba = readU32FromChar(&argument);
1606                     if (proba>100) proba = 100;
1607                     break;
1608
1609                 default:
1610                     return (FUZ_usage(programName), 1);
1611     }   }   }   }   /* for (argNb=1; argNb<argc; argNb++) */
1612
1613     /* Get Seed */
1614     DISPLAY("Starting zstd tester (%i-bits, %s)\n", (int)(sizeof(size_t)*8), ZSTD_VERSION_STRING);
1615
1616     if (!seedset) {
1617         time_t const t = time(NULL);
1618         U32 const h = XXH32(&t, sizeof(t), 1);
1619         seed = h % 10000;
1620     }
1621
1622     DISPLAY("Seed = %u\n", seed);
1623     if (proba!=FUZ_compressibility_default) DISPLAY("Compressibility : %u%%\n", proba);
1624
1625     if (memTestsOnly) {
1626         g_displayLevel = MAX(3, g_displayLevel);
1627         return FUZ_mallocTests(seed, ((double)proba) / 100, memTestsOnly);
1628     }
1629
1630     if (nbTests < testNb) nbTests = testNb;
1631
1632     if (testNb==0)
1633         result = basicUnitTests(0, ((double)proba) / 100);  /* constant seed for predictability */
1634     if (!result)
1635         result = fuzzerTests(seed, nbTests, testNb, maxDuration, ((double)proba) / 100, bigTests);
1636     if (mainPause) {
1637         int unused;
1638         DISPLAY("Press Enter \n");
1639         unused = getchar();
1640         (void)unused;
1641     }
1642     return result;
1643 }