1 ///////////////////////////////////////////////////////////////////////////////
4 /// \brief Simple single-threaded tool to uncompress .xz or .lzma files
6 // Author: Lasse Collin
8 // This file has been put into the public domain.
9 // You can do whatever you want with this file.
11 ///////////////////////////////////////////////////////////////////////////////
22 #include "tuklib_progname.h"
23 #include "tuklib_exit.h"
24 #include "tuklib_physmem.h"
33 # define TOOL_FORMAT "lzma"
35 # define TOOL_FORMAT "xz"
39 /// Number of bytes to use memory at maximum
40 static uint64_t memlimit;
42 /// Error messages are suppressed if this is zero, which is the case when
43 /// --quiet has been given at least twice.
44 static unsigned int display_errors = 2;
47 static void lzma_attribute((format(printf, 1, 2)))
48 my_errorf(const char *fmt, ...)
54 fprintf(stderr, "%s: ", progname);
55 vfprintf(stderr, fmt, ap);
56 fprintf(stderr, "\n");
64 static void lzma_attribute((noreturn))
68 "Usage: %s [OPTION]... [FILE]...\n"
69 "Uncompress files in the ." TOOL_FORMAT " format to the standard output.\n"
71 " -c, --stdout (ignored)\n"
72 " -d, --decompress (ignored)\n"
73 " -k, --keep (ignored)\n"
74 " -M, --memory=NUM use NUM bytes of memory at maximum (0 means default)\n"
75 " -q, --quiet specify *twice* to suppress errors\n"
76 " -Q, --no-warn (ignored)\n"
77 " -h, --help display this help and exit\n"
78 " -V, --version display the version number and exit\n"
80 "With no FILE, or when FILE is -, read standard input.\n"
82 "On this system and configuration, this program will use a maximum of roughly\n"
83 "%" PRIu64 " MiB RAM.\n"
85 "Report bugs to <" PACKAGE_BUGREPORT "> (in English or Finnish).\n"
86 PACKAGE_NAME " home page: <" PACKAGE_HOMEPAGE ">\n",
87 progname, memlimit / (1024 * 1024));
88 tuklib_exit(EXIT_SUCCESS, EXIT_FAILURE, display_errors);
92 static void lzma_attribute((noreturn))
95 printf(TOOL_FORMAT "dec (" PACKAGE_NAME ") " LZMA_VERSION_STRING "\n"
96 "liblzma %s\n", lzma_version_string());
98 tuklib_exit(EXIT_SUCCESS, EXIT_FAILURE, display_errors);
102 /// Find out the amount of physical memory (RAM) in the system, and set
103 /// the memory usage limit to the given percentage of RAM.
105 memlimit_set_percentage(uint32_t percentage)
107 uint64_t mem = tuklib_physmem();
109 // If we cannot determine the amount of RAM, assume 32 MiB.
111 mem = UINT64_C(32) * 1024 * 1024;
113 memlimit = percentage * mem / 100;
118 /// Set the memory usage limit to give number of bytes. Zero is a special
119 /// value to indicate the default limit.
121 memlimit_set(uint64_t new_memlimit)
123 if (new_memlimit == 0)
124 memlimit_set_percentage(40);
126 memlimit = new_memlimit;
132 /// \brief Convert a string to uint64_t
134 /// This is rudely copied from src/xz/util.c and modified a little. :-(
136 /// \param max Return value when the string "max" was specified.
139 str_to_uint64(const char *value, uint64_t max)
143 // Accept special value "max".
144 if (strcmp(value, "max") == 0)
147 if (*value < '0' || *value > '9') {
148 my_errorf("%s: Value is not a non-negative decimal integer",
155 if (result > (UINT64_MAX - 9) / 10)
159 result += *value - '0';
161 } while (*value >= '0' && *value <= '9');
163 if (*value != '\0') {
165 static const struct {
174 { "GB", 1000000000 },
179 { "Gi", 1073741824 },
180 { "GiB", 1073741824 }
183 uint32_t multiplier = 0;
184 for (size_t i = 0; i < ARRAY_SIZE(suffixes); ++i) {
185 if (strcmp(value, suffixes[i].name) == 0) {
186 multiplier = suffixes[i].multiplier;
191 if (multiplier == 0) {
192 my_errorf("%s: Invalid suffix", value);
196 // Don't overflow here either.
197 if (result > UINT64_MAX / multiplier)
200 result *= multiplier;
207 /// Parses command line options.
209 parse_options(int argc, char **argv)
211 static const char short_opts[] = "cdkM:hqQV";
212 static const struct option long_opts[] = {
213 { "stdout", no_argument, NULL, 'c' },
214 { "to-stdout", no_argument, NULL, 'c' },
215 { "decompress", no_argument, NULL, 'd' },
216 { "uncompress", no_argument, NULL, 'd' },
217 { "keep", no_argument, NULL, 'k' },
218 { "memory", required_argument, NULL, 'M' },
219 { "quiet", no_argument, NULL, 'q' },
220 { "no-warn", no_argument, NULL, 'Q' },
221 { "help", no_argument, NULL, 'h' },
222 { "version", no_argument, NULL, 'V' },
228 while ((c = getopt_long(argc, argv, short_opts, long_opts, NULL))
238 // Support specifying the limit as a percentage of
239 // installed physical RAM.
240 const size_t len = strlen(optarg);
241 if (len > 0 && optarg[len - 1] == '%') {
242 // Memory limit is a percentage of total
244 optarg[len - 1] = '\0';
245 const uint64_t percentage
246 = str_to_uint64(optarg, 100);
247 if (percentage < 1 || percentage > 100) {
248 my_errorf("Percentage must be in "
249 "the range [1, 100]");
253 memlimit_set_percentage(percentage);
255 memlimit_set(str_to_uint64(
256 optarg, UINT64_MAX));
263 if (display_errors > 0)
284 uncompress(lzma_stream *strm, FILE *file, const char *filename)
288 // Initialize the decoder
290 ret = lzma_alone_decoder(strm, memlimit);
292 ret = lzma_stream_decoder(strm, memlimit, LZMA_CONCATENATED);
295 // The only reasonable error here is LZMA_MEM_ERROR.
296 // FIXME: Maybe also LZMA_MEMLIMIT_ERROR in future?
297 if (ret != LZMA_OK) {
298 my_errorf("%s", ret == LZMA_MEM_ERROR ? strerror(ENOMEM)
299 : "Internal error (bug)");
303 // Input and output buffers
304 uint8_t in_buf[BUFSIZ];
305 uint8_t out_buf[BUFSIZ];
308 strm->next_out = out_buf;
309 strm->avail_out = BUFSIZ;
311 lzma_action action = LZMA_RUN;
314 if (strm->avail_in == 0) {
315 strm->next_in = in_buf;
316 strm->avail_in = fread(in_buf, 1, BUFSIZ, file);
319 // POSIX says that fread() sets errno if
320 // an error occurred. ferror() doesn't
322 my_errorf("%s: Error reading input file: %s",
323 filename, strerror(errno));
328 // When using LZMA_CONCATENATED, we need to tell
329 // liblzma when it has got all the input.
331 action = LZMA_FINISH;
335 ret = lzma_code(strm, action);
337 // Write and check write error before checking decoder error.
338 // This way as much data as possible gets written to output
339 // even if decoder detected an error.
340 if (strm->avail_out == 0 || ret != LZMA_OK) {
341 const size_t write_size = BUFSIZ - strm->avail_out;
343 if (fwrite(out_buf, 1, write_size, stdout)
345 // Wouldn't be a surprise if writing to stderr
346 // would fail too but at least try to show an
348 my_errorf("Cannot write to standard output: "
349 "%s", strerror(errno));
353 strm->next_out = out_buf;
354 strm->avail_out = BUFSIZ;
357 if (ret != LZMA_OK) {
358 if (ret == LZMA_STREAM_END) {
360 // Check that there's no trailing garbage.
361 if (strm->avail_in != 0
362 || fread(in_buf, 1, 1, file)
365 ret = LZMA_DATA_ERROR;
369 // lzma_stream_decoder() already guarantees
370 // that there's no trailing garbage.
371 assert(strm->avail_in == 0);
372 assert(action == LZMA_FINISH);
381 msg = strerror(ENOMEM);
384 case LZMA_MEMLIMIT_ERROR:
385 msg = "Memory usage limit reached";
388 case LZMA_FORMAT_ERROR:
389 msg = "File format not recognized";
392 case LZMA_OPTIONS_ERROR:
393 // FIXME: Better message?
394 msg = "Unsupported compression options";
397 case LZMA_DATA_ERROR:
398 msg = "File is corrupt";
402 msg = "Unexpected end of input";
406 msg = "Internal error (bug)";
410 my_errorf("%s: %s", filename, msg);
418 main(int argc, char **argv)
420 // Initialize progname which we will be used in error messages.
421 tuklib_progname_init(argv);
423 // Set the default memory usage limit. This is needed before parsing
424 // the command line arguments.
427 // Parse the command line options.
428 parse_options(argc, argv);
430 // The same lzma_stream is used for all files that we decode. This way
431 // we don't need to reallocate memory for every file if they use same
432 // compression settings.
433 lzma_stream strm = LZMA_STREAM_INIT;
435 // Some systems require setting stdin and stdout to binary mode.
436 #ifdef TUKLIB_DOSLIKE
437 setmode(fileno(stdin), O_BINARY);
438 setmode(fileno(stdout), O_BINARY);
441 if (optind == argc) {
442 // No filenames given, decode from stdin.
443 uncompress(&strm, stdin, "(stdin)");
445 // Loop through the filenames given on the command line.
447 // "-" indicates stdin.
448 if (strcmp(argv[optind], "-") == 0) {
449 uncompress(&strm, stdin, "(stdin)");
451 FILE *file = fopen(argv[optind], "rb");
453 my_errorf("%s: %s", argv[optind],
458 uncompress(&strm, file, argv[optind]);
461 } while (++optind < argc);
465 // Free the memory only when debugging. Freeing wastes some time,
466 // but allows detecting possible memory leaks with Valgrind.
470 tuklib_exit(EXIT_SUCCESS, EXIT_FAILURE, display_errors);