lz4cli.c 34 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784
  1. /*
  2. LZ4cli - LZ4 Command Line Interface
  3. Copyright (C) Yann Collet 2011-2020
  4. GPL v2 License
  5. This program is free software; you can redistribute it and/or modify
  6. it under the terms of the GNU General Public License as published by
  7. the Free Software Foundation; either version 2 of the License, or
  8. (at your option) any later version.
  9. This program is distributed in the hope that it will be useful,
  10. but WITHOUT ANY WARRANTY; without even the implied warranty of
  11. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  12. GNU General Public License for more details.
  13. You should have received a copy of the GNU General Public License along
  14. with this program; if not, write to the Free Software Foundation, Inc.,
  15. 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
  16. You can contact the author at :
  17. - LZ4 source repository : https://github.com/lz4/lz4
  18. - LZ4 public forum : https://groups.google.com/forum/#!forum/lz4c
  19. */
  20. /*
  21. Note : this is stand-alone program.
  22. It is not part of LZ4 compression library, it is a user program of the LZ4 library.
  23. The license of LZ4 library is BSD.
  24. The license of xxHash library is BSD.
  25. The license of this compression CLI program is GPLv2.
  26. */
  27. /****************************
  28. * Includes
  29. *****************************/
  30. #include "platform.h" /* Compiler options, IS_CONSOLE */
  31. #include "util.h" /* UTIL_HAS_CREATEFILELIST, UTIL_createFileList */
  32. #include <stdio.h> /* fprintf, getchar */
  33. #include <stdlib.h> /* exit, calloc, free */
  34. #include <string.h> /* strcmp, strlen */
  35. #include "bench.h" /* BMK_benchFile, BMK_SetNbIterations, BMK_SetBlocksize, BMK_SetPause */
  36. #include "lz4io.h" /* LZ4IO_compressFilename, LZ4IO_decompressFilename, LZ4IO_compressMultipleFilenames */
  37. #include "lz4hc.h" /* LZ4HC_CLEVEL_MAX */
  38. #include "lz4.h" /* LZ4_VERSION_STRING */
  39. /*****************************
  40. * Constants
  41. ******************************/
  42. #define COMPRESSOR_NAME "LZ4 command line interface"
  43. #define AUTHOR "Yann Collet"
  44. #define WELCOME_MESSAGE "*** %s %i-bits v%s, by %s ***\n", COMPRESSOR_NAME, (int)(sizeof(void*)*8), LZ4_versionString(), AUTHOR
  45. #define LZ4_EXTENSION ".lz4"
  46. #define LZ4CAT "lz4cat"
  47. #define UNLZ4 "unlz4"
  48. #define LZ4_LEGACY "lz4c"
  49. static int g_lz4c_legacy_commands = 0;
  50. #define KB *(1U<<10)
  51. #define MB *(1U<<20)
  52. #define GB *(1U<<30)
  53. #define LZ4_BLOCKSIZEID_DEFAULT 7
  54. /*-************************************
  55. * Macros
  56. ***************************************/
  57. #define DISPLAYOUT(...) fprintf(stdout, __VA_ARGS__)
  58. #define DISPLAY(...) fprintf(stderr, __VA_ARGS__)
  59. #define DISPLAYLEVEL(l, ...) if (displayLevel>=l) { DISPLAY(__VA_ARGS__); }
  60. static unsigned displayLevel = 2; /* 0 : no display ; 1: errors only ; 2 : downgradable normal ; 3 : non-downgradable normal; 4 : + information */
  61. /*-************************************
  62. * Exceptions
  63. ***************************************/
  64. #define DEBUG 0
  65. #define DEBUGOUTPUT(...) if (DEBUG) DISPLAY(__VA_ARGS__);
  66. #define EXM_THROW(error, ...) \
  67. { \
  68. DEBUGOUTPUT("Error defined at %s, line %i : \n", __FILE__, __LINE__); \
  69. DISPLAYLEVEL(1, "Error %i : ", error); \
  70. DISPLAYLEVEL(1, __VA_ARGS__); \
  71. DISPLAYLEVEL(1, "\n"); \
  72. exit(error); \
  73. }
  74. /*-************************************
  75. * Version modifiers
  76. ***************************************/
  77. #define DEFAULT_COMPRESSOR LZ4IO_compressFilename
  78. #define DEFAULT_DECOMPRESSOR LZ4IO_decompressFilename
  79. int LZ4IO_compressFilename_Legacy(const char* input_filename, const char* output_filename, int compressionlevel, const LZ4IO_prefs_t* prefs); /* hidden function */
  80. int LZ4IO_compressMultipleFilenames_Legacy(
  81. const char** inFileNamesTable, int ifntSize,
  82. const char* suffix,
  83. int compressionLevel, const LZ4IO_prefs_t* prefs);
  84. /*-***************************
  85. * Functions
  86. *****************************/
  87. static int usage(const char* exeName)
  88. {
  89. DISPLAY( "Usage : \n");
  90. DISPLAY( " %s [arg] [input] [output] \n", exeName);
  91. DISPLAY( "\n");
  92. DISPLAY( "input : a filename \n");
  93. DISPLAY( " with no FILE, or when FILE is - or %s, read standard input\n", stdinmark);
  94. DISPLAY( "Arguments : \n");
  95. DISPLAY( " -1 : Fast compression (default) \n");
  96. DISPLAY( " -9 : High compression \n");
  97. DISPLAY( " -d : decompression (default for %s extension)\n", LZ4_EXTENSION);
  98. DISPLAY( " -z : force compression \n");
  99. DISPLAY( " -D FILE: use FILE as dictionary \n");
  100. DISPLAY( " -f : overwrite output without prompting \n");
  101. DISPLAY( " -k : preserve source files(s) (default) \n");
  102. DISPLAY( "--rm : remove source file(s) after successful de/compression \n");
  103. DISPLAY( " -h/-H : display help/long help and exit \n");
  104. return 0;
  105. }
  106. static int usage_advanced(const char* exeName)
  107. {
  108. DISPLAY(WELCOME_MESSAGE);
  109. usage(exeName);
  110. DISPLAY( "\n");
  111. DISPLAY( "Advanced arguments :\n");
  112. DISPLAY( " -V : display Version number and exit \n");
  113. DISPLAY( " -v : verbose mode \n");
  114. DISPLAY( " -q : suppress warnings; specify twice to suppress errors too\n");
  115. DISPLAY( " -c : force write to standard output, even if it is the console\n");
  116. DISPLAY( " -t : test compressed file integrity\n");
  117. DISPLAY( " -m : multiple input files (implies automatic output filenames)\n");
  118. #ifdef UTIL_HAS_CREATEFILELIST
  119. DISPLAY( " -r : operate recursively on directories (sets also -m) \n");
  120. #endif
  121. DISPLAY( " -l : compress using Legacy format (Linux kernel compression)\n");
  122. DISPLAY( " -B# : cut file into blocks of size # bytes [32+] \n");
  123. DISPLAY( " or predefined block size [4-7] (default: 7) \n");
  124. DISPLAY( " -BI : Block Independence (default) \n");
  125. DISPLAY( " -BD : Block dependency (improves compression ratio) \n");
  126. DISPLAY( " -BX : enable block checksum (default:disabled) \n");
  127. DISPLAY( "--no-frame-crc : disable stream checksum (default:enabled) \n");
  128. DISPLAY( "--content-size : compressed frame includes original size (default:not present)\n");
  129. DISPLAY( "--list FILE : lists information about .lz4 files (useful for files compressed with --content-size flag)\n");
  130. DISPLAY( "--[no-]sparse : sparse mode (default:enabled on file, disabled on stdout)\n");
  131. DISPLAY( "--favor-decSpeed: compressed files decompress faster, but are less compressed \n");
  132. DISPLAY( "--fast[=#]: switch to ultra fast compression level (default: %i)\n", 1);
  133. DISPLAY( "--best : same as -%d\n", LZ4HC_CLEVEL_MAX);
  134. DISPLAY( "Benchmark arguments : \n");
  135. DISPLAY( " -b# : benchmark file(s), using # compression level (default : 1) \n");
  136. DISPLAY( " -e# : test all compression levels from -bX to # (default : 1)\n");
  137. DISPLAY( " -i# : minimum evaluation time in seconds (default : 3s) \n");
  138. if (g_lz4c_legacy_commands) {
  139. DISPLAY( "Legacy arguments : \n");
  140. DISPLAY( " -c0 : fast compression \n");
  141. DISPLAY( " -c1 : high compression \n");
  142. DISPLAY( " -c2,-hc: very high compression \n");
  143. DISPLAY( " -y : overwrite output without prompting \n");
  144. }
  145. return 0;
  146. }
  147. static int usage_longhelp(const char* exeName)
  148. {
  149. usage_advanced(exeName);
  150. DISPLAY( "\n");
  151. DISPLAY( "****************************\n");
  152. DISPLAY( "***** Advanced comment *****\n");
  153. DISPLAY( "****************************\n");
  154. DISPLAY( "\n");
  155. DISPLAY( "Which values can [output] have ? \n");
  156. DISPLAY( "---------------------------------\n");
  157. DISPLAY( "[output] : a filename \n");
  158. DISPLAY( " '%s', or '-' for standard output (pipe mode)\n", stdoutmark);
  159. DISPLAY( " '%s' to discard output (test mode) \n", NULL_OUTPUT);
  160. DISPLAY( "[output] can be left empty. In this case, it receives the following value :\n");
  161. DISPLAY( " - if stdout is not the console, then [output] = stdout \n");
  162. DISPLAY( " - if stdout is console : \n");
  163. DISPLAY( " + for compression, output to filename%s \n", LZ4_EXTENSION);
  164. DISPLAY( " + for decompression, output to filename without '%s'\n", LZ4_EXTENSION);
  165. DISPLAY( " > if input filename has no '%s' extension : error \n", LZ4_EXTENSION);
  166. DISPLAY( "\n");
  167. DISPLAY( "Compression levels : \n");
  168. DISPLAY( "---------------------\n");
  169. DISPLAY( "-0 ... -2 => Fast compression, all identical\n");
  170. DISPLAY( "-3 ... -%d => High compression; higher number == more compression but slower\n", LZ4HC_CLEVEL_MAX);
  171. DISPLAY( "\n");
  172. DISPLAY( "stdin, stdout and the console : \n");
  173. DISPLAY( "--------------------------------\n");
  174. DISPLAY( "To protect the console from binary flooding (bad argument mistake)\n");
  175. DISPLAY( "%s will refuse to read from console, or write to console \n", exeName);
  176. DISPLAY( "except if '-c' command is specified, to force output to console \n");
  177. DISPLAY( "\n");
  178. DISPLAY( "Simple example :\n");
  179. DISPLAY( "----------------\n");
  180. DISPLAY( "1 : compress 'filename' fast, using default output name 'filename.lz4'\n");
  181. DISPLAY( " %s filename\n", exeName);
  182. DISPLAY( "\n");
  183. DISPLAY( "Short arguments can be aggregated. For example :\n");
  184. DISPLAY( "----------------------------------\n");
  185. DISPLAY( "2 : compress 'filename' in high compression mode, overwrite output if exists\n");
  186. DISPLAY( " %s -9 -f filename \n", exeName);
  187. DISPLAY( " is equivalent to :\n");
  188. DISPLAY( " %s -9f filename \n", exeName);
  189. DISPLAY( "\n");
  190. DISPLAY( "%s can be used in 'pure pipe mode'. For example :\n", exeName);
  191. DISPLAY( "-------------------------------------\n");
  192. DISPLAY( "3 : compress data stream from 'generator', send result to 'consumer'\n");
  193. DISPLAY( " generator | %s | consumer \n", exeName);
  194. if (g_lz4c_legacy_commands) {
  195. DISPLAY( "\n");
  196. DISPLAY( "***** Warning ***** \n");
  197. DISPLAY( "Legacy arguments take precedence. Therefore : \n");
  198. DISPLAY( "--------------------------------- \n");
  199. DISPLAY( " %s -hc filename \n", exeName);
  200. DISPLAY( "means 'compress filename in high compression mode' \n");
  201. DISPLAY( "It is not equivalent to : \n");
  202. DISPLAY( " %s -h -c filename \n", exeName);
  203. DISPLAY( "which displays help text and exits \n");
  204. }
  205. return 0;
  206. }
  207. static int badusage(const char* exeName)
  208. {
  209. DISPLAYLEVEL(1, "Incorrect parameters\n");
  210. if (displayLevel >= 1) usage(exeName);
  211. exit(1);
  212. }
  213. static void waitEnter(void)
  214. {
  215. DISPLAY("Press enter to continue...\n");
  216. (void)getchar();
  217. }
  218. static const char* lastNameFromPath(const char* path)
  219. {
  220. const char* name = path;
  221. if (strrchr(name, '/')) name = strrchr(name, '/') + 1;
  222. if (strrchr(name, '\\')) name = strrchr(name, '\\') + 1; /* windows */
  223. return name;
  224. }
  225. /*! exeNameMatch() :
  226. @return : a non-zero value if exeName matches test, excluding the extension
  227. */
  228. static int exeNameMatch(const char* exeName, const char* test)
  229. {
  230. return !strncmp(exeName, test, strlen(test)) &&
  231. (exeName[strlen(test)] == '\0' || exeName[strlen(test)] == '.');
  232. }
  233. /*! readU32FromChar() :
  234. * @return : unsigned integer value read from input in `char` format
  235. * allows and interprets K, KB, KiB, M, MB and MiB suffix.
  236. * Will also modify `*stringPtr`, advancing it to position where it stopped reading.
  237. * Note : function result can overflow if digit string > MAX_UINT */
  238. static unsigned readU32FromChar(const char** stringPtr)
  239. {
  240. unsigned result = 0;
  241. while ((**stringPtr >='0') && (**stringPtr <='9')) {
  242. result *= 10;
  243. result += (unsigned)(**stringPtr - '0');
  244. (*stringPtr)++ ;
  245. }
  246. if ((**stringPtr=='K') || (**stringPtr=='M')) {
  247. result <<= 10;
  248. if (**stringPtr=='M') result <<= 10;
  249. (*stringPtr)++ ;
  250. if (**stringPtr=='i') (*stringPtr)++;
  251. if (**stringPtr=='B') (*stringPtr)++;
  252. }
  253. return result;
  254. }
  255. /** longCommandWArg() :
  256. * check if *stringPtr is the same as longCommand.
  257. * If yes, @return 1 and advances *stringPtr to the position which immediately follows longCommand.
  258. * @return 0 and doesn't modify *stringPtr otherwise.
  259. */
  260. static int longCommandWArg(const char** stringPtr, const char* longCommand)
  261. {
  262. size_t const comSize = strlen(longCommand);
  263. int const result = !strncmp(*stringPtr, longCommand, comSize);
  264. if (result) *stringPtr += comSize;
  265. return result;
  266. }
  267. typedef enum { om_auto, om_compress, om_decompress, om_test, om_bench, om_list } operationMode_e;
  268. /** determineOpMode() :
  269. * auto-determine operation mode, based on input filename extension
  270. * @return `om_decompress` if input filename has .lz4 extension and `om_compress` otherwise.
  271. */
  272. static operationMode_e determineOpMode(const char* inputFilename)
  273. {
  274. size_t const inSize = strlen(inputFilename);
  275. size_t const extSize = strlen(LZ4_EXTENSION);
  276. size_t const extStart= (inSize > extSize) ? inSize-extSize : 0;
  277. if (!strcmp(inputFilename+extStart, LZ4_EXTENSION)) return om_decompress;
  278. else return om_compress;
  279. }
  280. int main(int argc, const char** argv)
  281. {
  282. int i,
  283. cLevel=1,
  284. cLevelLast=-10000,
  285. legacy_format=0,
  286. forceStdout=0,
  287. forceOverwrite=0,
  288. main_pause=0,
  289. multiple_inputs=0,
  290. all_arguments_are_files=0,
  291. operationResult=0;
  292. operationMode_e mode = om_auto;
  293. const char* input_filename = NULL;
  294. const char* output_filename= NULL;
  295. const char* dictionary_filename = NULL;
  296. char* dynNameSpace = NULL;
  297. const char** inFileNames = (const char**)calloc((size_t)argc, sizeof(char*));
  298. unsigned ifnIdx=0;
  299. LZ4IO_prefs_t* const prefs = LZ4IO_defaultPreferences();
  300. const char nullOutput[] = NULL_OUTPUT;
  301. const char extension[] = LZ4_EXTENSION;
  302. size_t blockSize = LZ4IO_setBlockSizeID(prefs, LZ4_BLOCKSIZEID_DEFAULT);
  303. const char* const exeName = lastNameFromPath(argv[0]);
  304. char* fileNamesBuf = NULL;
  305. #ifdef UTIL_HAS_CREATEFILELIST
  306. unsigned fileNamesNb, recursive=0;
  307. #endif
  308. /* Init */
  309. if (inFileNames==NULL) {
  310. DISPLAY("Allocation error : not enough memory \n");
  311. return 1;
  312. }
  313. inFileNames[0] = stdinmark;
  314. LZ4IO_setOverwrite(prefs, 0);
  315. /* predefined behaviors, based on binary/link name */
  316. if (exeNameMatch(exeName, LZ4CAT)) {
  317. mode = om_decompress;
  318. LZ4IO_setOverwrite(prefs, 1);
  319. LZ4IO_setPassThrough(prefs, 1);
  320. LZ4IO_setRemoveSrcFile(prefs, 0);
  321. forceStdout=1;
  322. output_filename=stdoutmark;
  323. displayLevel=1;
  324. multiple_inputs=1;
  325. }
  326. if (exeNameMatch(exeName, UNLZ4)) { mode = om_decompress; }
  327. if (exeNameMatch(exeName, LZ4_LEGACY)) { g_lz4c_legacy_commands=1; }
  328. /* command switches */
  329. for(i=1; i<argc; i++) {
  330. const char* argument = argv[i];
  331. if(!argument) continue; /* Protection if argument empty */
  332. /* Short commands (note : aggregated short commands are allowed) */
  333. if (!all_arguments_are_files && argument[0]=='-') {
  334. /* '-' means stdin/stdout */
  335. if (argument[1]==0) {
  336. if (!input_filename) input_filename=stdinmark;
  337. else output_filename=stdoutmark;
  338. continue;
  339. }
  340. /* long commands (--long-word) */
  341. if (argument[1]=='-') {
  342. if (!strcmp(argument, "--")) { all_arguments_are_files = 1; continue; }
  343. if (!strcmp(argument, "--compress")) { mode = om_compress; continue; }
  344. if ( (!strcmp(argument, "--decompress"))
  345. || (!strcmp(argument, "--uncompress"))) {
  346. if (mode != om_bench) mode = om_decompress;
  347. BMK_setDecodeOnlyMode(1);
  348. continue;
  349. }
  350. if (!strcmp(argument, "--multiple")) { multiple_inputs = 1; continue; }
  351. if (!strcmp(argument, "--test")) { mode = om_test; continue; }
  352. if (!strcmp(argument, "--force")) { LZ4IO_setOverwrite(prefs, 1); continue; }
  353. if (!strcmp(argument, "--no-force")) { LZ4IO_setOverwrite(prefs, 0); continue; }
  354. if ((!strcmp(argument, "--stdout"))
  355. || (!strcmp(argument, "--to-stdout"))) { forceStdout=1; output_filename=stdoutmark; continue; }
  356. if (!strcmp(argument, "--frame-crc")) { LZ4IO_setStreamChecksumMode(prefs, 1); BMK_skipChecksums(0); continue; }
  357. if (!strcmp(argument, "--no-frame-crc")) { LZ4IO_setStreamChecksumMode(prefs, 0); BMK_skipChecksums(1); continue; }
  358. if (!strcmp(argument, "--no-crc")) { LZ4IO_setStreamChecksumMode(prefs, 0); LZ4IO_setBlockChecksumMode(prefs, 0); BMK_skipChecksums(1); continue; }
  359. if (!strcmp(argument, "--content-size")) { LZ4IO_setContentSize(prefs, 1); continue; }
  360. if (!strcmp(argument, "--no-content-size")) { LZ4IO_setContentSize(prefs, 0); continue; }
  361. if (!strcmp(argument, "--list")) { mode = om_list; continue; }
  362. if (!strcmp(argument, "--sparse")) { LZ4IO_setSparseFile(prefs, 2); continue; }
  363. if (!strcmp(argument, "--no-sparse")) { LZ4IO_setSparseFile(prefs, 0); continue; }
  364. if (!strcmp(argument, "--favor-decSpeed")) { LZ4IO_favorDecSpeed(prefs, 1); continue; }
  365. if (!strcmp(argument, "--verbose")) { displayLevel++; continue; }
  366. if (!strcmp(argument, "--quiet")) { if (displayLevel) displayLevel--; continue; }
  367. if (!strcmp(argument, "--version")) { DISPLAYOUT(WELCOME_MESSAGE); goto _cleanup; }
  368. if (!strcmp(argument, "--help")) { usage_advanced(exeName); goto _cleanup; }
  369. if (!strcmp(argument, "--keep")) { LZ4IO_setRemoveSrcFile(prefs, 0); continue; } /* keep source file (default) */
  370. if (!strcmp(argument, "--rm")) { LZ4IO_setRemoveSrcFile(prefs, 1); continue; }
  371. if (longCommandWArg(&argument, "--fast")) {
  372. /* Parse optional acceleration factor */
  373. if (*argument == '=') {
  374. U32 fastLevel;
  375. ++argument;
  376. fastLevel = readU32FromChar(&argument);
  377. if (fastLevel) {
  378. cLevel = -(int)fastLevel;
  379. } else {
  380. badusage(exeName);
  381. }
  382. } else if (*argument != 0) {
  383. /* Invalid character following --fast */
  384. badusage(exeName);
  385. } else {
  386. cLevel = -1; /* default for --fast */
  387. }
  388. continue;
  389. }
  390. /* For gzip(1) compatibility */
  391. if (!strcmp(argument, "--best")) { cLevel=LZ4HC_CLEVEL_MAX; continue; }
  392. }
  393. while (argument[1]!=0) {
  394. argument ++;
  395. if (g_lz4c_legacy_commands) {
  396. /* Legacy commands (-c0, -c1, -hc, -y) */
  397. if (!strcmp(argument, "c0")) { cLevel=0; argument++; continue; } /* -c0 (fast compression) */
  398. if (!strcmp(argument, "c1")) { cLevel=9; argument++; continue; } /* -c1 (high compression) */
  399. if (!strcmp(argument, "c2")) { cLevel=12; argument++; continue; } /* -c2 (very high compression) */
  400. if (!strcmp(argument, "hc")) { cLevel=12; argument++; continue; } /* -hc (very high compression) */
  401. if (!strcmp(argument, "y")) { LZ4IO_setOverwrite(prefs, 1); continue; } /* -y (answer 'yes' to overwrite permission) */
  402. }
  403. if ((*argument>='0') && (*argument<='9')) {
  404. cLevel = (int)readU32FromChar(&argument);
  405. argument--;
  406. continue;
  407. }
  408. switch(argument[0])
  409. {
  410. /* Display help */
  411. case 'V': DISPLAYOUT(WELCOME_MESSAGE); goto _cleanup; /* Version */
  412. case 'h': usage_advanced(exeName); goto _cleanup;
  413. case 'H': usage_longhelp(exeName); goto _cleanup;
  414. case 'e':
  415. argument++;
  416. cLevelLast = (int)readU32FromChar(&argument);
  417. argument--;
  418. break;
  419. /* Compression (default) */
  420. case 'z': mode = om_compress; break;
  421. case 'D':
  422. if (argument[1] == '\0') {
  423. /* path is next arg */
  424. if (i + 1 == argc) {
  425. /* there is no next arg */
  426. badusage(exeName);
  427. }
  428. dictionary_filename = argv[++i];
  429. } else {
  430. /* path follows immediately */
  431. dictionary_filename = argument + 1;
  432. }
  433. /* skip to end of argument so that we jump to parsing next argument */
  434. argument += strlen(argument) - 1;
  435. break;
  436. /* Use Legacy format (ex : Linux kernel compression) */
  437. case 'l': legacy_format = 1; blockSize = 8 MB; break;
  438. /* Decoding */
  439. case 'd':
  440. if (mode != om_bench) mode = om_decompress;
  441. BMK_setDecodeOnlyMode(1);
  442. break;
  443. /* Force stdout, even if stdout==console */
  444. case 'c':
  445. forceStdout=1;
  446. output_filename=stdoutmark;
  447. LZ4IO_setPassThrough(prefs, 1);
  448. break;
  449. /* Test integrity */
  450. case 't': mode = om_test; break;
  451. /* Overwrite */
  452. case 'f': forceOverwrite=1; LZ4IO_setOverwrite(prefs, 1); break;
  453. /* Verbose mode */
  454. case 'v': displayLevel++; break;
  455. /* Quiet mode */
  456. case 'q': if (displayLevel) displayLevel--; break;
  457. /* keep source file (default anyway, so useless) (for xz/lzma compatibility) */
  458. case 'k': LZ4IO_setRemoveSrcFile(prefs, 0); break;
  459. /* Modify Block Properties */
  460. case 'B':
  461. while (argument[1]!=0) {
  462. int exitBlockProperties=0;
  463. switch(argument[1])
  464. {
  465. case 'D': LZ4IO_setBlockMode(prefs, LZ4IO_blockLinked); argument++; break;
  466. case 'I': LZ4IO_setBlockMode(prefs, LZ4IO_blockIndependent); argument++; break;
  467. case 'X': LZ4IO_setBlockChecksumMode(prefs, 1); argument ++; break; /* disabled by default */
  468. default :
  469. if (argument[1] < '0' || argument[1] > '9') {
  470. exitBlockProperties=1;
  471. break;
  472. } else {
  473. unsigned B;
  474. argument++;
  475. B = readU32FromChar(&argument);
  476. argument--;
  477. if (B < 4) badusage(exeName);
  478. if (B <= 7) {
  479. blockSize = LZ4IO_setBlockSizeID(prefs, B);
  480. BMK_setBlockSize(blockSize);
  481. DISPLAYLEVEL(2, "using blocks of size %u KB \n", (U32)(blockSize>>10));
  482. } else {
  483. if (B < 32) badusage(exeName);
  484. blockSize = LZ4IO_setBlockSize(prefs, B);
  485. BMK_setBlockSize(blockSize);
  486. if (blockSize >= 1024) {
  487. DISPLAYLEVEL(2, "using blocks of size %u KB \n", (U32)(blockSize>>10));
  488. } else {
  489. DISPLAYLEVEL(2, "using blocks of size %u bytes \n", (U32)(blockSize));
  490. }
  491. }
  492. break;
  493. }
  494. }
  495. if (exitBlockProperties) break;
  496. }
  497. break;
  498. /* Benchmark */
  499. case 'b': mode = om_bench; multiple_inputs=1;
  500. break;
  501. /* hidden command : benchmark files, but do not fuse result */
  502. case 'S': BMK_setBenchSeparately(1);
  503. break;
  504. #ifdef UTIL_HAS_CREATEFILELIST
  505. /* recursive */
  506. case 'r': recursive=1;
  507. #endif
  508. /* fall-through */
  509. /* Treat non-option args as input files. See https://code.google.com/p/lz4/issues/detail?id=151 */
  510. case 'm': multiple_inputs=1;
  511. break;
  512. /* Modify Nb Seconds (benchmark only) */
  513. case 'i':
  514. { unsigned iters;
  515. argument++;
  516. iters = readU32FromChar(&argument);
  517. argument--;
  518. BMK_setNotificationLevel(displayLevel);
  519. BMK_setNbSeconds(iters); /* notification if displayLevel >= 3 */
  520. }
  521. break;
  522. /* Pause at the end (hidden option) */
  523. case 'p': main_pause=1; break;
  524. /* Unrecognised command */
  525. default : badusage(exeName);
  526. }
  527. }
  528. continue;
  529. }
  530. /* Store in *inFileNames[] if -m is used. */
  531. if (multiple_inputs) { inFileNames[ifnIdx++] = argument; continue; }
  532. /* original cli logic : lz4 input output */
  533. /* First non-option arg is input_filename. */
  534. if (!input_filename) { input_filename = argument; continue; }
  535. /* Second non-option arg is output_filename */
  536. if (!output_filename) {
  537. output_filename = argument;
  538. if (!strcmp (output_filename, nullOutput)) output_filename = nulmark;
  539. continue;
  540. }
  541. /* 3rd+ non-option arg should not exist */
  542. DISPLAYLEVEL(1, "%s : %s won't be used ! Do you want multiple input files (-m) ? \n",
  543. forceOverwrite ? "Warning" : "Error",
  544. argument);
  545. if (!forceOverwrite) exit(1);
  546. }
  547. DISPLAYLEVEL(3, WELCOME_MESSAGE);
  548. #ifdef _POSIX_C_SOURCE
  549. DISPLAYLEVEL(4, "_POSIX_C_SOURCE defined: %ldL\n", (long) _POSIX_C_SOURCE);
  550. #endif
  551. #ifdef _POSIX_VERSION
  552. DISPLAYLEVEL(4, "_POSIX_VERSION defined: %ldL\n", (long) _POSIX_VERSION);
  553. #endif
  554. #ifdef PLATFORM_POSIX_VERSION
  555. DISPLAYLEVEL(4, "PLATFORM_POSIX_VERSION defined: %ldL\n", (long) PLATFORM_POSIX_VERSION);
  556. #endif
  557. #ifdef _FILE_OFFSET_BITS
  558. DISPLAYLEVEL(4, "_FILE_OFFSET_BITS defined: %ldL\n", (long) _FILE_OFFSET_BITS);
  559. #endif
  560. if ((mode == om_compress) || (mode == om_bench))
  561. DISPLAYLEVEL(4, "Blocks size : %u KB\n", (U32)(blockSize>>10));
  562. if (multiple_inputs) {
  563. input_filename = inFileNames[0];
  564. #ifdef UTIL_HAS_CREATEFILELIST
  565. if (recursive) { /* at this stage, filenameTable is a list of paths, which can contain both files and directories */
  566. const char** extendedFileList = UTIL_createFileList(inFileNames, ifnIdx, &fileNamesBuf, &fileNamesNb);
  567. if (extendedFileList) {
  568. unsigned u;
  569. for (u=0; u<fileNamesNb; u++) DISPLAYLEVEL(4, "%u %s\n", u, extendedFileList[u]);
  570. free((void*)inFileNames);
  571. inFileNames = extendedFileList;
  572. ifnIdx = fileNamesNb;
  573. } }
  574. #endif
  575. }
  576. if (dictionary_filename) {
  577. if (!strcmp(dictionary_filename, stdinmark) && IS_CONSOLE(stdin)) {
  578. DISPLAYLEVEL(1, "refusing to read from a console\n");
  579. exit(1);
  580. }
  581. LZ4IO_setDictionaryFilename(prefs, dictionary_filename);
  582. }
  583. /* benchmark and test modes */
  584. if (mode == om_bench) {
  585. BMK_setNotificationLevel(displayLevel);
  586. operationResult = BMK_benchFiles(inFileNames, ifnIdx, cLevel, cLevelLast, dictionary_filename);
  587. goto _cleanup;
  588. }
  589. if (mode == om_test) {
  590. LZ4IO_setTestMode(prefs, 1);
  591. output_filename = nulmark;
  592. mode = om_decompress; /* defer to decompress */
  593. }
  594. /* No input provided => use stdin */
  595. if (!input_filename) input_filename = stdinmark;
  596. /* Refuse to use the console as input */
  597. if (!strcmp(input_filename, stdinmark) && IS_CONSOLE(stdin) ) {
  598. DISPLAYLEVEL(1, "refusing to read from a console\n");
  599. exit(1);
  600. }
  601. if (!strcmp(input_filename, stdinmark)) {
  602. /* if input==stdin and no output defined, stdout becomes default output */
  603. if (!output_filename) output_filename = stdoutmark;
  604. }
  605. /* No output filename ==> try to select one automatically (when possible) */
  606. while ((!output_filename) && (multiple_inputs==0)) {
  607. if (!IS_CONSOLE(stdout) && mode != om_list) {
  608. /* Default to stdout whenever stdout is not the console.
  609. * Note : this policy may change in the future, therefore don't rely on it !
  610. * To ensure `stdout` is explicitly selected, use `-c` command flag.
  611. * Conversely, to ensure output will not become `stdout`, use `-m` command flag */
  612. DISPLAYLEVEL(1, "Warning : using stdout as default output. Do not rely on this behavior: use explicit `-c` instead ! \n");
  613. output_filename = stdoutmark;
  614. break;
  615. }
  616. if (mode == om_auto) { /* auto-determine compression or decompression, based on file extension */
  617. mode = determineOpMode(input_filename);
  618. }
  619. if (mode == om_compress) { /* compression to file */
  620. size_t const l = strlen(input_filename);
  621. dynNameSpace = (char*)calloc(1,l+5);
  622. if (dynNameSpace==NULL) { perror(exeName); exit(1); }
  623. strcpy(dynNameSpace, input_filename);
  624. strcat(dynNameSpace, LZ4_EXTENSION);
  625. output_filename = dynNameSpace;
  626. DISPLAYLEVEL(2, "Compressed filename will be : %s \n", output_filename);
  627. break;
  628. }
  629. if (mode == om_decompress) {/* decompress to file (automatic output name only works if input filename has correct format extension) */
  630. size_t outl;
  631. size_t const inl = strlen(input_filename);
  632. dynNameSpace = (char*)calloc(1,inl+1);
  633. if (dynNameSpace==NULL) { perror(exeName); exit(1); }
  634. strcpy(dynNameSpace, input_filename);
  635. outl = inl;
  636. if (inl>4)
  637. while ((outl >= inl-4) && (input_filename[outl] == extension[outl-inl+4])) dynNameSpace[outl--]=0;
  638. if (outl != inl-5) { DISPLAYLEVEL(1, "Cannot determine an output filename \n"); badusage(exeName); }
  639. output_filename = dynNameSpace;
  640. DISPLAYLEVEL(2, "Decoding file %s \n", output_filename);
  641. }
  642. break;
  643. }
  644. if (mode == om_list) {
  645. if (!multiple_inputs) inFileNames[ifnIdx++] = input_filename;
  646. } else {
  647. if (!multiple_inputs) assert(output_filename != NULL);
  648. }
  649. /* when multiple_inputs==1, output_filename may simply be useless,
  650. * however, output_filename must be !NULL for next strcmp() tests */
  651. if (!output_filename) output_filename = "*\\dummy^!//";
  652. /* Check if output is defined as console; trigger an error in this case */
  653. if ( !strcmp(output_filename,stdoutmark)
  654. && mode != om_list
  655. && IS_CONSOLE(stdout)
  656. && !forceStdout) {
  657. DISPLAYLEVEL(1, "refusing to write to console without -c \n");
  658. exit(1);
  659. }
  660. /* Downgrade notification level in stdout and multiple file mode */
  661. if (!strcmp(output_filename,stdoutmark) && (displayLevel==2)) displayLevel=1;
  662. if ((multiple_inputs) && (displayLevel==2)) displayLevel=1;
  663. /* Auto-determine compression or decompression, based on file extension */
  664. if (mode == om_auto) {
  665. mode = determineOpMode(input_filename);
  666. }
  667. /* IO Stream/File */
  668. LZ4IO_setNotificationLevel((int)displayLevel);
  669. if (ifnIdx == 0) multiple_inputs = 0;
  670. if (mode == om_decompress) {
  671. if (multiple_inputs) {
  672. const char* dec_extension = LZ4_EXTENSION;
  673. if (!strcmp(output_filename, stdoutmark)) dec_extension = stdoutmark;
  674. if (!strcmp(output_filename, nulmark)) dec_extension = nulmark;
  675. assert(ifnIdx < INT_MAX);
  676. operationResult = LZ4IO_decompressMultipleFilenames(inFileNames, (int)ifnIdx, dec_extension, prefs);
  677. } else {
  678. operationResult = DEFAULT_DECOMPRESSOR(input_filename, output_filename, prefs);
  679. }
  680. } else if (mode == om_list){
  681. operationResult = LZ4IO_displayCompressedFilesInfo(inFileNames, ifnIdx);
  682. } else { /* compression is default action */
  683. if (legacy_format) {
  684. DISPLAYLEVEL(3, "! Generating LZ4 Legacy format (deprecated) ! \n");
  685. if(multiple_inputs){
  686. const char* const leg_extension = !strcmp(output_filename,stdoutmark) ? stdoutmark : LZ4_EXTENSION;
  687. LZ4IO_compressMultipleFilenames_Legacy(inFileNames, (int)ifnIdx, leg_extension, cLevel, prefs);
  688. } else {
  689. LZ4IO_compressFilename_Legacy(input_filename, output_filename, cLevel, prefs);
  690. }
  691. } else {
  692. if (multiple_inputs) {
  693. const char* const comp_extension = !strcmp(output_filename,stdoutmark) ? stdoutmark : LZ4_EXTENSION;
  694. assert(ifnIdx <= INT_MAX);
  695. operationResult = LZ4IO_compressMultipleFilenames(inFileNames, (int)ifnIdx, comp_extension, cLevel, prefs);
  696. } else {
  697. operationResult = DEFAULT_COMPRESSOR(input_filename, output_filename, cLevel, prefs);
  698. } } }
  699. _cleanup:
  700. if (main_pause) waitEnter();
  701. free(dynNameSpace);
  702. free(fileNamesBuf);
  703. LZ4IO_freePreferences(prefs);
  704. free((void*)inFileNames);
  705. return operationResult;
  706. }