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