git subrepo pull (merge) --force deps/libchdr
[pcsx_rearmed.git] / deps / libchdr / deps / zstd-1.5.6 / 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
f535537f 141 * error (badUsage) => stderr
142 * help (usageAdvanced) => stdout
648db22b 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
f535537f 178static void usageAdvanced(const char* programName)
648db22b 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");
f535537f 257 DISPLAYOUT(" --[no-]mmap-dict Memory-map dictionary file rather than mallocing and loading all at once\n");
648db22b 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
f535537f 319static void badUsage(const char* programName, const char* parameter)
648db22b 320{
f535537f 321 DISPLAYLEVEL(1, "Incorrect parameter: %s \n", parameter);
648db22b 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() :
f535537f 592 * reads adapt parameters from *stringPtr (e.g. "--adapt=min=1,max=19) and store them into adaptMinPtr and adaptMaxPtr.
648db22b 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;
f535537f 859 double compressibility = -1.0; /* lorem ipsum generator */
648db22b 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];
f535537f 936 const char* const originalArgument = argument;
648db22b 937 if (!argument) continue; /* Protection if argument empty */
938
939 if (nextArgumentsAreFiles) {
940 UTIL_refFilename(filenames, argument);
941 continue;
942 }
943
944 /* "-" means stdin/stdout */
945 if (!strcmp(argument, "-")){
946 UTIL_refFilename(filenames, stdinmark);
947 continue;
948 }
949
950 /* Decode commands (note : aggregated commands are allowed) */
951 if (argument[0]=='-') {
952
953 if (argument[1]=='-') {
954 /* long commands (--long-word) */
955 if (!strcmp(argument, "--")) { nextArgumentsAreFiles=1; continue; } /* only file names allowed from now on */
956 if (!strcmp(argument, "--list")) { operation=zom_list; continue; }
957 if (!strcmp(argument, "--compress")) { operation=zom_compress; continue; }
958 if (!strcmp(argument, "--decompress")) { operation=zom_decompress; continue; }
959 if (!strcmp(argument, "--uncompress")) { operation=zom_decompress; continue; }
960 if (!strcmp(argument, "--force")) { FIO_overwriteMode(prefs); forceStdin=1; forceStdout=1; followLinks=1; allowBlockDevices=1; continue; }
961 if (!strcmp(argument, "--version")) { printVersion(); CLEAN_RETURN(0); }
f535537f 962 if (!strcmp(argument, "--help")) { usageAdvanced(programName); CLEAN_RETURN(0); }
648db22b 963 if (!strcmp(argument, "--verbose")) { g_displayLevel++; continue; }
964 if (!strcmp(argument, "--quiet")) { g_displayLevel--; continue; }
f535537f 965 if (!strcmp(argument, "--stdout")) { forceStdout=1; outFileName=stdoutmark; continue; }
648db22b 966 if (!strcmp(argument, "--ultra")) { ultra=1; continue; }
967 if (!strcmp(argument, "--check")) { FIO_setChecksumFlag(prefs, 2); continue; }
968 if (!strcmp(argument, "--no-check")) { FIO_setChecksumFlag(prefs, 0); continue; }
969 if (!strcmp(argument, "--sparse")) { FIO_setSparseWrite(prefs, 2); continue; }
970 if (!strcmp(argument, "--no-sparse")) { FIO_setSparseWrite(prefs, 0); continue; }
971 if (!strcmp(argument, "--pass-through")) { FIO_setPassThroughFlag(prefs, 1); continue; }
972 if (!strcmp(argument, "--no-pass-through")) { FIO_setPassThroughFlag(prefs, 0); continue; }
973 if (!strcmp(argument, "--test")) { operation=zom_test; continue; }
974 if (!strcmp(argument, "--asyncio")) { FIO_setAsyncIOFlag(prefs, 1); continue;}
975 if (!strcmp(argument, "--no-asyncio")) { FIO_setAsyncIOFlag(prefs, 0); continue;}
976 if (!strcmp(argument, "--train")) { operation=zom_train; if (outFileName==NULL) outFileName=g_defaultDictName; continue; }
977 if (!strcmp(argument, "--no-dictID")) { FIO_setDictIDFlag(prefs, 0); continue; }
978 if (!strcmp(argument, "--keep")) { removeSrcFile=0; continue; }
979 if (!strcmp(argument, "--rm")) { removeSrcFile=1; continue; }
980 if (!strcmp(argument, "--priority=rt")) { setRealTimePrio = 1; continue; }
981 if (!strcmp(argument, "--show-default-cparams")) { showDefaultCParams = 1; continue; }
982 if (!strcmp(argument, "--content-size")) { contentSize = 1; continue; }
983 if (!strcmp(argument, "--no-content-size")) { contentSize = 0; continue; }
984 if (!strcmp(argument, "--adapt")) { adapt = 1; continue; }
985 if (!strcmp(argument, "--no-row-match-finder")) { useRowMatchFinder = ZSTD_ps_disable; continue; }
986 if (!strcmp(argument, "--row-match-finder")) { useRowMatchFinder = ZSTD_ps_enable; continue; }
f535537f 987 if (longCommandWArg(&argument, "--adapt=")) { adapt = 1; if (!parseAdaptParameters(argument, &adaptMin, &adaptMax)) { badUsage(programName, originalArgument); CLEAN_RETURN(1); } continue; }
648db22b 988 if (!strcmp(argument, "--single-thread")) { nbWorkers = 0; singleThread = 1; continue; }
989 if (!strcmp(argument, "--format=zstd")) { suffix = ZSTD_EXTENSION; cType = FIO_zstdCompression; continue; }
990 if (!strcmp(argument, "--mmap-dict")) { mmapDict = ZSTD_ps_enable; continue; }
991 if (!strcmp(argument, "--no-mmap-dict")) { mmapDict = ZSTD_ps_disable; continue; }
992#ifdef ZSTD_GZCOMPRESS
993 if (!strcmp(argument, "--format=gzip")) { suffix = GZ_EXTENSION; cType = FIO_gzipCompression; continue; }
994 if (exeNameMatch(programName, ZSTD_GZ)) { /* behave like gzip */
995 if (!strcmp(argument, "--best")) { dictCLevel = cLevel = 9; continue; }
996 if (!strcmp(argument, "--no-name")) { /* ignore for now */; continue; }
997 }
998#endif
999#ifdef ZSTD_LZMACOMPRESS
1000 if (!strcmp(argument, "--format=lzma")) { suffix = LZMA_EXTENSION; cType = FIO_lzmaCompression; continue; }
1001 if (!strcmp(argument, "--format=xz")) { suffix = XZ_EXTENSION; cType = FIO_xzCompression; continue; }
1002#endif
1003#ifdef ZSTD_LZ4COMPRESS
1004 if (!strcmp(argument, "--format=lz4")) { suffix = LZ4_EXTENSION; cType = FIO_lz4Compression; continue; }
1005#endif
1006 if (!strcmp(argument, "--rsyncable")) { rsyncable = 1; continue; }
1007 if (!strcmp(argument, "--compress-literals")) { literalCompressionMode = ZSTD_ps_enable; continue; }
1008 if (!strcmp(argument, "--no-compress-literals")) { literalCompressionMode = ZSTD_ps_disable; continue; }
1009 if (!strcmp(argument, "--no-progress")) { progress = FIO_ps_never; continue; }
1010 if (!strcmp(argument, "--progress")) { progress = FIO_ps_always; continue; }
1011 if (!strcmp(argument, "--exclude-compressed")) { FIO_setExcludeCompressedFile(prefs, 1); continue; }
1012 if (!strcmp(argument, "--fake-stdin-is-console")) { UTIL_fakeStdinIsConsole(); continue; }
1013 if (!strcmp(argument, "--fake-stdout-is-console")) { UTIL_fakeStdoutIsConsole(); continue; }
1014 if (!strcmp(argument, "--fake-stderr-is-console")) { UTIL_fakeStderrIsConsole(); continue; }
1015 if (!strcmp(argument, "--trace-file-stat")) { UTIL_traceFileStat(); continue; }
1016
1017 /* long commands with arguments */
1018#ifndef ZSTD_NODICT
1019 if (longCommandWArg(&argument, "--train-cover")) {
1020 operation = zom_train;
1021 if (outFileName == NULL)
1022 outFileName = g_defaultDictName;
1023 dict = cover;
1024 /* Allow optional arguments following an = */
1025 if (*argument == 0) { memset(&coverParams, 0, sizeof(coverParams)); }
f535537f 1026 else if (*argument++ != '=') { badUsage(programName, originalArgument); CLEAN_RETURN(1); }
1027 else if (!parseCoverParameters(argument, &coverParams)) { badUsage(programName, originalArgument); CLEAN_RETURN(1); }
648db22b 1028 continue;
1029 }
1030 if (longCommandWArg(&argument, "--train-fastcover")) {
1031 operation = zom_train;
1032 if (outFileName == NULL)
1033 outFileName = g_defaultDictName;
1034 dict = fastCover;
1035 /* Allow optional arguments following an = */
1036 if (*argument == 0) { memset(&fastCoverParams, 0, sizeof(fastCoverParams)); }
f535537f 1037 else if (*argument++ != '=') { badUsage(programName, originalArgument); CLEAN_RETURN(1); }
1038 else if (!parseFastCoverParameters(argument, &fastCoverParams)) { badUsage(programName, originalArgument); CLEAN_RETURN(1); }
648db22b 1039 continue;
1040 }
1041 if (longCommandWArg(&argument, "--train-legacy")) {
1042 operation = zom_train;
1043 if (outFileName == NULL)
1044 outFileName = g_defaultDictName;
1045 dict = legacy;
1046 /* Allow optional arguments following an = */
1047 if (*argument == 0) { continue; }
f535537f 1048 else if (*argument++ != '=') { badUsage(programName, originalArgument); CLEAN_RETURN(1); }
1049 else if (!parseLegacyParameters(argument, &dictSelect)) { badUsage(programName, originalArgument); CLEAN_RETURN(1); }
648db22b 1050 continue;
1051 }
1052#endif
1053 if (longCommandWArg(&argument, "--threads")) { NEXT_UINT32(nbWorkers); continue; }
1054 if (longCommandWArg(&argument, "--memlimit")) { NEXT_UINT32(memLimit); continue; }
1055 if (longCommandWArg(&argument, "--memory")) { NEXT_UINT32(memLimit); continue; }
1056 if (longCommandWArg(&argument, "--memlimit-decompress")) { NEXT_UINT32(memLimit); continue; }
1057 if (longCommandWArg(&argument, "--block-size")) { NEXT_TSIZE(blockSize); continue; }
1058 if (longCommandWArg(&argument, "--maxdict")) { NEXT_UINT32(maxDictSize); continue; }
1059 if (longCommandWArg(&argument, "--dictID")) { NEXT_UINT32(dictID); continue; }
f535537f 1060 if (longCommandWArg(&argument, "--zstd=")) { if (!parseCompressionParameters(argument, &compressionParams)) { badUsage(programName, originalArgument); CLEAN_RETURN(1); } ; cType = FIO_zstdCompression; continue; }
648db22b 1061 if (longCommandWArg(&argument, "--stream-size")) { NEXT_TSIZE(streamSrcSize); continue; }
1062 if (longCommandWArg(&argument, "--target-compressed-block-size")) { NEXT_TSIZE(targetCBlockSize); continue; }
1063 if (longCommandWArg(&argument, "--size-hint")) { NEXT_TSIZE(srcSizeHint); continue; }
1064 if (longCommandWArg(&argument, "--output-dir-flat")) {
1065 NEXT_FIELD(outDirName);
1066 if (strlen(outDirName) == 0) {
1067 DISPLAYLEVEL(1, "error: output dir cannot be empty string (did you mean to pass '.' instead?)\n");
1068 CLEAN_RETURN(1);
1069 }
1070 continue;
1071 }
1072 if (longCommandWArg(&argument, "--auto-threads")) {
1073 const char* threadDefault = NULL;
1074 NEXT_FIELD(threadDefault);
1075 if (strcmp(threadDefault, "logical") == 0)
1076 defaultLogicalCores = 1;
1077 continue;
1078 }
1079#ifdef UTIL_HAS_MIRRORFILELIST
1080 if (longCommandWArg(&argument, "--output-dir-mirror")) {
1081 NEXT_FIELD(outMirroredDirName);
1082 if (strlen(outMirroredDirName) == 0) {
1083 DISPLAYLEVEL(1, "error: output dir cannot be empty string (did you mean to pass '.' instead?)\n");
1084 CLEAN_RETURN(1);
1085 }
1086 continue;
1087 }
1088#endif
1089#ifndef ZSTD_NOTRACE
1090 if (longCommandWArg(&argument, "--trace")) { char const* traceFile; NEXT_FIELD(traceFile); TRACE_enable(traceFile); continue; }
1091#endif
1092 if (longCommandWArg(&argument, "--patch-from")) { NEXT_FIELD(patchFromDictFileName); continue; }
1093 if (longCommandWArg(&argument, "--long")) {
1094 unsigned ldmWindowLog = 0;
1095 ldmFlag = 1;
1096 /* Parse optional window log */
1097 if (*argument == '=') {
1098 ++argument;
1099 ldmWindowLog = readU32FromChar(&argument);
1100 } else if (*argument != 0) {
1101 /* Invalid character following --long */
f535537f 1102 badUsage(programName, originalArgument);
648db22b 1103 CLEAN_RETURN(1);
1104 } else {
1105 ldmWindowLog = g_defaultMaxWindowLog;
1106 }
1107 /* Only set windowLog if not already set by --zstd */
1108 if (compressionParams.windowLog == 0)
1109 compressionParams.windowLog = ldmWindowLog;
1110 continue;
1111 }
1112#ifndef ZSTD_NOCOMPRESS /* linking ZSTD_minCLevel() requires compression support */
1113 if (longCommandWArg(&argument, "--fast")) {
1114 /* Parse optional acceleration factor */
1115 if (*argument == '=') {
1116 U32 const maxFast = (U32)-ZSTD_minCLevel();
1117 U32 fastLevel;
1118 ++argument;
1119 fastLevel = readU32FromChar(&argument);
1120 if (fastLevel > maxFast) fastLevel = maxFast;
1121 if (fastLevel) {
1122 dictCLevel = cLevel = -(int)fastLevel;
1123 } else {
f535537f 1124 badUsage(programName, originalArgument);
648db22b 1125 CLEAN_RETURN(1);
1126 }
1127 } else if (*argument != 0) {
1128 /* Invalid character following --fast */
f535537f 1129 badUsage(programName, originalArgument);
648db22b 1130 CLEAN_RETURN(1);
1131 } else {
1132 cLevel = -1; /* default for --fast */
1133 }
1134 continue;
1135 }
1136#endif
1137
1138 if (longCommandWArg(&argument, "--filelist")) {
1139 const char* listName;
1140 NEXT_FIELD(listName);
1141 UTIL_refFilename(file_of_names, listName);
1142 continue;
1143 }
1144
f535537f 1145 badUsage(programName, originalArgument);
1146 CLEAN_RETURN(1);
648db22b 1147 }
1148
1149 argument++;
1150 while (argument[0]!=0) {
1151
1152#ifndef ZSTD_NOCOMPRESS
1153 /* compression Level */
1154 if ((*argument>='0') && (*argument<='9')) {
1155 dictCLevel = cLevel = (int)readU32FromChar(&argument);
1156 continue;
1157 }
1158#endif
1159
1160 switch(argument[0])
1161 {
1162 /* Display help */
1163 case 'V': printVersion(); CLEAN_RETURN(0); /* Version Only */
f535537f 1164 case 'H': usageAdvanced(programName); CLEAN_RETURN(0);
648db22b 1165 case 'h': usage(stdout, programName); CLEAN_RETURN(0);
1166
1167 /* Compress */
1168 case 'z': operation=zom_compress; argument++; break;
1169
1170 /* Decoding */
1171 case 'd':
1172#ifndef ZSTD_NOBENCH
1173 benchParams.mode = BMK_decodeOnly;
1174 if (operation==zom_bench) { argument++; break; } /* benchmark decode (hidden option) */
1175#endif
1176 operation=zom_decompress; argument++; break;
1177
1178 /* Force stdout, even if stdout==console */
f535537f 1179 case 'c': forceStdout=1; outFileName=stdoutmark; argument++; break;
1180
1181 /* destination file name */
1182 case 'o': argument++; NEXT_FIELD(outFileName); break;
648db22b 1183
1184 /* do not store filename - gzip compatibility - nothing to do */
1185 case 'n': argument++; break;
1186
1187 /* Use file content as dictionary */
1188 case 'D': argument++; NEXT_FIELD(dictFileName); break;
1189
1190 /* Overwrite */
1191 case 'f': FIO_overwriteMode(prefs); forceStdin=1; forceStdout=1; followLinks=1; allowBlockDevices=1; argument++; break;
1192
1193 /* Verbose mode */
1194 case 'v': g_displayLevel++; argument++; break;
1195
1196 /* Quiet mode */
1197 case 'q': g_displayLevel--; argument++; break;
1198
1199 /* keep source file (default) */
1200 case 'k': removeSrcFile=0; argument++; break;
1201
1202 /* Checksum */
1203 case 'C': FIO_setChecksumFlag(prefs, 2); argument++; break;
1204
1205 /* test compressed file */
1206 case 't': operation=zom_test; argument++; break;
1207
648db22b 1208 /* limit memory */
1209 case 'M':
1210 argument++;
1211 memLimit = readU32FromChar(&argument);
1212 break;
1213 case 'l': operation=zom_list; argument++; break;
1214#ifdef UTIL_HAS_CREATEFILELIST
1215 /* recursive */
1216 case 'r': recursive=1; argument++; break;
1217#endif
1218
1219#ifndef ZSTD_NOBENCH
1220 /* Benchmark */
1221 case 'b':
1222 operation=zom_bench;
1223 argument++;
1224 break;
1225
1226 /* range bench (benchmark only) */
1227 case 'e':
1228 /* compression Level */
1229 argument++;
1230 cLevelLast = (int)readU32FromChar(&argument);
1231 break;
1232
1233 /* Modify Nb Iterations (benchmark only) */
1234 case 'i':
1235 argument++;
1236 bench_nbSeconds = readU32FromChar(&argument);
1237 break;
1238
1239 /* cut input into blocks (benchmark only) */
1240 case 'B':
1241 argument++;
1242 blockSize = readU32FromChar(&argument);
1243 break;
1244
1245 /* benchmark files separately (hidden option) */
1246 case 'S':
1247 argument++;
1248 separateFiles = 1;
1249 break;
1250
1251#endif /* ZSTD_NOBENCH */
1252
1253 /* nb of threads (hidden option) */
1254 case 'T':
1255 argument++;
1256 nbWorkers = readU32FromChar(&argument);
1257 break;
1258
1259 /* Dictionary Selection level */
1260 case 's':
1261 argument++;
1262 dictSelect = readU32FromChar(&argument);
1263 break;
1264
1265 /* Pause at the end (-p) or set an additional param (-p#) (hidden option) */
1266 case 'p': argument++;
1267#ifndef ZSTD_NOBENCH
1268 if ((*argument>='0') && (*argument<='9')) {
1269 benchParams.additionalParam = (int)readU32FromChar(&argument);
1270 } else
1271#endif
1272 main_pause=1;
1273 break;
1274
1275 /* Select compressibility of synthetic sample */
1276 case 'P':
1277 argument++;
1278 compressibility = (double)readU32FromChar(&argument) / 100;
1279 break;
1280
1281 /* unknown command */
f535537f 1282 default :
1283 { char shortArgument[3] = {'-', 0, 0};
1284 shortArgument[1] = argument[0];
1285 badUsage(programName, shortArgument);
1286 CLEAN_RETURN(1);
1287 }
648db22b 1288 }
1289 }
1290 continue;
1291 } /* if (argument[0]=='-') */
1292
1293 /* none of the above : add filename to list */
1294 UTIL_refFilename(filenames, argument);
1295 }
1296
1297 /* Welcome message (if verbose) */
1298 DISPLAYLEVEL(3, WELCOME_MESSAGE);
1299
1300#ifdef ZSTD_MULTITHREAD
1301 if ((operation==zom_decompress) && (!singleThread) && (nbWorkers > 1)) {
1302 DISPLAYLEVEL(2, "Warning : decompression does not support multi-threading\n");
1303 }
1304 if ((nbWorkers==0) && (!singleThread)) {
1305 /* automatically set # workers based on # of reported cpus */
1306 if (defaultLogicalCores) {
1307 nbWorkers = (unsigned)UTIL_countLogicalCores();
1308 DISPLAYLEVEL(3, "Note: %d logical core(s) detected \n", nbWorkers);
1309 } else {
1310 nbWorkers = (unsigned)UTIL_countPhysicalCores();
1311 DISPLAYLEVEL(3, "Note: %d physical core(s) detected \n", nbWorkers);
1312 }
1313 }
1314#else
1315 (void)singleThread; (void)nbWorkers; (void)defaultLogicalCores;
1316#endif
1317
1318 g_utilDisplayLevel = g_displayLevel;
1319
1320#ifdef UTIL_HAS_CREATEFILELIST
1321 if (!followLinks) {
1322 unsigned u, fileNamesNb;
1323 unsigned const nbFilenames = (unsigned)filenames->tableSize;
1324 for (u=0, fileNamesNb=0; u<nbFilenames; u++) {
1325 if ( UTIL_isLink(filenames->fileNames[u])
1326 && !UTIL_isFIFO(filenames->fileNames[u])
1327 ) {
1328 DISPLAYLEVEL(2, "Warning : %s is a symbolic link, ignoring \n", filenames->fileNames[u]);
1329 } else {
1330 filenames->fileNames[fileNamesNb++] = filenames->fileNames[u];
1331 } }
1332 if (fileNamesNb == 0 && nbFilenames > 0) /* all names are eliminated */
1333 CLEAN_RETURN(1);
1334 filenames->tableSize = fileNamesNb;
1335 } /* if (!followLinks) */
1336
1337 /* read names from a file */
1338 if (file_of_names->tableSize) {
1339 size_t const nbFileLists = file_of_names->tableSize;
1340 size_t flNb;
1341 for (flNb=0; flNb < nbFileLists; flNb++) {
1342 FileNamesTable* const fnt = UTIL_createFileNamesTable_fromFileName(file_of_names->fileNames[flNb]);
1343 if (fnt==NULL) {
1344 DISPLAYLEVEL(1, "zstd: error reading %s \n", file_of_names->fileNames[flNb]);
1345 CLEAN_RETURN(1);
1346 }
1347 filenames = UTIL_mergeFileNamesTable(filenames, fnt);
1348 }
1349 }
1350
1351 nbInputFileNames = filenames->tableSize; /* saving number of input files */
1352
1353 if (recursive) { /* at this stage, filenameTable is a list of paths, which can contain both files and directories */
1354 UTIL_expandFNT(&filenames, followLinks);
1355 }
1356#else
1357 (void)followLinks;
1358#endif
1359
1360 if (operation == zom_list) {
1361#ifndef ZSTD_NODECOMPRESS
1362 int const ret = FIO_listMultipleFiles((unsigned)filenames->tableSize, filenames->fileNames, g_displayLevel);
1363 CLEAN_RETURN(ret);
1364#else
1365 DISPLAYLEVEL(1, "file information is not supported \n");
1366 CLEAN_RETURN(1);
1367#endif
1368 }
1369
1370 /* Check if benchmark is selected */
1371 if (operation==zom_bench) {
1372#ifndef ZSTD_NOBENCH
1373 if (cType != FIO_zstdCompression) {
1374 DISPLAYLEVEL(1, "benchmark mode is only compatible with zstd format \n");
1375 CLEAN_RETURN(1);
1376 }
1377 benchParams.blockSize = blockSize;
f535537f 1378 benchParams.targetCBlockSize = targetCBlockSize;
648db22b 1379 benchParams.nbWorkers = (int)nbWorkers;
1380 benchParams.realTime = (unsigned)setRealTimePrio;
1381 benchParams.nbSeconds = bench_nbSeconds;
1382 benchParams.ldmFlag = ldmFlag;
1383 benchParams.ldmMinMatch = (int)g_ldmMinMatch;
1384 benchParams.ldmHashLog = (int)g_ldmHashLog;
1385 benchParams.useRowMatchFinder = (int)useRowMatchFinder;
1386 if (g_ldmBucketSizeLog != LDM_PARAM_DEFAULT) {
1387 benchParams.ldmBucketSizeLog = (int)g_ldmBucketSizeLog;
1388 }
1389 if (g_ldmHashRateLog != LDM_PARAM_DEFAULT) {
1390 benchParams.ldmHashRateLog = (int)g_ldmHashRateLog;
1391 }
1392 benchParams.literalCompressionMode = literalCompressionMode;
1393
1394 if (cLevel > ZSTD_maxCLevel()) cLevel = ZSTD_maxCLevel();
1395 if (cLevelLast > ZSTD_maxCLevel()) cLevelLast = ZSTD_maxCLevel();
1396 if (cLevelLast < cLevel) cLevelLast = cLevel;
1397 if (cLevelLast > cLevel)
1398 DISPLAYLEVEL(3, "Benchmarking levels from %d to %d\n", cLevel, cLevelLast);
1399 if (filenames->tableSize > 0) {
1400 if(separateFiles) {
1401 unsigned i;
1402 for(i = 0; i < filenames->tableSize; i++) {
1403 int c;
1404 DISPLAYLEVEL(3, "Benchmarking %s \n", filenames->fileNames[i]);
1405 for(c = cLevel; c <= cLevelLast; c++) {
1406 operationResult = BMK_benchFilesAdvanced(&filenames->fileNames[i], 1, dictFileName, c, &compressionParams, g_displayLevel, &benchParams);
1407 } }
1408 } else {
1409 for(; cLevel <= cLevelLast; cLevel++) {
1410 operationResult = BMK_benchFilesAdvanced(filenames->fileNames, (unsigned)filenames->tableSize, dictFileName, cLevel, &compressionParams, g_displayLevel, &benchParams);
1411 } }
1412 } else {
1413 for(; cLevel <= cLevelLast; cLevel++) {
1414 operationResult = BMK_syntheticTest(cLevel, compressibility, &compressionParams, g_displayLevel, &benchParams);
1415 } }
1416
1417#else
1418 (void)bench_nbSeconds; (void)blockSize; (void)setRealTimePrio; (void)separateFiles; (void)compressibility;
1419#endif
1420 goto _end;
1421 }
1422
1423 /* Check if dictionary builder is selected */
1424 if (operation==zom_train) {
1425#ifndef ZSTD_NODICT
1426 ZDICT_params_t zParams;
1427 zParams.compressionLevel = dictCLevel;
1428 zParams.notificationLevel = (unsigned)g_displayLevel;
1429 zParams.dictID = dictID;
1430 if (dict == cover) {
1431 int const optimize = !coverParams.k || !coverParams.d;
1432 coverParams.nbThreads = (unsigned)nbWorkers;
1433 coverParams.zParams = zParams;
1434 operationResult = DiB_trainFromFiles(outFileName, maxDictSize, filenames->fileNames, (int)filenames->tableSize, blockSize, NULL, &coverParams, NULL, optimize, memLimit);
1435 } else if (dict == fastCover) {
1436 int const optimize = !fastCoverParams.k || !fastCoverParams.d;
1437 fastCoverParams.nbThreads = (unsigned)nbWorkers;
1438 fastCoverParams.zParams = zParams;
1439 operationResult = DiB_trainFromFiles(outFileName, maxDictSize, filenames->fileNames, (int)filenames->tableSize, blockSize, NULL, NULL, &fastCoverParams, optimize, memLimit);
1440 } else {
1441 ZDICT_legacy_params_t dictParams;
1442 memset(&dictParams, 0, sizeof(dictParams));
1443 dictParams.selectivityLevel = dictSelect;
1444 dictParams.zParams = zParams;
1445 operationResult = DiB_trainFromFiles(outFileName, maxDictSize, filenames->fileNames, (int)filenames->tableSize, blockSize, &dictParams, NULL, NULL, 0, memLimit);
1446 }
1447#else
1448 (void)dictCLevel; (void)dictSelect; (void)dictID; (void)maxDictSize; /* not used when ZSTD_NODICT set */
1449 DISPLAYLEVEL(1, "training mode not available \n");
1450 operationResult = 1;
1451#endif
1452 goto _end;
1453 }
1454
1455#ifndef ZSTD_NODECOMPRESS
1456 if (operation==zom_test) { FIO_setTestMode(prefs, 1); outFileName=nulmark; removeSrcFile=0; } /* test mode */
1457#endif
1458
1459 /* No input filename ==> use stdin and stdout */
1460 if (filenames->tableSize == 0) {
1461 /* It is possible that the input
1462 was a number of empty directories. In this case
1463 stdin and stdout should not be used */
1464 if (nbInputFileNames > 0 ){
1465 DISPLAYLEVEL(1, "please provide correct input file(s) or non-empty directories -- ignored \n");
1466 CLEAN_RETURN(0);
1467 }
1468 UTIL_refFilename(filenames, stdinmark);
1469 }
1470
1471 if (filenames->tableSize == 1 && !strcmp(filenames->fileNames[0], stdinmark) && !outFileName)
1472 outFileName = stdoutmark; /* when input is stdin, default output is stdout */
1473
1474 /* Check if input/output defined as console; trigger an error in this case */
1475 if (!forceStdin
1476 && (UTIL_searchFileNamesTable(filenames, stdinmark) != -1)
1477 && UTIL_isConsole(stdin) ) {
1478 DISPLAYLEVEL(1, "stdin is a console, aborting\n");
1479 CLEAN_RETURN(1);
1480 }
1481 if ( (!outFileName || !strcmp(outFileName, stdoutmark))
1482 && UTIL_isConsole(stdout)
1483 && (UTIL_searchFileNamesTable(filenames, stdinmark) != -1)
1484 && !forceStdout
1485 && operation!=zom_decompress ) {
1486 DISPLAYLEVEL(1, "stdout is a console, aborting\n");
1487 CLEAN_RETURN(1);
1488 }
1489
1490#ifndef ZSTD_NOCOMPRESS
1491 /* check compression level limits */
1492 { int const maxCLevel = ultra ? ZSTD_maxCLevel() : ZSTDCLI_CLEVEL_MAX;
1493 if (cLevel > maxCLevel) {
1494 DISPLAYLEVEL(2, "Warning : compression level higher than max, reduced to %i \n", maxCLevel);
1495 cLevel = maxCLevel;
1496 } }
1497#endif
1498
1499 if (showDefaultCParams) {
1500 if (operation == zom_decompress) {
1501 DISPLAYLEVEL(1, "error : can't use --show-default-cparams in decompression mode \n");
1502 CLEAN_RETURN(1);
1503 }
1504 }
1505
1506 if (dictFileName != NULL && patchFromDictFileName != NULL) {
1507 DISPLAYLEVEL(1, "error : can't use -D and --patch-from=# at the same time \n");
1508 CLEAN_RETURN(1);
1509 }
1510
1511 if (patchFromDictFileName != NULL && filenames->tableSize > 1) {
1512 DISPLAYLEVEL(1, "error : can't use --patch-from=# on multiple files \n");
1513 CLEAN_RETURN(1);
1514 }
1515
1516 /* No status message by default when output is stdout */
1517 hasStdout = outFileName && !strcmp(outFileName,stdoutmark);
1518 if (hasStdout && (g_displayLevel==2)) g_displayLevel=1;
1519
1520 /* when stderr is not the console, do not pollute it with progress updates (unless requested) */
1521 if (!UTIL_isConsole(stderr) && (progress!=FIO_ps_always)) progress=FIO_ps_never;
1522 FIO_setProgressSetting(progress);
1523
1524 /* don't remove source files when output is stdout */;
1525 if (hasStdout && removeSrcFile) {
1526 DISPLAYLEVEL(3, "Note: src files are not removed when output is stdout \n");
1527 removeSrcFile = 0;
1528 }
1529 FIO_setRemoveSrcFile(prefs, removeSrcFile);
1530
1531 /* IO Stream/File */
1532 FIO_setHasStdoutOutput(fCtx, hasStdout);
1533 FIO_setNbFilesTotal(fCtx, (int)filenames->tableSize);
1534 FIO_determineHasStdinInput(fCtx, filenames);
1535 FIO_setNotificationLevel(g_displayLevel);
1536 FIO_setAllowBlockDevices(prefs, allowBlockDevices);
1537 FIO_setPatchFromMode(prefs, patchFromDictFileName != NULL);
1538 FIO_setMMapDict(prefs, mmapDict);
1539 if (memLimit == 0) {
1540 if (compressionParams.windowLog == 0) {
1541 memLimit = (U32)1 << g_defaultMaxWindowLog;
1542 } else {
1543 memLimit = (U32)1 << (compressionParams.windowLog & 31);
1544 } }
1545 if (patchFromDictFileName != NULL)
1546 dictFileName = patchFromDictFileName;
1547 FIO_setMemLimit(prefs, memLimit);
1548 if (operation==zom_compress) {
1549#ifndef ZSTD_NOCOMPRESS
1550 FIO_setCompressionType(prefs, cType);
1551 FIO_setContentSize(prefs, contentSize);
1552 FIO_setNbWorkers(prefs, (int)nbWorkers);
1553 FIO_setBlockSize(prefs, (int)blockSize);
1554 if (g_overlapLog!=OVERLAP_LOG_DEFAULT) FIO_setOverlapLog(prefs, (int)g_overlapLog);
1555 FIO_setLdmFlag(prefs, (unsigned)ldmFlag);
1556 FIO_setLdmHashLog(prefs, (int)g_ldmHashLog);
1557 FIO_setLdmMinMatch(prefs, (int)g_ldmMinMatch);
1558 if (g_ldmBucketSizeLog != LDM_PARAM_DEFAULT) FIO_setLdmBucketSizeLog(prefs, (int)g_ldmBucketSizeLog);
1559 if (g_ldmHashRateLog != LDM_PARAM_DEFAULT) FIO_setLdmHashRateLog(prefs, (int)g_ldmHashRateLog);
1560 FIO_setAdaptiveMode(prefs, adapt);
1561 FIO_setUseRowMatchFinder(prefs, (int)useRowMatchFinder);
1562 FIO_setAdaptMin(prefs, adaptMin);
1563 FIO_setAdaptMax(prefs, adaptMax);
1564 FIO_setRsyncable(prefs, rsyncable);
1565 FIO_setStreamSrcSize(prefs, streamSrcSize);
1566 FIO_setTargetCBlockSize(prefs, targetCBlockSize);
1567 FIO_setSrcSizeHint(prefs, srcSizeHint);
1568 FIO_setLiteralCompressionMode(prefs, literalCompressionMode);
1569 FIO_setSparseWrite(prefs, 0);
1570 if (adaptMin > cLevel) cLevel = adaptMin;
1571 if (adaptMax < cLevel) cLevel = adaptMax;
1572
1573 /* Compare strategies constant with the ground truth */
1574 { ZSTD_bounds strategyBounds = ZSTD_cParam_getBounds(ZSTD_c_strategy);
1575 assert(ZSTD_NB_STRATEGIES == strategyBounds.upperBound);
1576 (void)strategyBounds; }
1577
1578 if (showDefaultCParams || g_displayLevel >= 4) {
1579 size_t fileNb;
1580 for (fileNb = 0; fileNb < (size_t)filenames->tableSize; fileNb++) {
1581 if (showDefaultCParams)
1582 printDefaultCParams(filenames->fileNames[fileNb], dictFileName, cLevel);
1583 if (g_displayLevel >= 4)
1584 printActualCParams(filenames->fileNames[fileNb], dictFileName, cLevel, &compressionParams);
1585 }
1586 }
1587
1588 if (g_displayLevel >= 4)
1589 FIO_displayCompressionParameters(prefs);
1590 if ((filenames->tableSize==1) && outFileName)
1591 operationResult = FIO_compressFilename(fCtx, prefs, outFileName, filenames->fileNames[0], dictFileName, cLevel, compressionParams);
1592 else
1593 operationResult = FIO_compressMultipleFilenames(fCtx, prefs, filenames->fileNames, outMirroredDirName, outDirName, outFileName, suffix, dictFileName, cLevel, compressionParams);
1594#else
1595 /* these variables are only used when compression mode is enabled */
1596 (void)contentSize; (void)suffix; (void)adapt; (void)rsyncable;
1597 (void)ultra; (void)cLevel; (void)ldmFlag; (void)literalCompressionMode;
1598 (void)targetCBlockSize; (void)streamSrcSize; (void)srcSizeHint;
1599 (void)ZSTD_strategyMap; (void)useRowMatchFinder; (void)cType;
1600 DISPLAYLEVEL(1, "Compression not supported \n");
1601#endif
1602 } else { /* decompression or test */
1603#ifndef ZSTD_NODECOMPRESS
1604 if (filenames->tableSize == 1 && outFileName) {
1605 operationResult = FIO_decompressFilename(fCtx, prefs, outFileName, filenames->fileNames[0], dictFileName);
1606 } else {
1607 operationResult = FIO_decompressMultipleFilenames(fCtx, prefs, filenames->fileNames, outMirroredDirName, outDirName, outFileName, dictFileName);
1608 }
1609#else
1610 DISPLAYLEVEL(1, "Decompression not supported \n");
1611#endif
1612 }
1613
1614_end:
1615 FIO_freePreferences(prefs);
1616 FIO_freeContext(fCtx);
1617 if (main_pause) waitEnter();
1618 UTIL_freeFileNamesTable(filenames);
1619 UTIL_freeFileNamesTable(file_of_names);
1620#ifndef ZSTD_NOTRACE
1621 TRACE_finish();
1622#endif
1623
1624 return operationResult;
1625}