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