xref: /freebsd/sys/contrib/zstd/programs/zstdcli.c (revision d8a0fe102c0cfdfcd5b818f850eff09d8536c9bc)
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 <string.h>   /* strcmp, strlen */
32 #include <errno.h>    /* errno */
33 #include "fileio.h"   /* stdinmark, stdoutmark, ZSTD_EXTENSION */
34 #ifndef ZSTD_NOBENCH
35 #  include "bench.h"  /* BMK_benchFiles, BMK_SetNbSeconds */
36 #endif
37 #ifndef ZSTD_NODICT
38 #  include "dibio.h"  /* ZDICT_cover_params_t, DiB_trainFromFiles() */
39 #endif
40 #define ZSTD_STATIC_LINKING_ONLY   /* ZSTD_maxCLevel */
41 #include "zstd.h"     /* ZSTD_VERSION_STRING */
42 
43 
44 /*-************************************
45 *  Constants
46 **************************************/
47 #define COMPRESSOR_NAME "zstd command line interface"
48 #ifndef ZSTD_VERSION
49 #  define ZSTD_VERSION "v" ZSTD_VERSION_STRING
50 #endif
51 #define AUTHOR "Yann Collet"
52 #define WELCOME_MESSAGE "*** %s %i-bits %s, by %s ***\n", COMPRESSOR_NAME, (int)(sizeof(size_t)*8), ZSTD_VERSION, AUTHOR
53 
54 #define ZSTD_ZSTDMT "zstdmt"
55 #define ZSTD_UNZSTD "unzstd"
56 #define ZSTD_CAT "zstdcat"
57 #define ZSTD_GZ "gzip"
58 #define ZSTD_GUNZIP "gunzip"
59 #define ZSTD_GZCAT "gzcat"
60 #define ZSTD_LZMA "lzma"
61 #define ZSTD_UNLZMA "unlzma"
62 #define ZSTD_XZ "xz"
63 #define ZSTD_UNXZ "unxz"
64 #define ZSTD_LZ4 "lz4"
65 #define ZSTD_UNLZ4 "unlz4"
66 
67 #define KB *(1 <<10)
68 #define MB *(1 <<20)
69 #define GB *(1U<<30)
70 
71 #define DISPLAY_LEVEL_DEFAULT 2
72 
73 static const char*    g_defaultDictName = "dictionary";
74 static const unsigned g_defaultMaxDictSize = 110 KB;
75 static const int      g_defaultDictCLevel = 3;
76 static const unsigned g_defaultSelectivityLevel = 9;
77 static const unsigned g_defaultMaxWindowLog = 27;
78 #define OVERLAP_LOG_DEFAULT 9999
79 #define LDM_PARAM_DEFAULT 9999  /* Default for parameters where 0 is valid */
80 static U32 g_overlapLog = OVERLAP_LOG_DEFAULT;
81 static U32 g_ldmHashLog = 0;
82 static U32 g_ldmMinMatch = 0;
83 static U32 g_ldmHashEveryLog = LDM_PARAM_DEFAULT;
84 static U32 g_ldmBucketSizeLog = LDM_PARAM_DEFAULT;
85 
86 
87 /*-************************************
88 *  Display Macros
89 **************************************/
90 #define DISPLAY(...)         fprintf(g_displayOut, __VA_ARGS__)
91 #define DISPLAYLEVEL(l, ...) { if (g_displayLevel>=l) { DISPLAY(__VA_ARGS__); } }
92 static int g_displayLevel = DISPLAY_LEVEL_DEFAULT;   /* 0 : no display,  1: errors,  2 : + result + interaction + warnings,  3 : + progression,  4 : + information */
93 static FILE* g_displayOut;
94 
95 
96 /*-************************************
97 *  Command Line
98 **************************************/
99 static int usage(const char* programName)
100 {
101     DISPLAY( "Usage : \n");
102     DISPLAY( "      %s [args] [FILE(s)] [-o file] \n", programName);
103     DISPLAY( "\n");
104     DISPLAY( "FILE    : a filename \n");
105     DISPLAY( "          with no FILE, or when FILE is - , read standard input\n");
106     DISPLAY( "Arguments : \n");
107 #ifndef ZSTD_NOCOMPRESS
108     DISPLAY( " -#     : # compression level (1-%d, default:%d) \n", ZSTDCLI_CLEVEL_MAX, ZSTDCLI_CLEVEL_DEFAULT);
109 #endif
110 #ifndef ZSTD_NODECOMPRESS
111     DISPLAY( " -d     : decompression \n");
112 #endif
113     DISPLAY( " -D file: use `file` as Dictionary \n");
114     DISPLAY( " -o file: result stored into `file` (only if 1 input file) \n");
115     DISPLAY( " -f     : overwrite output without prompting and (de)compress links \n");
116     DISPLAY( "--rm    : remove source file(s) after successful de/compression \n");
117     DISPLAY( " -k     : preserve source file(s) (default) \n");
118     DISPLAY( " -h/-H  : display help/long help and exit \n");
119     return 0;
120 }
121 
122 static int usage_advanced(const char* programName)
123 {
124     DISPLAY(WELCOME_MESSAGE);
125     usage(programName);
126     DISPLAY( "\n");
127     DISPLAY( "Advanced arguments : \n");
128     DISPLAY( " -V     : display Version number and exit \n");
129     DISPLAY( " -v     : verbose mode; specify multiple times to increase verbosity\n");
130     DISPLAY( " -q     : suppress warnings; specify twice to suppress errors too\n");
131     DISPLAY( " -c     : force write to standard output, even if it is the console\n");
132     DISPLAY( " -l     : print information about zstd compressed files \n");
133 #ifndef ZSTD_NOCOMPRESS
134     DISPLAY( "--ultra : enable levels beyond %i, up to %i (requires more memory)\n", ZSTDCLI_CLEVEL_MAX, ZSTD_maxCLevel());
135     DISPLAY( "--long[=#]  : enable long distance matching with given window log (default : %u)\n", g_defaultMaxWindowLog);
136 #ifdef ZSTD_MULTITHREAD
137     DISPLAY( " -T#    : use # threads for compression (default:1) \n");
138     DISPLAY( " -B#    : select size of each job (default:0==automatic) \n");
139 #endif
140     DISPLAY( "--no-dictID : don't write dictID into header (dictionary compression)\n");
141     DISPLAY( "--[no-]check : integrity check (default:enabled) \n");
142 #endif
143 #ifdef UTIL_HAS_CREATEFILELIST
144     DISPLAY( " -r     : operate recursively on directories \n");
145 #endif
146 #ifdef ZSTD_GZCOMPRESS
147     DISPLAY( "--format=gzip : compress files to the .gz format \n");
148 #endif
149 #ifdef ZSTD_LZMACOMPRESS
150     DISPLAY( "--format=xz : compress files to the .xz format \n");
151     DISPLAY( "--format=lzma : compress files to the .lzma format \n");
152 #endif
153 #ifdef ZSTD_LZ4COMPRESS
154     DISPLAY( "--format=lz4 : compress files to the .lz4 format \n");
155 #endif
156 #ifndef ZSTD_NODECOMPRESS
157     DISPLAY( "--test  : test compressed file integrity \n");
158 #if ZSTD_SPARSE_DEFAULT
159     DISPLAY( "--[no-]sparse : sparse mode (default:enabled on file, disabled on stdout)\n");
160 #else
161     DISPLAY( "--[no-]sparse : sparse mode (default:disabled)\n");
162 #endif
163 #endif
164     DISPLAY( " -M#    : Set a memory usage limit for decompression \n");
165     DISPLAY( "--      : All arguments after \"--\" are treated as files \n");
166 #ifndef ZSTD_NODICT
167     DISPLAY( "\n");
168     DISPLAY( "Dictionary builder : \n");
169     DISPLAY( "--train ## : create a dictionary from a training set of files \n");
170     DISPLAY( "--train-cover[=k=#,d=#,steps=#] : use the cover algorithm with optional args\n");
171     DISPLAY( "--train-legacy[=s=#] : use the legacy algorithm with selectivity (default: %u)\n", g_defaultSelectivityLevel);
172     DISPLAY( " -o file : `file` is dictionary name (default: %s) \n", g_defaultDictName);
173     DISPLAY( "--maxdict=# : limit dictionary to specified size (default : %u) \n", g_defaultMaxDictSize);
174     DISPLAY( "--dictID=# : force dictionary ID to specified value (default: random)\n");
175 #endif
176 #ifndef ZSTD_NOBENCH
177     DISPLAY( "\n");
178     DISPLAY( "Benchmark arguments : \n");
179     DISPLAY( " -b#    : benchmark file(s), using # compression level (default : 1) \n");
180     DISPLAY( " -e#    : test all compression levels from -bX to # (default: 1)\n");
181     DISPLAY( " -i#    : minimum evaluation time in seconds (default : 3s) \n");
182     DISPLAY( " -B#    : cut file into independent blocks of size # (default: no block)\n");
183     DISPLAY( "--priority=rt : set process priority to real-time \n");
184 #endif
185     return 0;
186 }
187 
188 static int badusage(const char* programName)
189 {
190     DISPLAYLEVEL(1, "Incorrect parameters\n");
191     if (g_displayLevel >= 2) usage(programName);
192     return 1;
193 }
194 
195 static void waitEnter(void)
196 {
197     int unused;
198     DISPLAY("Press enter to continue...\n");
199     unused = getchar();
200     (void)unused;
201 }
202 
203 static const char* lastNameFromPath(const char* path)
204 {
205     const char* name = path;
206     if (strrchr(name, '/')) name = strrchr(name, '/') + 1;
207     if (strrchr(name, '\\')) name = strrchr(name, '\\') + 1; /* windows */
208     return name;
209 }
210 
211 /*! exeNameMatch() :
212     @return : a non-zero value if exeName matches test, excluding the extension
213    */
214 static int exeNameMatch(const char* exeName, const char* test)
215 {
216     return !strncmp(exeName, test, strlen(test)) &&
217         (exeName[strlen(test)] == '\0' || exeName[strlen(test)] == '.');
218 }
219 
220 /*! readU32FromChar() :
221     @return : unsigned integer value read from input in `char` format
222     allows and interprets K, KB, KiB, M, MB and MiB suffix.
223     Will also modify `*stringPtr`, advancing it to position where it stopped reading.
224     Note : function result can overflow if digit string > MAX_UINT */
225 static unsigned readU32FromChar(const char** stringPtr)
226 {
227     unsigned result = 0;
228     while ((**stringPtr >='0') && (**stringPtr <='9'))
229         result *= 10, result += **stringPtr - '0', (*stringPtr)++ ;
230     if ((**stringPtr=='K') || (**stringPtr=='M')) {
231         result <<= 10;
232         if (**stringPtr=='M') result <<= 10;
233         (*stringPtr)++ ;
234         if (**stringPtr=='i') (*stringPtr)++;
235         if (**stringPtr=='B') (*stringPtr)++;
236     }
237     return result;
238 }
239 
240 /** longCommandWArg() :
241  *  check if *stringPtr is the same as longCommand.
242  *  If yes, @return 1 and advances *stringPtr to the position which immediately follows longCommand.
243  *  @return 0 and doesn't modify *stringPtr otherwise.
244  */
245 static unsigned longCommandWArg(const char** stringPtr, const char* longCommand)
246 {
247     size_t const comSize = strlen(longCommand);
248     int const result = !strncmp(*stringPtr, longCommand, comSize);
249     if (result) *stringPtr += comSize;
250     return result;
251 }
252 
253 
254 #ifndef ZSTD_NODICT
255 /**
256  * parseCoverParameters() :
257  * reads cover parameters from *stringPtr (e.g. "--train-cover=k=48,d=8,steps=32") into *params
258  * @return 1 means that cover parameters were correct
259  * @return 0 in case of malformed parameters
260  */
261 static unsigned parseCoverParameters(const char* stringPtr, ZDICT_cover_params_t* params)
262 {
263     memset(params, 0, sizeof(*params));
264     for (; ;) {
265         if (longCommandWArg(&stringPtr, "k=")) { params->k = readU32FromChar(&stringPtr); if (stringPtr[0]==',') { stringPtr++; continue; } else break; }
266         if (longCommandWArg(&stringPtr, "d=")) { params->d = readU32FromChar(&stringPtr); if (stringPtr[0]==',') { stringPtr++; continue; } else break; }
267         if (longCommandWArg(&stringPtr, "steps=")) { params->steps = readU32FromChar(&stringPtr); if (stringPtr[0]==',') { stringPtr++; continue; } else break; }
268         return 0;
269     }
270     if (stringPtr[0] != 0) return 0;
271     DISPLAYLEVEL(4, "cover: k=%u\nd=%u\nsteps=%u\n", params->k, params->d, params->steps);
272     return 1;
273 }
274 
275 /**
276  * parseLegacyParameters() :
277  * reads legacy dictioanry builter parameters from *stringPtr (e.g. "--train-legacy=selectivity=8") into *selectivity
278  * @return 1 means that legacy dictionary builder parameters were correct
279  * @return 0 in case of malformed parameters
280  */
281 static unsigned parseLegacyParameters(const char* stringPtr, unsigned* selectivity)
282 {
283     if (!longCommandWArg(&stringPtr, "s=") && !longCommandWArg(&stringPtr, "selectivity=")) { return 0; }
284     *selectivity = readU32FromChar(&stringPtr);
285     if (stringPtr[0] != 0) return 0;
286     DISPLAYLEVEL(4, "legacy: selectivity=%u\n", *selectivity);
287     return 1;
288 }
289 
290 static ZDICT_cover_params_t defaultCoverParams(void)
291 {
292     ZDICT_cover_params_t params;
293     memset(&params, 0, sizeof(params));
294     params.d = 8;
295     params.steps = 4;
296     return params;
297 }
298 #endif
299 
300 
301 /** parseCompressionParameters() :
302  *  reads compression parameters from *stringPtr (e.g. "--zstd=wlog=23,clog=23,hlog=22,slog=6,slen=3,tlen=48,strat=6") into *params
303  *  @return 1 means that compression parameters were correct
304  *  @return 0 in case of malformed parameters
305  */
306 static unsigned parseCompressionParameters(const char* stringPtr, ZSTD_compressionParameters* params)
307 {
308     for ( ; ;) {
309         if (longCommandWArg(&stringPtr, "windowLog=") || longCommandWArg(&stringPtr, "wlog=")) { params->windowLog = readU32FromChar(&stringPtr); if (stringPtr[0]==',') { stringPtr++; continue; } else break; }
310         if (longCommandWArg(&stringPtr, "chainLog=") || longCommandWArg(&stringPtr, "clog=")) { params->chainLog = readU32FromChar(&stringPtr); if (stringPtr[0]==',') { stringPtr++; continue; } else break; }
311         if (longCommandWArg(&stringPtr, "hashLog=") || longCommandWArg(&stringPtr, "hlog=")) { params->hashLog = readU32FromChar(&stringPtr); if (stringPtr[0]==',') { stringPtr++; continue; } else break; }
312         if (longCommandWArg(&stringPtr, "searchLog=") || longCommandWArg(&stringPtr, "slog=")) { params->searchLog = readU32FromChar(&stringPtr); if (stringPtr[0]==',') { stringPtr++; continue; } else break; }
313         if (longCommandWArg(&stringPtr, "searchLength=") || longCommandWArg(&stringPtr, "slen=")) { params->searchLength = readU32FromChar(&stringPtr); if (stringPtr[0]==',') { stringPtr++; continue; } else break; }
314         if (longCommandWArg(&stringPtr, "targetLength=") || longCommandWArg(&stringPtr, "tlen=")) { params->targetLength = readU32FromChar(&stringPtr); if (stringPtr[0]==',') { stringPtr++; continue; } else break; }
315         if (longCommandWArg(&stringPtr, "strategy=") || longCommandWArg(&stringPtr, "strat=")) { params->strategy = (ZSTD_strategy)(readU32FromChar(&stringPtr)); if (stringPtr[0]==',') { stringPtr++; continue; } else break; }
316         if (longCommandWArg(&stringPtr, "overlapLog=") || longCommandWArg(&stringPtr, "ovlog=")) { g_overlapLog = readU32FromChar(&stringPtr); if (stringPtr[0]==',') { stringPtr++; continue; } else break; }
317         if (longCommandWArg(&stringPtr, "ldmHashLog=") || longCommandWArg(&stringPtr, "ldmhlog=")) { g_ldmHashLog = readU32FromChar(&stringPtr); if (stringPtr[0]==',') { stringPtr++; continue; } else break; }
318         if (longCommandWArg(&stringPtr, "ldmSearchLength=") || longCommandWArg(&stringPtr, "ldmslen=")) { g_ldmMinMatch = readU32FromChar(&stringPtr); if (stringPtr[0]==',') { stringPtr++; continue; } else break; }
319         if (longCommandWArg(&stringPtr, "ldmBucketSizeLog=") || longCommandWArg(&stringPtr, "ldmblog=")) { g_ldmBucketSizeLog = readU32FromChar(&stringPtr); if (stringPtr[0]==',') { stringPtr++; continue; } else break; }
320         if (longCommandWArg(&stringPtr, "ldmHashEveryLog=") || longCommandWArg(&stringPtr, "ldmhevery=")) { g_ldmHashEveryLog = readU32FromChar(&stringPtr); if (stringPtr[0]==',') { stringPtr++; continue; } else break; }
321         return 0;
322     }
323 
324     if (stringPtr[0] != 0) return 0; /* check the end of string */
325     DISPLAYLEVEL(4, "windowLog=%d\nchainLog=%d\nhashLog=%d\nsearchLog=%d\n", params->windowLog, params->chainLog, params->hashLog, params->searchLog);
326     DISPLAYLEVEL(4, "searchLength=%d\ntargetLength=%d\nstrategy=%d\n", params->searchLength, params->targetLength, params->strategy);
327     return 1;
328 }
329 
330 static void printVersion(void)
331 {
332     DISPLAY(WELCOME_MESSAGE);
333     /* format support */
334     DISPLAYLEVEL(3, "*** supports: zstd");
335 #if defined(ZSTD_LEGACY_SUPPORT) && (ZSTD_LEGACY_SUPPORT>0) && (ZSTD_LEGACY_SUPPORT<8)
336     DISPLAYLEVEL(3, ", zstd legacy v0.%d+", ZSTD_LEGACY_SUPPORT);
337 #endif
338 #ifdef ZSTD_GZCOMPRESS
339     DISPLAYLEVEL(3, ", gzip");
340 #endif
341 #ifdef ZSTD_LZ4COMPRESS
342     DISPLAYLEVEL(3, ", lz4");
343 #endif
344 #ifdef ZSTD_LZMACOMPRESS
345     DISPLAYLEVEL(3, ", lzma, xz ");
346 #endif
347     DISPLAYLEVEL(3, "\n");
348     /* posix support */
349 #ifdef _POSIX_C_SOURCE
350     DISPLAYLEVEL(4, "_POSIX_C_SOURCE defined: %ldL\n", (long) _POSIX_C_SOURCE);
351 #endif
352 #ifdef _POSIX_VERSION
353     DISPLAYLEVEL(4, "_POSIX_VERSION defined: %ldL \n", (long) _POSIX_VERSION);
354 #endif
355 #ifdef PLATFORM_POSIX_VERSION
356     DISPLAYLEVEL(4, "PLATFORM_POSIX_VERSION defined: %ldL\n", (long) PLATFORM_POSIX_VERSION);
357 #endif
358 }
359 
360 typedef enum { zom_compress, zom_decompress, zom_test, zom_bench, zom_train, zom_list } zstd_operation_mode;
361 
362 #define CLEAN_RETURN(i) { operationResult = (i); goto _end; }
363 
364 int main(int argCount, const char* argv[])
365 {
366     int argNb,
367         forceStdout=0,
368         followLinks=0,
369         main_pause=0,
370         nextEntryIsDictionary=0,
371         operationResult=0,
372         nextArgumentIsOutFileName=0,
373         nextArgumentIsMaxDict=0,
374         nextArgumentIsDictID=0,
375         nextArgumentsAreFiles=0,
376         ultra=0,
377         lastCommand = 0,
378         nbThreads = 1,
379         setRealTimePrio = 0,
380         ldmFlag = 0;
381     unsigned bench_nbSeconds = 3;   /* would be better if this value was synchronized from bench */
382     size_t blockSize = 0;
383     zstd_operation_mode operation = zom_compress;
384     ZSTD_compressionParameters compressionParams;
385     int cLevel = ZSTDCLI_CLEVEL_DEFAULT;
386     int cLevelLast = 1;
387     unsigned recursive = 0;
388     unsigned memLimit = 0;
389     const char** filenameTable = (const char**)malloc(argCount * sizeof(const char*));   /* argCount >= 1 */
390     unsigned filenameIdx = 0;
391     const char* programName = argv[0];
392     const char* outFileName = NULL;
393     const char* dictFileName = NULL;
394     const char* suffix = ZSTD_EXTENSION;
395     unsigned maxDictSize = g_defaultMaxDictSize;
396     unsigned dictID = 0;
397     int dictCLevel = g_defaultDictCLevel;
398     unsigned dictSelect = g_defaultSelectivityLevel;
399 #ifdef UTIL_HAS_CREATEFILELIST
400     const char** extendedFileList = NULL;
401     char* fileNamesBuf = NULL;
402     unsigned fileNamesNb;
403 #endif
404 #ifndef ZSTD_NODICT
405     ZDICT_cover_params_t coverParams = defaultCoverParams();
406     int cover = 1;
407 #endif
408 
409 
410     /* init */
411     (void)recursive; (void)cLevelLast;    /* not used when ZSTD_NOBENCH set */
412     (void)dictCLevel; (void)dictSelect; (void)dictID;  (void)maxDictSize; /* not used when ZSTD_NODICT set */
413     (void)ultra; (void)cLevel; (void)ldmFlag; /* not used when ZSTD_NOCOMPRESS set */
414     (void)memLimit;   /* not used when ZSTD_NODECOMPRESS set */
415     if (filenameTable==NULL) { DISPLAY("zstd: %s \n", strerror(errno)); exit(1); }
416     filenameTable[0] = stdinmark;
417     g_displayOut = stderr;
418 
419     programName = lastNameFromPath(programName);
420 
421     /* preset behaviors */
422     if (exeNameMatch(programName, ZSTD_ZSTDMT)) nbThreads=0;
423     if (exeNameMatch(programName, ZSTD_UNZSTD)) operation=zom_decompress;
424     if (exeNameMatch(programName, ZSTD_CAT)) { operation=zom_decompress; forceStdout=1; FIO_overwriteMode(); outFileName=stdoutmark; g_displayLevel=1; }
425     if (exeNameMatch(programName, ZSTD_GZ)) { suffix = GZ_EXTENSION; FIO_setCompressionType(FIO_gzipCompression); FIO_setRemoveSrcFile(1); }    /* behave like gzip */
426     if (exeNameMatch(programName, ZSTD_GUNZIP)) { operation=zom_decompress; FIO_setRemoveSrcFile(1); }                                          /* behave like gunzip */
427     if (exeNameMatch(programName, ZSTD_GZCAT)) { operation=zom_decompress; forceStdout=1; FIO_overwriteMode(); outFileName=stdoutmark; g_displayLevel=1; }  /* behave like gzcat */
428     if (exeNameMatch(programName, ZSTD_LZMA)) { suffix = LZMA_EXTENSION; FIO_setCompressionType(FIO_lzmaCompression); FIO_setRemoveSrcFile(1); }    /* behave like lzma */
429     if (exeNameMatch(programName, ZSTD_UNLZMA)) { operation=zom_decompress; FIO_setCompressionType(FIO_lzmaCompression); FIO_setRemoveSrcFile(1); }    /* behave like unlzma */
430     if (exeNameMatch(programName, ZSTD_XZ)) { suffix = XZ_EXTENSION; FIO_setCompressionType(FIO_xzCompression); FIO_setRemoveSrcFile(1); }    /* behave like xz */
431     if (exeNameMatch(programName, ZSTD_UNXZ)) { operation=zom_decompress; FIO_setCompressionType(FIO_xzCompression); FIO_setRemoveSrcFile(1); }    /* behave like unxz */
432     if (exeNameMatch(programName, ZSTD_LZ4)) { suffix = LZ4_EXTENSION; FIO_setCompressionType(FIO_lz4Compression); FIO_setRemoveSrcFile(1); }    /* behave like xz */
433     if (exeNameMatch(programName, ZSTD_UNLZ4)) { operation=zom_decompress; FIO_setCompressionType(FIO_lz4Compression); FIO_setRemoveSrcFile(1); }    /* behave like unxz */
434     memset(&compressionParams, 0, sizeof(compressionParams));
435 
436     /* command switches */
437     for (argNb=1; argNb<argCount; argNb++) {
438         const char* argument = argv[argNb];
439         if(!argument) continue;   /* Protection if argument empty */
440 
441         if (nextArgumentsAreFiles==0) {
442             /* "-" means stdin/stdout */
443             if (!strcmp(argument, "-")){
444                 if (!filenameIdx) {
445                     filenameIdx=1, filenameTable[0]=stdinmark;
446                     outFileName=stdoutmark;
447                     g_displayLevel-=(g_displayLevel==2);
448                     continue;
449             }   }
450 
451             /* Decode commands (note : aggregated commands are allowed) */
452             if (argument[0]=='-') {
453 
454                 if (argument[1]=='-') {
455                     /* long commands (--long-word) */
456                     if (!strcmp(argument, "--")) { nextArgumentsAreFiles=1; continue; }   /* only file names allowed from now on */
457                     if (!strcmp(argument, "--list")) { operation=zom_list; continue; }
458                     if (!strcmp(argument, "--compress")) { operation=zom_compress; continue; }
459                     if (!strcmp(argument, "--decompress")) { operation=zom_decompress; continue; }
460                     if (!strcmp(argument, "--uncompress")) { operation=zom_decompress; continue; }
461                     if (!strcmp(argument, "--force")) { FIO_overwriteMode(); forceStdout=1; followLinks=1; continue; }
462                     if (!strcmp(argument, "--version")) { g_displayOut=stdout; DISPLAY(WELCOME_MESSAGE); CLEAN_RETURN(0); }
463                     if (!strcmp(argument, "--help")) { g_displayOut=stdout; CLEAN_RETURN(usage_advanced(programName)); }
464                     if (!strcmp(argument, "--verbose")) { g_displayLevel++; continue; }
465                     if (!strcmp(argument, "--quiet")) { g_displayLevel--; continue; }
466                     if (!strcmp(argument, "--stdout")) { forceStdout=1; outFileName=stdoutmark; g_displayLevel-=(g_displayLevel==2); continue; }
467                     if (!strcmp(argument, "--ultra")) { ultra=1; continue; }
468                     if (!strcmp(argument, "--check")) { FIO_setChecksumFlag(2); continue; }
469                     if (!strcmp(argument, "--no-check")) { FIO_setChecksumFlag(0); continue; }
470                     if (!strcmp(argument, "--sparse")) { FIO_setSparseWrite(2); continue; }
471                     if (!strcmp(argument, "--no-sparse")) { FIO_setSparseWrite(0); continue; }
472                     if (!strcmp(argument, "--test")) { operation=zom_test; continue; }
473                     if (!strcmp(argument, "--train")) { operation=zom_train; outFileName=g_defaultDictName; continue; }
474                     if (!strcmp(argument, "--maxdict")) { nextArgumentIsMaxDict=1; lastCommand=1; continue; }  /* kept available for compatibility with old syntax ; will be removed one day */
475                     if (!strcmp(argument, "--dictID")) { nextArgumentIsDictID=1; lastCommand=1; continue; }  /* kept available for compatibility with old syntax ; will be removed one day */
476                     if (!strcmp(argument, "--no-dictID")) { FIO_setDictIDFlag(0); continue; }
477                     if (!strcmp(argument, "--keep")) { FIO_setRemoveSrcFile(0); continue; }
478                     if (!strcmp(argument, "--rm")) { FIO_setRemoveSrcFile(1); continue; }
479                     if (!strcmp(argument, "--priority=rt")) { setRealTimePrio = 1; continue; }
480 #ifdef ZSTD_GZCOMPRESS
481                     if (!strcmp(argument, "--format=gzip")) { suffix = GZ_EXTENSION; FIO_setCompressionType(FIO_gzipCompression); continue; }
482 #endif
483 #ifdef ZSTD_LZMACOMPRESS
484                     if (!strcmp(argument, "--format=lzma")) { suffix = LZMA_EXTENSION; FIO_setCompressionType(FIO_lzmaCompression);  continue; }
485                     if (!strcmp(argument, "--format=xz")) { suffix = XZ_EXTENSION; FIO_setCompressionType(FIO_xzCompression);  continue; }
486 #endif
487 #ifdef ZSTD_LZ4COMPRESS
488                     if (!strcmp(argument, "--format=lz4")) { suffix = LZ4_EXTENSION; FIO_setCompressionType(FIO_lz4Compression);  continue; }
489 #endif
490 
491                     /* long commands with arguments */
492 #ifndef ZSTD_NODICT
493                     if (longCommandWArg(&argument, "--train-cover")) {
494                       operation = zom_train;
495                       outFileName = g_defaultDictName;
496                       cover = 1;
497                       /* Allow optional arguments following an = */
498                       if (*argument == 0) { memset(&coverParams, 0, sizeof(coverParams)); }
499                       else if (*argument++ != '=') { CLEAN_RETURN(badusage(programName)); }
500                       else if (!parseCoverParameters(argument, &coverParams)) { CLEAN_RETURN(badusage(programName)); }
501                       continue;
502                     }
503                     if (longCommandWArg(&argument, "--train-legacy")) {
504                       operation = zom_train;
505                       outFileName = g_defaultDictName;
506                       cover = 0;
507                       /* Allow optional arguments following an = */
508                       if (*argument == 0) { continue; }
509                       else if (*argument++ != '=') { CLEAN_RETURN(badusage(programName)); }
510                       else if (!parseLegacyParameters(argument, &dictSelect)) { CLEAN_RETURN(badusage(programName)); }
511                       continue;
512                     }
513 #endif
514                     if (longCommandWArg(&argument, "--threads=")) { nbThreads = readU32FromChar(&argument); continue; }
515                     if (longCommandWArg(&argument, "--memlimit=")) { memLimit = readU32FromChar(&argument); continue; }
516                     if (longCommandWArg(&argument, "--memory=")) { memLimit = readU32FromChar(&argument); continue; }
517                     if (longCommandWArg(&argument, "--memlimit-decompress=")) { memLimit = readU32FromChar(&argument); continue; }
518                     if (longCommandWArg(&argument, "--block-size=")) { blockSize = readU32FromChar(&argument); continue; }
519                     if (longCommandWArg(&argument, "--maxdict=")) { maxDictSize = readU32FromChar(&argument); continue; }
520                     if (longCommandWArg(&argument, "--dictID=")) { dictID = readU32FromChar(&argument); continue; }
521                     if (longCommandWArg(&argument, "--zstd=")) { if (!parseCompressionParameters(argument, &compressionParams)) CLEAN_RETURN(badusage(programName)); continue; }
522                     if (longCommandWArg(&argument, "--long")) {
523                         unsigned ldmWindowLog = 0;
524                         ldmFlag = 1;
525                         /* Parse optional window log */
526                         if (*argument == '=') {
527                             ++argument;
528                             ldmWindowLog = readU32FromChar(&argument);
529                         } else if (*argument != 0) {
530                             /* Invalid character following --long */
531                             CLEAN_RETURN(badusage(programName));
532                         }
533                         /* Only set windowLog if not already set by --zstd */
534                         if (compressionParams.windowLog == 0)
535                             compressionParams.windowLog = ldmWindowLog;
536                         continue;
537                     }
538                     /* fall-through, will trigger bad_usage() later on */
539                 }
540 
541                 argument++;
542                 while (argument[0]!=0) {
543                     if (lastCommand) {
544                         DISPLAY("error : command must be followed by argument \n");
545                         CLEAN_RETURN(1);
546                     }
547 #ifndef ZSTD_NOCOMPRESS
548                     /* compression Level */
549                     if ((*argument>='0') && (*argument<='9')) {
550                         dictCLevel = cLevel = readU32FromChar(&argument);
551                         continue;
552                     }
553 #endif
554 
555                     switch(argument[0])
556                     {
557                         /* Display help */
558                     case 'V': g_displayOut=stdout; printVersion(); CLEAN_RETURN(0);   /* Version Only */
559                     case 'H':
560                     case 'h': g_displayOut=stdout; CLEAN_RETURN(usage_advanced(programName));
561 
562                          /* Compress */
563                     case 'z': operation=zom_compress; argument++; break;
564 
565                          /* Decoding */
566                     case 'd':
567 #ifndef ZSTD_NOBENCH
568                             if (operation==zom_bench) { BMK_setDecodeOnlyMode(1); argument++; break; }  /* benchmark decode (hidden option) */
569 #endif
570                             operation=zom_decompress; argument++; break;
571 
572                         /* Force stdout, even if stdout==console */
573                     case 'c': forceStdout=1; outFileName=stdoutmark; argument++; break;
574 
575                         /* Use file content as dictionary */
576                     case 'D': nextEntryIsDictionary = 1; lastCommand = 1; argument++; break;
577 
578                         /* Overwrite */
579                     case 'f': FIO_overwriteMode(); forceStdout=1; followLinks=1; argument++; break;
580 
581                         /* Verbose mode */
582                     case 'v': g_displayLevel++; argument++; break;
583 
584                         /* Quiet mode */
585                     case 'q': g_displayLevel--; argument++; break;
586 
587                         /* keep source file (default) */
588                     case 'k': FIO_setRemoveSrcFile(0); argument++; break;
589 
590                         /* Checksum */
591                     case 'C': FIO_setChecksumFlag(2); argument++; break;
592 
593                         /* test compressed file */
594                     case 't': operation=zom_test; argument++; break;
595 
596                         /* destination file name */
597                     case 'o': nextArgumentIsOutFileName=1; lastCommand=1; argument++; break;
598 
599                         /* limit decompression memory */
600                     case 'M':
601                         argument++;
602                         memLimit = readU32FromChar(&argument);
603                         break;
604                     case 'l': operation=zom_list; argument++; break;
605 #ifdef UTIL_HAS_CREATEFILELIST
606                         /* recursive */
607                     case 'r': recursive=1; argument++; break;
608 #endif
609 
610 #ifndef ZSTD_NOBENCH
611                         /* Benchmark */
612                     case 'b':
613                         operation=zom_bench;
614                         argument++;
615                         break;
616 
617                         /* range bench (benchmark only) */
618                     case 'e':
619                         /* compression Level */
620                         argument++;
621                         cLevelLast = readU32FromChar(&argument);
622                         break;
623 
624                         /* Modify Nb Iterations (benchmark only) */
625                     case 'i':
626                         argument++;
627                         bench_nbSeconds = readU32FromChar(&argument);
628                         break;
629 
630                         /* cut input into blocks (benchmark only) */
631                     case 'B':
632                         argument++;
633                         blockSize = readU32FromChar(&argument);
634                         break;
635 
636 #endif   /* ZSTD_NOBENCH */
637 
638                         /* nb of threads (hidden option) */
639                     case 'T':
640                         argument++;
641                         nbThreads = readU32FromChar(&argument);
642                         break;
643 
644                         /* Dictionary Selection level */
645                     case 's':
646                         argument++;
647                         dictSelect = readU32FromChar(&argument);
648                         break;
649 
650                         /* Pause at the end (-p) or set an additional param (-p#) (hidden option) */
651                     case 'p': argument++;
652 #ifndef ZSTD_NOBENCH
653                         if ((*argument>='0') && (*argument<='9')) {
654                             BMK_setAdditionalParam(readU32FromChar(&argument));
655                         } else
656 #endif
657                             main_pause=1;
658                         break;
659                         /* unknown command */
660                     default : CLEAN_RETURN(badusage(programName));
661                     }
662                 }
663                 continue;
664             }   /* if (argument[0]=='-') */
665 
666             if (nextArgumentIsMaxDict) {  /* kept available for compatibility with old syntax ; will be removed one day */
667                 nextArgumentIsMaxDict = 0;
668                 lastCommand = 0;
669                 maxDictSize = readU32FromChar(&argument);
670                 continue;
671             }
672 
673             if (nextArgumentIsDictID) {  /* kept available for compatibility with old syntax ; will be removed one day */
674                 nextArgumentIsDictID = 0;
675                 lastCommand = 0;
676                 dictID = readU32FromChar(&argument);
677                 continue;
678             }
679 
680         }   /* if (nextArgumentIsAFile==0) */
681 
682         if (nextEntryIsDictionary) {
683             nextEntryIsDictionary = 0;
684             lastCommand = 0;
685             dictFileName = argument;
686             continue;
687         }
688 
689         if (nextArgumentIsOutFileName) {
690             nextArgumentIsOutFileName = 0;
691             lastCommand = 0;
692             outFileName = argument;
693             if (!strcmp(outFileName, "-")) outFileName = stdoutmark;
694             continue;
695         }
696 
697         /* add filename to list */
698         filenameTable[filenameIdx++] = argument;
699     }
700 
701     if (lastCommand) { /* forgotten argument */
702         DISPLAY("error : command must be followed by argument \n");
703         CLEAN_RETURN(1);
704     }
705 
706     /* Welcome message (if verbose) */
707     DISPLAYLEVEL(3, WELCOME_MESSAGE);
708 
709     if (nbThreads == 0) {
710         /* try to guess */
711         nbThreads = UTIL_countPhysicalCores();
712         DISPLAYLEVEL(3, "Note: %d physical core(s) detected \n", nbThreads);
713     }
714 
715     g_utilDisplayLevel = g_displayLevel;
716     if (!followLinks) {
717         unsigned u;
718         for (u=0, fileNamesNb=0; u<filenameIdx; u++) {
719             if (UTIL_isLink(filenameTable[u])) {
720                 DISPLAYLEVEL(2, "Warning : %s is a symbolic link, ignoring\n", filenameTable[u]);
721             } else {
722                 filenameTable[fileNamesNb++] = filenameTable[u];
723             }
724         }
725         filenameIdx = fileNamesNb;
726     }
727 #ifdef UTIL_HAS_CREATEFILELIST
728     if (recursive) {  /* at this stage, filenameTable is a list of paths, which can contain both files and directories */
729         extendedFileList = UTIL_createFileList(filenameTable, filenameIdx, &fileNamesBuf, &fileNamesNb, followLinks);
730         if (extendedFileList) {
731             unsigned u;
732             for (u=0; u<fileNamesNb; u++) DISPLAYLEVEL(4, "%u %s\n", u, extendedFileList[u]);
733             free((void*)filenameTable);
734             filenameTable = extendedFileList;
735             filenameIdx = fileNamesNb;
736         }
737     }
738 #endif
739 
740     if (operation == zom_list) {
741 #ifndef ZSTD_NODECOMPRESS
742         int const ret = FIO_listMultipleFiles(filenameIdx, filenameTable, g_displayLevel);
743         CLEAN_RETURN(ret);
744 #else
745         DISPLAY("file information is not supported \n");
746         CLEAN_RETURN(1);
747 #endif
748     }
749 
750     /* Check if benchmark is selected */
751     if (operation==zom_bench) {
752 #ifndef ZSTD_NOBENCH
753         BMK_setNotificationLevel(g_displayLevel);
754         BMK_setBlockSize(blockSize);
755         BMK_setNbThreads(nbThreads);
756         BMK_setNbSeconds(bench_nbSeconds);
757         BMK_setLdmFlag(ldmFlag);
758         BMK_setLdmMinMatch(g_ldmMinMatch);
759         BMK_setLdmHashLog(g_ldmHashLog);
760         if (g_ldmBucketSizeLog != LDM_PARAM_DEFAULT) {
761             BMK_setLdmBucketSizeLog(g_ldmBucketSizeLog);
762         }
763         if (g_ldmHashEveryLog != LDM_PARAM_DEFAULT) {
764             BMK_setLdmHashEveryLog(g_ldmHashEveryLog);
765         }
766         BMK_benchFiles(filenameTable, filenameIdx, dictFileName, cLevel, cLevelLast, &compressionParams, setRealTimePrio);
767 #endif
768         (void)bench_nbSeconds; (void)blockSize; (void)setRealTimePrio;
769         goto _end;
770     }
771 
772     /* Check if dictionary builder is selected */
773     if (operation==zom_train) {
774 #ifndef ZSTD_NODICT
775         ZDICT_params_t zParams;
776         zParams.compressionLevel = dictCLevel;
777         zParams.notificationLevel = g_displayLevel;
778         zParams.dictID = dictID;
779         if (cover) {
780             int const optimize = !coverParams.k || !coverParams.d;
781             coverParams.nbThreads = nbThreads;
782             coverParams.zParams = zParams;
783             operationResult = DiB_trainFromFiles(outFileName, maxDictSize, filenameTable, filenameIdx, blockSize, NULL, &coverParams, optimize);
784         } else {
785             ZDICT_legacy_params_t dictParams;
786             memset(&dictParams, 0, sizeof(dictParams));
787             dictParams.selectivityLevel = dictSelect;
788             dictParams.zParams = zParams;
789             operationResult = DiB_trainFromFiles(outFileName, maxDictSize, filenameTable, filenameIdx, blockSize, &dictParams, NULL, 0);
790         }
791 #endif
792         goto _end;
793     }
794 
795 #ifndef ZSTD_NODECOMPRESS
796     if (operation==zom_test) { outFileName=nulmark; FIO_setRemoveSrcFile(0); } /* test mode */
797 #endif
798 
799     /* No input filename ==> use stdin and stdout */
800     filenameIdx += !filenameIdx;   /* filenameTable[0] is stdin by default */
801     if (!strcmp(filenameTable[0], stdinmark) && !outFileName) outFileName = stdoutmark;   /* when input is stdin, default output is stdout */
802 
803     /* Check if input/output defined as console; trigger an error in this case */
804     if (!strcmp(filenameTable[0], stdinmark) && IS_CONSOLE(stdin) ) CLEAN_RETURN(badusage(programName));
805     if (outFileName && !strcmp(outFileName, stdoutmark) && IS_CONSOLE(stdout) && !strcmp(filenameTable[0], stdinmark) && !forceStdout && operation!=zom_decompress)
806         CLEAN_RETURN(badusage(programName));
807 
808     /* user-selected output filename, only possible with a single file */
809     if (outFileName && strcmp(outFileName,stdoutmark) && strcmp(outFileName,nulmark) && (filenameIdx>1)) {
810         DISPLAY("Too many files (%u) on the command line. \n", filenameIdx);
811         CLEAN_RETURN(filenameIdx);
812     }
813 
814 #ifndef ZSTD_NOCOMPRESS
815     /* check compression level limits */
816     {   int const maxCLevel = ultra ? ZSTD_maxCLevel() : ZSTDCLI_CLEVEL_MAX;
817         if (cLevel > maxCLevel) {
818             DISPLAYLEVEL(2, "Warning : compression level higher than max, reduced to %i \n", maxCLevel);
819             cLevel = maxCLevel;
820     }   }
821 #endif
822 
823     /* No status message in pipe mode (stdin - stdout) or multi-files mode */
824     if (!strcmp(filenameTable[0], stdinmark) && outFileName && !strcmp(outFileName,stdoutmark) && (g_displayLevel==2)) g_displayLevel=1;
825     if ((filenameIdx>1) & (g_displayLevel==2)) g_displayLevel=1;
826 
827     /* IO Stream/File */
828     FIO_setNotificationLevel(g_displayLevel);
829     if (operation==zom_compress) {
830 #ifndef ZSTD_NOCOMPRESS
831         FIO_setNbThreads(nbThreads);
832         FIO_setBlockSize((U32)blockSize);
833         FIO_setLdmFlag(ldmFlag);
834         FIO_setLdmHashLog(g_ldmHashLog);
835         FIO_setLdmMinMatch(g_ldmMinMatch);
836         if (g_ldmBucketSizeLog != LDM_PARAM_DEFAULT) {
837             FIO_setLdmBucketSizeLog(g_ldmBucketSizeLog);
838         }
839         if (g_ldmHashEveryLog != LDM_PARAM_DEFAULT) {
840             FIO_setLdmHashEveryLog(g_ldmHashEveryLog);
841         }
842 
843         if (g_overlapLog!=OVERLAP_LOG_DEFAULT) FIO_setOverlapLog(g_overlapLog);
844         if ((filenameIdx==1) && outFileName)
845           operationResult = FIO_compressFilename(outFileName, filenameTable[0], dictFileName, cLevel, &compressionParams);
846         else
847           operationResult = FIO_compressMultipleFilenames(filenameTable, filenameIdx, outFileName ? outFileName : suffix, dictFileName, cLevel, &compressionParams);
848 #else
849         (void)suffix;
850         DISPLAY("Compression not supported\n");
851 #endif
852     } else {  /* decompression or test */
853 #ifndef ZSTD_NODECOMPRESS
854         if (memLimit == 0) {
855             if (compressionParams.windowLog == 0)
856                 memLimit = (U32)1 << g_defaultMaxWindowLog;
857             else {
858                 memLimit = (U32)1 << (compressionParams.windowLog & 31);
859             }
860         }
861         FIO_setMemLimit(memLimit);
862         if (filenameIdx==1 && outFileName)
863             operationResult = FIO_decompressFilename(outFileName, filenameTable[0], dictFileName);
864         else
865             operationResult = FIO_decompressMultipleFilenames(filenameTable, filenameIdx, outFileName ? outFileName : ZSTD_EXTENSION, dictFileName);
866 #else
867         DISPLAY("Decompression not supported\n");
868 #endif
869     }
870 
871 _end:
872     if (main_pause) waitEnter();
873 #ifdef UTIL_HAS_CREATEFILELIST
874     if (extendedFileList)
875         UTIL_freeFileList(extendedFileList, fileNamesBuf);
876     else
877 #endif
878         free((void*)filenameTable);
879     return operationResult;
880 }
881