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