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