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 **************************************/
usage(const char * programName)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
usage_advanced(const char * programName)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
badusage(const char * programName)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
waitEnter(void)195 static void waitEnter(void)
196 {
197 int unused;
198 DISPLAY("Press enter to continue...\n");
199 unused = getchar();
200 (void)unused;
201 }
202
lastNameFromPath(const char * path)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 */
exeNameMatch(const char * exeName,const char * test)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 */
readU32FromChar(const char ** stringPtr)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 */
longCommandWArg(const char ** stringPtr,const char * longCommand)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 */
parseCoverParameters(const char * stringPtr,ZDICT_cover_params_t * params)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 */
parseLegacyParameters(const char * stringPtr,unsigned * selectivity)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
defaultCoverParams(void)290 static ZDICT_cover_params_t defaultCoverParams(void)
291 {
292 ZDICT_cover_params_t params;
293 memset(¶ms, 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 */
parseCompressionParameters(const char * stringPtr,ZSTD_compressionParameters * params)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
printVersion(void)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
main(int argCount,const char * argv[])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 separateFiles = 0,
381 ldmFlag = 0;
382 unsigned bench_nbSeconds = 3; /* would be better if this value was synchronized from bench */
383 size_t blockSize = 0;
384 zstd_operation_mode operation = zom_compress;
385 ZSTD_compressionParameters compressionParams;
386 int cLevel = ZSTDCLI_CLEVEL_DEFAULT;
387 int cLevelLast = 1;
388 unsigned recursive = 0;
389 unsigned memLimit = 0;
390 const char** filenameTable = (const char**)malloc(argCount * sizeof(const char*)); /* argCount >= 1 */
391 unsigned filenameIdx = 0;
392 const char* programName = argv[0];
393 const char* outFileName = NULL;
394 const char* dictFileName = NULL;
395 const char* suffix = ZSTD_EXTENSION;
396 unsigned maxDictSize = g_defaultMaxDictSize;
397 unsigned dictID = 0;
398 int dictCLevel = g_defaultDictCLevel;
399 unsigned dictSelect = g_defaultSelectivityLevel;
400 #ifdef UTIL_HAS_CREATEFILELIST
401 const char** extendedFileList = NULL;
402 char* fileNamesBuf = NULL;
403 unsigned fileNamesNb;
404 #endif
405 #ifndef ZSTD_NODICT
406 ZDICT_cover_params_t coverParams = defaultCoverParams();
407 int cover = 1;
408 #endif
409
410
411 /* init */
412 (void)recursive; (void)cLevelLast; /* not used when ZSTD_NOBENCH set */
413 (void)dictCLevel; (void)dictSelect; (void)dictID; (void)maxDictSize; /* not used when ZSTD_NODICT set */
414 (void)ultra; (void)cLevel; (void)ldmFlag; /* not used when ZSTD_NOCOMPRESS set */
415 (void)memLimit; /* not used when ZSTD_NODECOMPRESS set */
416 if (filenameTable==NULL) { DISPLAY("zstd: %s \n", strerror(errno)); exit(1); }
417 filenameTable[0] = stdinmark;
418 g_displayOut = stderr;
419
420 programName = lastNameFromPath(programName);
421
422 /* preset behaviors */
423 if (exeNameMatch(programName, ZSTD_ZSTDMT)) nbThreads=0;
424 if (exeNameMatch(programName, ZSTD_UNZSTD)) operation=zom_decompress;
425 if (exeNameMatch(programName, ZSTD_CAT)) { operation=zom_decompress; forceStdout=1; FIO_overwriteMode(); outFileName=stdoutmark; g_displayLevel=1; }
426 if (exeNameMatch(programName, ZSTD_GZ)) { suffix = GZ_EXTENSION; FIO_setCompressionType(FIO_gzipCompression); FIO_setRemoveSrcFile(1); } /* behave like gzip */
427 if (exeNameMatch(programName, ZSTD_GUNZIP)) { operation=zom_decompress; FIO_setRemoveSrcFile(1); } /* behave like gunzip */
428 if (exeNameMatch(programName, ZSTD_GZCAT)) { operation=zom_decompress; forceStdout=1; FIO_overwriteMode(); outFileName=stdoutmark; g_displayLevel=1; } /* behave like gzcat */
429 if (exeNameMatch(programName, ZSTD_LZMA)) { suffix = LZMA_EXTENSION; FIO_setCompressionType(FIO_lzmaCompression); FIO_setRemoveSrcFile(1); } /* behave like lzma */
430 if (exeNameMatch(programName, ZSTD_UNLZMA)) { operation=zom_decompress; FIO_setCompressionType(FIO_lzmaCompression); FIO_setRemoveSrcFile(1); } /* behave like unlzma */
431 if (exeNameMatch(programName, ZSTD_XZ)) { suffix = XZ_EXTENSION; FIO_setCompressionType(FIO_xzCompression); FIO_setRemoveSrcFile(1); } /* behave like xz */
432 if (exeNameMatch(programName, ZSTD_UNXZ)) { operation=zom_decompress; FIO_setCompressionType(FIO_xzCompression); FIO_setRemoveSrcFile(1); } /* behave like unxz */
433 if (exeNameMatch(programName, ZSTD_LZ4)) { suffix = LZ4_EXTENSION; FIO_setCompressionType(FIO_lz4Compression); FIO_setRemoveSrcFile(1); } /* behave like xz */
434 if (exeNameMatch(programName, ZSTD_UNLZ4)) { operation=zom_decompress; FIO_setCompressionType(FIO_lz4Compression); FIO_setRemoveSrcFile(1); } /* behave like unxz */
435 memset(&compressionParams, 0, sizeof(compressionParams));
436
437 /* command switches */
438 for (argNb=1; argNb<argCount; argNb++) {
439 const char* argument = argv[argNb];
440 if(!argument) continue; /* Protection if argument empty */
441
442 if (nextArgumentsAreFiles==0) {
443 /* "-" means stdin/stdout */
444 if (!strcmp(argument, "-")){
445 if (!filenameIdx) {
446 filenameIdx=1, filenameTable[0]=stdinmark;
447 outFileName=stdoutmark;
448 g_displayLevel-=(g_displayLevel==2);
449 continue;
450 } }
451
452 /* Decode commands (note : aggregated commands are allowed) */
453 if (argument[0]=='-') {
454
455 if (argument[1]=='-') {
456 /* long commands (--long-word) */
457 if (!strcmp(argument, "--")) { nextArgumentsAreFiles=1; continue; } /* only file names allowed from now on */
458 if (!strcmp(argument, "--list")) { operation=zom_list; continue; }
459 if (!strcmp(argument, "--compress")) { operation=zom_compress; continue; }
460 if (!strcmp(argument, "--decompress")) { operation=zom_decompress; continue; }
461 if (!strcmp(argument, "--uncompress")) { operation=zom_decompress; continue; }
462 if (!strcmp(argument, "--force")) { FIO_overwriteMode(); forceStdout=1; followLinks=1; continue; }
463 if (!strcmp(argument, "--version")) { g_displayOut=stdout; DISPLAY(WELCOME_MESSAGE); CLEAN_RETURN(0); }
464 if (!strcmp(argument, "--help")) { g_displayOut=stdout; CLEAN_RETURN(usage_advanced(programName)); }
465 if (!strcmp(argument, "--verbose")) { g_displayLevel++; continue; }
466 if (!strcmp(argument, "--quiet")) { g_displayLevel--; continue; }
467 if (!strcmp(argument, "--stdout")) { forceStdout=1; outFileName=stdoutmark; g_displayLevel-=(g_displayLevel==2); continue; }
468 if (!strcmp(argument, "--ultra")) { ultra=1; continue; }
469 if (!strcmp(argument, "--check")) { FIO_setChecksumFlag(2); continue; }
470 if (!strcmp(argument, "--no-check")) { FIO_setChecksumFlag(0); continue; }
471 if (!strcmp(argument, "--sparse")) { FIO_setSparseWrite(2); continue; }
472 if (!strcmp(argument, "--no-sparse")) { FIO_setSparseWrite(0); continue; }
473 if (!strcmp(argument, "--test")) { operation=zom_test; continue; }
474 if (!strcmp(argument, "--train")) { operation=zom_train; outFileName=g_defaultDictName; continue; }
475 if (!strcmp(argument, "--maxdict")) { nextArgumentIsMaxDict=1; lastCommand=1; continue; } /* kept available for compatibility with old syntax ; will be removed one day */
476 if (!strcmp(argument, "--dictID")) { nextArgumentIsDictID=1; lastCommand=1; continue; } /* kept available for compatibility with old syntax ; will be removed one day */
477 if (!strcmp(argument, "--no-dictID")) { FIO_setDictIDFlag(0); continue; }
478 if (!strcmp(argument, "--keep")) { FIO_setRemoveSrcFile(0); continue; }
479 if (!strcmp(argument, "--rm")) { FIO_setRemoveSrcFile(1); continue; }
480 if (!strcmp(argument, "--priority=rt")) { setRealTimePrio = 1; continue; }
481 #ifdef ZSTD_GZCOMPRESS
482 if (!strcmp(argument, "--format=gzip")) { suffix = GZ_EXTENSION; FIO_setCompressionType(FIO_gzipCompression); continue; }
483 #endif
484 #ifdef ZSTD_LZMACOMPRESS
485 if (!strcmp(argument, "--format=lzma")) { suffix = LZMA_EXTENSION; FIO_setCompressionType(FIO_lzmaCompression); continue; }
486 if (!strcmp(argument, "--format=xz")) { suffix = XZ_EXTENSION; FIO_setCompressionType(FIO_xzCompression); continue; }
487 #endif
488 #ifdef ZSTD_LZ4COMPRESS
489 if (!strcmp(argument, "--format=lz4")) { suffix = LZ4_EXTENSION; FIO_setCompressionType(FIO_lz4Compression); continue; }
490 #endif
491
492 /* long commands with arguments */
493 #ifndef ZSTD_NODICT
494 if (longCommandWArg(&argument, "--train-cover")) {
495 operation = zom_train;
496 outFileName = g_defaultDictName;
497 cover = 1;
498 /* Allow optional arguments following an = */
499 if (*argument == 0) { memset(&coverParams, 0, sizeof(coverParams)); }
500 else if (*argument++ != '=') { CLEAN_RETURN(badusage(programName)); }
501 else if (!parseCoverParameters(argument, &coverParams)) { CLEAN_RETURN(badusage(programName)); }
502 continue;
503 }
504 if (longCommandWArg(&argument, "--train-legacy")) {
505 operation = zom_train;
506 outFileName = g_defaultDictName;
507 cover = 0;
508 /* Allow optional arguments following an = */
509 if (*argument == 0) { continue; }
510 else if (*argument++ != '=') { CLEAN_RETURN(badusage(programName)); }
511 else if (!parseLegacyParameters(argument, &dictSelect)) { CLEAN_RETURN(badusage(programName)); }
512 continue;
513 }
514 #endif
515 if (longCommandWArg(&argument, "--threads=")) { nbThreads = readU32FromChar(&argument); continue; }
516 if (longCommandWArg(&argument, "--memlimit=")) { memLimit = readU32FromChar(&argument); continue; }
517 if (longCommandWArg(&argument, "--memory=")) { memLimit = readU32FromChar(&argument); continue; }
518 if (longCommandWArg(&argument, "--memlimit-decompress=")) { memLimit = readU32FromChar(&argument); continue; }
519 if (longCommandWArg(&argument, "--block-size=")) { blockSize = readU32FromChar(&argument); continue; }
520 if (longCommandWArg(&argument, "--maxdict=")) { maxDictSize = readU32FromChar(&argument); continue; }
521 if (longCommandWArg(&argument, "--dictID=")) { dictID = readU32FromChar(&argument); continue; }
522 if (longCommandWArg(&argument, "--zstd=")) { if (!parseCompressionParameters(argument, &compressionParams)) CLEAN_RETURN(badusage(programName)); continue; }
523 if (longCommandWArg(&argument, "--long")) {
524 unsigned ldmWindowLog = 0;
525 ldmFlag = 1;
526 /* Parse optional window log */
527 if (*argument == '=') {
528 ++argument;
529 ldmWindowLog = readU32FromChar(&argument);
530 } else if (*argument != 0) {
531 /* Invalid character following --long */
532 CLEAN_RETURN(badusage(programName));
533 }
534 /* Only set windowLog if not already set by --zstd */
535 if (compressionParams.windowLog == 0)
536 compressionParams.windowLog = ldmWindowLog;
537 continue;
538 }
539 /* fall-through, will trigger bad_usage() later on */
540 }
541
542 argument++;
543 while (argument[0]!=0) {
544 if (lastCommand) {
545 DISPLAY("error : command must be followed by argument \n");
546 CLEAN_RETURN(1);
547 }
548 #ifndef ZSTD_NOCOMPRESS
549 /* compression Level */
550 if ((*argument>='0') && (*argument<='9')) {
551 dictCLevel = cLevel = readU32FromChar(&argument);
552 continue;
553 }
554 #endif
555
556 switch(argument[0])
557 {
558 /* Display help */
559 case 'V': g_displayOut=stdout; printVersion(); CLEAN_RETURN(0); /* Version Only */
560 case 'H':
561 case 'h': g_displayOut=stdout; CLEAN_RETURN(usage_advanced(programName));
562
563 /* Compress */
564 case 'z': operation=zom_compress; argument++; break;
565
566 /* Decoding */
567 case 'd':
568 #ifndef ZSTD_NOBENCH
569 if (operation==zom_bench) { BMK_setDecodeOnlyMode(1); argument++; break; } /* benchmark decode (hidden option) */
570 #endif
571 operation=zom_decompress; argument++; break;
572
573 /* Force stdout, even if stdout==console */
574 case 'c': forceStdout=1; outFileName=stdoutmark; argument++; break;
575
576 /* Use file content as dictionary */
577 case 'D': nextEntryIsDictionary = 1; lastCommand = 1; argument++; break;
578
579 /* Overwrite */
580 case 'f': FIO_overwriteMode(); forceStdout=1; followLinks=1; argument++; break;
581
582 /* Verbose mode */
583 case 'v': g_displayLevel++; argument++; break;
584
585 /* Quiet mode */
586 case 'q': g_displayLevel--; argument++; break;
587
588 /* keep source file (default) */
589 case 'k': FIO_setRemoveSrcFile(0); argument++; break;
590
591 /* Checksum */
592 case 'C': FIO_setChecksumFlag(2); argument++; break;
593
594 /* test compressed file */
595 case 't': operation=zom_test; argument++; break;
596
597 /* destination file name */
598 case 'o': nextArgumentIsOutFileName=1; lastCommand=1; argument++; break;
599
600 /* limit decompression memory */
601 case 'M':
602 argument++;
603 memLimit = readU32FromChar(&argument);
604 break;
605 case 'l': operation=zom_list; argument++; break;
606 #ifdef UTIL_HAS_CREATEFILELIST
607 /* recursive */
608 case 'r': recursive=1; argument++; break;
609 #endif
610
611 #ifndef ZSTD_NOBENCH
612 /* Benchmark */
613 case 'b':
614 operation=zom_bench;
615 argument++;
616 break;
617
618 /* range bench (benchmark only) */
619 case 'e':
620 /* compression Level */
621 argument++;
622 cLevelLast = readU32FromChar(&argument);
623 break;
624
625 /* Modify Nb Iterations (benchmark only) */
626 case 'i':
627 argument++;
628 bench_nbSeconds = readU32FromChar(&argument);
629 break;
630
631 /* cut input into blocks (benchmark only) */
632 case 'B':
633 argument++;
634 blockSize = readU32FromChar(&argument);
635 break;
636
637 /* benchmark files separately (hidden option) */
638 case 'S':
639 argument++;
640 separateFiles = 1;
641 break;
642
643 #endif /* ZSTD_NOBENCH */
644
645 /* nb of threads (hidden option) */
646 case 'T':
647 argument++;
648 nbThreads = readU32FromChar(&argument);
649 break;
650
651 /* Dictionary Selection level */
652 case 's':
653 argument++;
654 dictSelect = readU32FromChar(&argument);
655 break;
656
657 /* Pause at the end (-p) or set an additional param (-p#) (hidden option) */
658 case 'p': argument++;
659 #ifndef ZSTD_NOBENCH
660 if ((*argument>='0') && (*argument<='9')) {
661 BMK_setAdditionalParam(readU32FromChar(&argument));
662 } else
663 #endif
664 main_pause=1;
665 break;
666 /* unknown command */
667 default : CLEAN_RETURN(badusage(programName));
668 }
669 }
670 continue;
671 } /* if (argument[0]=='-') */
672
673 if (nextArgumentIsMaxDict) { /* kept available for compatibility with old syntax ; will be removed one day */
674 nextArgumentIsMaxDict = 0;
675 lastCommand = 0;
676 maxDictSize = readU32FromChar(&argument);
677 continue;
678 }
679
680 if (nextArgumentIsDictID) { /* kept available for compatibility with old syntax ; will be removed one day */
681 nextArgumentIsDictID = 0;
682 lastCommand = 0;
683 dictID = readU32FromChar(&argument);
684 continue;
685 }
686
687 } /* if (nextArgumentIsAFile==0) */
688
689 if (nextEntryIsDictionary) {
690 nextEntryIsDictionary = 0;
691 lastCommand = 0;
692 dictFileName = argument;
693 continue;
694 }
695
696 if (nextArgumentIsOutFileName) {
697 nextArgumentIsOutFileName = 0;
698 lastCommand = 0;
699 outFileName = argument;
700 if (!strcmp(outFileName, "-")) outFileName = stdoutmark;
701 continue;
702 }
703
704 /* add filename to list */
705 filenameTable[filenameIdx++] = argument;
706 }
707
708 if (lastCommand) { /* forgotten argument */
709 DISPLAY("error : command must be followed by argument \n");
710 CLEAN_RETURN(1);
711 }
712
713 /* Welcome message (if verbose) */
714 DISPLAYLEVEL(3, WELCOME_MESSAGE);
715
716 if (nbThreads == 0) {
717 /* try to guess */
718 nbThreads = UTIL_countPhysicalCores();
719 DISPLAYLEVEL(3, "Note: %d physical core(s) detected \n", nbThreads);
720 }
721
722 g_utilDisplayLevel = g_displayLevel;
723 if (!followLinks) {
724 unsigned u;
725 for (u=0, fileNamesNb=0; u<filenameIdx; u++) {
726 if (UTIL_isLink(filenameTable[u])) {
727 DISPLAYLEVEL(2, "Warning : %s is a symbolic link, ignoring\n", filenameTable[u]);
728 } else {
729 filenameTable[fileNamesNb++] = filenameTable[u];
730 }
731 }
732 filenameIdx = fileNamesNb;
733 }
734 #ifdef UTIL_HAS_CREATEFILELIST
735 if (recursive) { /* at this stage, filenameTable is a list of paths, which can contain both files and directories */
736 extendedFileList = UTIL_createFileList(filenameTable, filenameIdx, &fileNamesBuf, &fileNamesNb, followLinks);
737 if (extendedFileList) {
738 unsigned u;
739 for (u=0; u<fileNamesNb; u++) DISPLAYLEVEL(4, "%u %s\n", u, extendedFileList[u]);
740 free((void*)filenameTable);
741 filenameTable = extendedFileList;
742 filenameIdx = fileNamesNb;
743 }
744 }
745 #endif
746
747 if (operation == zom_list) {
748 #ifndef ZSTD_NODECOMPRESS
749 int const ret = FIO_listMultipleFiles(filenameIdx, filenameTable, g_displayLevel);
750 CLEAN_RETURN(ret);
751 #else
752 DISPLAY("file information is not supported \n");
753 CLEAN_RETURN(1);
754 #endif
755 }
756
757 /* Check if benchmark is selected */
758 if (operation==zom_bench) {
759 #ifndef ZSTD_NOBENCH
760 BMK_setNotificationLevel(g_displayLevel);
761 BMK_setSeparateFiles(separateFiles);
762 BMK_setBlockSize(blockSize);
763 BMK_setNbThreads(nbThreads);
764 BMK_setRealTime(setRealTimePrio);
765 BMK_setNbSeconds(bench_nbSeconds);
766 BMK_setLdmFlag(ldmFlag);
767 BMK_setLdmMinMatch(g_ldmMinMatch);
768 BMK_setLdmHashLog(g_ldmHashLog);
769 if (g_ldmBucketSizeLog != LDM_PARAM_DEFAULT) {
770 BMK_setLdmBucketSizeLog(g_ldmBucketSizeLog);
771 }
772 if (g_ldmHashEveryLog != LDM_PARAM_DEFAULT) {
773 BMK_setLdmHashEveryLog(g_ldmHashEveryLog);
774 }
775 BMK_benchFiles(filenameTable, filenameIdx, dictFileName, cLevel, cLevelLast, &compressionParams);
776 #else
777 (void)bench_nbSeconds; (void)blockSize; (void)setRealTimePrio; (void)separateFiles;
778 #endif
779 goto _end;
780 }
781
782 /* Check if dictionary builder is selected */
783 if (operation==zom_train) {
784 #ifndef ZSTD_NODICT
785 ZDICT_params_t zParams;
786 zParams.compressionLevel = dictCLevel;
787 zParams.notificationLevel = g_displayLevel;
788 zParams.dictID = dictID;
789 if (cover) {
790 int const optimize = !coverParams.k || !coverParams.d;
791 coverParams.nbThreads = nbThreads;
792 coverParams.zParams = zParams;
793 operationResult = DiB_trainFromFiles(outFileName, maxDictSize, filenameTable, filenameIdx, blockSize, NULL, &coverParams, optimize);
794 } else {
795 ZDICT_legacy_params_t dictParams;
796 memset(&dictParams, 0, sizeof(dictParams));
797 dictParams.selectivityLevel = dictSelect;
798 dictParams.zParams = zParams;
799 operationResult = DiB_trainFromFiles(outFileName, maxDictSize, filenameTable, filenameIdx, blockSize, &dictParams, NULL, 0);
800 }
801 #endif
802 goto _end;
803 }
804
805 #ifndef ZSTD_NODECOMPRESS
806 if (operation==zom_test) { outFileName=nulmark; FIO_setRemoveSrcFile(0); } /* test mode */
807 #endif
808
809 /* No input filename ==> use stdin and stdout */
810 filenameIdx += !filenameIdx; /* filenameTable[0] is stdin by default */
811 if (!strcmp(filenameTable[0], stdinmark) && !outFileName) outFileName = stdoutmark; /* when input is stdin, default output is stdout */
812
813 /* Check if input/output defined as console; trigger an error in this case */
814 if (!strcmp(filenameTable[0], stdinmark) && IS_CONSOLE(stdin) ) CLEAN_RETURN(badusage(programName));
815 if (outFileName && !strcmp(outFileName, stdoutmark) && IS_CONSOLE(stdout) && !strcmp(filenameTable[0], stdinmark) && !forceStdout && operation!=zom_decompress)
816 CLEAN_RETURN(badusage(programName));
817
818 #ifndef ZSTD_NOCOMPRESS
819 /* check compression level limits */
820 { int const maxCLevel = ultra ? ZSTD_maxCLevel() : ZSTDCLI_CLEVEL_MAX;
821 if (cLevel > maxCLevel) {
822 DISPLAYLEVEL(2, "Warning : compression level higher than max, reduced to %i \n", maxCLevel);
823 cLevel = maxCLevel;
824 } }
825 #endif
826
827 /* No status message in pipe mode (stdin - stdout) or multi-files mode */
828 if (!strcmp(filenameTable[0], stdinmark) && outFileName && !strcmp(outFileName,stdoutmark) && (g_displayLevel==2)) g_displayLevel=1;
829 if ((filenameIdx>1) & (g_displayLevel==2)) g_displayLevel=1;
830
831 /* IO Stream/File */
832 FIO_setNotificationLevel(g_displayLevel);
833 if (operation==zom_compress) {
834 #ifndef ZSTD_NOCOMPRESS
835 FIO_setNbThreads(nbThreads);
836 FIO_setBlockSize((U32)blockSize);
837 FIO_setLdmFlag(ldmFlag);
838 FIO_setLdmHashLog(g_ldmHashLog);
839 FIO_setLdmMinMatch(g_ldmMinMatch);
840 if (g_ldmBucketSizeLog != LDM_PARAM_DEFAULT) {
841 FIO_setLdmBucketSizeLog(g_ldmBucketSizeLog);
842 }
843 if (g_ldmHashEveryLog != LDM_PARAM_DEFAULT) {
844 FIO_setLdmHashEveryLog(g_ldmHashEveryLog);
845 }
846
847 if (g_overlapLog!=OVERLAP_LOG_DEFAULT) FIO_setOverlapLog(g_overlapLog);
848 if ((filenameIdx==1) && outFileName)
849 operationResult = FIO_compressFilename(outFileName, filenameTable[0], dictFileName, cLevel, &compressionParams);
850 else
851 operationResult = FIO_compressMultipleFilenames(filenameTable, filenameIdx, outFileName, suffix, dictFileName, cLevel, &compressionParams);
852 #else
853 (void)suffix;
854 DISPLAY("Compression not supported\n");
855 #endif
856 } else { /* decompression or test */
857 #ifndef ZSTD_NODECOMPRESS
858 if (memLimit == 0) {
859 if (compressionParams.windowLog == 0)
860 memLimit = (U32)1 << g_defaultMaxWindowLog;
861 else {
862 memLimit = (U32)1 << (compressionParams.windowLog & 31);
863 }
864 }
865 FIO_setMemLimit(memLimit);
866 if (filenameIdx==1 && outFileName)
867 operationResult = FIO_decompressFilename(outFileName, filenameTable[0], dictFileName);
868 else
869 operationResult = FIO_decompressMultipleFilenames(filenameTable, filenameIdx, outFileName, dictFileName);
870 #else
871 DISPLAY("Decompression not supported\n");
872 #endif
873 }
874
875 _end:
876 if (main_pause) waitEnter();
877 #ifdef UTIL_HAS_CREATEFILELIST
878 if (extendedFileList)
879 UTIL_freeFileList(extendedFileList, fileNamesBuf);
880 else
881 #endif
882 free((void*)filenameTable);
883 return operationResult;
884 }
885