]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - contrib/zstd/programs/zstdcli.c
Import zstandard 1.1.4 in base
[FreeBSD/FreeBSD.git] / contrib / zstd / programs / zstdcli.c
1 /**
2  * Copyright (c) 2016-present, Yann Collet, Facebook, Inc.
3  * All rights reserved.
4  *
5  * This source code is licensed under the BSD-style license found in the
6  * LICENSE file in the root directory of this source tree. An additional grant
7  * of patent rights can be found in the PATENTS file in the same directory.
8  */
9
10
11 /*-************************************
12 *  Tuning parameters
13 **************************************/
14 #ifndef ZSTDCLI_CLEVEL_DEFAULT
15 #  define ZSTDCLI_CLEVEL_DEFAULT 3
16 #endif
17
18 #ifndef ZSTDCLI_CLEVEL_MAX
19 #  define ZSTDCLI_CLEVEL_MAX 19   /* when not using --ultra */
20 #endif
21
22
23
24 /*-************************************
25 *  Dependencies
26 **************************************/
27 #include "platform.h" /* IS_CONSOLE, PLATFORM_POSIX_VERSION */
28 #include "util.h"     /* UTIL_HAS_CREATEFILELIST, UTIL_createFileList */
29 #include <string.h>   /* strcmp, strlen */
30 #include <errno.h>    /* errno */
31 #include "fileio.h"
32 #ifndef ZSTD_NOBENCH
33 #  include "bench.h"  /* BMK_benchFiles, BMK_SetNbSeconds */
34 #endif
35 #ifndef ZSTD_NODICT
36 #  include "dibio.h"
37 #endif
38 #define ZSTD_STATIC_LINKING_ONLY   /* ZSTD_maxCLevel */
39 #include "zstd.h"     /* ZSTD_VERSION_STRING */
40
41
42 /*-************************************
43 *  Constants
44 **************************************/
45 #define COMPRESSOR_NAME "zstd command line interface"
46 #ifndef ZSTD_VERSION
47 #  define ZSTD_VERSION "v" ZSTD_VERSION_STRING
48 #endif
49 #define AUTHOR "Yann Collet"
50 #define WELCOME_MESSAGE "*** %s %i-bits %s, by %s ***\n", COMPRESSOR_NAME, (int)(sizeof(size_t)*8), ZSTD_VERSION, AUTHOR
51
52 #define ZSTD_UNZSTD "unzstd"
53 #define ZSTD_CAT "zstdcat"
54 #define ZSTD_GZ "gzip"
55 #define ZSTD_GUNZIP "gunzip"
56 #define ZSTD_GZCAT "gzcat"
57 #define ZSTD_LZMA "lzma"
58 #define ZSTD_XZ "xz"
59
60 #define KB *(1 <<10)
61 #define MB *(1 <<20)
62 #define GB *(1U<<30)
63
64 #define DEFAULT_DISPLAY_LEVEL 2
65
66 static const char*    g_defaultDictName = "dictionary";
67 static const unsigned g_defaultMaxDictSize = 110 KB;
68 static const int      g_defaultDictCLevel = 3;
69 static const unsigned g_defaultSelectivityLevel = 9;
70 #define OVERLAP_LOG_DEFAULT 9999
71 static U32 g_overlapLog = OVERLAP_LOG_DEFAULT;
72
73
74 /*-************************************
75 *  Display Macros
76 **************************************/
77 #define DISPLAY(...)           fprintf(displayOut, __VA_ARGS__)
78 #define DISPLAYLEVEL(l, ...)   if (displayLevel>=l) { DISPLAY(__VA_ARGS__); }
79 static FILE* displayOut;
80 static unsigned displayLevel = DEFAULT_DISPLAY_LEVEL;   /* 0 : no display,  1: errors,  2 : + result + interaction + warnings,  3 : + progression,  4 : + information */
81
82
83 /*-************************************
84 *  Command Line
85 **************************************/
86 static int usage(const char* programName)
87 {
88     DISPLAY( "Usage :\n");
89     DISPLAY( "      %s [args] [FILE(s)] [-o file]\n", programName);
90     DISPLAY( "\n");
91     DISPLAY( "FILE    : a filename\n");
92     DISPLAY( "          with no FILE, or when FILE is - , read standard input\n");
93     DISPLAY( "Arguments :\n");
94 #ifndef ZSTD_NOCOMPRESS
95     DISPLAY( " -#     : # compression level (1-%d, default:%d) \n", ZSTDCLI_CLEVEL_MAX, ZSTDCLI_CLEVEL_DEFAULT);
96 #endif
97 #ifndef ZSTD_NODECOMPRESS
98     DISPLAY( " -d     : decompression \n");
99 #endif
100     DISPLAY( " -D file: use `file` as Dictionary \n");
101     DISPLAY( " -o file: result stored into `file` (only if 1 input file) \n");
102     DISPLAY( " -f     : overwrite output without prompting \n");
103     DISPLAY( "--rm    : remove source file(s) after successful de/compression \n");
104     DISPLAY( " -k     : preserve source file(s) (default) \n");
105     DISPLAY( " -h/-H  : display help/long help and exit\n");
106     return 0;
107 }
108
109 static int usage_advanced(const char* programName)
110 {
111     DISPLAY(WELCOME_MESSAGE);
112     usage(programName);
113     DISPLAY( "\n");
114     DISPLAY( "Advanced arguments :\n");
115     DISPLAY( " -V     : display Version number and exit\n");
116     DISPLAY( " -v     : verbose mode; specify multiple times to increase log level (default:%d)\n", DEFAULT_DISPLAY_LEVEL);
117     DISPLAY( " -q     : suppress warnings; specify twice to suppress errors too\n");
118     DISPLAY( " -c     : force write to standard output, even if it is the console\n");
119 #ifdef UTIL_HAS_CREATEFILELIST
120     DISPLAY( " -r     : operate recursively on directories \n");
121 #endif
122 #ifndef ZSTD_NOCOMPRESS
123     DISPLAY( "--ultra : enable levels beyond %i, up to %i (requires more memory)\n", ZSTDCLI_CLEVEL_MAX, ZSTD_maxCLevel());
124     DISPLAY( "--no-dictID : don't write dictID into header (dictionary compression)\n");
125     DISPLAY( "--[no-]check : integrity check (default:enabled) \n");
126 #ifdef ZSTD_MULTITHREAD
127     DISPLAY( " -T#    : use # threads for compression (default:1) \n");
128     DISPLAY( " -B#    : select size of independent sections (default:0==automatic) \n");
129 #endif
130 #ifdef ZSTD_GZCOMPRESS
131     DISPLAY( "--format=gzip : compress files to the .gz format \n");
132 #endif
133 #ifdef ZSTD_LZMACOMPRESS
134     DISPLAY( "--format=xz : compress files to the .xz format \n");
135     DISPLAY( "--format=lzma : compress files to the .lzma format \n");
136 #endif
137 #endif
138 #ifndef ZSTD_NODECOMPRESS
139     DISPLAY( "--test  : test compressed file integrity \n");
140     DISPLAY( "--[no-]sparse : sparse mode (default:enabled on file, disabled on stdout)\n");
141 #endif
142     DISPLAY( " -M#    : Set a memory usage limit for decompression \n");
143     DISPLAY( "--      : All arguments after \"--\" are treated as files \n");
144 #ifndef ZSTD_NODICT
145     DISPLAY( "\n");
146     DISPLAY( "Dictionary builder :\n");
147     DISPLAY( "--train ## : create a dictionary from a training set of files \n");
148     DISPLAY( "--cover=k=#,d=# : use the cover algorithm with parameters k and d \n");
149     DISPLAY( "--optimize-cover[=steps=#,k=#,d=#] : optimize cover parameters with optional parameters\n");
150     DISPLAY( " -o file : `file` is dictionary name (default: %s) \n", g_defaultDictName);
151     DISPLAY( "--maxdict ## : limit dictionary to specified size (default : %u) \n", g_defaultMaxDictSize);
152     DISPLAY( " -s#    : dictionary selectivity level (default: %u)\n", g_defaultSelectivityLevel);
153     DISPLAY( "--dictID ## : force dictionary ID to specified value (default: random)\n");
154 #endif
155 #ifndef ZSTD_NOBENCH
156     DISPLAY( "\n");
157     DISPLAY( "Benchmark arguments :\n");
158     DISPLAY( " -b#    : benchmark file(s), using # compression level (default : 1) \n");
159     DISPLAY( " -e#    : test all compression levels from -bX to # (default: 1)\n");
160     DISPLAY( " -i#    : minimum evaluation time in seconds (default : 3s)\n");
161     DISPLAY( " -B#    : cut file into independent blocks of size # (default: no block)\n");
162     DISPLAY( "--priority=rt : set process priority to real-time\n");
163 #endif
164     return 0;
165 }
166
167 static int badusage(const char* programName)
168 {
169     DISPLAYLEVEL(1, "Incorrect parameters\n");
170     if (displayLevel >= 1) usage(programName);
171     return 1;
172 }
173
174 static void waitEnter(void)
175 {
176     int unused;
177     DISPLAY("Press enter to continue...\n");
178     unused = getchar();
179     (void)unused;
180 }
181
182 /*! readU32FromChar() :
183     @return : unsigned integer value read from input in `char` format
184     allows and interprets K, KB, KiB, M, MB and MiB suffix.
185     Will also modify `*stringPtr`, advancing it to position where it stopped reading.
186     Note : function result can overflow if digit string > MAX_UINT */
187 static unsigned readU32FromChar(const char** stringPtr)
188 {
189     unsigned result = 0;
190     while ((**stringPtr >='0') && (**stringPtr <='9'))
191         result *= 10, result += **stringPtr - '0', (*stringPtr)++ ;
192     if ((**stringPtr=='K') || (**stringPtr=='M')) {
193         result <<= 10;
194         if (**stringPtr=='M') result <<= 10;
195         (*stringPtr)++ ;
196         if (**stringPtr=='i') (*stringPtr)++;
197         if (**stringPtr=='B') (*stringPtr)++;
198     }
199     return result;
200 }
201
202 /** longCommandWArg() :
203  *  check if *stringPtr is the same as longCommand.
204  *  If yes, @return 1 and advances *stringPtr to the position which immediately follows longCommand.
205  *  @return 0 and doesn't modify *stringPtr otherwise.
206  */
207 static unsigned longCommandWArg(const char** stringPtr, const char* longCommand)
208 {
209     size_t const comSize = strlen(longCommand);
210     int const result = !strncmp(*stringPtr, longCommand, comSize);
211     if (result) *stringPtr += comSize;
212     return result;
213 }
214
215
216 #ifndef ZSTD_NODICT
217 /**
218  * parseCoverParameters() :
219  * reads cover parameters from *stringPtr (e.g. "--cover=smoothing=100,kmin=48,kstep=4,kmax=64,d=8") into *params
220  * @return 1 means that cover parameters were correct
221  * @return 0 in case of malformed parameters
222  */
223 static unsigned parseCoverParameters(const char* stringPtr, COVER_params_t *params)
224 {
225     memset(params, 0, sizeof(*params));
226     for (; ;) {
227         if (longCommandWArg(&stringPtr, "k=")) { params->k = readU32FromChar(&stringPtr); if (stringPtr[0]==',') { stringPtr++; continue; } else break; }
228         if (longCommandWArg(&stringPtr, "d=")) { params->d = readU32FromChar(&stringPtr); if (stringPtr[0]==',') { stringPtr++; continue; } else break; }
229         if (longCommandWArg(&stringPtr, "steps=")) { params->steps = readU32FromChar(&stringPtr); if (stringPtr[0]==',') { stringPtr++; continue; } else break; }
230         return 0;
231     }
232     if (stringPtr[0] != 0) return 0;
233     DISPLAYLEVEL(4, "k=%u\nd=%u\nsteps=%u\n", params->k, params->d, params->steps);
234     return 1;
235 }
236 #endif
237
238
239 /** parseCompressionParameters() :
240  *  reads compression parameters from *stringPtr (e.g. "--zstd=wlog=23,clog=23,hlog=22,slog=6,slen=3,tlen=48,strat=6") into *params
241  *  @return 1 means that compression parameters were correct
242  *  @return 0 in case of malformed parameters
243  */
244 static unsigned parseCompressionParameters(const char* stringPtr, ZSTD_compressionParameters* params)
245 {
246     for ( ; ;) {
247         if (longCommandWArg(&stringPtr, "windowLog=") || longCommandWArg(&stringPtr, "wlog=")) { params->windowLog = readU32FromChar(&stringPtr); if (stringPtr[0]==',') { stringPtr++; continue; } else break; }
248         if (longCommandWArg(&stringPtr, "chainLog=") || longCommandWArg(&stringPtr, "clog=")) { params->chainLog = readU32FromChar(&stringPtr); if (stringPtr[0]==',') { stringPtr++; continue; } else break; }
249         if (longCommandWArg(&stringPtr, "hashLog=") || longCommandWArg(&stringPtr, "hlog=")) { params->hashLog = readU32FromChar(&stringPtr); if (stringPtr[0]==',') { stringPtr++; continue; } else break; }
250         if (longCommandWArg(&stringPtr, "searchLog=") || longCommandWArg(&stringPtr, "slog=")) { params->searchLog = readU32FromChar(&stringPtr); if (stringPtr[0]==',') { stringPtr++; continue; } else break; }
251         if (longCommandWArg(&stringPtr, "searchLength=") || longCommandWArg(&stringPtr, "slen=")) { params->searchLength = readU32FromChar(&stringPtr); if (stringPtr[0]==',') { stringPtr++; continue; } else break; }
252         if (longCommandWArg(&stringPtr, "targetLength=") || longCommandWArg(&stringPtr, "tlen=")) { params->targetLength = readU32FromChar(&stringPtr); if (stringPtr[0]==',') { stringPtr++; continue; } else break; }
253         if (longCommandWArg(&stringPtr, "strategy=") || longCommandWArg(&stringPtr, "strat=")) { params->strategy = (ZSTD_strategy)(1 + readU32FromChar(&stringPtr)); if (stringPtr[0]==',') { stringPtr++; continue; } else break; }
254         if (longCommandWArg(&stringPtr, "overlapLog=") || longCommandWArg(&stringPtr, "ovlog=")) { g_overlapLog = readU32FromChar(&stringPtr); if (stringPtr[0]==',') { stringPtr++; continue; } else break; }
255         return 0;
256     }
257
258     if (stringPtr[0] != 0) return 0; /* check the end of string */
259     DISPLAYLEVEL(4, "windowLog=%d\nchainLog=%d\nhashLog=%d\nsearchLog=%d\n", params->windowLog, params->chainLog, params->hashLog, params->searchLog);
260     DISPLAYLEVEL(4, "searchLength=%d\ntargetLength=%d\nstrategy=%d\n", params->searchLength, params->targetLength, params->strategy);
261     return 1;
262 }
263
264
265 typedef enum { zom_compress, zom_decompress, zom_test, zom_bench, zom_train } zstd_operation_mode;
266
267 #define CLEAN_RETURN(i) { operationResult = (i); goto _end; }
268
269 int main(int argCount, const char* argv[])
270 {
271     int argNb,
272         forceStdout=0,
273         main_pause=0,
274         nextEntryIsDictionary=0,
275         operationResult=0,
276         nextArgumentIsOutFileName=0,
277         nextArgumentIsMaxDict=0,
278         nextArgumentIsDictID=0,
279         nextArgumentsAreFiles=0,
280         ultra=0,
281         lastCommand = 0,
282         nbThreads = 1,
283         setRealTimePrio = 0;
284     unsigned bench_nbSeconds = 3;   /* would be better if this value was synchronized from bench */
285     size_t blockSize = 0;
286     zstd_operation_mode operation = zom_compress;
287     ZSTD_compressionParameters compressionParams;
288     int cLevel = ZSTDCLI_CLEVEL_DEFAULT;
289     int cLevelLast = 1;
290     unsigned recursive = 0;
291     unsigned memLimit = 0;
292     const char** filenameTable = (const char**)malloc(argCount * sizeof(const char*));   /* argCount >= 1 */
293     unsigned filenameIdx = 0;
294     const char* programName = argv[0];
295     const char* outFileName = NULL;
296     const char* dictFileName = NULL;
297     const char* suffix = ZSTD_EXTENSION;
298     unsigned maxDictSize = g_defaultMaxDictSize;
299     unsigned dictID = 0;
300     int dictCLevel = g_defaultDictCLevel;
301     unsigned dictSelect = g_defaultSelectivityLevel;
302 #ifdef UTIL_HAS_CREATEFILELIST
303     const char** extendedFileList = NULL;
304     char* fileNamesBuf = NULL;
305     unsigned fileNamesNb;
306 #endif
307 #ifndef ZSTD_NODICT
308     COVER_params_t coverParams;
309     int cover = 0;
310 #endif
311
312     /* init */
313     (void)recursive; (void)cLevelLast;    /* not used when ZSTD_NOBENCH set */
314     (void)dictCLevel; (void)dictSelect; (void)dictID;  (void)maxDictSize; /* not used when ZSTD_NODICT set */
315     (void)ultra; (void)cLevel; /* not used when ZSTD_NOCOMPRESS set */
316     (void)memLimit;   /* not used when ZSTD_NODECOMPRESS set */
317     if (filenameTable==NULL) { DISPLAY("zstd: %s \n", strerror(errno)); exit(1); }
318     filenameTable[0] = stdinmark;
319     displayOut = stderr;
320     /* Pick out program name from path. Don't rely on stdlib because of conflicting behavior */
321     {   size_t pos;
322         for (pos = (int)strlen(programName); pos > 0; pos--) { if (programName[pos] == '/') { pos++; break; } }
323         programName += pos;
324     }
325
326     /* preset behaviors */
327     if (!strcmp(programName, ZSTD_UNZSTD)) operation=zom_decompress;
328     if (!strcmp(programName, ZSTD_CAT)) { operation=zom_decompress; forceStdout=1; FIO_overwriteMode(); outFileName=stdoutmark; displayLevel=1; }
329     if (!strcmp(programName, ZSTD_GZ)) { suffix = GZ_EXTENSION; FIO_setCompressionType(FIO_gzipCompression); FIO_setRemoveSrcFile(1); }    /* behave like gzip */
330     if (!strcmp(programName, ZSTD_GUNZIP)) { operation=zom_decompress; FIO_setRemoveSrcFile(1); }                                          /* behave like gunzip */
331     if (!strcmp(programName, ZSTD_GZCAT)) { operation=zom_decompress; forceStdout=1; FIO_overwriteMode(); outFileName=stdoutmark; displayLevel=1; }  /* behave like gzcat */
332     if (!strcmp(programName, ZSTD_LZMA)) { suffix = LZMA_EXTENSION; FIO_setCompressionType(FIO_lzmaCompression); FIO_setRemoveSrcFile(1); }    /* behave like lzma */
333     if (!strcmp(programName, ZSTD_XZ)) { suffix = XZ_EXTENSION; FIO_setCompressionType(FIO_xzCompression); FIO_setRemoveSrcFile(1); }    /* behave like xz */
334     memset(&compressionParams, 0, sizeof(compressionParams));
335
336     /* command switches */
337     for (argNb=1; argNb<argCount; argNb++) {
338         const char* argument = argv[argNb];
339         if(!argument) continue;   /* Protection if argument empty */
340
341         if (nextArgumentsAreFiles==0) {
342             /* "-" means stdin/stdout */
343             if (!strcmp(argument, "-")){
344                 if (!filenameIdx) {
345                     filenameIdx=1, filenameTable[0]=stdinmark;
346                     outFileName=stdoutmark;
347                     displayLevel-=(displayLevel==2);
348                     continue;
349             }   }
350
351             /* Decode commands (note : aggregated commands are allowed) */
352             if (argument[0]=='-') {
353
354                 if (argument[1]=='-') {
355                     /* long commands (--long-word) */
356                     if (!strcmp(argument, "--")) { nextArgumentsAreFiles=1; continue; }   /* only file names allowed from now on */
357                     if (!strcmp(argument, "--compress")) { operation=zom_compress; continue; }
358                     if (!strcmp(argument, "--decompress")) { operation=zom_decompress; continue; }
359                     if (!strcmp(argument, "--uncompress")) { operation=zom_decompress; continue; }
360                     if (!strcmp(argument, "--force")) { FIO_overwriteMode(); continue; }
361                     if (!strcmp(argument, "--version")) { displayOut=stdout; DISPLAY(WELCOME_MESSAGE); CLEAN_RETURN(0); }
362                     if (!strcmp(argument, "--help")) { displayOut=stdout; CLEAN_RETURN(usage_advanced(programName)); }
363                     if (!strcmp(argument, "--verbose")) { displayLevel++; continue; }
364                     if (!strcmp(argument, "--quiet")) { displayLevel--; continue; }
365                     if (!strcmp(argument, "--stdout")) { forceStdout=1; outFileName=stdoutmark; displayLevel-=(displayLevel==2); continue; }
366                     if (!strcmp(argument, "--ultra")) { ultra=1; continue; }
367                     if (!strcmp(argument, "--check")) { FIO_setChecksumFlag(2); continue; }
368                     if (!strcmp(argument, "--no-check")) { FIO_setChecksumFlag(0); continue; }
369                     if (!strcmp(argument, "--sparse")) { FIO_setSparseWrite(2); continue; }
370                     if (!strcmp(argument, "--no-sparse")) { FIO_setSparseWrite(0); continue; }
371                     if (!strcmp(argument, "--test")) { operation=zom_test; continue; }
372                     if (!strcmp(argument, "--train")) { operation=zom_train; outFileName=g_defaultDictName; continue; }
373                     if (!strcmp(argument, "--maxdict")) { nextArgumentIsMaxDict=1; lastCommand=1; continue; }
374                     if (!strcmp(argument, "--dictID")) { nextArgumentIsDictID=1; lastCommand=1; continue; }
375                     if (!strcmp(argument, "--no-dictID")) { FIO_setDictIDFlag(0); continue; }
376                     if (!strcmp(argument, "--keep")) { FIO_setRemoveSrcFile(0); continue; }
377                     if (!strcmp(argument, "--rm")) { FIO_setRemoveSrcFile(1); continue; }
378                     if (!strcmp(argument, "--priority=rt")) { setRealTimePrio = 1; continue; }
379 #ifdef ZSTD_GZCOMPRESS
380                     if (!strcmp(argument, "--format=gzip")) { suffix = GZ_EXTENSION; FIO_setCompressionType(FIO_gzipCompression); continue; }
381 #endif
382 #ifdef ZSTD_LZMACOMPRESS
383                     if (!strcmp(argument, "--format=lzma")) { suffix = LZMA_EXTENSION; FIO_setCompressionType(FIO_lzmaCompression);  continue; }
384                     if (!strcmp(argument, "--format=xz")) { suffix = XZ_EXTENSION; FIO_setCompressionType(FIO_xzCompression);  continue; }
385 #endif
386
387                     /* long commands with arguments */
388 #ifndef ZSTD_NODICT
389                     if (longCommandWArg(&argument, "--cover=")) {
390                       cover=1; if (!parseCoverParameters(argument, &coverParams)) CLEAN_RETURN(badusage(programName));
391                       continue;
392                     }
393                     if (longCommandWArg(&argument, "--optimize-cover")) {
394                       cover=2;
395                       /* Allow optional arguments following an = */
396                       if (*argument == 0) { memset(&coverParams, 0, sizeof(coverParams)); }
397                       else if (*argument++ != '=') { CLEAN_RETURN(badusage(programName)); }
398                       else if (!parseCoverParameters(argument, &coverParams)) { CLEAN_RETURN(badusage(programName)); }
399                       continue;
400                     }
401 #endif
402                     if (longCommandWArg(&argument, "--memlimit=")) { memLimit = readU32FromChar(&argument); continue; }
403                     if (longCommandWArg(&argument, "--memory=")) { memLimit = readU32FromChar(&argument); continue; }
404                     if (longCommandWArg(&argument, "--memlimit-decompress=")) { memLimit = readU32FromChar(&argument); continue; }
405                     if (longCommandWArg(&argument, "--block-size=")) { blockSize = readU32FromChar(&argument); continue; }
406                     if (longCommandWArg(&argument, "--zstd=")) { if (!parseCompressionParameters(argument, &compressionParams)) CLEAN_RETURN(badusage(programName)); continue; }
407                     /* fall-through, will trigger bad_usage() later on */
408                 }
409
410                 argument++;
411                 while (argument[0]!=0) {
412                     if (lastCommand) {
413                         DISPLAY("error : command must be followed by argument \n");
414                         CLEAN_RETURN(1);
415                     }
416 #ifndef ZSTD_NOCOMPRESS
417                     /* compression Level */
418                     if ((*argument>='0') && (*argument<='9')) {
419                         dictCLevel = cLevel = readU32FromChar(&argument);
420                         continue;
421                     }
422 #endif
423
424                     switch(argument[0])
425                     {
426                         /* Display help */
427                     case 'V': displayOut=stdout; DISPLAY(WELCOME_MESSAGE); CLEAN_RETURN(0);   /* Version Only */
428                     case 'H':
429                     case 'h': displayOut=stdout; CLEAN_RETURN(usage_advanced(programName));
430
431                          /* Compress */
432                     case 'z': operation=zom_compress; argument++; break;
433
434                          /* Decoding */
435                     case 'd':
436 #ifndef ZSTD_NOBENCH
437                             if (operation==zom_bench) { BMK_setDecodeOnlyMode(1); argument++; break; }  /* benchmark decode (hidden option) */
438 #endif
439                             operation=zom_decompress; argument++; break;
440
441                         /* Force stdout, even if stdout==console */
442                     case 'c': forceStdout=1; outFileName=stdoutmark; argument++; break;
443
444                         /* Use file content as dictionary */
445                     case 'D': nextEntryIsDictionary = 1; lastCommand = 1; argument++; break;
446
447                         /* Overwrite */
448                     case 'f': FIO_overwriteMode(); forceStdout=1; argument++; break;
449
450                         /* Verbose mode */
451                     case 'v': displayLevel++; argument++; break;
452
453                         /* Quiet mode */
454                     case 'q': displayLevel--; argument++; break;
455
456                         /* keep source file (default); for gzip/xz compatibility */
457                     case 'k': FIO_setRemoveSrcFile(0); argument++; break;
458
459                         /* Checksum */
460                     case 'C': argument++; FIO_setChecksumFlag(2); break;
461
462                         /* test compressed file */
463                     case 't': operation=zom_test; argument++; break;
464
465                         /* destination file name */
466                     case 'o': nextArgumentIsOutFileName=1; lastCommand=1; argument++; break;
467
468                         /* limit decompression memory */
469                     case 'M':
470                         argument++;
471                         memLimit = readU32FromChar(&argument);
472                         break;
473
474 #ifdef UTIL_HAS_CREATEFILELIST
475                         /* recursive */
476                     case 'r': recursive=1; argument++; break;
477 #endif
478
479 #ifndef ZSTD_NOBENCH
480                         /* Benchmark */
481                     case 'b':
482                         operation=zom_bench;
483                         argument++;
484                         break;
485
486                         /* range bench (benchmark only) */
487                     case 'e':
488                         /* compression Level */
489                         argument++;
490                         cLevelLast = readU32FromChar(&argument);
491                         break;
492
493                         /* Modify Nb Iterations (benchmark only) */
494                     case 'i':
495                         argument++;
496                         bench_nbSeconds = readU32FromChar(&argument);
497                         break;
498
499                         /* cut input into blocks (benchmark only) */
500                     case 'B':
501                         argument++;
502                         blockSize = readU32FromChar(&argument);
503                         break;
504
505 #endif   /* ZSTD_NOBENCH */
506
507                         /* nb of threads (hidden option) */
508                     case 'T':
509                         argument++;
510                         nbThreads = readU32FromChar(&argument);
511                         break;
512
513                         /* Dictionary Selection level */
514                     case 's':
515                         argument++;
516                         dictSelect = readU32FromChar(&argument);
517                         break;
518
519                         /* Pause at the end (-p) or set an additional param (-p#) (hidden option) */
520                     case 'p': argument++;
521 #ifndef ZSTD_NOBENCH
522                         if ((*argument>='0') && (*argument<='9')) {
523                             BMK_setAdditionalParam(readU32FromChar(&argument));
524                         } else
525 #endif
526                             main_pause=1;
527                         break;
528                         /* unknown command */
529                     default : CLEAN_RETURN(badusage(programName));
530                     }
531                 }
532                 continue;
533             }   /* if (argument[0]=='-') */
534
535             if (nextArgumentIsMaxDict) {
536                 nextArgumentIsMaxDict = 0;
537                 lastCommand = 0;
538                 maxDictSize = readU32FromChar(&argument);
539                 continue;
540             }
541
542             if (nextArgumentIsDictID) {
543                 nextArgumentIsDictID = 0;
544                 lastCommand = 0;
545                 dictID = readU32FromChar(&argument);
546                 continue;
547             }
548
549         }   /* if (nextArgumentIsAFile==0) */
550
551         if (nextEntryIsDictionary) {
552             nextEntryIsDictionary = 0;
553             lastCommand = 0;
554             dictFileName = argument;
555             continue;
556         }
557
558         if (nextArgumentIsOutFileName) {
559             nextArgumentIsOutFileName = 0;
560             lastCommand = 0;
561             outFileName = argument;
562             if (!strcmp(outFileName, "-")) outFileName = stdoutmark;
563             continue;
564         }
565
566         /* add filename to list */
567         filenameTable[filenameIdx++] = argument;
568     }
569
570     if (lastCommand) { DISPLAY("error : command must be followed by argument \n"); CLEAN_RETURN(1); }  /* forgotten argument */
571
572     /* Welcome message (if verbose) */
573     DISPLAYLEVEL(3, WELCOME_MESSAGE);
574 #ifdef _POSIX_C_SOURCE
575     DISPLAYLEVEL(4, "_POSIX_C_SOURCE defined: %ldL\n", (long) _POSIX_C_SOURCE);
576 #endif
577 #ifdef _POSIX_VERSION
578     DISPLAYLEVEL(4, "_POSIX_VERSION defined: %ldL\n", (long) _POSIX_VERSION);
579 #endif
580 #ifdef PLATFORM_POSIX_VERSION
581     DISPLAYLEVEL(4, "PLATFORM_POSIX_VERSION defined: %ldL\n", (long) PLATFORM_POSIX_VERSION);
582 #endif
583
584 #ifdef UTIL_HAS_CREATEFILELIST
585     if (recursive) {  /* at this stage, filenameTable is a list of paths, which can contain both files and directories */
586         extendedFileList = UTIL_createFileList(filenameTable, filenameIdx, &fileNamesBuf, &fileNamesNb);
587         if (extendedFileList) {
588             unsigned u;
589             for (u=0; u<fileNamesNb; u++) DISPLAYLEVEL(4, "%u %s\n", u, extendedFileList[u]);
590             free((void*)filenameTable);
591             filenameTable = extendedFileList;
592             filenameIdx = fileNamesNb;
593         }
594     }
595 #endif
596
597     /* Check if benchmark is selected */
598     if (operation==zom_bench) {
599 #ifndef ZSTD_NOBENCH
600         BMK_setNotificationLevel(displayLevel);
601         BMK_setBlockSize(blockSize);
602         BMK_setNbThreads(nbThreads);
603         BMK_setNbSeconds(bench_nbSeconds);
604         BMK_benchFiles(filenameTable, filenameIdx, dictFileName, cLevel, cLevelLast, &compressionParams, setRealTimePrio);
605 #endif
606         (void)bench_nbSeconds;
607         goto _end;
608     }
609
610     /* Check if dictionary builder is selected */
611     if (operation==zom_train) {
612 #ifndef ZSTD_NODICT
613         if (cover) {
614             coverParams.nbThreads = nbThreads;
615             coverParams.compressionLevel = dictCLevel;
616             coverParams.notificationLevel = displayLevel;
617             coverParams.dictID = dictID;
618             DiB_trainFromFiles(outFileName, maxDictSize, filenameTable, filenameIdx, NULL, &coverParams, cover - 1);
619         } else {
620             ZDICT_params_t dictParams;
621             memset(&dictParams, 0, sizeof(dictParams));
622             dictParams.compressionLevel = dictCLevel;
623             dictParams.selectivityLevel = dictSelect;
624             dictParams.notificationLevel = displayLevel;
625             dictParams.dictID = dictID;
626             DiB_trainFromFiles(outFileName, maxDictSize, filenameTable, filenameIdx, &dictParams, NULL, 0);
627         }
628 #endif
629         goto _end;
630     }
631
632     /* No input filename ==> use stdin and stdout */
633     filenameIdx += !filenameIdx;   /* filenameTable[0] is stdin by default */
634     if (!strcmp(filenameTable[0], stdinmark) && !outFileName) outFileName = stdoutmark;   /* when input is stdin, default output is stdout */
635
636     /* Check if input/output defined as console; trigger an error in this case */
637     if (!strcmp(filenameTable[0], stdinmark) && IS_CONSOLE(stdin) ) CLEAN_RETURN(badusage(programName));
638     if (outFileName && !strcmp(outFileName, stdoutmark) && IS_CONSOLE(stdout) && strcmp(filenameTable[0], stdinmark) && !(forceStdout && (operation==zom_decompress)))
639         CLEAN_RETURN(badusage(programName));
640
641     /* user-selected output filename, only possible with a single file */
642     if (outFileName && strcmp(outFileName,stdoutmark) && strcmp(outFileName,nulmark) && (filenameIdx>1)) {
643         DISPLAY("Too many files (%u) on the command line. \n", filenameIdx);
644         CLEAN_RETURN(filenameIdx);
645     }
646
647 #ifndef ZSTD_NOCOMPRESS
648     /* check compression level limits */
649     {   int const maxCLevel = ultra ? ZSTD_maxCLevel() : ZSTDCLI_CLEVEL_MAX;
650         if (cLevel > maxCLevel) {
651             DISPLAYLEVEL(2, "Warning : compression level higher than max, reduced to %i \n", maxCLevel);
652             cLevel = maxCLevel;
653     }   }
654 #endif
655
656     /* No status message in pipe mode (stdin - stdout) or multi-files mode */
657     if (!strcmp(filenameTable[0], stdinmark) && outFileName && !strcmp(outFileName,stdoutmark) && (displayLevel==2)) displayLevel=1;
658     if ((filenameIdx>1) & (displayLevel==2)) displayLevel=1;
659
660     /* IO Stream/File */
661     FIO_setNotificationLevel(displayLevel);
662     if (operation==zom_compress) {
663 #ifndef ZSTD_NOCOMPRESS
664         FIO_setNbThreads(nbThreads);
665         FIO_setBlockSize((U32)blockSize);
666         if (g_overlapLog!=OVERLAP_LOG_DEFAULT) FIO_setOverlapLog(g_overlapLog);
667         if ((filenameIdx==1) && outFileName)
668           operationResult = FIO_compressFilename(outFileName, filenameTable[0], dictFileName, cLevel, &compressionParams);
669         else
670           operationResult = FIO_compressMultipleFilenames(filenameTable, filenameIdx, outFileName ? outFileName : suffix, dictFileName, cLevel, &compressionParams);
671 #else
672         DISPLAY("Compression not supported\n");
673 #endif
674     } else {  /* decompression or test */
675 #ifndef ZSTD_NODECOMPRESS
676         if (operation==zom_test) { outFileName=nulmark; FIO_setRemoveSrcFile(0); } /* test mode */
677         FIO_setMemLimit(memLimit);
678         if (filenameIdx==1 && outFileName)
679             operationResult = FIO_decompressFilename(outFileName, filenameTable[0], dictFileName);
680         else
681             operationResult = FIO_decompressMultipleFilenames(filenameTable, filenameIdx, outFileName ? outFileName : ZSTD_EXTENSION, dictFileName);
682 #else
683         DISPLAY("Decompression not supported\n");
684 #endif
685     }
686
687 _end:
688     if (main_pause) waitEnter();
689 #ifdef UTIL_HAS_CREATEFILELIST
690     if (extendedFileList)
691         UTIL_freeFileList(extendedFileList, fileNamesBuf);
692     else
693 #endif
694         free((void*)filenameTable);
695     return operationResult;
696 }