1 /*
2  * Copyright (c) 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 *  Tuning parameters
14 **************************************/
15 #ifndef ZSTDCLI_CLEVEL_DEFAULT
16 #  define ZSTDCLI_CLEVEL_DEFAULT 3
17 #endif
18 
19 #ifndef ZSTDCLI_CLEVEL_MAX
20 #  define ZSTDCLI_CLEVEL_MAX 19   /* without using --ultra */
21 #endif
22 
23 #ifndef ZSTDCLI_NBTHREADS_DEFAULT
24 #  define ZSTDCLI_NBTHREADS_DEFAULT 1
25 #endif
26 
27 /*-************************************
28 *  Dependencies
29 **************************************/
30 #include "platform.h" /* IS_CONSOLE, PLATFORM_POSIX_VERSION */
31 #include "util.h"     /* UTIL_HAS_CREATEFILELIST, UTIL_createFileList */
32 #include <stdlib.h>   /* getenv */
33 #include <string.h>   /* strcmp, strlen */
34 #include <stdio.h>    /* fprintf(), stdin, stdout, stderr */
35 #include <errno.h>    /* errno */
36 #include <assert.h>   /* assert */
37 
38 #include "fileio.h"   /* stdinmark, stdoutmark, ZSTD_EXTENSION */
39 #ifndef ZSTD_NOBENCH
40 #  include "benchzstd.h"  /* BMK_benchFiles */
41 #endif
42 #ifndef ZSTD_NODICT
43 #  include "dibio.h"  /* ZDICT_cover_params_t, DiB_trainFromFiles() */
44 #endif
45 #ifndef ZSTD_NOTRACE
46 #  include "zstdcli_trace.h"
47 #endif
48 #include "../lib/zstd.h"  /* ZSTD_VERSION_STRING, ZSTD_minCLevel, ZSTD_maxCLevel */
49 
50 
51 /*-************************************
52 *  Constants
53 **************************************/
54 #define COMPRESSOR_NAME "zstd command line interface"
55 #ifndef ZSTD_VERSION
56 #  define ZSTD_VERSION "v" ZSTD_VERSION_STRING
57 #endif
58 #define AUTHOR "Yann Collet"
59 #define WELCOME_MESSAGE "*** %s %i-bits %s, by %s ***\n", COMPRESSOR_NAME, (int)(sizeof(size_t)*8), ZSTD_VERSION, AUTHOR
60 
61 #define ZSTD_ZSTDMT "zstdmt"
62 #define ZSTD_UNZSTD "unzstd"
63 #define ZSTD_CAT "zstdcat"
64 #define ZSTD_ZCAT "zcat"
65 #define ZSTD_GZ "gzip"
66 #define ZSTD_GUNZIP "gunzip"
67 #define ZSTD_GZCAT "gzcat"
68 #define ZSTD_LZMA "lzma"
69 #define ZSTD_UNLZMA "unlzma"
70 #define ZSTD_XZ "xz"
71 #define ZSTD_UNXZ "unxz"
72 #define ZSTD_LZ4 "lz4"
73 #define ZSTD_UNLZ4 "unlz4"
74 
75 #define KB *(1 <<10)
76 #define MB *(1 <<20)
77 #define GB *(1U<<30)
78 
79 #define DISPLAY_LEVEL_DEFAULT 2
80 
81 static const char*    g_defaultDictName = "dictionary";
82 static const unsigned g_defaultMaxDictSize = 110 KB;
83 static const int      g_defaultDictCLevel = 3;
84 static const unsigned g_defaultSelectivityLevel = 9;
85 static const unsigned g_defaultMaxWindowLog = 27;
86 #define OVERLAP_LOG_DEFAULT 9999
87 #define LDM_PARAM_DEFAULT 9999  /* Default for parameters where 0 is valid */
88 static U32 g_overlapLog = OVERLAP_LOG_DEFAULT;
89 static U32 g_ldmHashLog = 0;
90 static U32 g_ldmMinMatch = 0;
91 static U32 g_ldmHashRateLog = LDM_PARAM_DEFAULT;
92 static U32 g_ldmBucketSizeLog = LDM_PARAM_DEFAULT;
93 
94 
95 #define DEFAULT_ACCEL 1
96 
97 typedef enum { cover, fastCover, legacy } dictType;
98 
99 /*-************************************
100 *  Display Macros
101 **************************************/
102 #define DISPLAY_F(f, ...)    fprintf((f), __VA_ARGS__)
103 #define DISPLAYOUT(...)      DISPLAY_F(stdout, __VA_ARGS__)
104 #define DISPLAY(...)         DISPLAY_F(stderr, __VA_ARGS__)
105 #define DISPLAYLEVEL(l, ...) { if (g_displayLevel>=l) { DISPLAY(__VA_ARGS__); } }
106 static int g_displayLevel = DISPLAY_LEVEL_DEFAULT;   /* 0 : no display,  1: errors,  2 : + result + interaction + warnings,  3 : + progression,  4 : + information */
107 
108 
109 /*-************************************
110 *  Check Version (when CLI linked to dynamic library)
111 **************************************/
112 
113 /* Due to usage of experimental symbols and capabilities by the CLI,
114  * the CLI must be linked against a dynamic library of same version */
checkLibVersion(void)115 static void checkLibVersion(void)
116 {
117     if (strcmp(ZSTD_VERSION_STRING, ZSTD_versionString())) {
118         DISPLAYLEVEL(1, "Error : incorrect library version (expecting : %s ; actual : %s ) \n",
119                     ZSTD_VERSION_STRING, ZSTD_versionString());
120         DISPLAYLEVEL(1, "Please update library to version %s, or use stand-alone zstd binary \n",
121                     ZSTD_VERSION_STRING);
122         exit(1);
123     }
124 }
125 
126 
127 /*-************************************
128 *  Command Line
129 **************************************/
130 /* print help either in `stderr` or `stdout` depending on originating request
131  * error (badusage) => stderr
132  * help (usage_advanced) => stdout
133  */
usage(FILE * f,const char * programName)134 static void usage(FILE* f, const char* programName)
135 {
136     DISPLAY_F(f, "Usage : \n");
137     DISPLAY_F(f, "      %s [args] [FILE(s)] [-o file] \n", programName);
138     DISPLAY_F(f, "\n");
139     DISPLAY_F(f, "FILE    : a filename \n");
140     DISPLAY_F(f, "          with no FILE, or when FILE is - , read standard input\n");
141     DISPLAY_F(f, "Arguments : \n");
142 #ifndef ZSTD_NOCOMPRESS
143     DISPLAY_F(f, " -#     : # compression level (1-%d, default: %d) \n", ZSTDCLI_CLEVEL_MAX, ZSTDCLI_CLEVEL_DEFAULT);
144 #endif
145 #ifndef ZSTD_NODECOMPRESS
146     DISPLAY_F(f, " -d     : decompression \n");
147 #endif
148     DISPLAY_F(f, " -D DICT: use DICT as Dictionary for compression or decompression \n");
149     DISPLAY_F(f, " -o file: result stored into `file` (only 1 output file) \n");
150     DISPLAY_F(f, " -f     : disable input and output checks. Allows overwriting existing files,\n");
151     DISPLAY_F(f, "          input from console, output to stdout, operating on links,\n");
152     DISPLAY_F(f, "          block devices, etc.\n");
153     DISPLAY_F(f, "--rm    : remove source file(s) after successful de/compression \n");
154     DISPLAY_F(f, " -k     : preserve source file(s) (default) \n");
155     DISPLAY_F(f, " -h/-H  : display help/long help and exit \n");
156 }
157 
usage_advanced(const char * programName)158 static void usage_advanced(const char* programName)
159 {
160     DISPLAYOUT(WELCOME_MESSAGE);
161     usage(stdout, programName);
162     DISPLAYOUT( "\n");
163     DISPLAYOUT( "Advanced arguments : \n");
164     DISPLAYOUT( " -V     : display Version number and exit \n");
165 
166     DISPLAYOUT( " -c     : force write to standard output, even if it is the console \n");
167 
168     DISPLAYOUT( " -v     : verbose mode; specify multiple times to increase verbosity \n");
169     DISPLAYOUT( " -q     : suppress warnings; specify twice to suppress errors too \n");
170     DISPLAYOUT( "--[no-]progress : forcibly display, or never display the progress counter.\n");
171     DISPLAYOUT( "                  note: any (de)compressed output to terminal will mix with progress counter text. \n");
172 
173 #ifdef UTIL_HAS_CREATEFILELIST
174     DISPLAYOUT( " -r     : operate recursively on directories \n");
175     DISPLAYOUT( "--filelist FILE : read list of files to operate upon from FILE \n");
176     DISPLAYOUT( "--output-dir-flat DIR : processed files are stored into DIR \n");
177 #endif
178 
179 #ifdef UTIL_HAS_MIRRORFILELIST
180     DISPLAYOUT( "--output-dir-mirror DIR : processed files are stored into DIR respecting original directory structure \n");
181 #endif
182 
183 
184 #ifndef ZSTD_NOCOMPRESS
185     DISPLAYOUT( "--[no-]check : during compression, add XXH64 integrity checksum to frame (default: enabled)");
186 #ifndef ZSTD_NODECOMPRESS
187     DISPLAYOUT( ". If specified with -d, decompressor will ignore/validate checksums in compressed frame (default: validate).");
188 #endif
189 #else
190 #ifdef ZSTD_NOCOMPRESS
191     DISPLAYOUT( "--[no-]check : during decompression, ignore/validate checksums in compressed frame (default: validate).");
192 #endif
193 #endif /* ZSTD_NOCOMPRESS */
194 
195 #ifndef ZSTD_NOTRACE
196     DISPLAYOUT( "\n");
197     DISPLAYOUT( "--trace FILE : log tracing information to FILE.");
198 #endif
199     DISPLAYOUT( "\n");
200 
201     DISPLAYOUT( "--      : All arguments after \"--\" are treated as files \n");
202 
203 #ifndef ZSTD_NOCOMPRESS
204     DISPLAYOUT( "\n");
205     DISPLAYOUT( "Advanced compression arguments : \n");
206     DISPLAYOUT( "--ultra : enable levels beyond %i, up to %i (requires more memory) \n", ZSTDCLI_CLEVEL_MAX, ZSTD_maxCLevel());
207     DISPLAYOUT( "--long[=#]: enable long distance matching with given window log (default: %u) \n", g_defaultMaxWindowLog);
208     DISPLAYOUT( "--fast[=#]: switch to very fast compression levels (default: %u) \n", 1);
209     DISPLAYOUT( "--adapt : dynamically adapt compression level to I/O conditions \n");
210     DISPLAYOUT( "--[no-]row-match-finder : force enable/disable usage of fast row-based matchfinder for greedy, lazy, and lazy2 strategies \n");
211 # ifdef ZSTD_MULTITHREAD
212     DISPLAYOUT( " -T#    : spawns # compression threads (default: 1, 0==# cores) \n");
213     DISPLAYOUT( " -B#    : select size of each job (default: 0==automatic) \n");
214     DISPLAYOUT( "--single-thread : use a single thread for both I/O and compression (result slightly different than -T1) \n");
215     DISPLAYOUT( "--rsyncable : compress using a rsync-friendly method (-B sets block size) \n");
216 # endif
217     DISPLAYOUT( "--exclude-compressed: only compress files that are not already compressed \n");
218     DISPLAYOUT( "--stream-size=# : specify size of streaming input from `stdin` \n");
219     DISPLAYOUT( "--size-hint=# optimize compression parameters for streaming input of approximately this size \n");
220     DISPLAYOUT( "--target-compressed-block-size=# : generate compressed block of approximately targeted size \n");
221     DISPLAYOUT( "--no-dictID : don't write dictID into header (dictionary compression only) \n");
222     DISPLAYOUT( "--[no-]compress-literals : force (un)compressed literals \n");
223 
224     DISPLAYOUT( "--format=zstd : compress files to the .zst format (default) \n");
225 #ifdef ZSTD_GZCOMPRESS
226     DISPLAYOUT( "--format=gzip : compress files to the .gz format \n");
227 #endif
228 #ifdef ZSTD_LZMACOMPRESS
229     DISPLAYOUT( "--format=xz : compress files to the .xz format \n");
230     DISPLAYOUT( "--format=lzma : compress files to the .lzma format \n");
231 #endif
232 #ifdef ZSTD_LZ4COMPRESS
233     DISPLAYOUT( "--format=lz4 : compress files to the .lz4 format \n");
234 #endif
235 #endif  /* !ZSTD_NOCOMPRESS */
236 
237 #ifndef ZSTD_NODECOMPRESS
238     DISPLAYOUT( "\n");
239     DISPLAYOUT( "Advanced decompression arguments : \n");
240     DISPLAYOUT( " -l     : print information about zstd compressed files \n");
241     DISPLAYOUT( "--test  : test compressed file integrity \n");
242     DISPLAYOUT( " -M#    : Set a memory usage limit for decompression \n");
243 # if ZSTD_SPARSE_DEFAULT
244     DISPLAYOUT( "--[no-]sparse : sparse mode (default: enabled on file, disabled on stdout) \n");
245 # else
246     DISPLAYOUT( "--[no-]sparse : sparse mode (default: disabled) \n");
247 # endif
248 #endif  /* ZSTD_NODECOMPRESS */
249 
250 #ifndef ZSTD_NODICT
251     DISPLAYOUT( "\n");
252     DISPLAYOUT( "Dictionary builder : \n");
253     DISPLAYOUT( "--train ## : create a dictionary from a training set of files \n");
254     DISPLAYOUT( "--train-cover[=k=#,d=#,steps=#,split=#,shrink[=#]] : use the cover algorithm with optional args \n");
255     DISPLAYOUT( "--train-fastcover[=k=#,d=#,f=#,steps=#,split=#,accel=#,shrink[=#]] : use the fast cover algorithm with optional args \n");
256     DISPLAYOUT( "--train-legacy[=s=#] : use the legacy algorithm with selectivity (default: %u) \n", g_defaultSelectivityLevel);
257     DISPLAYOUT( " -o DICT : DICT is dictionary name (default: %s) \n", g_defaultDictName);
258     DISPLAYOUT( "--maxdict=# : limit dictionary to specified size (default: %u) \n", g_defaultMaxDictSize);
259     DISPLAYOUT( "--dictID=# : force dictionary ID to specified value (default: random) \n");
260 #endif
261 
262 #ifndef ZSTD_NOBENCH
263     DISPLAYOUT( "\n");
264     DISPLAYOUT( "Benchmark arguments : \n");
265     DISPLAYOUT( " -b#    : benchmark file(s), using # compression level (default: %d) \n", ZSTDCLI_CLEVEL_DEFAULT);
266     DISPLAYOUT( " -e#    : test all compression levels successively from -b# to -e# (default: 1) \n");
267     DISPLAYOUT( " -i#    : minimum evaluation time in seconds (default: 3s) \n");
268     DISPLAYOUT( " -B#    : cut file into independent blocks of size # (default: no block) \n");
269     DISPLAYOUT( " -S     : output one benchmark result per input file (default: consolidated result) \n");
270     DISPLAYOUT( "--priority=rt : set process priority to real-time \n");
271 #endif
272 
273 }
274 
badusage(const char * programName)275 static void badusage(const char* programName)
276 {
277     DISPLAYLEVEL(1, "Incorrect parameters \n");
278     if (g_displayLevel >= 2) usage(stderr, programName);
279 }
280 
waitEnter(void)281 static void waitEnter(void)
282 {
283     int unused;
284     DISPLAY("Press enter to continue... \n");
285     unused = getchar();
286     (void)unused;
287 }
288 
lastNameFromPath(const char * path)289 static const char* lastNameFromPath(const char* path)
290 {
291     const char* name = path;
292     if (strrchr(name, '/')) name = strrchr(name, '/') + 1;
293     if (strrchr(name, '\\')) name = strrchr(name, '\\') + 1; /* windows */
294     return name;
295 }
296 
297 /*! exeNameMatch() :
298     @return : a non-zero value if exeName matches test, excluding the extension
299    */
exeNameMatch(const char * exeName,const char * test)300 static int exeNameMatch(const char* exeName, const char* test)
301 {
302     return !strncmp(exeName, test, strlen(test)) &&
303         (exeName[strlen(test)] == '\0' || exeName[strlen(test)] == '.');
304 }
305 
errorOut(const char * msg)306 static void errorOut(const char* msg)
307 {
308     DISPLAY("%s \n", msg); exit(1);
309 }
310 
311 /*! readU32FromCharChecked() :
312  * @return 0 if success, and store the result in *value.
313  *  allows and interprets K, KB, KiB, M, MB and MiB suffix.
314  *  Will also modify `*stringPtr`, advancing it to position where it stopped reading.
315  * @return 1 if an overflow error occurs */
readU32FromCharChecked(const char ** stringPtr,unsigned * value)316 static int readU32FromCharChecked(const char** stringPtr, unsigned* value)
317 {
318     unsigned result = 0;
319     while ((**stringPtr >='0') && (**stringPtr <='9')) {
320         unsigned const max = ((unsigned)(-1)) / 10;
321         unsigned last = result;
322         if (result > max) return 1; /* overflow error */
323         result *= 10;
324         result += (unsigned)(**stringPtr - '0');
325         if (result < last) return 1; /* overflow error */
326         (*stringPtr)++ ;
327     }
328     if ((**stringPtr=='K') || (**stringPtr=='M')) {
329         unsigned const maxK = ((unsigned)(-1)) >> 10;
330         if (result > maxK) return 1; /* overflow error */
331         result <<= 10;
332         if (**stringPtr=='M') {
333             if (result > maxK) return 1; /* overflow error */
334             result <<= 10;
335         }
336         (*stringPtr)++;  /* skip `K` or `M` */
337         if (**stringPtr=='i') (*stringPtr)++;
338         if (**stringPtr=='B') (*stringPtr)++;
339     }
340     *value = result;
341     return 0;
342 }
343 
344 /*! readU32FromChar() :
345  * @return : unsigned integer value read from input in `char` format.
346  *  allows and interprets K, KB, KiB, M, MB and MiB suffix.
347  *  Will also modify `*stringPtr`, advancing it to position where it stopped reading.
348  *  Note : function will exit() program if digit sequence overflows */
readU32FromChar(const char ** stringPtr)349 static unsigned readU32FromChar(const char** stringPtr) {
350     static const char errorMsg[] = "error: numeric value overflows 32-bit unsigned int";
351     unsigned result;
352     if (readU32FromCharChecked(stringPtr, &result)) { errorOut(errorMsg); }
353     return result;
354 }
355 
356 /*! readSizeTFromCharChecked() :
357  * @return 0 if success, and store the result in *value.
358  *  allows and interprets K, KB, KiB, M, MB and MiB suffix.
359  *  Will also modify `*stringPtr`, advancing it to position where it stopped reading.
360  * @return 1 if an overflow error occurs */
readSizeTFromCharChecked(const char ** stringPtr,size_t * value)361 static int readSizeTFromCharChecked(const char** stringPtr, size_t* value)
362 {
363     size_t result = 0;
364     while ((**stringPtr >='0') && (**stringPtr <='9')) {
365         size_t const max = ((size_t)(-1)) / 10;
366         size_t last = result;
367         if (result > max) return 1; /* overflow error */
368         result *= 10;
369         result += (size_t)(**stringPtr - '0');
370         if (result < last) return 1; /* overflow error */
371         (*stringPtr)++ ;
372     }
373     if ((**stringPtr=='K') || (**stringPtr=='M')) {
374         size_t const maxK = ((size_t)(-1)) >> 10;
375         if (result > maxK) return 1; /* overflow error */
376         result <<= 10;
377         if (**stringPtr=='M') {
378             if (result > maxK) return 1; /* overflow error */
379             result <<= 10;
380         }
381         (*stringPtr)++;  /* skip `K` or `M` */
382         if (**stringPtr=='i') (*stringPtr)++;
383         if (**stringPtr=='B') (*stringPtr)++;
384     }
385     *value = result;
386     return 0;
387 }
388 
389 /*! readSizeTFromChar() :
390  * @return : size_t value read from input in `char` format.
391  *  allows and interprets K, KB, KiB, M, MB and MiB suffix.
392  *  Will also modify `*stringPtr`, advancing it to position where it stopped reading.
393  *  Note : function will exit() program if digit sequence overflows */
readSizeTFromChar(const char ** stringPtr)394 static size_t readSizeTFromChar(const char** stringPtr) {
395     static const char errorMsg[] = "error: numeric value overflows size_t";
396     size_t result;
397     if (readSizeTFromCharChecked(stringPtr, &result)) { errorOut(errorMsg); }
398     return result;
399 }
400 
401 /** longCommandWArg() :
402  *  check if *stringPtr is the same as longCommand.
403  *  If yes, @return 1 and advances *stringPtr to the position which immediately follows longCommand.
404  * @return 0 and doesn't modify *stringPtr otherwise.
405  */
longCommandWArg(const char ** stringPtr,const char * longCommand)406 static int longCommandWArg(const char** stringPtr, const char* longCommand)
407 {
408     size_t const comSize = strlen(longCommand);
409     int const result = !strncmp(*stringPtr, longCommand, comSize);
410     if (result) *stringPtr += comSize;
411     return result;
412 }
413 
414 
415 #ifndef ZSTD_NODICT
416 
417 static const unsigned kDefaultRegression = 1;
418 /**
419  * parseCoverParameters() :
420  * reads cover parameters from *stringPtr (e.g. "--train-cover=k=48,d=8,steps=32") into *params
421  * @return 1 means that cover parameters were correct
422  * @return 0 in case of malformed parameters
423  */
parseCoverParameters(const char * stringPtr,ZDICT_cover_params_t * params)424 static unsigned parseCoverParameters(const char* stringPtr, ZDICT_cover_params_t* params)
425 {
426     memset(params, 0, sizeof(*params));
427     for (; ;) {
428         if (longCommandWArg(&stringPtr, "k=")) { params->k = readU32FromChar(&stringPtr); if (stringPtr[0]==',') { stringPtr++; continue; } else break; }
429         if (longCommandWArg(&stringPtr, "d=")) { params->d = readU32FromChar(&stringPtr); if (stringPtr[0]==',') { stringPtr++; continue; } else break; }
430         if (longCommandWArg(&stringPtr, "steps=")) { params->steps = readU32FromChar(&stringPtr); if (stringPtr[0]==',') { stringPtr++; continue; } else break; }
431         if (longCommandWArg(&stringPtr, "split=")) {
432           unsigned splitPercentage = readU32FromChar(&stringPtr);
433           params->splitPoint = (double)splitPercentage / 100.0;
434           if (stringPtr[0]==',') { stringPtr++; continue; } else break;
435         }
436         if (longCommandWArg(&stringPtr, "shrink")) {
437           params->shrinkDictMaxRegression = kDefaultRegression;
438           params->shrinkDict = 1;
439           if (stringPtr[0]=='=') {
440             stringPtr++;
441             params->shrinkDictMaxRegression = readU32FromChar(&stringPtr);
442           }
443           if (stringPtr[0]==',') {
444             stringPtr++;
445             continue;
446           }
447           else break;
448         }
449         return 0;
450     }
451     if (stringPtr[0] != 0) return 0;
452     DISPLAYLEVEL(4, "cover: k=%u\nd=%u\nsteps=%u\nsplit=%u\nshrink%u\n", params->k, params->d, params->steps, (unsigned)(params->splitPoint * 100), params->shrinkDictMaxRegression);
453     return 1;
454 }
455 
456 /**
457  * parseFastCoverParameters() :
458  * reads fastcover parameters from *stringPtr (e.g. "--train-fastcover=k=48,d=8,f=20,steps=32,accel=2") into *params
459  * @return 1 means that fastcover parameters were correct
460  * @return 0 in case of malformed parameters
461  */
parseFastCoverParameters(const char * stringPtr,ZDICT_fastCover_params_t * params)462 static unsigned parseFastCoverParameters(const char* stringPtr, ZDICT_fastCover_params_t* params)
463 {
464     memset(params, 0, sizeof(*params));
465     for (; ;) {
466         if (longCommandWArg(&stringPtr, "k=")) { params->k = readU32FromChar(&stringPtr); if (stringPtr[0]==',') { stringPtr++; continue; } else break; }
467         if (longCommandWArg(&stringPtr, "d=")) { params->d = readU32FromChar(&stringPtr); if (stringPtr[0]==',') { stringPtr++; continue; } else break; }
468         if (longCommandWArg(&stringPtr, "f=")) { params->f = readU32FromChar(&stringPtr); if (stringPtr[0]==',') { stringPtr++; continue; } else break; }
469         if (longCommandWArg(&stringPtr, "steps=")) { params->steps = readU32FromChar(&stringPtr); if (stringPtr[0]==',') { stringPtr++; continue; } else break; }
470         if (longCommandWArg(&stringPtr, "accel=")) { params->accel = readU32FromChar(&stringPtr); if (stringPtr[0]==',') { stringPtr++; continue; } else break; }
471         if (longCommandWArg(&stringPtr, "split=")) {
472           unsigned splitPercentage = readU32FromChar(&stringPtr);
473           params->splitPoint = (double)splitPercentage / 100.0;
474           if (stringPtr[0]==',') { stringPtr++; continue; } else break;
475         }
476         if (longCommandWArg(&stringPtr, "shrink")) {
477           params->shrinkDictMaxRegression = kDefaultRegression;
478           params->shrinkDict = 1;
479           if (stringPtr[0]=='=') {
480             stringPtr++;
481             params->shrinkDictMaxRegression = readU32FromChar(&stringPtr);
482           }
483           if (stringPtr[0]==',') {
484             stringPtr++;
485             continue;
486           }
487           else break;
488         }
489         return 0;
490     }
491     if (stringPtr[0] != 0) return 0;
492     DISPLAYLEVEL(4, "cover: k=%u\nd=%u\nf=%u\nsteps=%u\nsplit=%u\naccel=%u\nshrink=%u\n", params->k, params->d, params->f, params->steps, (unsigned)(params->splitPoint * 100), params->accel, params->shrinkDictMaxRegression);
493     return 1;
494 }
495 
496 /**
497  * parseLegacyParameters() :
498  * reads legacy dictionary builder parameters from *stringPtr (e.g. "--train-legacy=selectivity=8") into *selectivity
499  * @return 1 means that legacy dictionary builder parameters were correct
500  * @return 0 in case of malformed parameters
501  */
parseLegacyParameters(const char * stringPtr,unsigned * selectivity)502 static unsigned parseLegacyParameters(const char* stringPtr, unsigned* selectivity)
503 {
504     if (!longCommandWArg(&stringPtr, "s=") && !longCommandWArg(&stringPtr, "selectivity=")) { return 0; }
505     *selectivity = readU32FromChar(&stringPtr);
506     if (stringPtr[0] != 0) return 0;
507     DISPLAYLEVEL(4, "legacy: selectivity=%u\n", *selectivity);
508     return 1;
509 }
510 
defaultCoverParams(void)511 static ZDICT_cover_params_t defaultCoverParams(void)
512 {
513     ZDICT_cover_params_t params;
514     memset(&params, 0, sizeof(params));
515     params.d = 8;
516     params.steps = 4;
517     params.splitPoint = 1.0;
518     params.shrinkDict = 0;
519     params.shrinkDictMaxRegression = kDefaultRegression;
520     return params;
521 }
522 
defaultFastCoverParams(void)523 static ZDICT_fastCover_params_t defaultFastCoverParams(void)
524 {
525     ZDICT_fastCover_params_t params;
526     memset(&params, 0, sizeof(params));
527     params.d = 8;
528     params.f = 20;
529     params.steps = 4;
530     params.splitPoint = 0.75; /* different from default splitPoint of cover */
531     params.accel = DEFAULT_ACCEL;
532     params.shrinkDict = 0;
533     params.shrinkDictMaxRegression = kDefaultRegression;
534     return params;
535 }
536 #endif
537 
538 
539 /** parseAdaptParameters() :
540  *  reads adapt parameters from *stringPtr (e.g. "--zstd=min=1,max=19) and store them into adaptMinPtr and adaptMaxPtr.
541  *  Both adaptMinPtr and adaptMaxPtr must be already allocated and correctly initialized.
542  *  There is no guarantee that any of these values will be updated.
543  *  @return 1 means that parsing was successful,
544  *  @return 0 in case of malformed parameters
545  */
parseAdaptParameters(const char * stringPtr,int * adaptMinPtr,int * adaptMaxPtr)546 static unsigned parseAdaptParameters(const char* stringPtr, int* adaptMinPtr, int* adaptMaxPtr)
547 {
548     for ( ; ;) {
549         if (longCommandWArg(&stringPtr, "min=")) { *adaptMinPtr = (int)readU32FromChar(&stringPtr); if (stringPtr[0]==',') { stringPtr++; continue; } else break; }
550         if (longCommandWArg(&stringPtr, "max=")) { *adaptMaxPtr = (int)readU32FromChar(&stringPtr); if (stringPtr[0]==',') { stringPtr++; continue; } else break; }
551         DISPLAYLEVEL(4, "invalid compression parameter \n");
552         return 0;
553     }
554     if (stringPtr[0] != 0) return 0; /* check the end of string */
555     if (*adaptMinPtr > *adaptMaxPtr) {
556         DISPLAYLEVEL(4, "incoherent adaptation limits \n");
557         return 0;
558     }
559     return 1;
560 }
561 
562 
563 /** parseCompressionParameters() :
564  *  reads compression parameters from *stringPtr (e.g. "--zstd=wlog=23,clog=23,hlog=22,slog=6,mml=3,tlen=48,strat=6") into *params
565  *  @return 1 means that compression parameters were correct
566  *  @return 0 in case of malformed parameters
567  */
parseCompressionParameters(const char * stringPtr,ZSTD_compressionParameters * params)568 static unsigned parseCompressionParameters(const char* stringPtr, ZSTD_compressionParameters* params)
569 {
570     for ( ; ;) {
571         if (longCommandWArg(&stringPtr, "windowLog=") || longCommandWArg(&stringPtr, "wlog=")) { params->windowLog = readU32FromChar(&stringPtr); if (stringPtr[0]==',') { stringPtr++; continue; } else break; }
572         if (longCommandWArg(&stringPtr, "chainLog=") || longCommandWArg(&stringPtr, "clog=")) { params->chainLog = readU32FromChar(&stringPtr); if (stringPtr[0]==',') { stringPtr++; continue; } else break; }
573         if (longCommandWArg(&stringPtr, "hashLog=") || longCommandWArg(&stringPtr, "hlog=")) { params->hashLog = readU32FromChar(&stringPtr); if (stringPtr[0]==',') { stringPtr++; continue; } else break; }
574         if (longCommandWArg(&stringPtr, "searchLog=") || longCommandWArg(&stringPtr, "slog=")) { params->searchLog = readU32FromChar(&stringPtr); if (stringPtr[0]==',') { stringPtr++; continue; } else break; }
575         if (longCommandWArg(&stringPtr, "minMatch=") || longCommandWArg(&stringPtr, "mml=")) { params->minMatch = readU32FromChar(&stringPtr); if (stringPtr[0]==',') { stringPtr++; continue; } else break; }
576         if (longCommandWArg(&stringPtr, "targetLength=") || longCommandWArg(&stringPtr, "tlen=")) { params->targetLength = readU32FromChar(&stringPtr); if (stringPtr[0]==',') { stringPtr++; continue; } else break; }
577         if (longCommandWArg(&stringPtr, "strategy=") || longCommandWArg(&stringPtr, "strat=")) { params->strategy = (ZSTD_strategy)(readU32FromChar(&stringPtr)); if (stringPtr[0]==',') { stringPtr++; continue; } else break; }
578         if (longCommandWArg(&stringPtr, "overlapLog=") || longCommandWArg(&stringPtr, "ovlog=")) { g_overlapLog = readU32FromChar(&stringPtr); if (stringPtr[0]==',') { stringPtr++; continue; } else break; }
579         if (longCommandWArg(&stringPtr, "ldmHashLog=") || longCommandWArg(&stringPtr, "lhlog=")) { g_ldmHashLog = readU32FromChar(&stringPtr); if (stringPtr[0]==',') { stringPtr++; continue; } else break; }
580         if (longCommandWArg(&stringPtr, "ldmMinMatch=") || longCommandWArg(&stringPtr, "lmml=")) { g_ldmMinMatch = readU32FromChar(&stringPtr); if (stringPtr[0]==',') { stringPtr++; continue; } else break; }
581         if (longCommandWArg(&stringPtr, "ldmBucketSizeLog=") || longCommandWArg(&stringPtr, "lblog=")) { g_ldmBucketSizeLog = readU32FromChar(&stringPtr); if (stringPtr[0]==',') { stringPtr++; continue; } else break; }
582         if (longCommandWArg(&stringPtr, "ldmHashRateLog=") || longCommandWArg(&stringPtr, "lhrlog=")) { g_ldmHashRateLog = readU32FromChar(&stringPtr); if (stringPtr[0]==',') { stringPtr++; continue; } else break; }
583         DISPLAYLEVEL(4, "invalid compression parameter \n");
584         return 0;
585     }
586 
587     DISPLAYLEVEL(4, "windowLog=%d, chainLog=%d, hashLog=%d, searchLog=%d \n", params->windowLog, params->chainLog, params->hashLog, params->searchLog);
588     DISPLAYLEVEL(4, "minMatch=%d, targetLength=%d, strategy=%d \n", params->minMatch, params->targetLength, params->strategy);
589     if (stringPtr[0] != 0) return 0; /* check the end of string */
590     return 1;
591 }
592 
printVersion(void)593 static void printVersion(void)
594 {
595     if (g_displayLevel < DISPLAY_LEVEL_DEFAULT) {
596         DISPLAYOUT("%s\n", ZSTD_VERSION_STRING);
597         return;
598     }
599 
600     DISPLAYOUT(WELCOME_MESSAGE);
601     if (g_displayLevel >= 3) {
602     /* format support */
603         DISPLAYOUT("*** supports: zstd");
604     #if defined(ZSTD_LEGACY_SUPPORT) && (ZSTD_LEGACY_SUPPORT>0) && (ZSTD_LEGACY_SUPPORT<8)
605         DISPLAYOUT(", zstd legacy v0.%d+", ZSTD_LEGACY_SUPPORT);
606     #endif
607     #ifdef ZSTD_GZCOMPRESS
608         DISPLAYOUT(", gzip");
609     #endif
610     #ifdef ZSTD_LZ4COMPRESS
611         DISPLAYOUT(", lz4");
612     #endif
613     #ifdef ZSTD_LZMACOMPRESS
614         DISPLAYOUT(", lzma, xz ");
615     #endif
616         DISPLAYOUT("\n");
617         if (g_displayLevel >= 4) {
618             /* posix support */
619         #ifdef _POSIX_C_SOURCE
620             DISPLAYOUT("_POSIX_C_SOURCE defined: %ldL\n", (long) _POSIX_C_SOURCE);
621         #endif
622         #ifdef _POSIX_VERSION
623             DISPLAYOUT("_POSIX_VERSION defined: %ldL \n", (long) _POSIX_VERSION);
624         #endif
625         #ifdef PLATFORM_POSIX_VERSION
626             DISPLAYOUT("PLATFORM_POSIX_VERSION defined: %ldL\n", (long) PLATFORM_POSIX_VERSION);
627         #endif
628     }   }
629 }
630 
631 /* Environment variables for parameter setting */
632 #define ENV_CLEVEL "ZSTD_CLEVEL"
633 #define ENV_NBTHREADS "ZSTD_NBTHREADS"    /* takes lower precedence than directly specifying -T# in the CLI */
634 
635 /* pick up environment variable */
init_cLevel(void)636 static int init_cLevel(void) {
637     const char* const env = getenv(ENV_CLEVEL);
638     if (env != NULL) {
639         const char* ptr = env;
640         int sign = 1;
641         if (*ptr == '-') {
642             sign = -1;
643             ptr++;
644         } else if (*ptr == '+') {
645             ptr++;
646         }
647 
648         if ((*ptr>='0') && (*ptr<='9')) {
649             unsigned absLevel;
650             if (readU32FromCharChecked(&ptr, &absLevel)) {
651                 DISPLAYLEVEL(2, "Ignore environment variable setting %s=%s: numeric value too large \n", ENV_CLEVEL, env);
652                 return ZSTDCLI_CLEVEL_DEFAULT;
653             } else if (*ptr == 0) {
654                 return sign * (int)absLevel;
655         }   }
656 
657         DISPLAYLEVEL(2, "Ignore environment variable setting %s=%s: not a valid integer value \n", ENV_CLEVEL, env);
658     }
659 
660     return ZSTDCLI_CLEVEL_DEFAULT;
661 }
662 
663 #ifdef ZSTD_MULTITHREAD
init_nbThreads(void)664 static unsigned init_nbThreads(void) {
665     const char* const env = getenv(ENV_NBTHREADS);
666     if (env != NULL) {
667         const char* ptr = env;
668         if ((*ptr>='0') && (*ptr<='9')) {
669             unsigned nbThreads;
670             if (readU32FromCharChecked(&ptr, &nbThreads)) {
671                 DISPLAYLEVEL(2, "Ignore environment variable setting %s=%s: numeric value too large \n", ENV_NBTHREADS, env);
672                 return ZSTDCLI_NBTHREADS_DEFAULT;
673             } else if (*ptr == 0) {
674                 return nbThreads;
675             }
676         }
677         DISPLAYLEVEL(2, "Ignore environment variable setting %s=%s: not a valid unsigned value \n", ENV_NBTHREADS, env);
678     }
679 
680     return ZSTDCLI_NBTHREADS_DEFAULT;
681 }
682 #endif
683 
684 #define NEXT_FIELD(ptr) {         \
685     if (*argument == '=') {       \
686         ptr = ++argument;         \
687         argument += strlen(ptr);  \
688     } else {                      \
689         argNb++;                  \
690         if (argNb >= argCount) {  \
691             DISPLAY("error: missing command argument \n"); \
692             CLEAN_RETURN(1);      \
693         }                         \
694         ptr = argv[argNb];        \
695         assert(ptr != NULL);      \
696         if (ptr[0]=='-') {        \
697             DISPLAY("error: command cannot be separated from its argument by another command \n"); \
698             CLEAN_RETURN(1);      \
699 }   }   }
700 
701 #define NEXT_UINT32(val32) {      \
702     const char* __nb;             \
703     NEXT_FIELD(__nb);             \
704     val32 = readU32FromChar(&__nb); \
705 }
706 
707 #define ZSTD_NB_STRATEGIES 9
708 static const char* ZSTD_strategyMap[ZSTD_NB_STRATEGIES + 1] = { "", "ZSTD_fast",
709                 "ZSTD_dfast", "ZSTD_greedy", "ZSTD_lazy", "ZSTD_lazy2", "ZSTD_btlazy2",
710                 "ZSTD_btopt", "ZSTD_btultra", "ZSTD_btultra2"};
711 
712 typedef enum { zom_compress, zom_decompress, zom_test, zom_bench, zom_train, zom_list } zstd_operation_mode;
713 
714 #define CLEAN_RETURN(i) { operationResult = (i); goto _end; }
715 
716 #ifdef ZSTD_NOCOMPRESS
717 /* symbols from compression library are not defined and should not be invoked */
718 # define MINCLEVEL  -99
719 # define MAXCLEVEL   22
720 #else
721 # define MINCLEVEL  ZSTD_minCLevel()
722 # define MAXCLEVEL  ZSTD_maxCLevel()
723 #endif
724 
main(int const argCount,const char * argv[])725 int main(int const argCount, const char* argv[])
726 {
727     int argNb,
728         followLinks = 0,
729         allowBlockDevices = 0,
730         forceStdin = 0,
731         forceStdout = 0,
732         hasStdout = 0,
733         ldmFlag = 0,
734         main_pause = 0,
735         nbWorkers = 0,
736         adapt = 0,
737         useRowMatchFinder = 0,
738         adaptMin = MINCLEVEL,
739         adaptMax = MAXCLEVEL,
740         rsyncable = 0,
741         nextArgumentsAreFiles = 0,
742         operationResult = 0,
743         separateFiles = 0,
744         setRealTimePrio = 0,
745         singleThread = 0,
746         showDefaultCParams = 0,
747         ultra=0,
748         contentSize=1;
749     double compressibility = 0.5;
750     unsigned bench_nbSeconds = 3;   /* would be better if this value was synchronized from bench */
751     size_t blockSize = 0;
752 
753     FIO_prefs_t* const prefs = FIO_createPreferences();
754     FIO_ctx_t* const fCtx = FIO_createContext();
755     zstd_operation_mode operation = zom_compress;
756     ZSTD_compressionParameters compressionParams;
757     int cLevel = init_cLevel();
758     int cLevelLast = MINCLEVEL - 1;  /* lower than minimum */
759     unsigned recursive = 0;
760     unsigned memLimit = 0;
761     FileNamesTable* filenames = UTIL_allocateFileNamesTable((size_t)argCount);  /* argCount >= 1 */
762     FileNamesTable* file_of_names = UTIL_allocateFileNamesTable((size_t)argCount);  /* argCount >= 1 */
763     const char* programName = argv[0];
764     const char* outFileName = NULL;
765     const char* outDirName = NULL;
766     const char* outMirroredDirName = NULL;
767     const char* dictFileName = NULL;
768     const char* patchFromDictFileName = NULL;
769     const char* suffix = ZSTD_EXTENSION;
770     unsigned maxDictSize = g_defaultMaxDictSize;
771     unsigned dictID = 0;
772     size_t streamSrcSize = 0;
773     size_t targetCBlockSize = 0;
774     size_t srcSizeHint = 0;
775     int dictCLevel = g_defaultDictCLevel;
776     unsigned dictSelect = g_defaultSelectivityLevel;
777 #ifndef ZSTD_NODICT
778     ZDICT_cover_params_t coverParams = defaultCoverParams();
779     ZDICT_fastCover_params_t fastCoverParams = defaultFastCoverParams();
780     dictType dict = fastCover;
781 #endif
782 #ifndef ZSTD_NOBENCH
783     BMK_advancedParams_t benchParams = BMK_initAdvancedParams();
784 #endif
785     ZSTD_literalCompressionMode_e literalCompressionMode = ZSTD_lcm_auto;
786 
787 
788     /* init */
789     checkLibVersion();
790     (void)recursive; (void)cLevelLast;    /* not used when ZSTD_NOBENCH set */
791     (void)memLimit;
792     assert(argCount >= 1);
793     if ((filenames==NULL) || (file_of_names==NULL)) { DISPLAY("zstd: allocation error \n"); exit(1); }
794     programName = lastNameFromPath(programName);
795 #ifdef ZSTD_MULTITHREAD
796     nbWorkers = init_nbThreads();
797 #endif
798 
799     /* preset behaviors */
800     if (exeNameMatch(programName, ZSTD_ZSTDMT)) nbWorkers=0, singleThread=0;
801     if (exeNameMatch(programName, ZSTD_UNZSTD)) operation=zom_decompress;
802     if (exeNameMatch(programName, ZSTD_CAT)) { operation=zom_decompress; FIO_overwriteMode(prefs); forceStdout=1; followLinks=1; outFileName=stdoutmark; g_displayLevel=1; }     /* supports multiple formats */
803     if (exeNameMatch(programName, ZSTD_ZCAT)) { operation=zom_decompress; FIO_overwriteMode(prefs); forceStdout=1; followLinks=1; outFileName=stdoutmark; g_displayLevel=1; }    /* behave like zcat, also supports multiple formats */
804     if (exeNameMatch(programName, ZSTD_GZ)) { suffix = GZ_EXTENSION; FIO_setCompressionType(prefs, FIO_gzipCompression); FIO_setRemoveSrcFile(prefs, 1); }        /* behave like gzip */
805     if (exeNameMatch(programName, ZSTD_GUNZIP)) { operation=zom_decompress; FIO_setRemoveSrcFile(prefs, 1); }                                                     /* behave like gunzip, also supports multiple formats */
806     if (exeNameMatch(programName, ZSTD_GZCAT)) { operation=zom_decompress; FIO_overwriteMode(prefs); forceStdout=1; followLinks=1; outFileName=stdoutmark; g_displayLevel=1; }   /* behave like gzcat, also supports multiple formats */
807     if (exeNameMatch(programName, ZSTD_LZMA)) { suffix = LZMA_EXTENSION; FIO_setCompressionType(prefs, FIO_lzmaCompression); FIO_setRemoveSrcFile(prefs, 1); }    /* behave like lzma */
808     if (exeNameMatch(programName, ZSTD_UNLZMA)) { operation=zom_decompress; FIO_setCompressionType(prefs, FIO_lzmaCompression); FIO_setRemoveSrcFile(prefs, 1); } /* behave like unlzma, also supports multiple formats */
809     if (exeNameMatch(programName, ZSTD_XZ)) { suffix = XZ_EXTENSION; FIO_setCompressionType(prefs, FIO_xzCompression); FIO_setRemoveSrcFile(prefs, 1); }          /* behave like xz */
810     if (exeNameMatch(programName, ZSTD_UNXZ)) { operation=zom_decompress; FIO_setCompressionType(prefs, FIO_xzCompression); FIO_setRemoveSrcFile(prefs, 1); }     /* behave like unxz, also supports multiple formats */
811     if (exeNameMatch(programName, ZSTD_LZ4)) { suffix = LZ4_EXTENSION; FIO_setCompressionType(prefs, FIO_lz4Compression); }                                       /* behave like lz4 */
812     if (exeNameMatch(programName, ZSTD_UNLZ4)) { operation=zom_decompress; FIO_setCompressionType(prefs, FIO_lz4Compression); }                                   /* behave like unlz4, also supports multiple formats */
813     memset(&compressionParams, 0, sizeof(compressionParams));
814 
815     /* init crash handler */
816     FIO_addAbortHandler();
817 
818     /* command switches */
819     for (argNb=1; argNb<argCount; argNb++) {
820         const char* argument = argv[argNb];
821         if (!argument) continue;   /* Protection if argument empty */
822 
823         if (nextArgumentsAreFiles) {
824             UTIL_refFilename(filenames, argument);
825             continue;
826         }
827 
828         /* "-" means stdin/stdout */
829         if (!strcmp(argument, "-")){
830             UTIL_refFilename(filenames, stdinmark);
831             continue;
832         }
833 
834         /* Decode commands (note : aggregated commands are allowed) */
835         if (argument[0]=='-') {
836 
837             if (argument[1]=='-') {
838                 /* long commands (--long-word) */
839                 if (!strcmp(argument, "--")) { nextArgumentsAreFiles=1; continue; }   /* only file names allowed from now on */
840                 if (!strcmp(argument, "--list")) { operation=zom_list; continue; }
841                 if (!strcmp(argument, "--compress")) { operation=zom_compress; continue; }
842                 if (!strcmp(argument, "--decompress")) { operation=zom_decompress; continue; }
843                 if (!strcmp(argument, "--uncompress")) { operation=zom_decompress; continue; }
844                 if (!strcmp(argument, "--force")) { FIO_overwriteMode(prefs); forceStdin=1; forceStdout=1; followLinks=1; allowBlockDevices=1; continue; }
845                 if (!strcmp(argument, "--version")) { printVersion(); CLEAN_RETURN(0); }
846                 if (!strcmp(argument, "--help")) { usage_advanced(programName); CLEAN_RETURN(0); }
847                 if (!strcmp(argument, "--verbose")) { g_displayLevel++; continue; }
848                 if (!strcmp(argument, "--quiet")) { g_displayLevel--; continue; }
849                 if (!strcmp(argument, "--stdout")) { forceStdout=1; outFileName=stdoutmark; g_displayLevel-=(g_displayLevel==2); continue; }
850                 if (!strcmp(argument, "--ultra")) { ultra=1; continue; }
851                 if (!strcmp(argument, "--check")) { FIO_setChecksumFlag(prefs, 2); continue; }
852                 if (!strcmp(argument, "--no-check")) { FIO_setChecksumFlag(prefs, 0); continue; }
853                 if (!strcmp(argument, "--sparse")) { FIO_setSparseWrite(prefs, 2); continue; }
854                 if (!strcmp(argument, "--no-sparse")) { FIO_setSparseWrite(prefs, 0); continue; }
855                 if (!strcmp(argument, "--test")) { operation=zom_test; continue; }
856                 if (!strcmp(argument, "--train")) { operation=zom_train; if (outFileName==NULL) outFileName=g_defaultDictName; continue; }
857                 if (!strcmp(argument, "--no-dictID")) { FIO_setDictIDFlag(prefs, 0); continue; }
858                 if (!strcmp(argument, "--keep")) { FIO_setRemoveSrcFile(prefs, 0); continue; }
859                 if (!strcmp(argument, "--rm")) { FIO_setRemoveSrcFile(prefs, 1); continue; }
860                 if (!strcmp(argument, "--priority=rt")) { setRealTimePrio = 1; continue; }
861                 if (!strcmp(argument, "--show-default-cparams")) { showDefaultCParams = 1; continue; }
862                 if (!strcmp(argument, "--content-size")) { contentSize = 1; continue; }
863                 if (!strcmp(argument, "--no-content-size")) { contentSize = 0; continue; }
864                 if (!strcmp(argument, "--adapt")) { adapt = 1; continue; }
865                 if (!strcmp(argument, "--no-row-match-finder")) { useRowMatchFinder = 1; continue; }
866                 if (!strcmp(argument, "--row-match-finder")) { useRowMatchFinder = 2; continue; }
867                 if (longCommandWArg(&argument, "--adapt=")) { adapt = 1; if (!parseAdaptParameters(argument, &adaptMin, &adaptMax)) { badusage(programName); CLEAN_RETURN(1); } continue; }
868                 if (!strcmp(argument, "--single-thread")) { nbWorkers = 0; singleThread = 1; continue; }
869                 if (!strcmp(argument, "--format=zstd")) { suffix = ZSTD_EXTENSION; FIO_setCompressionType(prefs, FIO_zstdCompression); continue; }
870 #ifdef ZSTD_GZCOMPRESS
871                 if (!strcmp(argument, "--format=gzip")) { suffix = GZ_EXTENSION; FIO_setCompressionType(prefs, FIO_gzipCompression); continue; }
872 #endif
873 #ifdef ZSTD_LZMACOMPRESS
874                 if (!strcmp(argument, "--format=lzma")) { suffix = LZMA_EXTENSION; FIO_setCompressionType(prefs, FIO_lzmaCompression);  continue; }
875                 if (!strcmp(argument, "--format=xz")) { suffix = XZ_EXTENSION; FIO_setCompressionType(prefs, FIO_xzCompression);  continue; }
876 #endif
877 #ifdef ZSTD_LZ4COMPRESS
878                 if (!strcmp(argument, "--format=lz4")) { suffix = LZ4_EXTENSION; FIO_setCompressionType(prefs, FIO_lz4Compression);  continue; }
879 #endif
880                 if (!strcmp(argument, "--rsyncable")) { rsyncable = 1; continue; }
881                 if (!strcmp(argument, "--compress-literals")) { literalCompressionMode = ZSTD_lcm_huffman; continue; }
882                 if (!strcmp(argument, "--no-compress-literals")) { literalCompressionMode = ZSTD_lcm_uncompressed; continue; }
883                 if (!strcmp(argument, "--no-progress")) { FIO_setProgressSetting(FIO_ps_never); continue; }
884                 if (!strcmp(argument, "--progress")) { FIO_setProgressSetting(FIO_ps_always); continue; }
885                 if (!strcmp(argument, "--exclude-compressed")) { FIO_setExcludeCompressedFile(prefs, 1); continue; }
886 
887                 /* long commands with arguments */
888 #ifndef ZSTD_NODICT
889                 if (longCommandWArg(&argument, "--train-cover")) {
890                   operation = zom_train;
891                   if (outFileName == NULL)
892                       outFileName = g_defaultDictName;
893                   dict = cover;
894                   /* Allow optional arguments following an = */
895                   if (*argument == 0) { memset(&coverParams, 0, sizeof(coverParams)); }
896                   else if (*argument++ != '=') { badusage(programName); CLEAN_RETURN(1); }
897                   else if (!parseCoverParameters(argument, &coverParams)) { badusage(programName); CLEAN_RETURN(1); }
898                   continue;
899                 }
900                 if (longCommandWArg(&argument, "--train-fastcover")) {
901                   operation = zom_train;
902                   if (outFileName == NULL)
903                       outFileName = g_defaultDictName;
904                   dict = fastCover;
905                   /* Allow optional arguments following an = */
906                   if (*argument == 0) { memset(&fastCoverParams, 0, sizeof(fastCoverParams)); }
907                   else if (*argument++ != '=') { badusage(programName); CLEAN_RETURN(1); }
908                   else if (!parseFastCoverParameters(argument, &fastCoverParams)) { badusage(programName); CLEAN_RETURN(1); }
909                   continue;
910                 }
911                 if (longCommandWArg(&argument, "--train-legacy")) {
912                   operation = zom_train;
913                   if (outFileName == NULL)
914                       outFileName = g_defaultDictName;
915                   dict = legacy;
916                   /* Allow optional arguments following an = */
917                   if (*argument == 0) { continue; }
918                   else if (*argument++ != '=') { badusage(programName); CLEAN_RETURN(1); }
919                   else if (!parseLegacyParameters(argument, &dictSelect)) { badusage(programName); CLEAN_RETURN(1); }
920                   continue;
921                 }
922 #endif
923                 if (longCommandWArg(&argument, "--threads")) { NEXT_UINT32(nbWorkers); continue; }
924                 if (longCommandWArg(&argument, "--memlimit")) { NEXT_UINT32(memLimit); continue; }
925                 if (longCommandWArg(&argument, "--memory")) { NEXT_UINT32(memLimit); continue; }
926                 if (longCommandWArg(&argument, "--memlimit-decompress")) { NEXT_UINT32(memLimit); continue; }
927                 if (longCommandWArg(&argument, "--block-size=")) { blockSize = readSizeTFromChar(&argument); continue; }
928                 if (longCommandWArg(&argument, "--maxdict")) { NEXT_UINT32(maxDictSize); continue; }
929                 if (longCommandWArg(&argument, "--dictID")) { NEXT_UINT32(dictID); continue; }
930                 if (longCommandWArg(&argument, "--zstd=")) { if (!parseCompressionParameters(argument, &compressionParams)) { badusage(programName); CLEAN_RETURN(1); } continue; }
931                 if (longCommandWArg(&argument, "--stream-size=")) { streamSrcSize = readSizeTFromChar(&argument); continue; }
932                 if (longCommandWArg(&argument, "--target-compressed-block-size=")) { targetCBlockSize = readSizeTFromChar(&argument); continue; }
933                 if (longCommandWArg(&argument, "--size-hint=")) { srcSizeHint = readSizeTFromChar(&argument); continue; }
934                 if (longCommandWArg(&argument, "--output-dir-flat")) { NEXT_FIELD(outDirName); continue; }
935 #ifdef UTIL_HAS_MIRRORFILELIST
936                 if (longCommandWArg(&argument, "--output-dir-mirror")) { NEXT_FIELD(outMirroredDirName); continue; }
937 #endif
938 #ifndef ZSTD_NOTRACE
939                 if (longCommandWArg(&argument, "--trace")) { char const* traceFile; NEXT_FIELD(traceFile); TRACE_enable(traceFile); continue; }
940 #endif
941                 if (longCommandWArg(&argument, "--patch-from")) { NEXT_FIELD(patchFromDictFileName); continue; }
942                 if (longCommandWArg(&argument, "--long")) {
943                     unsigned ldmWindowLog = 0;
944                     ldmFlag = 1;
945                     /* Parse optional window log */
946                     if (*argument == '=') {
947                         ++argument;
948                         ldmWindowLog = readU32FromChar(&argument);
949                     } else if (*argument != 0) {
950                         /* Invalid character following --long */
951                         badusage(programName);
952                         CLEAN_RETURN(1);
953                     }
954                     /* Only set windowLog if not already set by --zstd */
955                     if (compressionParams.windowLog == 0)
956                         compressionParams.windowLog = ldmWindowLog;
957                     continue;
958                 }
959 #ifndef ZSTD_NOCOMPRESS   /* linking ZSTD_minCLevel() requires compression support */
960                 if (longCommandWArg(&argument, "--fast")) {
961                     /* Parse optional acceleration factor */
962                     if (*argument == '=') {
963                         U32 const maxFast = (U32)-ZSTD_minCLevel();
964                         U32 fastLevel;
965                         ++argument;
966                         fastLevel = readU32FromChar(&argument);
967                         if (fastLevel > maxFast) fastLevel = maxFast;
968                         if (fastLevel) {
969                             dictCLevel = cLevel = -(int)fastLevel;
970                         } else {
971                             badusage(programName);
972                             CLEAN_RETURN(1);
973                         }
974                     } else if (*argument != 0) {
975                         /* Invalid character following --fast */
976                         badusage(programName);
977                         CLEAN_RETURN(1);
978                     } else {
979                         cLevel = -1;  /* default for --fast */
980                     }
981                     continue;
982                 }
983 #endif
984 
985                 if (longCommandWArg(&argument, "--filelist")) {
986                     const char* listName;
987                     NEXT_FIELD(listName);
988                     UTIL_refFilename(file_of_names, listName);
989                     continue;
990                 }
991 
992                 /* fall-through, will trigger bad_usage() later on */
993             }
994 
995             argument++;
996             while (argument[0]!=0) {
997 
998 #ifndef ZSTD_NOCOMPRESS
999                 /* compression Level */
1000                 if ((*argument>='0') && (*argument<='9')) {
1001                     dictCLevel = cLevel = (int)readU32FromChar(&argument);
1002                     continue;
1003                 }
1004 #endif
1005 
1006                 switch(argument[0])
1007                 {
1008                     /* Display help */
1009                 case 'V': printVersion(); CLEAN_RETURN(0);   /* Version Only */
1010                 case 'H':
1011                 case 'h': usage_advanced(programName); CLEAN_RETURN(0);
1012 
1013                      /* Compress */
1014                 case 'z': operation=zom_compress; argument++; break;
1015 
1016                      /* Decoding */
1017                 case 'd':
1018 #ifndef ZSTD_NOBENCH
1019                         benchParams.mode = BMK_decodeOnly;
1020                         if (operation==zom_bench) { argument++; break; }  /* benchmark decode (hidden option) */
1021 #endif
1022                         operation=zom_decompress; argument++; break;
1023 
1024                     /* Force stdout, even if stdout==console */
1025                 case 'c': forceStdout=1; outFileName=stdoutmark; argument++; break;
1026 
1027                     /* Use file content as dictionary */
1028                 case 'D': argument++; NEXT_FIELD(dictFileName); break;
1029 
1030                     /* Overwrite */
1031                 case 'f': FIO_overwriteMode(prefs); forceStdin=1; forceStdout=1; followLinks=1; allowBlockDevices=1; argument++; break;
1032 
1033                     /* Verbose mode */
1034                 case 'v': g_displayLevel++; argument++; break;
1035 
1036                     /* Quiet mode */
1037                 case 'q': g_displayLevel--; argument++; break;
1038 
1039                     /* keep source file (default) */
1040                 case 'k': FIO_setRemoveSrcFile(prefs, 0); argument++; break;
1041 
1042                     /* Checksum */
1043                 case 'C': FIO_setChecksumFlag(prefs, 2); argument++; break;
1044 
1045                     /* test compressed file */
1046                 case 't': operation=zom_test; argument++; break;
1047 
1048                     /* destination file name */
1049                 case 'o': argument++; NEXT_FIELD(outFileName); break;
1050 
1051                     /* limit memory */
1052                 case 'M':
1053                     argument++;
1054                     memLimit = readU32FromChar(&argument);
1055                     break;
1056                 case 'l': operation=zom_list; argument++; break;
1057 #ifdef UTIL_HAS_CREATEFILELIST
1058                     /* recursive */
1059                 case 'r': recursive=1; argument++; break;
1060 #endif
1061 
1062 #ifndef ZSTD_NOBENCH
1063                     /* Benchmark */
1064                 case 'b':
1065                     operation=zom_bench;
1066                     argument++;
1067                     break;
1068 
1069                     /* range bench (benchmark only) */
1070                 case 'e':
1071                     /* compression Level */
1072                     argument++;
1073                     cLevelLast = (int)readU32FromChar(&argument);
1074                     break;
1075 
1076                     /* Modify Nb Iterations (benchmark only) */
1077                 case 'i':
1078                     argument++;
1079                     bench_nbSeconds = readU32FromChar(&argument);
1080                     break;
1081 
1082                     /* cut input into blocks (benchmark only) */
1083                 case 'B':
1084                     argument++;
1085                     blockSize = readU32FromChar(&argument);
1086                     break;
1087 
1088                     /* benchmark files separately (hidden option) */
1089                 case 'S':
1090                     argument++;
1091                     separateFiles = 1;
1092                     break;
1093 
1094 #endif   /* ZSTD_NOBENCH */
1095 
1096                     /* nb of threads (hidden option) */
1097                 case 'T':
1098                     argument++;
1099                     nbWorkers = (int)readU32FromChar(&argument);
1100                     break;
1101 
1102                     /* Dictionary Selection level */
1103                 case 's':
1104                     argument++;
1105                     dictSelect = readU32FromChar(&argument);
1106                     break;
1107 
1108                     /* Pause at the end (-p) or set an additional param (-p#) (hidden option) */
1109                 case 'p': argument++;
1110 #ifndef ZSTD_NOBENCH
1111                     if ((*argument>='0') && (*argument<='9')) {
1112                         benchParams.additionalParam = (int)readU32FromChar(&argument);
1113                     } else
1114 #endif
1115                         main_pause=1;
1116                     break;
1117 
1118                     /* Select compressibility of synthetic sample */
1119                 case 'P':
1120                     argument++;
1121                     compressibility = (double)readU32FromChar(&argument) / 100;
1122                     break;
1123 
1124                     /* unknown command */
1125                 default : badusage(programName); CLEAN_RETURN(1);
1126                 }
1127             }
1128             continue;
1129         }   /* if (argument[0]=='-') */
1130 
1131         /* none of the above : add filename to list */
1132         UTIL_refFilename(filenames, argument);
1133     }
1134 
1135     /* Welcome message (if verbose) */
1136     DISPLAYLEVEL(3, WELCOME_MESSAGE);
1137 
1138 #ifdef ZSTD_MULTITHREAD
1139     if ((nbWorkers==0) && (!singleThread)) {
1140         /* automatically set # workers based on # of reported cpus */
1141         nbWorkers = UTIL_countPhysicalCores();
1142         DISPLAYLEVEL(3, "Note: %d physical core(s) detected \n", nbWorkers);
1143     }
1144 #else
1145     (void)singleThread; (void)nbWorkers;
1146 #endif
1147 
1148 #ifdef UTIL_HAS_CREATEFILELIST
1149     g_utilDisplayLevel = g_displayLevel;
1150     if (!followLinks) {
1151         unsigned u, fileNamesNb;
1152         unsigned const nbFilenames = (unsigned)filenames->tableSize;
1153         for (u=0, fileNamesNb=0; u<nbFilenames; u++) {
1154             if ( UTIL_isLink(filenames->fileNames[u])
1155              && !UTIL_isFIFO(filenames->fileNames[u])
1156             ) {
1157                 DISPLAYLEVEL(2, "Warning : %s is a symbolic link, ignoring \n", filenames->fileNames[u]);
1158             } else {
1159                 filenames->fileNames[fileNamesNb++] = filenames->fileNames[u];
1160         }   }
1161         if (fileNamesNb == 0 && nbFilenames > 0)  /* all names are eliminated */
1162             CLEAN_RETURN(1);
1163         filenames->tableSize = fileNamesNb;
1164     }   /* if (!followLinks) */
1165 
1166     /* read names from a file */
1167     if (file_of_names->tableSize) {
1168         size_t const nbFileLists = file_of_names->tableSize;
1169         size_t flNb;
1170         for (flNb=0; flNb < nbFileLists; flNb++) {
1171             FileNamesTable* const fnt = UTIL_createFileNamesTable_fromFileName(file_of_names->fileNames[flNb]);
1172             if (fnt==NULL) {
1173                 DISPLAYLEVEL(1, "zstd: error reading %s \n", file_of_names->fileNames[flNb]);
1174                 CLEAN_RETURN(1);
1175             }
1176             filenames = UTIL_mergeFileNamesTable(filenames, fnt);
1177         }
1178     }
1179 
1180     if (recursive) {  /* at this stage, filenameTable is a list of paths, which can contain both files and directories */
1181         UTIL_expandFNT(&filenames, followLinks);
1182     }
1183 #else
1184     (void)followLinks;
1185 #endif
1186 
1187     if (operation == zom_list) {
1188 #ifndef ZSTD_NODECOMPRESS
1189         int const ret = FIO_listMultipleFiles((unsigned)filenames->tableSize, filenames->fileNames, g_displayLevel);
1190         CLEAN_RETURN(ret);
1191 #else
1192         DISPLAY("file information is not supported \n");
1193         CLEAN_RETURN(1);
1194 #endif
1195     }
1196 
1197     /* Check if benchmark is selected */
1198     if (operation==zom_bench) {
1199 #ifndef ZSTD_NOBENCH
1200         benchParams.blockSize = blockSize;
1201         benchParams.nbWorkers = nbWorkers;
1202         benchParams.realTime = (unsigned)setRealTimePrio;
1203         benchParams.nbSeconds = bench_nbSeconds;
1204         benchParams.ldmFlag = ldmFlag;
1205         benchParams.ldmMinMatch = (int)g_ldmMinMatch;
1206         benchParams.ldmHashLog = (int)g_ldmHashLog;
1207         benchParams.useRowMatchFinder = useRowMatchFinder;
1208         if (g_ldmBucketSizeLog != LDM_PARAM_DEFAULT) {
1209             benchParams.ldmBucketSizeLog = (int)g_ldmBucketSizeLog;
1210         }
1211         if (g_ldmHashRateLog != LDM_PARAM_DEFAULT) {
1212             benchParams.ldmHashRateLog = (int)g_ldmHashRateLog;
1213         }
1214         benchParams.literalCompressionMode = literalCompressionMode;
1215 
1216         if (cLevel > ZSTD_maxCLevel()) cLevel = ZSTD_maxCLevel();
1217         if (cLevelLast > ZSTD_maxCLevel()) cLevelLast = ZSTD_maxCLevel();
1218         if (cLevelLast < cLevel) cLevelLast = cLevel;
1219         if (cLevelLast > cLevel)
1220             DISPLAYLEVEL(3, "Benchmarking levels from %d to %d\n", cLevel, cLevelLast);
1221         if (filenames->tableSize > 0) {
1222             if(separateFiles) {
1223                 unsigned i;
1224                 for(i = 0; i < filenames->tableSize; i++) {
1225                     int c;
1226                     DISPLAYLEVEL(3, "Benchmarking %s \n", filenames->fileNames[i]);
1227                     for(c = cLevel; c <= cLevelLast; c++) {
1228                         BMK_benchFilesAdvanced(&filenames->fileNames[i], 1, dictFileName, c, &compressionParams, g_displayLevel, &benchParams);
1229                 }   }
1230             } else {
1231                 for(; cLevel <= cLevelLast; cLevel++) {
1232                     BMK_benchFilesAdvanced(filenames->fileNames, (unsigned)filenames->tableSize, dictFileName, cLevel, &compressionParams, g_displayLevel, &benchParams);
1233             }   }
1234         } else {
1235             for(; cLevel <= cLevelLast; cLevel++) {
1236                 BMK_syntheticTest(cLevel, compressibility, &compressionParams, g_displayLevel, &benchParams);
1237         }   }
1238 
1239 #else
1240         (void)bench_nbSeconds; (void)blockSize; (void)setRealTimePrio; (void)separateFiles; (void)compressibility;
1241 #endif
1242         goto _end;
1243     }
1244 
1245     /* Check if dictionary builder is selected */
1246     if (operation==zom_train) {
1247 #ifndef ZSTD_NODICT
1248         ZDICT_params_t zParams;
1249         zParams.compressionLevel = dictCLevel;
1250         zParams.notificationLevel = (unsigned)g_displayLevel;
1251         zParams.dictID = dictID;
1252         if (dict == cover) {
1253             int const optimize = !coverParams.k || !coverParams.d;
1254             coverParams.nbThreads = (unsigned)nbWorkers;
1255             coverParams.zParams = zParams;
1256             operationResult = DiB_trainFromFiles(outFileName, maxDictSize, filenames->fileNames, (unsigned)filenames->tableSize, blockSize, NULL, &coverParams, NULL, optimize);
1257         } else if (dict == fastCover) {
1258             int const optimize = !fastCoverParams.k || !fastCoverParams.d;
1259             fastCoverParams.nbThreads = (unsigned)nbWorkers;
1260             fastCoverParams.zParams = zParams;
1261             operationResult = DiB_trainFromFiles(outFileName, maxDictSize, filenames->fileNames, (unsigned)filenames->tableSize, blockSize, NULL, NULL, &fastCoverParams, optimize);
1262         } else {
1263             ZDICT_legacy_params_t dictParams;
1264             memset(&dictParams, 0, sizeof(dictParams));
1265             dictParams.selectivityLevel = dictSelect;
1266             dictParams.zParams = zParams;
1267             operationResult = DiB_trainFromFiles(outFileName, maxDictSize, filenames->fileNames, (unsigned)filenames->tableSize, blockSize, &dictParams, NULL, NULL, 0);
1268         }
1269 #else
1270         (void)dictCLevel; (void)dictSelect; (void)dictID;  (void)maxDictSize; /* not used when ZSTD_NODICT set */
1271         DISPLAYLEVEL(1, "training mode not available \n");
1272         operationResult = 1;
1273 #endif
1274         goto _end;
1275     }
1276 
1277 #ifndef ZSTD_NODECOMPRESS
1278     if (operation==zom_test) { FIO_setTestMode(prefs, 1); outFileName=nulmark; FIO_setRemoveSrcFile(prefs, 0); }  /* test mode */
1279 #endif
1280 
1281     /* No input filename ==> use stdin and stdout */
1282     if (filenames->tableSize == 0) UTIL_refFilename(filenames, stdinmark);
1283     if (!strcmp(filenames->fileNames[0], stdinmark) && !outFileName)
1284         outFileName = stdoutmark;  /* when input is stdin, default output is stdout */
1285 
1286     /* Check if input/output defined as console; trigger an error in this case */
1287     if (!forceStdin
1288      && !strcmp(filenames->fileNames[0], stdinmark)
1289      && IS_CONSOLE(stdin) ) {
1290         DISPLAYLEVEL(1, "stdin is a console, aborting\n");
1291         CLEAN_RETURN(1);
1292     }
1293     if ( outFileName && !strcmp(outFileName, stdoutmark)
1294       && IS_CONSOLE(stdout)
1295       && !strcmp(filenames->fileNames[0], stdinmark)
1296       && !forceStdout
1297       && operation!=zom_decompress ) {
1298         DISPLAYLEVEL(1, "stdout is a console, aborting\n");
1299         CLEAN_RETURN(1);
1300     }
1301 
1302 #ifndef ZSTD_NOCOMPRESS
1303     /* check compression level limits */
1304     {   int const maxCLevel = ultra ? ZSTD_maxCLevel() : ZSTDCLI_CLEVEL_MAX;
1305         if (cLevel > maxCLevel) {
1306             DISPLAYLEVEL(2, "Warning : compression level higher than max, reduced to %i \n", maxCLevel);
1307             cLevel = maxCLevel;
1308     }   }
1309 #endif
1310 
1311     if (showDefaultCParams) {
1312         if (operation == zom_decompress) {
1313             DISPLAY("error : can't use --show-default-cparams in decomrpession mode \n");
1314             CLEAN_RETURN(1);
1315         }
1316     }
1317 
1318     if (dictFileName != NULL && patchFromDictFileName != NULL) {
1319         DISPLAY("error : can't use -D and --patch-from=# at the same time \n");
1320         CLEAN_RETURN(1);
1321     }
1322 
1323     if (patchFromDictFileName != NULL && filenames->tableSize > 1) {
1324         DISPLAY("error : can't use --patch-from=# on multiple files \n");
1325         CLEAN_RETURN(1);
1326     }
1327 
1328     /* No status message in pipe mode (stdin - stdout) */
1329     hasStdout = outFileName && !strcmp(outFileName,stdoutmark);
1330 
1331     if (hasStdout && (g_displayLevel==2)) g_displayLevel=1;
1332 
1333     /* IO Stream/File */
1334     FIO_setHasStdoutOutput(fCtx, hasStdout);
1335     FIO_setNbFilesTotal(fCtx, (int)filenames->tableSize);
1336     FIO_determineHasStdinInput(fCtx, filenames);
1337     FIO_setNotificationLevel(g_displayLevel);
1338     FIO_setAllowBlockDevices(prefs, allowBlockDevices);
1339     FIO_setPatchFromMode(prefs, patchFromDictFileName != NULL);
1340     if (memLimit == 0) {
1341         if (compressionParams.windowLog == 0) {
1342             memLimit = (U32)1 << g_defaultMaxWindowLog;
1343         } else {
1344             memLimit = (U32)1 << (compressionParams.windowLog & 31);
1345     }   }
1346     if (patchFromDictFileName != NULL)
1347         dictFileName = patchFromDictFileName;
1348     FIO_setMemLimit(prefs, memLimit);
1349     if (operation==zom_compress) {
1350 #ifndef ZSTD_NOCOMPRESS
1351         FIO_setContentSize(prefs, contentSize);
1352         FIO_setNbWorkers(prefs, nbWorkers);
1353         FIO_setBlockSize(prefs, (int)blockSize);
1354         if (g_overlapLog!=OVERLAP_LOG_DEFAULT) FIO_setOverlapLog(prefs, (int)g_overlapLog);
1355         FIO_setLdmFlag(prefs, (unsigned)ldmFlag);
1356         FIO_setLdmHashLog(prefs, (int)g_ldmHashLog);
1357         FIO_setLdmMinMatch(prefs, (int)g_ldmMinMatch);
1358         if (g_ldmBucketSizeLog != LDM_PARAM_DEFAULT) FIO_setLdmBucketSizeLog(prefs, (int)g_ldmBucketSizeLog);
1359         if (g_ldmHashRateLog != LDM_PARAM_DEFAULT) FIO_setLdmHashRateLog(prefs, (int)g_ldmHashRateLog);
1360         FIO_setAdaptiveMode(prefs, (unsigned)adapt);
1361         FIO_setUseRowMatchFinder(prefs, useRowMatchFinder);
1362         FIO_setAdaptMin(prefs, adaptMin);
1363         FIO_setAdaptMax(prefs, adaptMax);
1364         FIO_setRsyncable(prefs, rsyncable);
1365         FIO_setStreamSrcSize(prefs, streamSrcSize);
1366         FIO_setTargetCBlockSize(prefs, targetCBlockSize);
1367         FIO_setSrcSizeHint(prefs, srcSizeHint);
1368         FIO_setLiteralCompressionMode(prefs, literalCompressionMode);
1369         if (adaptMin > cLevel) cLevel = adaptMin;
1370         if (adaptMax < cLevel) cLevel = adaptMax;
1371 
1372         /* Compare strategies constant with the ground truth */
1373         { ZSTD_bounds strategyBounds = ZSTD_cParam_getBounds(ZSTD_c_strategy);
1374           assert(ZSTD_NB_STRATEGIES == strategyBounds.upperBound);
1375           (void)strategyBounds; }
1376 
1377         if (showDefaultCParams) {
1378             size_t fileNb;
1379             for (fileNb = 0; fileNb < (size_t)filenames->tableSize; fileNb++) {
1380                 unsigned long long fileSize = UTIL_getFileSize(filenames->fileNames[fileNb]);
1381                 const size_t dictSize = dictFileName != NULL ? (size_t)UTIL_getFileSize(dictFileName) : 0;
1382                 const ZSTD_compressionParameters cParams = ZSTD_getCParams(cLevel, fileSize, dictSize);
1383                 if (fileSize != UTIL_FILESIZE_UNKNOWN) DISPLAY("%s (%u bytes)\n", filenames->fileNames[fileNb], (unsigned)fileSize);
1384                 else DISPLAY("%s (src size unknown)\n", filenames->fileNames[fileNb]);
1385                 DISPLAY(" - windowLog     : %u\n", cParams.windowLog);
1386                 DISPLAY(" - chainLog      : %u\n", cParams.chainLog);
1387                 DISPLAY(" - hashLog       : %u\n", cParams.hashLog);
1388                 DISPLAY(" - searchLog     : %u\n", cParams.searchLog);
1389                 DISPLAY(" - minMatch      : %u\n", cParams.minMatch);
1390                 DISPLAY(" - targetLength  : %u\n", cParams.targetLength);
1391                 assert(cParams.strategy < ZSTD_NB_STRATEGIES + 1);
1392                 DISPLAY(" - strategy      : %s (%u)\n", ZSTD_strategyMap[(int)cParams.strategy], (unsigned)cParams.strategy);
1393             }
1394         }
1395 
1396         if ((filenames->tableSize==1) && outFileName)
1397             operationResult = FIO_compressFilename(fCtx, prefs, outFileName, filenames->fileNames[0], dictFileName, cLevel, compressionParams);
1398         else
1399             operationResult = FIO_compressMultipleFilenames(fCtx, prefs, filenames->fileNames, outMirroredDirName, outDirName, outFileName, suffix, dictFileName, cLevel, compressionParams);
1400 #else
1401         (void)contentSize; (void)suffix; (void)adapt; (void)rsyncable; (void)ultra; (void)cLevel; (void)ldmFlag; (void)literalCompressionMode; (void)targetCBlockSize; (void)streamSrcSize; (void)srcSizeHint; (void)ZSTD_strategyMap; (void)useRowMatchFinder; /* not used when ZSTD_NOCOMPRESS set */
1402         DISPLAY("Compression not supported \n");
1403 #endif
1404     } else {  /* decompression or test */
1405 #ifndef ZSTD_NODECOMPRESS
1406         if (filenames->tableSize == 1 && outFileName) {
1407             operationResult = FIO_decompressFilename(fCtx, prefs, outFileName, filenames->fileNames[0], dictFileName);
1408         } else {
1409             operationResult = FIO_decompressMultipleFilenames(fCtx, prefs, filenames->fileNames, outMirroredDirName, outDirName, outFileName, dictFileName);
1410         }
1411 #else
1412         DISPLAY("Decompression not supported \n");
1413 #endif
1414     }
1415 
1416 _end:
1417     FIO_freePreferences(prefs);
1418     FIO_freeContext(fCtx);
1419     if (main_pause) waitEnter();
1420     UTIL_freeFileNamesTable(filenames);
1421     UTIL_freeFileNamesTable(file_of_names);
1422 #ifndef ZSTD_NOTRACE
1423     TRACE_finish();
1424 #endif
1425 
1426     return operationResult;
1427 }
1428