zstdcli.c 75 KB

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