1 /*
2 * Copyright (c) Meta Platforms, Inc. and affiliates.
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 * Dependencies
13 **************************************/
14 #include "platform.h" /* PLATFORM_POSIX_VERSION */
15 #include "util.h" /* UTIL_HAS_CREATEFILELIST, UTIL_createFileList, UTIL_isConsole */
16 #include <stdlib.h> /* getenv */
17 #include <string.h> /* strcmp, strlen */
18 #include <stdio.h> /* fprintf(), stdin, stdout, stderr */
19 #include <assert.h> /* assert */
20
21 #include "fileio.h" /* stdinmark, stdoutmark, ZSTD_EXTENSION */
22 #ifndef ZSTD_NOBENCH
23 # include "benchzstd.h" /* BMK_benchFilesAdvanced */
24 #endif
25 #ifndef ZSTD_NODICT
26 # include "dibio.h" /* ZDICT_cover_params_t, DiB_trainFromFiles() */
27 #endif
28 #ifndef ZSTD_NOTRACE
29 # include "zstdcli_trace.h"
30 #endif
31 #include "../lib/zstd.h" /* ZSTD_VERSION_STRING, ZSTD_minCLevel, ZSTD_maxCLevel */
32 #include "fileio_asyncio.h"
33 #include "fileio_common.h"
34
35 /*-************************************
36 * Tuning parameters
37 **************************************/
38 #ifndef ZSTDCLI_CLEVEL_DEFAULT
39 # define ZSTDCLI_CLEVEL_DEFAULT 3
40 #endif
41
42 #ifndef ZSTDCLI_CLEVEL_MAX
43 # define ZSTDCLI_CLEVEL_MAX 19 /* without using --ultra */
44 #endif
45
46 #ifndef ZSTDCLI_NBTHREADS_DEFAULT
47 #define ZSTDCLI_NBTHREADS_DEFAULT MAX(1, MIN(4, UTIL_countLogicalCores() / 4))
48 #endif
49
50
51
52 /*-************************************
53 * Constants
54 **************************************/
55 #define COMPRESSOR_NAME "Zstandard CLI"
56 #ifndef ZSTD_VERSION
57 # define ZSTD_VERSION "v" ZSTD_VERSION_STRING
58 #endif
59 #define AUTHOR "Yann Collet"
60 #define WELCOME_MESSAGE "*** %s (%i-bit) %s, by %s ***\n", COMPRESSOR_NAME, (int)(sizeof(size_t)*8), ZSTD_VERSION, AUTHOR
61
62 #define ZSTD_ZSTDMT "zstdmt"
63 #define ZSTD_UNZSTD "unzstd"
64 #define ZSTD_CAT "zstdcat"
65 #define ZSTD_ZCAT "zcat"
66 #define ZSTD_GZ "gzip"
67 #define ZSTD_GUNZIP "gunzip"
68 #define ZSTD_GZCAT "gzcat"
69 #define ZSTD_LZMA "lzma"
70 #define ZSTD_UNLZMA "unlzma"
71 #define ZSTD_XZ "xz"
72 #define ZSTD_UNXZ "unxz"
73 #define ZSTD_LZ4 "lz4"
74 #define ZSTD_UNLZ4 "unlz4"
75
76 #define KB *(1 <<10)
77 #define MB *(1 <<20)
78 #define GB *(1U<<30)
79
80 #define DISPLAY_LEVEL_DEFAULT 2
81
82 static const char* g_defaultDictName = "dictionary";
83 static const unsigned g_defaultMaxDictSize = 110 KB;
84 static const int g_defaultDictCLevel = 3;
85 static const unsigned g_defaultSelectivityLevel = 9;
86 static const unsigned g_defaultMaxWindowLog = 27;
87 #define OVERLAP_LOG_DEFAULT 9999
88 #define LDM_PARAM_DEFAULT 9999 /* Default for parameters where 0 is valid */
89 static U32 g_overlapLog = OVERLAP_LOG_DEFAULT;
90 static U32 g_ldmHashLog = 0;
91 static U32 g_ldmMinMatch = 0;
92 static U32 g_ldmHashRateLog = LDM_PARAM_DEFAULT;
93 static U32 g_ldmBucketSizeLog = LDM_PARAM_DEFAULT;
94
95
96 #define DEFAULT_ACCEL 1
97
98 typedef enum { cover, fastCover, legacy } dictType;
99
100 /*-************************************
101 * Display Macros
102 **************************************/
103 #undef DISPLAYLEVEL
104 #define DISPLAYLEVEL(l, ...) { if (g_displayLevel>=l) { DISPLAY(__VA_ARGS__); } }
105 static int g_displayLevel = DISPLAY_LEVEL_DEFAULT; /* 0 : no display, 1: errors, 2 : + result + interaction + warnings, 3 : + progression, 4 : + information */
106
107
108 /*-************************************
109 * Check Version (when CLI linked to dynamic library)
110 **************************************/
111
112 /* Due to usage of experimental symbols and capabilities by the CLI,
113 * the CLI must be linked against a dynamic library of same version */
checkLibVersion(void)114 static void checkLibVersion(void)
115 {
116 if (strcmp(ZSTD_VERSION_STRING, ZSTD_versionString())) {
117 DISPLAYLEVEL(1, "Error : incorrect library version (expecting : %s ; actual : %s ) \n",
118 ZSTD_VERSION_STRING, ZSTD_versionString());
119 DISPLAYLEVEL(1, "Please update library to version %s, or use stand-alone zstd binary \n",
120 ZSTD_VERSION_STRING);
121 exit(1);
122 }
123 }
124
125
126 /*! exeNameMatch() :
127 @return : a non-zero value if exeName matches test, excluding the extension
128 */
exeNameMatch(const char * exeName,const char * test)129 static int exeNameMatch(const char* exeName, const char* test)
130 {
131 return !strncmp(exeName, test, strlen(test)) &&
132 (exeName[strlen(test)] == '\0' || exeName[strlen(test)] == '.');
133 }
134
135 /*-************************************
136 * Command Line
137 **************************************/
138 /* print help either in `stderr` or `stdout` depending on originating request
139 * error (badUsage) => stderr
140 * help (usageAdvanced) => stdout
141 */
usage(FILE * f,const char * programName)142 static void usage(FILE* f, const char* programName)
143 {
144 DISPLAY_F(f, "Compress or decompress the INPUT file(s); reads from STDIN if INPUT is `-` or not provided.\n\n");
145 DISPLAY_F(f, "Usage: %s [OPTIONS...] [INPUT... | -] [-o OUTPUT]\n\n", programName);
146 DISPLAY_F(f, "Options:\n");
147 DISPLAY_F(f, " -o OUTPUT Write output to a single file, OUTPUT.\n");
148 DISPLAY_F(f, " -k, --keep Preserve INPUT file(s). [Default] \n");
149 DISPLAY_F(f, " --rm Remove INPUT file(s) after successful (de)compression.\n");
150 #ifdef ZSTD_GZCOMPRESS
151 if (exeNameMatch(programName, ZSTD_GZ)) { /* behave like gzip */
152 DISPLAY_F(f, " -n, --no-name Do not store original filename when compressing.\n\n");
153 }
154 #endif
155 DISPLAY_F(f, "\n");
156 #ifndef ZSTD_NOCOMPRESS
157 DISPLAY_F(f, " -# Desired compression level, where `#` is a number between 1 and %d;\n", ZSTDCLI_CLEVEL_MAX);
158 DISPLAY_F(f, " lower numbers provide faster compression, higher numbers yield\n");
159 DISPLAY_F(f, " better compression ratios. [Default: %d]\n\n", ZSTDCLI_CLEVEL_DEFAULT);
160 #endif
161 #ifndef ZSTD_NODECOMPRESS
162 DISPLAY_F(f, " -d, --decompress Perform decompression.\n");
163 #endif
164 DISPLAY_F(f, " -D DICT Use DICT as the dictionary for compression or decompression.\n\n");
165 DISPLAY_F(f, " -f, --force Disable input and output checks. Allows overwriting existing files,\n");
166 DISPLAY_F(f, " receiving input from the console, printing output to STDOUT, and\n");
167 DISPLAY_F(f, " operating on links, block devices, etc. Unrecognized formats will be\n");
168 DISPLAY_F(f, " passed-through through as-is.\n\n");
169
170 DISPLAY_F(f, " -h Display short usage and exit.\n");
171 DISPLAY_F(f, " -H, --help Display full help and exit.\n");
172 DISPLAY_F(f, " -V, --version Display the program version and exit.\n");
173 DISPLAY_F(f, "\n");
174 }
175
usageAdvanced(const char * programName)176 static void usageAdvanced(const char* programName)
177 {
178 DISPLAYOUT(WELCOME_MESSAGE);
179 DISPLAYOUT("\n");
180 usage(stdout, programName);
181 DISPLAYOUT("Advanced options:\n");
182 DISPLAYOUT(" -c, --stdout Write to STDOUT (even if it is a console) and keep the INPUT file(s).\n\n");
183
184 DISPLAYOUT(" -v, --verbose Enable verbose output; pass multiple times to increase verbosity.\n");
185 DISPLAYOUT(" -q, --quiet Suppress warnings; pass twice to suppress errors.\n");
186 #ifndef ZSTD_NOTRACE
187 DISPLAYOUT(" --trace LOG Log tracing information to LOG.\n");
188 #endif
189 DISPLAYOUT("\n");
190 DISPLAYOUT(" --[no-]progress Forcibly show/hide the progress counter. NOTE: Any (de)compressed\n");
191 DISPLAYOUT(" output to terminal will mix with progress counter text.\n\n");
192
193 #ifdef UTIL_HAS_CREATEFILELIST
194 DISPLAYOUT(" -r Operate recursively on directories.\n");
195 DISPLAYOUT(" --filelist LIST Read a list of files to operate on from LIST.\n");
196 DISPLAYOUT(" --output-dir-flat DIR Store processed files in DIR.\n");
197 #endif
198
199 #ifdef UTIL_HAS_MIRRORFILELIST
200 DISPLAYOUT(" --output-dir-mirror DIR Store processed files in DIR, respecting original directory structure.\n");
201 #endif
202 if (AIO_supported())
203 DISPLAYOUT(" --[no-]asyncio Use asynchronous IO. [Default: Enabled]\n");
204
205 DISPLAYOUT("\n");
206 #ifndef ZSTD_NOCOMPRESS
207 DISPLAYOUT(" --[no-]check Add XXH64 integrity checksums during compression. [Default: Add, Validate]\n");
208 #ifndef ZSTD_NODECOMPRESS
209 DISPLAYOUT(" If `-d` is present, ignore/validate checksums during decompression.\n");
210 #endif
211 #else
212 #ifdef ZSTD_NOCOMPRESS
213 DISPLAYOUT(" --[no-]check Ignore/validate checksums during decompression. [Default: Validate]");
214 #endif
215 #endif /* ZSTD_NOCOMPRESS */
216
217 DISPLAYOUT("\n");
218 DISPLAYOUT(" -- Treat remaining arguments after `--` as files.\n");
219
220 #ifndef ZSTD_NOCOMPRESS
221 DISPLAYOUT("\n");
222 DISPLAYOUT("Advanced compression options:\n");
223 DISPLAYOUT(" --ultra Enable levels beyond %i, up to %i; requires more memory.\n", ZSTDCLI_CLEVEL_MAX, ZSTD_maxCLevel());
224 DISPLAYOUT(" --fast[=#] Use to very fast compression levels. [Default: %u]\n", 1);
225 #ifdef ZSTD_GZCOMPRESS
226 if (exeNameMatch(programName, ZSTD_GZ)) { /* behave like gzip */
227 DISPLAYOUT(" --best Compatibility alias for `-9`.\n");
228 }
229 #endif
230 DISPLAYOUT(" --adapt Dynamically adapt compression level to I/O conditions.\n");
231 DISPLAYOUT(" --long[=#] Enable long distance matching with window log #. [Default: %u]\n", g_defaultMaxWindowLog);
232 DISPLAYOUT(" --patch-from=REF Use REF as the reference point for Zstandard's diff engine. \n\n");
233 # ifdef ZSTD_MULTITHREAD
234 DISPLAYOUT(" -T# Spawn # compression threads. [Default: 1; pass 0 for core count.]\n");
235 DISPLAYOUT(" --single-thread Share a single thread for I/O and compression (slightly different than `-T1`).\n");
236 DISPLAYOUT(" --auto-threads={physical|logical}\n");
237 DISPLAYOUT(" Use physical/logical cores when using `-T0`. [Default: Physical]\n\n");
238 DISPLAYOUT(" -B# Set job size to #. [Default: 0 (automatic)]\n");
239 DISPLAYOUT(" --rsyncable Compress using a rsync-friendly method (`-B` sets block size). \n");
240 DISPLAYOUT("\n");
241 # endif
242 DISPLAYOUT(" --exclude-compressed Only compress files that are not already compressed.\n\n");
243
244 DISPLAYOUT(" --stream-size=# Specify size of streaming input from STDIN.\n");
245 DISPLAYOUT(" --size-hint=# Optimize compression parameters for streaming input of approximately size #.\n");
246 DISPLAYOUT(" --target-compressed-block-size=#\n");
247 DISPLAYOUT(" Generate compressed blocks of approximately # size.\n\n");
248 DISPLAYOUT(" --no-dictID Don't write `dictID` into the header (dictionary compression only).\n");
249 DISPLAYOUT(" --[no-]compress-literals Force (un)compressed literals.\n");
250 DISPLAYOUT(" --[no-]row-match-finder Explicitly enable/disable the fast, row-based matchfinder for\n");
251 DISPLAYOUT(" the 'greedy', 'lazy', and 'lazy2' strategies.\n");
252
253 DISPLAYOUT("\n");
254 DISPLAYOUT(" --format=zstd Compress files to the `.zst` format. [Default]\n");
255 DISPLAYOUT(" --[no-]mmap-dict Memory-map dictionary file rather than mallocing and loading all at once\n");
256 #ifdef ZSTD_GZCOMPRESS
257 DISPLAYOUT(" --format=gzip Compress files to the `.gz` format.\n");
258 #endif
259 #ifdef ZSTD_LZMACOMPRESS
260 DISPLAYOUT(" --format=xz Compress files to the `.xz` format.\n");
261 DISPLAYOUT(" --format=lzma Compress files to the `.lzma` format.\n");
262 #endif
263 #ifdef ZSTD_LZ4COMPRESS
264 DISPLAYOUT( " --format=lz4 Compress files to the `.lz4` format.\n");
265 #endif
266 #endif /* !ZSTD_NOCOMPRESS */
267
268 #ifndef ZSTD_NODECOMPRESS
269 DISPLAYOUT("\n");
270 DISPLAYOUT("Advanced decompression options:\n");
271 DISPLAYOUT(" -l Print information about Zstandard-compressed files.\n");
272 DISPLAYOUT(" --test Test compressed file integrity.\n");
273 DISPLAYOUT(" -M# Set the memory usage limit to # megabytes.\n");
274 # if ZSTD_SPARSE_DEFAULT
275 DISPLAYOUT(" --[no-]sparse Enable sparse mode. [Default: Enabled for files, disabled for STDOUT.]\n");
276 # else
277 DISPLAYOUT(" --[no-]sparse Enable sparse mode. [Default: Disabled]\n");
278 # endif
279 {
280 char const* passThroughDefault = "Disabled";
281 if (exeNameMatch(programName, ZSTD_CAT) ||
282 exeNameMatch(programName, ZSTD_ZCAT) ||
283 exeNameMatch(programName, ZSTD_GZCAT)) {
284 passThroughDefault = "Enabled";
285 }
286 DISPLAYOUT(" --[no-]pass-through Pass through uncompressed files as-is. [Default: %s]\n", passThroughDefault);
287 }
288 #endif /* ZSTD_NODECOMPRESS */
289
290 #ifndef ZSTD_NODICT
291 DISPLAYOUT("\n");
292 DISPLAYOUT("Dictionary builder:\n");
293 DISPLAYOUT(" --train Create a dictionary from a training set of files.\n\n");
294 DISPLAYOUT(" --train-cover[=k=#,d=#,steps=#,split=#,shrink[=#]]\n");
295 DISPLAYOUT(" Use the cover algorithm (with optional arguments).\n");
296 DISPLAYOUT(" --train-fastcover[=k=#,d=#,f=#,steps=#,split=#,accel=#,shrink[=#]]\n");
297 DISPLAYOUT(" Use the fast cover algorithm (with optional arguments).\n\n");
298 DISPLAYOUT(" --train-legacy[=s=#] Use the legacy algorithm with selectivity #. [Default: %u]\n", g_defaultSelectivityLevel);
299 DISPLAYOUT(" -o NAME Use NAME as dictionary name. [Default: %s]\n", g_defaultDictName);
300 DISPLAYOUT(" --maxdict=# Limit dictionary to specified size #. [Default: %u]\n", g_defaultMaxDictSize);
301 DISPLAYOUT(" --dictID=# Force dictionary ID to #. [Default: Random]\n");
302 #endif
303
304 #ifndef ZSTD_NOBENCH
305 DISPLAYOUT("\n");
306 DISPLAYOUT("Benchmark options:\n");
307 DISPLAYOUT(" -b# Perform benchmarking with compression level #. [Default: %d]\n", ZSTDCLI_CLEVEL_DEFAULT);
308 DISPLAYOUT(" -e# Test all compression levels up to #; starting level is `-b#`. [Default: 1]\n");
309 DISPLAYOUT(" -i# Set the minimum evaluation to time # seconds. [Default: 3]\n");
310 DISPLAYOUT(" -B# Cut file into independent chunks of size #. [Default: No chunking]\n");
311 DISPLAYOUT(" -S Output one benchmark result per input file. [Default: Consolidated result]\n");
312 DISPLAYOUT(" -D dictionary Benchmark using dictionary \n");
313 DISPLAYOUT(" --priority=rt Set process priority to real-time.\n");
314 #endif
315
316 }
317
badUsage(const char * programName,const char * parameter)318 static void badUsage(const char* programName, const char* parameter)
319 {
320 DISPLAYLEVEL(1, "Incorrect parameter: %s \n", parameter);
321 if (g_displayLevel >= 2) usage(stderr, programName);
322 }
323
waitEnter(void)324 static void waitEnter(void)
325 {
326 int unused;
327 DISPLAY("Press enter to continue... \n");
328 unused = getchar();
329 (void)unused;
330 }
331
lastNameFromPath(const char * path)332 static const char* lastNameFromPath(const char* path)
333 {
334 const char* name = path;
335 if (strrchr(name, '/')) name = strrchr(name, '/') + 1;
336 if (strrchr(name, '\\')) name = strrchr(name, '\\') + 1; /* windows */
337 return name;
338 }
339
errorOut(const char * msg)340 static void errorOut(const char* msg)
341 {
342 DISPLAYLEVEL(1, "%s \n", msg); exit(1);
343 }
344
345 /*! readU32FromCharChecked() :
346 * @return 0 if success, and store the result in *value.
347 * allows and interprets K, KB, KiB, M, MB and MiB suffix.
348 * Will also modify `*stringPtr`, advancing it to position where it stopped reading.
349 * @return 1 if an overflow error occurs */
readU32FromCharChecked(const char ** stringPtr,unsigned * value)350 static int readU32FromCharChecked(const char** stringPtr, unsigned* value)
351 {
352 unsigned result = 0;
353 while ((**stringPtr >='0') && (**stringPtr <='9')) {
354 unsigned const max = ((unsigned)(-1)) / 10;
355 unsigned last = result;
356 if (result > max) return 1; /* overflow error */
357 result *= 10;
358 result += (unsigned)(**stringPtr - '0');
359 if (result < last) return 1; /* overflow error */
360 (*stringPtr)++ ;
361 }
362 if ((**stringPtr=='K') || (**stringPtr=='M')) {
363 unsigned const maxK = ((unsigned)(-1)) >> 10;
364 if (result > maxK) return 1; /* overflow error */
365 result <<= 10;
366 if (**stringPtr=='M') {
367 if (result > maxK) return 1; /* overflow error */
368 result <<= 10;
369 }
370 (*stringPtr)++; /* skip `K` or `M` */
371 if (**stringPtr=='i') (*stringPtr)++;
372 if (**stringPtr=='B') (*stringPtr)++;
373 }
374 *value = result;
375 return 0;
376 }
377
378 /*! readU32FromChar() :
379 * @return : unsigned integer value read from input in `char` format.
380 * allows and interprets K, KB, KiB, M, MB and MiB suffix.
381 * Will also modify `*stringPtr`, advancing it to position where it stopped reading.
382 * Note : function will exit() program if digit sequence overflows */
readU32FromChar(const char ** stringPtr)383 static unsigned readU32FromChar(const char** stringPtr) {
384 static const char errorMsg[] = "error: numeric value overflows 32-bit unsigned int";
385 unsigned result;
386 if (readU32FromCharChecked(stringPtr, &result)) { errorOut(errorMsg); }
387 return result;
388 }
389
390 /*! readIntFromChar() :
391 * @return : signed integer value read from input in `char` format.
392 * allows and interprets K, KB, KiB, M, MB and MiB suffix.
393 * Will also modify `*stringPtr`, advancing it to position where it stopped reading.
394 * Note : function will exit() program if digit sequence overflows */
readIntFromChar(const char ** stringPtr)395 static int readIntFromChar(const char** stringPtr) {
396 static const char errorMsg[] = "error: numeric value overflows 32-bit int";
397 int sign = 1;
398 unsigned result;
399 if (**stringPtr=='-') {
400 (*stringPtr)++;
401 sign = -1;
402 }
403 if (readU32FromCharChecked(stringPtr, &result)) { errorOut(errorMsg); }
404 return (int) result * sign;
405 }
406
407 /*! readSizeTFromCharChecked() :
408 * @return 0 if success, and store the result in *value.
409 * allows and interprets K, KB, KiB, M, MB and MiB suffix.
410 * Will also modify `*stringPtr`, advancing it to position where it stopped reading.
411 * @return 1 if an overflow error occurs */
readSizeTFromCharChecked(const char ** stringPtr,size_t * value)412 static int readSizeTFromCharChecked(const char** stringPtr, size_t* value)
413 {
414 size_t result = 0;
415 while ((**stringPtr >='0') && (**stringPtr <='9')) {
416 size_t const max = ((size_t)(-1)) / 10;
417 size_t last = result;
418 if (result > max) return 1; /* overflow error */
419 result *= 10;
420 result += (size_t)(**stringPtr - '0');
421 if (result < last) return 1; /* overflow error */
422 (*stringPtr)++ ;
423 }
424 if ((**stringPtr=='K') || (**stringPtr=='M')) {
425 size_t const maxK = ((size_t)(-1)) >> 10;
426 if (result > maxK) return 1; /* overflow error */
427 result <<= 10;
428 if (**stringPtr=='M') {
429 if (result > maxK) return 1; /* overflow error */
430 result <<= 10;
431 }
432 (*stringPtr)++; /* skip `K` or `M` */
433 if (**stringPtr=='i') (*stringPtr)++;
434 if (**stringPtr=='B') (*stringPtr)++;
435 }
436 *value = result;
437 return 0;
438 }
439
440 /*! readSizeTFromChar() :
441 * @return : size_t value read from input in `char` format.
442 * allows and interprets K, KB, KiB, M, MB and MiB suffix.
443 * Will also modify `*stringPtr`, advancing it to position where it stopped reading.
444 * Note : function will exit() program if digit sequence overflows */
readSizeTFromChar(const char ** stringPtr)445 static size_t readSizeTFromChar(const char** stringPtr) {
446 static const char errorMsg[] = "error: numeric value overflows size_t";
447 size_t result;
448 if (readSizeTFromCharChecked(stringPtr, &result)) { errorOut(errorMsg); }
449 return result;
450 }
451
452 /** longCommandWArg() :
453 * check if *stringPtr is the same as longCommand.
454 * If yes, @return 1 and advances *stringPtr to the position which immediately follows longCommand.
455 * @return 0 and doesn't modify *stringPtr otherwise.
456 */
longCommandWArg(const char ** stringPtr,const char * longCommand)457 static int longCommandWArg(const char** stringPtr, const char* longCommand)
458 {
459 size_t const comSize = strlen(longCommand);
460 int const result = !strncmp(*stringPtr, longCommand, comSize);
461 if (result) *stringPtr += comSize;
462 return result;
463 }
464
465
466 #ifndef ZSTD_NODICT
467
468 static const unsigned kDefaultRegression = 1;
469 /**
470 * parseCoverParameters() :
471 * reads cover parameters from *stringPtr (e.g. "--train-cover=k=48,d=8,steps=32") into *params
472 * @return 1 means that cover parameters were correct
473 * @return 0 in case of malformed parameters
474 */
parseCoverParameters(const char * stringPtr,ZDICT_cover_params_t * params)475 static unsigned parseCoverParameters(const char* stringPtr, ZDICT_cover_params_t* params)
476 {
477 memset(params, 0, sizeof(*params));
478 for (; ;) {
479 if (longCommandWArg(&stringPtr, "k=")) { params->k = readU32FromChar(&stringPtr); if (stringPtr[0]==',') { stringPtr++; continue; } else break; }
480 if (longCommandWArg(&stringPtr, "d=")) { params->d = readU32FromChar(&stringPtr); if (stringPtr[0]==',') { stringPtr++; continue; } else break; }
481 if (longCommandWArg(&stringPtr, "steps=")) { params->steps = readU32FromChar(&stringPtr); if (stringPtr[0]==',') { stringPtr++; continue; } else break; }
482 if (longCommandWArg(&stringPtr, "split=")) {
483 unsigned splitPercentage = readU32FromChar(&stringPtr);
484 params->splitPoint = (double)splitPercentage / 100.0;
485 if (stringPtr[0]==',') { stringPtr++; continue; } else break;
486 }
487 if (longCommandWArg(&stringPtr, "shrink")) {
488 params->shrinkDictMaxRegression = kDefaultRegression;
489 params->shrinkDict = 1;
490 if (stringPtr[0]=='=') {
491 stringPtr++;
492 params->shrinkDictMaxRegression = readU32FromChar(&stringPtr);
493 }
494 if (stringPtr[0]==',') {
495 stringPtr++;
496 continue;
497 }
498 else break;
499 }
500 return 0;
501 }
502 if (stringPtr[0] != 0) return 0;
503 DISPLAYLEVEL(4, "cover: k=%u\nd=%u\nsteps=%u\nsplit=%u\nshrink%u\n", params->k, params->d, params->steps, (unsigned)(params->splitPoint * 100), params->shrinkDictMaxRegression);
504 return 1;
505 }
506
507 /**
508 * parseFastCoverParameters() :
509 * reads fastcover parameters from *stringPtr (e.g. "--train-fastcover=k=48,d=8,f=20,steps=32,accel=2") into *params
510 * @return 1 means that fastcover parameters were correct
511 * @return 0 in case of malformed parameters
512 */
parseFastCoverParameters(const char * stringPtr,ZDICT_fastCover_params_t * params)513 static unsigned parseFastCoverParameters(const char* stringPtr, ZDICT_fastCover_params_t* params)
514 {
515 memset(params, 0, sizeof(*params));
516 for (; ;) {
517 if (longCommandWArg(&stringPtr, "k=")) { params->k = readU32FromChar(&stringPtr); if (stringPtr[0]==',') { stringPtr++; continue; } else break; }
518 if (longCommandWArg(&stringPtr, "d=")) { params->d = readU32FromChar(&stringPtr); if (stringPtr[0]==',') { stringPtr++; continue; } else break; }
519 if (longCommandWArg(&stringPtr, "f=")) { params->f = readU32FromChar(&stringPtr); if (stringPtr[0]==',') { stringPtr++; continue; } else break; }
520 if (longCommandWArg(&stringPtr, "steps=")) { params->steps = readU32FromChar(&stringPtr); if (stringPtr[0]==',') { stringPtr++; continue; } else break; }
521 if (longCommandWArg(&stringPtr, "accel=")) { params->accel = readU32FromChar(&stringPtr); if (stringPtr[0]==',') { stringPtr++; continue; } else break; }
522 if (longCommandWArg(&stringPtr, "split=")) {
523 unsigned splitPercentage = readU32FromChar(&stringPtr);
524 params->splitPoint = (double)splitPercentage / 100.0;
525 if (stringPtr[0]==',') { stringPtr++; continue; } else break;
526 }
527 if (longCommandWArg(&stringPtr, "shrink")) {
528 params->shrinkDictMaxRegression = kDefaultRegression;
529 params->shrinkDict = 1;
530 if (stringPtr[0]=='=') {
531 stringPtr++;
532 params->shrinkDictMaxRegression = readU32FromChar(&stringPtr);
533 }
534 if (stringPtr[0]==',') {
535 stringPtr++;
536 continue;
537 }
538 else break;
539 }
540 return 0;
541 }
542 if (stringPtr[0] != 0) return 0;
543 DISPLAYLEVEL(4, "cover: k=%u\nd=%u\nf=%u\nsteps=%u\nsplit=%u\naccel=%u\nshrink=%u\n", params->k, params->d, params->f, params->steps, (unsigned)(params->splitPoint * 100), params->accel, params->shrinkDictMaxRegression);
544 return 1;
545 }
546
547 /**
548 * parseLegacyParameters() :
549 * reads legacy dictionary builder parameters from *stringPtr (e.g. "--train-legacy=selectivity=8") into *selectivity
550 * @return 1 means that legacy dictionary builder parameters were correct
551 * @return 0 in case of malformed parameters
552 */
parseLegacyParameters(const char * stringPtr,unsigned * selectivity)553 static unsigned parseLegacyParameters(const char* stringPtr, unsigned* selectivity)
554 {
555 if (!longCommandWArg(&stringPtr, "s=") && !longCommandWArg(&stringPtr, "selectivity=")) { return 0; }
556 *selectivity = readU32FromChar(&stringPtr);
557 if (stringPtr[0] != 0) return 0;
558 DISPLAYLEVEL(4, "legacy: selectivity=%u\n", *selectivity);
559 return 1;
560 }
561
defaultCoverParams(void)562 static ZDICT_cover_params_t defaultCoverParams(void)
563 {
564 ZDICT_cover_params_t params;
565 memset(¶ms, 0, sizeof(params));
566 params.d = 8;
567 params.steps = 4;
568 params.splitPoint = 1.0;
569 params.shrinkDict = 0;
570 params.shrinkDictMaxRegression = kDefaultRegression;
571 return params;
572 }
573
defaultFastCoverParams(void)574 static ZDICT_fastCover_params_t defaultFastCoverParams(void)
575 {
576 ZDICT_fastCover_params_t params;
577 memset(¶ms, 0, sizeof(params));
578 params.d = 8;
579 params.f = 20;
580 params.steps = 4;
581 params.splitPoint = 0.75; /* different from default splitPoint of cover */
582 params.accel = DEFAULT_ACCEL;
583 params.shrinkDict = 0;
584 params.shrinkDictMaxRegression = kDefaultRegression;
585 return params;
586 }
587 #endif
588
589
590 /** parseAdaptParameters() :
591 * reads adapt parameters from *stringPtr (e.g. "--adapt=min=1,max=19) and store them into adaptMinPtr and adaptMaxPtr.
592 * Both adaptMinPtr and adaptMaxPtr must be already allocated and correctly initialized.
593 * There is no guarantee that any of these values will be updated.
594 * @return 1 means that parsing was successful,
595 * @return 0 in case of malformed parameters
596 */
parseAdaptParameters(const char * stringPtr,int * adaptMinPtr,int * adaptMaxPtr)597 static unsigned parseAdaptParameters(const char* stringPtr, int* adaptMinPtr, int* adaptMaxPtr)
598 {
599 for ( ; ;) {
600 if (longCommandWArg(&stringPtr, "min=")) { *adaptMinPtr = readIntFromChar(&stringPtr); if (stringPtr[0]==',') { stringPtr++; continue; } else break; }
601 if (longCommandWArg(&stringPtr, "max=")) { *adaptMaxPtr = readIntFromChar(&stringPtr); if (stringPtr[0]==',') { stringPtr++; continue; } else break; }
602 DISPLAYLEVEL(4, "invalid compression parameter \n");
603 return 0;
604 }
605 if (stringPtr[0] != 0) return 0; /* check the end of string */
606 if (*adaptMinPtr > *adaptMaxPtr) {
607 DISPLAYLEVEL(4, "incoherent adaptation limits \n");
608 return 0;
609 }
610 return 1;
611 }
612
613
614 /** parseCompressionParameters() :
615 * reads compression parameters from *stringPtr (e.g. "--zstd=wlog=23,clog=23,hlog=22,slog=6,mml=3,tlen=48,strat=6") into *params
616 * @return 1 means that compression parameters were correct
617 * @return 0 in case of malformed parameters
618 */
parseCompressionParameters(const char * stringPtr,ZSTD_compressionParameters * params)619 static unsigned parseCompressionParameters(const char* stringPtr, ZSTD_compressionParameters* params)
620 {
621 for ( ; ;) {
622 if (longCommandWArg(&stringPtr, "windowLog=") || longCommandWArg(&stringPtr, "wlog=")) { params->windowLog = readU32FromChar(&stringPtr); if (stringPtr[0]==',') { stringPtr++; continue; } else break; }
623 if (longCommandWArg(&stringPtr, "chainLog=") || longCommandWArg(&stringPtr, "clog=")) { params->chainLog = readU32FromChar(&stringPtr); if (stringPtr[0]==',') { stringPtr++; continue; } else break; }
624 if (longCommandWArg(&stringPtr, "hashLog=") || longCommandWArg(&stringPtr, "hlog=")) { params->hashLog = readU32FromChar(&stringPtr); if (stringPtr[0]==',') { stringPtr++; continue; } else break; }
625 if (longCommandWArg(&stringPtr, "searchLog=") || longCommandWArg(&stringPtr, "slog=")) { params->searchLog = readU32FromChar(&stringPtr); if (stringPtr[0]==',') { stringPtr++; continue; } else break; }
626 if (longCommandWArg(&stringPtr, "minMatch=") || longCommandWArg(&stringPtr, "mml=")) { params->minMatch = readU32FromChar(&stringPtr); if (stringPtr[0]==',') { stringPtr++; continue; } else break; }
627 if (longCommandWArg(&stringPtr, "targetLength=") || longCommandWArg(&stringPtr, "tlen=")) { params->targetLength = readU32FromChar(&stringPtr); if (stringPtr[0]==',') { stringPtr++; continue; } else break; }
628 if (longCommandWArg(&stringPtr, "strategy=") || longCommandWArg(&stringPtr, "strat=")) { params->strategy = (ZSTD_strategy)(readU32FromChar(&stringPtr)); if (stringPtr[0]==',') { stringPtr++; continue; } else break; }
629 if (longCommandWArg(&stringPtr, "overlapLog=") || longCommandWArg(&stringPtr, "ovlog=")) { g_overlapLog = readU32FromChar(&stringPtr); if (stringPtr[0]==',') { stringPtr++; continue; } else break; }
630 if (longCommandWArg(&stringPtr, "ldmHashLog=") || longCommandWArg(&stringPtr, "lhlog=")) { g_ldmHashLog = readU32FromChar(&stringPtr); if (stringPtr[0]==',') { stringPtr++; continue; } else break; }
631 if (longCommandWArg(&stringPtr, "ldmMinMatch=") || longCommandWArg(&stringPtr, "lmml=")) { g_ldmMinMatch = readU32FromChar(&stringPtr); if (stringPtr[0]==',') { stringPtr++; continue; } else break; }
632 if (longCommandWArg(&stringPtr, "ldmBucketSizeLog=") || longCommandWArg(&stringPtr, "lblog=")) { g_ldmBucketSizeLog = readU32FromChar(&stringPtr); if (stringPtr[0]==',') { stringPtr++; continue; } else break; }
633 if (longCommandWArg(&stringPtr, "ldmHashRateLog=") || longCommandWArg(&stringPtr, "lhrlog=")) { g_ldmHashRateLog = readU32FromChar(&stringPtr); if (stringPtr[0]==',') { stringPtr++; continue; } else break; }
634 DISPLAYLEVEL(4, "invalid compression parameter \n");
635 return 0;
636 }
637
638 if (stringPtr[0] != 0) return 0; /* check the end of string */
639 return 1;
640 }
641
setMaxCompression(ZSTD_compressionParameters * params)642 static void setMaxCompression(ZSTD_compressionParameters* params)
643 {
644 params->windowLog = ZSTD_WINDOWLOG_MAX;
645 params->chainLog = ZSTD_CHAINLOG_MAX;
646 params->hashLog = ZSTD_HASHLOG_MAX;
647 params->searchLog = ZSTD_SEARCHLOG_MAX;
648 params->minMatch = ZSTD_MINMATCH_MIN;
649 params->targetLength = ZSTD_TARGETLENGTH_MAX;
650 params->strategy = ZSTD_STRATEGY_MAX;
651 g_overlapLog = ZSTD_OVERLAPLOG_MAX;
652 g_ldmHashLog = ZSTD_LDM_HASHLOG_MAX;
653 g_ldmHashRateLog = 0; /* automatically derived */
654 g_ldmMinMatch = 16; /* heuristic */
655 g_ldmBucketSizeLog = ZSTD_LDM_BUCKETSIZELOG_MAX;
656 }
657
printVersion(void)658 static void printVersion(void)
659 {
660 if (g_displayLevel < DISPLAY_LEVEL_DEFAULT) {
661 DISPLAYOUT("%s\n", ZSTD_VERSION_STRING);
662 return;
663 }
664
665 DISPLAYOUT(WELCOME_MESSAGE);
666 if (g_displayLevel >= 3) {
667 /* format support */
668 DISPLAYOUT("*** supports: zstd");
669 #if defined(ZSTD_LEGACY_SUPPORT) && (ZSTD_LEGACY_SUPPORT>0) && (ZSTD_LEGACY_SUPPORT<8)
670 DISPLAYOUT(", zstd legacy v0.%d+", ZSTD_LEGACY_SUPPORT);
671 #endif
672 #ifdef ZSTD_GZCOMPRESS
673 DISPLAYOUT(", gzip");
674 #endif
675 #ifdef ZSTD_LZ4COMPRESS
676 DISPLAYOUT(", lz4");
677 #endif
678 #ifdef ZSTD_LZMACOMPRESS
679 DISPLAYOUT(", lzma, xz ");
680 #endif
681 DISPLAYOUT("\n");
682 if (g_displayLevel >= 4) {
683 /* library versions */
684 DISPLAYOUT("zlib version %s\n", FIO_zlibVersion());
685 DISPLAYOUT("lz4 version %s\n", FIO_lz4Version());
686 DISPLAYOUT("lzma version %s\n", FIO_lzmaVersion());
687
688 /* posix support */
689 #ifdef _POSIX_C_SOURCE
690 DISPLAYOUT("_POSIX_C_SOURCE defined: %ldL\n", (long) _POSIX_C_SOURCE);
691 #endif
692 #ifdef _POSIX_VERSION
693 DISPLAYOUT("_POSIX_VERSION defined: %ldL \n", (long) _POSIX_VERSION);
694 #endif
695 #ifdef PLATFORM_POSIX_VERSION
696 DISPLAYOUT("PLATFORM_POSIX_VERSION defined: %ldL\n", (long) PLATFORM_POSIX_VERSION);
697 #endif
698 } }
699 }
700
701 #define ZSTD_NB_STRATEGIES 9
702 static const char* ZSTD_strategyMap[ZSTD_NB_STRATEGIES + 1] = { "", "ZSTD_fast",
703 "ZSTD_dfast", "ZSTD_greedy", "ZSTD_lazy", "ZSTD_lazy2", "ZSTD_btlazy2",
704 "ZSTD_btopt", "ZSTD_btultra", "ZSTD_btultra2"};
705
706 #ifndef ZSTD_NOCOMPRESS
707
printDefaultCParams(const char * filename,const char * dictFileName,int cLevel)708 static void printDefaultCParams(const char* filename, const char* dictFileName, int cLevel) {
709 unsigned long long fileSize = UTIL_getFileSize(filename);
710 const size_t dictSize = dictFileName != NULL ? (size_t)UTIL_getFileSize(dictFileName) : 0;
711 const ZSTD_compressionParameters cParams = ZSTD_getCParams(cLevel, fileSize, dictSize);
712 if (fileSize != UTIL_FILESIZE_UNKNOWN) DISPLAY("%s (%llu bytes)\n", filename, fileSize);
713 else DISPLAY("%s (src size unknown)\n", filename);
714 DISPLAY(" - windowLog : %u\n", cParams.windowLog);
715 DISPLAY(" - chainLog : %u\n", cParams.chainLog);
716 DISPLAY(" - hashLog : %u\n", cParams.hashLog);
717 DISPLAY(" - searchLog : %u\n", cParams.searchLog);
718 DISPLAY(" - minMatch : %u\n", cParams.minMatch);
719 DISPLAY(" - targetLength : %u\n", cParams.targetLength);
720 assert(cParams.strategy < ZSTD_NB_STRATEGIES + 1);
721 DISPLAY(" - strategy : %s (%u)\n", ZSTD_strategyMap[(int)cParams.strategy], (unsigned)cParams.strategy);
722 }
723
printActualCParams(const char * filename,const char * dictFileName,int cLevel,const ZSTD_compressionParameters * cParams)724 static void printActualCParams(const char* filename, const char* dictFileName, int cLevel, const ZSTD_compressionParameters* cParams) {
725 unsigned long long fileSize = UTIL_getFileSize(filename);
726 const size_t dictSize = dictFileName != NULL ? (size_t)UTIL_getFileSize(dictFileName) : 0;
727 ZSTD_compressionParameters actualCParams = ZSTD_getCParams(cLevel, fileSize, dictSize);
728 assert(g_displayLevel >= 4);
729 actualCParams.windowLog = cParams->windowLog == 0 ? actualCParams.windowLog : cParams->windowLog;
730 actualCParams.chainLog = cParams->chainLog == 0 ? actualCParams.chainLog : cParams->chainLog;
731 actualCParams.hashLog = cParams->hashLog == 0 ? actualCParams.hashLog : cParams->hashLog;
732 actualCParams.searchLog = cParams->searchLog == 0 ? actualCParams.searchLog : cParams->searchLog;
733 actualCParams.minMatch = cParams->minMatch == 0 ? actualCParams.minMatch : cParams->minMatch;
734 actualCParams.targetLength = cParams->targetLength == 0 ? actualCParams.targetLength : cParams->targetLength;
735 actualCParams.strategy = cParams->strategy == 0 ? actualCParams.strategy : cParams->strategy;
736 DISPLAY("--zstd=wlog=%d,clog=%d,hlog=%d,slog=%d,mml=%d,tlen=%d,strat=%d\n",
737 actualCParams.windowLog, actualCParams.chainLog, actualCParams.hashLog, actualCParams.searchLog,
738 actualCParams.minMatch, actualCParams.targetLength, actualCParams.strategy);
739 }
740
741 #endif
742
743 /* Environment variables for parameter setting */
744 #define ENV_CLEVEL "ZSTD_CLEVEL"
745 #define ENV_NBTHREADS "ZSTD_NBTHREADS" /* takes lower precedence than directly specifying -T# in the CLI */
746
747 /* pick up environment variable */
init_cLevel(void)748 static int init_cLevel(void) {
749 const char* const env = getenv(ENV_CLEVEL);
750 if (env != NULL) {
751 const char* ptr = env;
752 int sign = 1;
753 if (*ptr == '-') {
754 sign = -1;
755 ptr++;
756 } else if (*ptr == '+') {
757 ptr++;
758 }
759
760 if ((*ptr>='0') && (*ptr<='9')) {
761 unsigned absLevel;
762 if (readU32FromCharChecked(&ptr, &absLevel)) {
763 DISPLAYLEVEL(2, "Ignore environment variable setting %s=%s: numeric value too large \n", ENV_CLEVEL, env);
764 return ZSTDCLI_CLEVEL_DEFAULT;
765 } else if (*ptr == 0) {
766 return sign * (int)absLevel;
767 } }
768
769 DISPLAYLEVEL(2, "Ignore environment variable setting %s=%s: not a valid integer value \n", ENV_CLEVEL, env);
770 }
771
772 return ZSTDCLI_CLEVEL_DEFAULT;
773 }
774
775 #ifdef ZSTD_MULTITHREAD
default_nbThreads(void)776 static unsigned default_nbThreads(void) {
777 const char* const env = getenv(ENV_NBTHREADS);
778 if (env != NULL) {
779 const char* ptr = env;
780 if ((*ptr>='0') && (*ptr<='9')) {
781 unsigned nbThreads;
782 if (readU32FromCharChecked(&ptr, &nbThreads)) {
783 DISPLAYLEVEL(2, "Ignore environment variable setting %s=%s: numeric value too large \n", ENV_NBTHREADS, env);
784 return ZSTDCLI_NBTHREADS_DEFAULT;
785 } else if (*ptr == 0) {
786 return nbThreads;
787 }
788 }
789 DISPLAYLEVEL(2, "Ignore environment variable setting %s=%s: not a valid unsigned value \n", ENV_NBTHREADS, env);
790 }
791
792 return ZSTDCLI_NBTHREADS_DEFAULT;
793 }
794 #endif
795
796 #define NEXT_FIELD(ptr) { \
797 if (*argument == '=') { \
798 ptr = ++argument; \
799 argument += strlen(ptr); \
800 } else { \
801 argNb++; \
802 if (argNb >= argCount) { \
803 DISPLAYLEVEL(1, "error: missing command argument \n"); \
804 CLEAN_RETURN(1); \
805 } \
806 ptr = argv[argNb]; \
807 assert(ptr != NULL); \
808 if (ptr[0]=='-') { \
809 DISPLAYLEVEL(1, "error: command cannot be separated from its argument by another command \n"); \
810 CLEAN_RETURN(1); \
811 } } }
812
813 #define NEXT_UINT32(val32) { \
814 const char* __nb; \
815 NEXT_FIELD(__nb); \
816 val32 = readU32FromChar(&__nb); \
817 if(*__nb != 0) { \
818 errorOut("error: only numeric values with optional suffixes K, KB, KiB, M, MB, MiB are allowed"); \
819 } \
820 }
821
822 #define NEXT_TSIZE(valTsize) { \
823 const char* __nb; \
824 NEXT_FIELD(__nb); \
825 valTsize = readSizeTFromChar(&__nb); \
826 if(*__nb != 0) { \
827 errorOut("error: only numeric values with optional suffixes K, KB, KiB, M, MB, MiB are allowed"); \
828 } \
829 }
830
831 typedef enum { zom_compress, zom_decompress, zom_test, zom_bench, zom_train, zom_list } zstd_operation_mode;
832
833 #define CLEAN_RETURN(i) { operationResult = (i); goto _end; }
834
835 #ifdef ZSTD_NOCOMPRESS
836 /* symbols from compression library are not defined and should not be invoked */
837 # define MINCLEVEL -99
838 # define MAXCLEVEL 22
839 #else
840 # define MINCLEVEL ZSTD_minCLevel()
841 # define MAXCLEVEL ZSTD_maxCLevel()
842 #endif
843
main(int argCount,const char * argv[])844 int main(int argCount, const char* argv[])
845 {
846 int argNb,
847 followLinks = 0,
848 allowBlockDevices = 0,
849 forceStdin = 0,
850 forceStdout = 0,
851 hasStdout = 0,
852 ldmFlag = 0,
853 main_pause = 0,
854 adapt = 0,
855 adaptMin = MINCLEVEL,
856 adaptMax = MAXCLEVEL,
857 rsyncable = 0,
858 nextArgumentsAreFiles = 0,
859 operationResult = 0,
860 separateFiles = 0,
861 setRealTimePrio = 0,
862 singleThread = 0,
863 defaultLogicalCores = 0,
864 showDefaultCParams = 0,
865 ultra=0,
866 contentSize=1,
867 removeSrcFile=0;
868 ZSTD_ParamSwitch_e mmapDict=ZSTD_ps_auto;
869 ZSTD_ParamSwitch_e useRowMatchFinder = ZSTD_ps_auto;
870 FIO_compressionType_t cType = FIO_zstdCompression;
871 int nbWorkers = -1; /* -1 means unset */
872 double compressibility = -1.0; /* lorem ipsum generator */
873 unsigned bench_nbSeconds = 3; /* would be better if this value was synchronized from bench */
874 size_t blockSize = 0;
875
876 FIO_prefs_t* const prefs = FIO_createPreferences();
877 FIO_ctx_t* const fCtx = FIO_createContext();
878 FIO_progressSetting_e progress = FIO_ps_auto;
879 zstd_operation_mode operation = zom_compress;
880 ZSTD_compressionParameters compressionParams;
881 int cLevel = init_cLevel();
882 int cLevelLast = MINCLEVEL - 1; /* lower than minimum */
883 unsigned recursive = 0;
884 unsigned memLimit = 0;
885 FileNamesTable* filenames = UTIL_allocateFileNamesTable((size_t)argCount); /* argCount >= 1 */
886 FileNamesTable* file_of_names = UTIL_allocateFileNamesTable((size_t)argCount); /* argCount >= 1 */
887 const char* programName = argv[0];
888 const char* outFileName = NULL;
889 const char* outDirName = NULL;
890 const char* outMirroredDirName = NULL;
891 const char* dictFileName = NULL;
892 const char* patchFromDictFileName = NULL;
893 const char* suffix = ZSTD_EXTENSION;
894 unsigned maxDictSize = g_defaultMaxDictSize;
895 unsigned dictID = 0;
896 size_t streamSrcSize = 0;
897 size_t targetCBlockSize = 0;
898 size_t srcSizeHint = 0;
899 size_t nbInputFileNames = 0;
900 int dictCLevel = g_defaultDictCLevel;
901 unsigned dictSelect = g_defaultSelectivityLevel;
902 #ifndef ZSTD_NODICT
903 ZDICT_cover_params_t coverParams = defaultCoverParams();
904 ZDICT_fastCover_params_t fastCoverParams = defaultFastCoverParams();
905 dictType dict = fastCover;
906 #endif
907 #ifndef ZSTD_NOBENCH
908 BMK_advancedParams_t benchParams = BMK_initAdvancedParams();
909 #endif
910 ZSTD_ParamSwitch_e literalCompressionMode = ZSTD_ps_auto;
911
912 /* init */
913 checkLibVersion();
914 (void)recursive; (void)cLevelLast; /* not used when ZSTD_NOBENCH set */
915 (void)memLimit;
916 assert(argCount >= 1);
917 if ((filenames==NULL) || (file_of_names==NULL)) { DISPLAYLEVEL(1, "zstd: allocation error \n"); exit(1); }
918 programName = lastNameFromPath(programName);
919
920 /* preset behaviors */
921 if (exeNameMatch(programName, ZSTD_ZSTDMT)) nbWorkers=0, singleThread=0;
922 if (exeNameMatch(programName, ZSTD_UNZSTD)) operation=zom_decompress;
923 if (exeNameMatch(programName, ZSTD_CAT)) { operation=zom_decompress; FIO_overwriteMode(prefs); forceStdout=1; followLinks=1; FIO_setPassThroughFlag(prefs, 1); outFileName=stdoutmark; g_displayLevel=1; } /* supports multiple formats */
924 if (exeNameMatch(programName, ZSTD_ZCAT)) { operation=zom_decompress; FIO_overwriteMode(prefs); forceStdout=1; followLinks=1; FIO_setPassThroughFlag(prefs, 1); outFileName=stdoutmark; g_displayLevel=1; } /* behave like zcat, also supports multiple formats */
925 if (exeNameMatch(programName, ZSTD_GZ)) { /* behave like gzip */
926 suffix = GZ_EXTENSION; cType = FIO_gzipCompression; removeSrcFile=1;
927 dictCLevel = cLevel = 6; /* gzip default is -6 */
928 }
929 if (exeNameMatch(programName, ZSTD_GUNZIP)) { operation=zom_decompress; removeSrcFile=1; } /* behave like gunzip, also supports multiple formats */
930 if (exeNameMatch(programName, ZSTD_GZCAT)) { operation=zom_decompress; FIO_overwriteMode(prefs); forceStdout=1; followLinks=1; FIO_setPassThroughFlag(prefs, 1); outFileName=stdoutmark; g_displayLevel=1; } /* behave like gzcat, also supports multiple formats */
931 if (exeNameMatch(programName, ZSTD_LZMA)) { suffix = LZMA_EXTENSION; cType = FIO_lzmaCompression; removeSrcFile=1; } /* behave like lzma */
932 if (exeNameMatch(programName, ZSTD_UNLZMA)) { operation=zom_decompress; cType = FIO_lzmaCompression; removeSrcFile=1; } /* behave like unlzma, also supports multiple formats */
933 if (exeNameMatch(programName, ZSTD_XZ)) { suffix = XZ_EXTENSION; cType = FIO_xzCompression; removeSrcFile=1; } /* behave like xz */
934 if (exeNameMatch(programName, ZSTD_UNXZ)) { operation=zom_decompress; cType = FIO_xzCompression; removeSrcFile=1; } /* behave like unxz, also supports multiple formats */
935 if (exeNameMatch(programName, ZSTD_LZ4)) { suffix = LZ4_EXTENSION; cType = FIO_lz4Compression; } /* behave like lz4 */
936 if (exeNameMatch(programName, ZSTD_UNLZ4)) { operation=zom_decompress; cType = FIO_lz4Compression; } /* behave like unlz4, also supports multiple formats */
937 memset(&compressionParams, 0, sizeof(compressionParams));
938
939 /* init crash handler */
940 FIO_addAbortHandler();
941
942 /* command switches */
943 for (argNb=1; argNb<argCount; argNb++) {
944 const char* argument = argv[argNb];
945 const char* const originalArgument = argument;
946 if (!argument) continue; /* Protection if argument empty */
947
948 if (nextArgumentsAreFiles) {
949 UTIL_refFilename(filenames, argument);
950 continue;
951 }
952
953 /* "-" means stdin/stdout */
954 if (!strcmp(argument, "-")){
955 UTIL_refFilename(filenames, stdinmark);
956 continue;
957 }
958
959 /* Decode commands (note : aggregated commands are allowed) */
960 if (argument[0]=='-') {
961
962 if (argument[1]=='-') {
963 /* long commands (--long-word) */
964 if (!strcmp(argument, "--")) { nextArgumentsAreFiles=1; continue; } /* only file names allowed from now on */
965 if (!strcmp(argument, "--list")) { operation=zom_list; continue; }
966 if (!strcmp(argument, "--compress")) { operation=zom_compress; continue; }
967 if (!strcmp(argument, "--decompress")) { operation=zom_decompress; continue; }
968 if (!strcmp(argument, "--uncompress")) { operation=zom_decompress; continue; }
969 if (!strcmp(argument, "--force")) { FIO_overwriteMode(prefs); forceStdin=1; forceStdout=1; followLinks=1; allowBlockDevices=1; continue; }
970 if (!strcmp(argument, "--version")) { printVersion(); CLEAN_RETURN(0); }
971 if (!strcmp(argument, "--help")) { usageAdvanced(programName); CLEAN_RETURN(0); }
972 if (!strcmp(argument, "--verbose")) { g_displayLevel++; continue; }
973 if (!strcmp(argument, "--quiet")) { g_displayLevel--; continue; }
974 if (!strcmp(argument, "--stdout")) { forceStdout=1; outFileName=stdoutmark; continue; }
975 if (!strcmp(argument, "--ultra")) { ultra=1; continue; }
976 if (!strcmp(argument, "--check")) { FIO_setChecksumFlag(prefs, 2); continue; }
977 if (!strcmp(argument, "--no-check")) { FIO_setChecksumFlag(prefs, 0); continue; }
978 if (!strcmp(argument, "--sparse")) { FIO_setSparseWrite(prefs, 2); continue; }
979 if (!strcmp(argument, "--no-sparse")) { FIO_setSparseWrite(prefs, 0); continue; }
980 if (!strcmp(argument, "--pass-through")) { FIO_setPassThroughFlag(prefs, 1); continue; }
981 if (!strcmp(argument, "--no-pass-through")) { FIO_setPassThroughFlag(prefs, 0); continue; }
982 if (!strcmp(argument, "--test")) { operation=zom_test; continue; }
983 if (!strcmp(argument, "--asyncio")) { FIO_setAsyncIOFlag(prefs, 1); continue;}
984 if (!strcmp(argument, "--no-asyncio")) { FIO_setAsyncIOFlag(prefs, 0); continue;}
985 if (!strcmp(argument, "--train")) { operation=zom_train; if (outFileName==NULL) outFileName=g_defaultDictName; continue; }
986 if (!strcmp(argument, "--no-dictID")) { FIO_setDictIDFlag(prefs, 0); continue; }
987 if (!strcmp(argument, "--keep")) { removeSrcFile=0; continue; }
988 if (!strcmp(argument, "--rm")) { removeSrcFile=1; continue; }
989 if (!strcmp(argument, "--priority=rt")) { setRealTimePrio = 1; continue; }
990 if (!strcmp(argument, "--show-default-cparams")) { showDefaultCParams = 1; continue; }
991 if (!strcmp(argument, "--content-size")) { contentSize = 1; continue; }
992 if (!strcmp(argument, "--no-content-size")) { contentSize = 0; continue; }
993 if (!strcmp(argument, "--adapt")) { adapt = 1; continue; }
994 if (!strcmp(argument, "--no-row-match-finder")) { useRowMatchFinder = ZSTD_ps_disable; continue; }
995 if (!strcmp(argument, "--row-match-finder")) { useRowMatchFinder = ZSTD_ps_enable; continue; }
996 if (longCommandWArg(&argument, "--adapt=")) { adapt = 1; if (!parseAdaptParameters(argument, &adaptMin, &adaptMax)) { badUsage(programName, originalArgument); CLEAN_RETURN(1); } continue; }
997 if (!strcmp(argument, "--single-thread")) { nbWorkers = 0; singleThread = 1; continue; }
998 if (!strcmp(argument, "--format=zstd")) { suffix = ZSTD_EXTENSION; cType = FIO_zstdCompression; continue; }
999 if (!strcmp(argument, "--mmap-dict")) { mmapDict = ZSTD_ps_enable; continue; }
1000 if (!strcmp(argument, "--no-mmap-dict")) { mmapDict = ZSTD_ps_disable; continue; }
1001 #ifdef ZSTD_GZCOMPRESS
1002 if (!strcmp(argument, "--format=gzip")) { suffix = GZ_EXTENSION; cType = FIO_gzipCompression; continue; }
1003 if (exeNameMatch(programName, ZSTD_GZ)) { /* behave like gzip */
1004 if (!strcmp(argument, "--best")) { dictCLevel = cLevel = 9; continue; }
1005 if (!strcmp(argument, "--no-name")) { /* ignore for now */; continue; }
1006 }
1007 #endif
1008 #ifdef ZSTD_LZMACOMPRESS
1009 if (!strcmp(argument, "--format=lzma")) { suffix = LZMA_EXTENSION; cType = FIO_lzmaCompression; continue; }
1010 if (!strcmp(argument, "--format=xz")) { suffix = XZ_EXTENSION; cType = FIO_xzCompression; continue; }
1011 #endif
1012 #ifdef ZSTD_LZ4COMPRESS
1013 if (!strcmp(argument, "--format=lz4")) { suffix = LZ4_EXTENSION; cType = FIO_lz4Compression; continue; }
1014 #endif
1015 if (!strcmp(argument, "--rsyncable")) { rsyncable = 1; continue; }
1016 if (!strcmp(argument, "--compress-literals")) { literalCompressionMode = ZSTD_ps_enable; continue; }
1017 if (!strcmp(argument, "--no-compress-literals")) { literalCompressionMode = ZSTD_ps_disable; continue; }
1018 if (!strcmp(argument, "--no-progress")) { progress = FIO_ps_never; continue; }
1019 if (!strcmp(argument, "--progress")) { progress = FIO_ps_always; continue; }
1020 if (!strcmp(argument, "--exclude-compressed")) { FIO_setExcludeCompressedFile(prefs, 1); continue; }
1021 if (!strcmp(argument, "--fake-stdin-is-console")) { UTIL_fakeStdinIsConsole(); continue; }
1022 if (!strcmp(argument, "--fake-stdout-is-console")) { UTIL_fakeStdoutIsConsole(); continue; }
1023 if (!strcmp(argument, "--fake-stderr-is-console")) { UTIL_fakeStderrIsConsole(); continue; }
1024 if (!strcmp(argument, "--trace-file-stat")) { UTIL_traceFileStat(); continue; }
1025
1026 if (!strcmp(argument, "--max")) {
1027 if (sizeof(void*)==4) {
1028 DISPLAYLEVEL(2, "--max is incompatible with 32-bit mode \n");
1029 badUsage(programName, originalArgument);
1030 CLEAN_RETURN(1);
1031 }
1032 ultra=1; ldmFlag = 1; setMaxCompression(&compressionParams);
1033 continue;
1034 }
1035
1036 /* long commands with arguments */
1037 #ifndef ZSTD_NODICT
1038 if (longCommandWArg(&argument, "--train-cover")) {
1039 operation = zom_train;
1040 if (outFileName == NULL)
1041 outFileName = g_defaultDictName;
1042 dict = cover;
1043 /* Allow optional arguments following an = */
1044 if (*argument == 0) { memset(&coverParams, 0, sizeof(coverParams)); }
1045 else if (*argument++ != '=') { badUsage(programName, originalArgument); CLEAN_RETURN(1); }
1046 else if (!parseCoverParameters(argument, &coverParams)) { badUsage(programName, originalArgument); CLEAN_RETURN(1); }
1047 continue;
1048 }
1049 if (longCommandWArg(&argument, "--train-fastcover")) {
1050 operation = zom_train;
1051 if (outFileName == NULL)
1052 outFileName = g_defaultDictName;
1053 dict = fastCover;
1054 /* Allow optional arguments following an = */
1055 if (*argument == 0) { memset(&fastCoverParams, 0, sizeof(fastCoverParams)); }
1056 else if (*argument++ != '=') { badUsage(programName, originalArgument); CLEAN_RETURN(1); }
1057 else if (!parseFastCoverParameters(argument, &fastCoverParams)) { badUsage(programName, originalArgument); CLEAN_RETURN(1); }
1058 continue;
1059 }
1060 if (longCommandWArg(&argument, "--train-legacy")) {
1061 operation = zom_train;
1062 if (outFileName == NULL)
1063 outFileName = g_defaultDictName;
1064 dict = legacy;
1065 /* Allow optional arguments following an = */
1066 if (*argument == 0) { continue; }
1067 else if (*argument++ != '=') { badUsage(programName, originalArgument); CLEAN_RETURN(1); }
1068 else if (!parseLegacyParameters(argument, &dictSelect)) { badUsage(programName, originalArgument); CLEAN_RETURN(1); }
1069 continue;
1070 }
1071 #endif
1072 if (longCommandWArg(&argument, "--threads")) { NEXT_UINT32(nbWorkers); continue; }
1073 if (longCommandWArg(&argument, "--memlimit")) { NEXT_UINT32(memLimit); continue; }
1074 if (longCommandWArg(&argument, "--memory")) { NEXT_UINT32(memLimit); continue; }
1075 if (longCommandWArg(&argument, "--memlimit-decompress")) { NEXT_UINT32(memLimit); continue; }
1076 if (longCommandWArg(&argument, "--block-size")) { NEXT_TSIZE(blockSize); continue; }
1077 if (longCommandWArg(&argument, "--maxdict")) { NEXT_UINT32(maxDictSize); continue; }
1078 if (longCommandWArg(&argument, "--dictID")) { NEXT_UINT32(dictID); continue; }
1079 if (longCommandWArg(&argument, "--zstd=")) { if (!parseCompressionParameters(argument, &compressionParams)) { badUsage(programName, originalArgument); CLEAN_RETURN(1); } ; cType = FIO_zstdCompression; continue; }
1080 if (longCommandWArg(&argument, "--stream-size")) { NEXT_TSIZE(streamSrcSize); continue; }
1081 if (longCommandWArg(&argument, "--target-compressed-block-size")) { NEXT_TSIZE(targetCBlockSize); continue; }
1082 if (longCommandWArg(&argument, "--size-hint")) { NEXT_TSIZE(srcSizeHint); continue; }
1083 if (longCommandWArg(&argument, "--output-dir-flat")) {
1084 NEXT_FIELD(outDirName);
1085 if (strlen(outDirName) == 0) {
1086 DISPLAYLEVEL(1, "error: output dir cannot be empty string (did you mean to pass '.' instead?)\n");
1087 CLEAN_RETURN(1);
1088 }
1089 continue;
1090 }
1091 if (longCommandWArg(&argument, "--auto-threads")) {
1092 const char* threadDefault = NULL;
1093 NEXT_FIELD(threadDefault);
1094 if (strcmp(threadDefault, "logical") == 0)
1095 defaultLogicalCores = 1;
1096 continue;
1097 }
1098 #ifdef UTIL_HAS_MIRRORFILELIST
1099 if (longCommandWArg(&argument, "--output-dir-mirror")) {
1100 NEXT_FIELD(outMirroredDirName);
1101 if (strlen(outMirroredDirName) == 0) {
1102 DISPLAYLEVEL(1, "error: output dir cannot be empty string (did you mean to pass '.' instead?)\n");
1103 CLEAN_RETURN(1);
1104 }
1105 continue;
1106 }
1107 #endif
1108 #ifndef ZSTD_NOTRACE
1109 if (longCommandWArg(&argument, "--trace")) { char const* traceFile; NEXT_FIELD(traceFile); TRACE_enable(traceFile); continue; }
1110 #endif
1111 if (longCommandWArg(&argument, "--patch-from")) { NEXT_FIELD(patchFromDictFileName); ultra = 1; continue; }
1112 if (longCommandWArg(&argument, "--long")) {
1113 unsigned ldmWindowLog = 0;
1114 ldmFlag = 1;
1115 ultra = 1;
1116 /* Parse optional window log */
1117 if (*argument == '=') {
1118 ++argument;
1119 ldmWindowLog = readU32FromChar(&argument);
1120 } else if (*argument != 0) {
1121 /* Invalid character following --long */
1122 badUsage(programName, originalArgument);
1123 CLEAN_RETURN(1);
1124 } else {
1125 ldmWindowLog = g_defaultMaxWindowLog;
1126 }
1127 /* Only set windowLog if not already set by --zstd */
1128 if (compressionParams.windowLog == 0)
1129 compressionParams.windowLog = ldmWindowLog;
1130 continue;
1131 }
1132 #ifndef ZSTD_NOCOMPRESS /* linking ZSTD_minCLevel() requires compression support */
1133 if (longCommandWArg(&argument, "--fast")) {
1134 /* Parse optional acceleration factor */
1135 if (*argument == '=') {
1136 U32 const maxFast = (U32)-ZSTD_minCLevel();
1137 U32 fastLevel;
1138 ++argument;
1139 fastLevel = readU32FromChar(&argument);
1140 if (fastLevel > maxFast) fastLevel = maxFast;
1141 if (fastLevel) {
1142 dictCLevel = cLevel = -(int)fastLevel;
1143 } else {
1144 badUsage(programName, originalArgument);
1145 CLEAN_RETURN(1);
1146 }
1147 } else if (*argument != 0) {
1148 /* Invalid character following --fast */
1149 badUsage(programName, originalArgument);
1150 CLEAN_RETURN(1);
1151 } else {
1152 cLevel = -1; /* default for --fast */
1153 }
1154 continue;
1155 }
1156 #endif
1157
1158 if (longCommandWArg(&argument, "--filelist")) {
1159 const char* listName;
1160 NEXT_FIELD(listName);
1161 UTIL_refFilename(file_of_names, listName);
1162 continue;
1163 }
1164
1165 badUsage(programName, originalArgument);
1166 CLEAN_RETURN(1);
1167 }
1168
1169 argument++;
1170 while (argument[0]!=0) {
1171
1172 #ifndef ZSTD_NOCOMPRESS
1173 /* compression Level */
1174 if ((*argument>='0') && (*argument<='9')) {
1175 dictCLevel = cLevel = (int)readU32FromChar(&argument);
1176 continue;
1177 }
1178 #endif
1179
1180 switch(argument[0])
1181 {
1182 /* Display help */
1183 case 'V': printVersion(); CLEAN_RETURN(0); /* Version Only */
1184 case 'H': usageAdvanced(programName); CLEAN_RETURN(0);
1185 case 'h': usage(stdout, programName); CLEAN_RETURN(0);
1186
1187 /* Compress */
1188 case 'z': operation=zom_compress; argument++; break;
1189
1190 /* Decoding */
1191 case 'd':
1192 #ifndef ZSTD_NOBENCH
1193 benchParams.mode = BMK_decodeOnly;
1194 if (operation==zom_bench) { argument++; break; } /* benchmark decode (hidden option) */
1195 #endif
1196 operation=zom_decompress; argument++; break;
1197
1198 /* Force stdout, even if stdout==console */
1199 case 'c': forceStdout=1; outFileName=stdoutmark; argument++; break;
1200
1201 /* destination file name */
1202 case 'o': argument++; NEXT_FIELD(outFileName); break;
1203
1204 /* do not store filename - gzip compatibility - nothing to do */
1205 case 'n': argument++; break;
1206
1207 /* Use file content as dictionary */
1208 case 'D': argument++; NEXT_FIELD(dictFileName); break;
1209
1210 /* Overwrite */
1211 case 'f': FIO_overwriteMode(prefs); forceStdin=1; forceStdout=1; followLinks=1; allowBlockDevices=1; argument++; break;
1212
1213 /* Verbose mode */
1214 case 'v': g_displayLevel++; argument++; break;
1215
1216 /* Quiet mode */
1217 case 'q': g_displayLevel--; argument++; break;
1218
1219 /* keep source file (default) */
1220 case 'k': removeSrcFile=0; argument++; break;
1221
1222 /* Checksum */
1223 case 'C': FIO_setChecksumFlag(prefs, 2); argument++; break;
1224
1225 /* test compressed file */
1226 case 't': operation=zom_test; argument++; break;
1227
1228 /* limit memory */
1229 case 'M':
1230 argument++;
1231 memLimit = readU32FromChar(&argument);
1232 break;
1233 case 'l': operation=zom_list; argument++; break;
1234 #ifdef UTIL_HAS_CREATEFILELIST
1235 /* recursive */
1236 case 'r': recursive=1; argument++; break;
1237 #endif
1238
1239 #ifndef ZSTD_NOBENCH
1240 /* Benchmark */
1241 case 'b':
1242 operation=zom_bench;
1243 argument++;
1244 break;
1245
1246 /* range bench (benchmark only) */
1247 case 'e':
1248 /* compression Level */
1249 argument++;
1250 cLevelLast = (int)readU32FromChar(&argument);
1251 break;
1252
1253 /* Modify Nb Iterations (benchmark only) */
1254 case 'i':
1255 argument++;
1256 bench_nbSeconds = readU32FromChar(&argument);
1257 break;
1258
1259 /* cut input into blocks (benchmark only) */
1260 case 'B':
1261 argument++;
1262 blockSize = readU32FromChar(&argument);
1263 break;
1264
1265 /* benchmark files separately (hidden option) */
1266 case 'S':
1267 argument++;
1268 separateFiles = 1;
1269 break;
1270
1271 #endif /* ZSTD_NOBENCH */
1272
1273 /* nb of threads (hidden option) */
1274 case 'T':
1275 argument++;
1276 nbWorkers = readU32FromChar(&argument);
1277 break;
1278
1279 /* Dictionary Selection level */
1280 case 's':
1281 argument++;
1282 dictSelect = readU32FromChar(&argument);
1283 break;
1284
1285 /* Pause at the end (-p) or set an additional param (-p#) (hidden option) */
1286 case 'p': argument++;
1287 #ifndef ZSTD_NOBENCH
1288 if ((*argument>='0') && (*argument<='9')) {
1289 benchParams.additionalParam = (int)readU32FromChar(&argument);
1290 } else
1291 #endif
1292 main_pause=1;
1293 break;
1294
1295 /* Select compressibility of synthetic sample */
1296 case 'P':
1297 argument++;
1298 compressibility = (double)readU32FromChar(&argument) / 100;
1299 break;
1300
1301 /* unknown command */
1302 default :
1303 { char shortArgument[3] = {'-', 0, 0};
1304 shortArgument[1] = argument[0];
1305 badUsage(programName, shortArgument);
1306 CLEAN_RETURN(1);
1307 }
1308 }
1309 }
1310 continue;
1311 } /* if (argument[0]=='-') */
1312
1313 /* none of the above : add filename to list */
1314 UTIL_refFilename(filenames, argument);
1315 }
1316
1317 /* Welcome message (if verbose) */
1318 DISPLAYLEVEL(3, WELCOME_MESSAGE);
1319
1320 #ifdef ZSTD_MULTITHREAD
1321 if ((operation==zom_decompress) && (nbWorkers > 1)) {
1322 DISPLAYLEVEL(2, "Warning : decompression does not support multi-threading\n");
1323 }
1324 if ((nbWorkers==0) && (!singleThread)) {
1325 /* automatically set # workers based on # of reported cpus */
1326 if (defaultLogicalCores) {
1327 nbWorkers = (unsigned)UTIL_countLogicalCores();
1328 DISPLAYLEVEL(3, "Note: %d logical core(s) detected \n", nbWorkers);
1329 } else {
1330 nbWorkers = (unsigned)UTIL_countPhysicalCores();
1331 DISPLAYLEVEL(3, "Note: %d physical core(s) detected \n", nbWorkers);
1332 }
1333 }
1334 /* Resolve to default if nbWorkers is still unset */
1335 if (nbWorkers == -1) {
1336 if (operation == zom_decompress) {
1337 nbWorkers = 1;
1338 } else {
1339 nbWorkers = default_nbThreads();
1340 }
1341 }
1342 if (operation != zom_bench)
1343 DISPLAYLEVEL(4, "Compressing with %u worker threads \n", nbWorkers);
1344 #else
1345 (void)singleThread; (void)nbWorkers; (void)defaultLogicalCores;
1346 #endif
1347
1348 g_utilDisplayLevel = g_displayLevel;
1349
1350 #ifdef UTIL_HAS_CREATEFILELIST
1351 if (!followLinks) {
1352 unsigned u, fileNamesNb;
1353 unsigned const nbFilenames = (unsigned)filenames->tableSize;
1354 for (u=0, fileNamesNb=0; u<nbFilenames; u++) {
1355 if ( UTIL_isLink(filenames->fileNames[u])
1356 && !UTIL_isFIFO(filenames->fileNames[u])
1357 ) {
1358 DISPLAYLEVEL(2, "Warning : %s is a symbolic link, ignoring \n", filenames->fileNames[u]);
1359 } else {
1360 filenames->fileNames[fileNamesNb++] = filenames->fileNames[u];
1361 } }
1362 if (fileNamesNb == 0 && nbFilenames > 0) /* all names are eliminated */
1363 CLEAN_RETURN(1);
1364 filenames->tableSize = fileNamesNb;
1365 } /* if (!followLinks) */
1366
1367 /* read names from a file */
1368 if (file_of_names->tableSize) {
1369 size_t const nbFileLists = file_of_names->tableSize;
1370 size_t flNb;
1371 for (flNb=0; flNb < nbFileLists; flNb++) {
1372 FileNamesTable* const fnt = UTIL_createFileNamesTable_fromFileName(file_of_names->fileNames[flNb]);
1373 if (fnt==NULL) {
1374 DISPLAYLEVEL(1, "zstd: error reading %s \n", file_of_names->fileNames[flNb]);
1375 CLEAN_RETURN(1);
1376 }
1377 filenames = UTIL_mergeFileNamesTable(filenames, fnt);
1378 }
1379 }
1380
1381 nbInputFileNames = filenames->tableSize; /* saving number of input files */
1382
1383 if (recursive) { /* at this stage, filenameTable is a list of paths, which can contain both files and directories */
1384 UTIL_expandFNT(&filenames, followLinks);
1385 }
1386 #else
1387 (void)followLinks;
1388 #endif
1389
1390 if (operation == zom_list) {
1391 #ifndef ZSTD_NODECOMPRESS
1392 int const ret = FIO_listMultipleFiles((unsigned)filenames->tableSize, filenames->fileNames, g_displayLevel);
1393 CLEAN_RETURN(ret);
1394 #else
1395 DISPLAYLEVEL(1, "file information is not supported \n");
1396 CLEAN_RETURN(1);
1397 #endif
1398 }
1399
1400 /* Check if benchmark is selected */
1401 if (operation==zom_bench) {
1402 #ifndef ZSTD_NOBENCH
1403 if (cType != FIO_zstdCompression) {
1404 DISPLAYLEVEL(1, "benchmark mode is only compatible with zstd format \n");
1405 CLEAN_RETURN(1);
1406 }
1407 benchParams.blockSize = blockSize;
1408 benchParams.targetCBlockSize = targetCBlockSize;
1409 benchParams.nbWorkers = (int)nbWorkers;
1410 benchParams.realTime = (unsigned)setRealTimePrio;
1411 benchParams.nbSeconds = bench_nbSeconds;
1412 benchParams.ldmFlag = ldmFlag;
1413 benchParams.ldmMinMatch = (int)g_ldmMinMatch;
1414 benchParams.ldmHashLog = (int)g_ldmHashLog;
1415 benchParams.useRowMatchFinder = (int)useRowMatchFinder;
1416 if (g_ldmBucketSizeLog != LDM_PARAM_DEFAULT) {
1417 benchParams.ldmBucketSizeLog = (int)g_ldmBucketSizeLog;
1418 }
1419 if (g_ldmHashRateLog != LDM_PARAM_DEFAULT) {
1420 benchParams.ldmHashRateLog = (int)g_ldmHashRateLog;
1421 }
1422 benchParams.literalCompressionMode = literalCompressionMode;
1423
1424 if (benchParams.mode == BMK_decodeOnly) cLevel = cLevelLast = 0;
1425 if (cLevel > ZSTD_maxCLevel()) cLevel = ZSTD_maxCLevel();
1426 if (cLevelLast > ZSTD_maxCLevel()) cLevelLast = ZSTD_maxCLevel();
1427 if (cLevelLast < cLevel) cLevelLast = cLevel;
1428 DISPLAYLEVEL(3, "Benchmarking ");
1429 if (filenames->tableSize > 1)
1430 DISPLAYLEVEL(3, "%u files ", (unsigned)filenames->tableSize);
1431 if (cLevelLast > cLevel) {
1432 DISPLAYLEVEL(3, "from level %d to %d ", cLevel, cLevelLast);
1433 } else {
1434 DISPLAYLEVEL(3, "at level %d ", cLevel);
1435 }
1436 DISPLAYLEVEL(3, "using %i threads \n", nbWorkers);
1437 if (filenames->tableSize > 0) {
1438 if(separateFiles) {
1439 unsigned i;
1440 for(i = 0; i < filenames->tableSize; i++) {
1441 operationResult = BMK_benchFilesAdvanced(&filenames->fileNames[i], 1, dictFileName, cLevel, cLevelLast, &compressionParams, g_displayLevel, &benchParams);
1442 }
1443 } else {
1444 operationResult = BMK_benchFilesAdvanced(filenames->fileNames, (unsigned)filenames->tableSize, dictFileName, cLevel, cLevelLast, &compressionParams, g_displayLevel, &benchParams);
1445 }
1446 } else {
1447 operationResult = BMK_syntheticTest(compressibility, cLevel, cLevelLast, &compressionParams, g_displayLevel, &benchParams);
1448 }
1449
1450 #else
1451 (void)bench_nbSeconds; (void)blockSize; (void)setRealTimePrio; (void)separateFiles; (void)compressibility;
1452 #endif
1453 goto _end;
1454 }
1455
1456 /* Check if dictionary builder is selected */
1457 if (operation==zom_train) {
1458 #ifndef ZSTD_NODICT
1459 ZDICT_params_t zParams;
1460 zParams.compressionLevel = dictCLevel;
1461 zParams.notificationLevel = (unsigned)g_displayLevel;
1462 zParams.dictID = dictID;
1463 if (dict == cover) {
1464 int const optimize = !coverParams.k || !coverParams.d;
1465 coverParams.nbThreads = (unsigned)nbWorkers;
1466 coverParams.zParams = zParams;
1467 operationResult = DiB_trainFromFiles(outFileName, maxDictSize, filenames->fileNames, (int)filenames->tableSize, blockSize, NULL, &coverParams, NULL, optimize, memLimit);
1468 } else if (dict == fastCover) {
1469 int const optimize = !fastCoverParams.k || !fastCoverParams.d;
1470 fastCoverParams.nbThreads = (unsigned)nbWorkers;
1471 fastCoverParams.zParams = zParams;
1472 operationResult = DiB_trainFromFiles(outFileName, maxDictSize, filenames->fileNames, (int)filenames->tableSize, blockSize, NULL, NULL, &fastCoverParams, optimize, memLimit);
1473 } else {
1474 ZDICT_legacy_params_t dictParams;
1475 memset(&dictParams, 0, sizeof(dictParams));
1476 dictParams.selectivityLevel = dictSelect;
1477 dictParams.zParams = zParams;
1478 operationResult = DiB_trainFromFiles(outFileName, maxDictSize, filenames->fileNames, (int)filenames->tableSize, blockSize, &dictParams, NULL, NULL, 0, memLimit);
1479 }
1480 #else
1481 (void)dictCLevel; (void)dictSelect; (void)dictID; (void)maxDictSize; /* not used when ZSTD_NODICT set */
1482 DISPLAYLEVEL(1, "training mode not available \n");
1483 operationResult = 1;
1484 #endif
1485 goto _end;
1486 }
1487
1488 #ifndef ZSTD_NODECOMPRESS
1489 if (operation==zom_test) { FIO_setTestMode(prefs, 1); outFileName=nulmark; removeSrcFile=0; } /* test mode */
1490 #endif
1491
1492 /* No input filename ==> use stdin and stdout */
1493 if (filenames->tableSize == 0) {
1494 /* It is possible that the input
1495 was a number of empty directories. In this case
1496 stdin and stdout should not be used */
1497 if (nbInputFileNames > 0 ){
1498 DISPLAYLEVEL(1, "please provide correct input file(s) or non-empty directories -- ignored \n");
1499 CLEAN_RETURN(0);
1500 }
1501 UTIL_refFilename(filenames, stdinmark);
1502 }
1503
1504 if (filenames->tableSize == 1 && !strcmp(filenames->fileNames[0], stdinmark) && !outFileName)
1505 outFileName = stdoutmark; /* when input is stdin, default output is stdout */
1506
1507 /* Check if input/output defined as console; trigger an error in this case */
1508 if (!forceStdin
1509 && (UTIL_searchFileNamesTable(filenames, stdinmark) != -1)
1510 && UTIL_isConsole(stdin) ) {
1511 DISPLAYLEVEL(1, "stdin is a console, aborting\n");
1512 CLEAN_RETURN(1);
1513 }
1514 if ( (!outFileName || !strcmp(outFileName, stdoutmark))
1515 && UTIL_isConsole(stdout)
1516 && (UTIL_searchFileNamesTable(filenames, stdinmark) != -1)
1517 && !forceStdout
1518 && operation!=zom_decompress ) {
1519 DISPLAYLEVEL(1, "stdout is a console, aborting\n");
1520 CLEAN_RETURN(1);
1521 }
1522
1523 #ifndef ZSTD_NOCOMPRESS
1524 /* check compression level limits */
1525 { int const maxCLevel = ultra ? ZSTD_maxCLevel() : ZSTDCLI_CLEVEL_MAX;
1526 if (cLevel > maxCLevel) {
1527 DISPLAYLEVEL(2, "Warning : compression level higher than max, reduced to %i \n", maxCLevel);
1528 cLevel = maxCLevel;
1529 } }
1530 #endif
1531
1532 if (showDefaultCParams) {
1533 if (operation == zom_decompress) {
1534 DISPLAYLEVEL(1, "error : can't use --show-default-cparams in decompression mode \n");
1535 CLEAN_RETURN(1);
1536 }
1537 }
1538
1539 if (dictFileName != NULL && patchFromDictFileName != NULL) {
1540 DISPLAYLEVEL(1, "error : can't use -D and --patch-from=# at the same time \n");
1541 CLEAN_RETURN(1);
1542 }
1543
1544 if (patchFromDictFileName != NULL && filenames->tableSize > 1) {
1545 DISPLAYLEVEL(1, "error : can't use --patch-from=# on multiple files \n");
1546 CLEAN_RETURN(1);
1547 }
1548
1549 /* No status message by default when output is stdout */
1550 hasStdout = outFileName && !strcmp(outFileName,stdoutmark);
1551 if (hasStdout && (g_displayLevel==2)) g_displayLevel=1;
1552
1553 /* when stderr is not the console, do not pollute it with progress updates (unless requested) */
1554 if (!UTIL_isConsole(stderr) && (progress!=FIO_ps_always)) progress=FIO_ps_never;
1555 FIO_setProgressSetting(progress);
1556
1557 /* don't remove source files when output is stdout */;
1558 if (hasStdout && removeSrcFile) {
1559 DISPLAYLEVEL(3, "Note: src files are not removed when output is stdout \n");
1560 removeSrcFile = 0;
1561 }
1562 FIO_setRemoveSrcFile(prefs, removeSrcFile);
1563
1564 /* IO Stream/File */
1565 FIO_setHasStdoutOutput(fCtx, hasStdout);
1566 FIO_setNbFilesTotal(fCtx, (int)filenames->tableSize);
1567 FIO_determineHasStdinInput(fCtx, filenames);
1568 FIO_setNotificationLevel(g_displayLevel);
1569 FIO_setAllowBlockDevices(prefs, allowBlockDevices);
1570 FIO_setPatchFromMode(prefs, patchFromDictFileName != NULL);
1571 FIO_setMMapDict(prefs, mmapDict);
1572 if (memLimit == 0) {
1573 if (compressionParams.windowLog == 0) {
1574 memLimit = (U32)1 << g_defaultMaxWindowLog;
1575 } else {
1576 memLimit = (U32)1 << (compressionParams.windowLog & 31);
1577 } }
1578 if (patchFromDictFileName != NULL)
1579 dictFileName = patchFromDictFileName;
1580 FIO_setMemLimit(prefs, memLimit);
1581 if (operation==zom_compress) {
1582 #ifndef ZSTD_NOCOMPRESS
1583 FIO_setCompressionType(prefs, cType);
1584 FIO_setContentSize(prefs, contentSize);
1585 FIO_setNbWorkers(prefs, (int)nbWorkers);
1586 FIO_setBlockSize(prefs, (int)blockSize);
1587 if (g_overlapLog!=OVERLAP_LOG_DEFAULT) FIO_setOverlapLog(prefs, (int)g_overlapLog);
1588 FIO_setLdmFlag(prefs, (unsigned)ldmFlag);
1589 FIO_setLdmHashLog(prefs, (int)g_ldmHashLog);
1590 FIO_setLdmMinMatch(prefs, (int)g_ldmMinMatch);
1591 if (g_ldmBucketSizeLog != LDM_PARAM_DEFAULT) FIO_setLdmBucketSizeLog(prefs, (int)g_ldmBucketSizeLog);
1592 if (g_ldmHashRateLog != LDM_PARAM_DEFAULT) FIO_setLdmHashRateLog(prefs, (int)g_ldmHashRateLog);
1593 FIO_setAdaptiveMode(prefs, adapt);
1594 FIO_setUseRowMatchFinder(prefs, (int)useRowMatchFinder);
1595 FIO_setAdaptMin(prefs, adaptMin);
1596 FIO_setAdaptMax(prefs, adaptMax);
1597 FIO_setRsyncable(prefs, rsyncable);
1598 FIO_setStreamSrcSize(prefs, streamSrcSize);
1599 FIO_setTargetCBlockSize(prefs, targetCBlockSize);
1600 FIO_setSrcSizeHint(prefs, srcSizeHint);
1601 FIO_setLiteralCompressionMode(prefs, literalCompressionMode);
1602 FIO_setSparseWrite(prefs, 0);
1603 if (adaptMin > cLevel) cLevel = adaptMin;
1604 if (adaptMax < cLevel) cLevel = adaptMax;
1605
1606 /* Compare strategies constant with the ground truth */
1607 { ZSTD_bounds strategyBounds = ZSTD_cParam_getBounds(ZSTD_c_strategy);
1608 assert(ZSTD_NB_STRATEGIES == strategyBounds.upperBound);
1609 (void)strategyBounds; }
1610
1611 if (showDefaultCParams || g_displayLevel >= 4) {
1612 size_t fileNb;
1613 for (fileNb = 0; fileNb < (size_t)filenames->tableSize; fileNb++) {
1614 if (showDefaultCParams)
1615 printDefaultCParams(filenames->fileNames[fileNb], dictFileName, cLevel);
1616 if (g_displayLevel >= 4)
1617 printActualCParams(filenames->fileNames[fileNb], dictFileName, cLevel, &compressionParams);
1618 }
1619 }
1620
1621 if (g_displayLevel >= 4)
1622 FIO_displayCompressionParameters(prefs);
1623 if ((filenames->tableSize==1) && outFileName)
1624 operationResult = FIO_compressFilename(fCtx, prefs, outFileName, filenames->fileNames[0], dictFileName, cLevel, compressionParams);
1625 else
1626 operationResult = FIO_compressMultipleFilenames(fCtx, prefs, filenames->fileNames, outMirroredDirName, outDirName, outFileName, suffix, dictFileName, cLevel, compressionParams);
1627 #else
1628 /* these variables are only used when compression mode is enabled */
1629 (void)contentSize; (void)suffix; (void)adapt; (void)rsyncable;
1630 (void)ultra; (void)cLevel; (void)ldmFlag; (void)literalCompressionMode;
1631 (void)targetCBlockSize; (void)streamSrcSize; (void)srcSizeHint;
1632 (void)ZSTD_strategyMap; (void)useRowMatchFinder; (void)cType;
1633 DISPLAYLEVEL(1, "Compression not supported \n");
1634 #endif
1635 } else { /* decompression or test */
1636 #ifndef ZSTD_NODECOMPRESS
1637 if (filenames->tableSize == 1 && outFileName) {
1638 operationResult = FIO_decompressFilename(fCtx, prefs, outFileName, filenames->fileNames[0], dictFileName);
1639 } else {
1640 operationResult = FIO_decompressMultipleFilenames(fCtx, prefs, filenames->fileNames, outMirroredDirName, outDirName, outFileName, dictFileName);
1641 }
1642 #else
1643 DISPLAYLEVEL(1, "Decompression not supported \n");
1644 #endif
1645 }
1646
1647 _end:
1648 FIO_freePreferences(prefs);
1649 FIO_freeContext(fCtx);
1650 if (main_pause) waitEnter();
1651 UTIL_freeFileNamesTable(filenames);
1652 UTIL_freeFileNamesTable(file_of_names);
1653 #ifndef ZSTD_NOTRACE
1654 TRACE_finish();
1655 #endif
1656
1657 return operationResult;
1658 }
1659