zstdcli.c 77 KB

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