zstdcli.c 75 KB

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