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 ///////////////////////////////////////////////////////////////////////////////
31 # define TOOL_FORMAT "lzma"
33 # define TOOL_FORMAT "xz"
37 /// Number of bytes to use memory at maximum
38 static uint64_t memlimit;
40 /// Error messages are suppressed if this is zero, which is the case when
41 /// --quiet has been given at least twice.
42 static unsigned int display_errors = 2;
44 /// Program name to be shown in error messages
45 static const char *argv0;
48 static void lzma_attribute((format(printf, 1, 2)))
49 my_errorf(const char *fmt, ...)
55 fprintf(stderr, "%s: ", argv0);
56 vfprintf(stderr, fmt, ap);
57 fprintf(stderr, "\n");
65 static void lzma_attribute((noreturn))
68 int status = EXIT_SUCCESS;
70 // Close stdout. We don't care about stderr, because we write to it
71 // only when an error has already occurred.
72 const int ferror_err = ferror(stdout);
73 const int fclose_err = fclose(stdout);
75 if (ferror_err || fclose_err) {
76 // If it was fclose() that failed, we have the reason
77 // in errno. If only ferror() indicated an error,
78 // we have no idea what the reason was.
79 my_errorf("Cannot write to standard output: %s", fclose_err
80 ? strerror(errno) : "Unknown error");
81 status = EXIT_FAILURE;
88 static void lzma_attribute((noreturn))
92 "Usage: %s [OPTION]... [FILE]...\n"
93 "Uncompress files in the ." TOOL_FORMAT " format to the standard output.\n"
95 " -c, --stdout (ignored)\n"
96 " -d, --decompress (ignored)\n"
97 " -k, --keep (ignored)\n"
98 " -f, --force (ignored)\n"
99 " -M, --memory=NUM use NUM bytes of memory at maximum (0 means default)\n"
100 " -q, --quiet specify *twice* to suppress errors\n"
101 " -Q, --no-warn (ignored)\n"
102 " -h, --help display this help and exit\n"
103 " -V, --version display the version number and exit\n"
105 "With no FILE, or when FILE is -, read standard input.\n"
107 "On this system and configuration, this program will use at maximum of roughly\n"
108 "%" PRIu64 " MiB RAM.\n"
110 "Report bugs to <" PACKAGE_BUGREPORT "> (in English or Finnish).\n"
111 PACKAGE_NAME " home page: <" PACKAGE_HOMEPAGE ">\n",
112 argv0, memlimit / (1024 * 1024));
117 static void lzma_attribute((noreturn))
120 printf(TOOL_FORMAT "dec (" PACKAGE_NAME ") " LZMA_VERSION_STRING "\n"
121 "liblzma %s\n", lzma_version_string());
127 /// Find out the amount of physical memory (RAM) in the system, and set
128 /// the memory usage limit to the given percentage of RAM.
130 memlimit_set_percentage(uint32_t percentage)
132 uint64_t mem = physmem();
134 // If we cannot determine the amount of RAM, assume 32 MiB.
136 mem = UINT64_C(32) * 1024 * 1024;
138 memlimit = percentage * mem / 100;
143 /// Set the memory usage limit to give number of bytes. Zero is a special
144 /// value to indicate the default limit.
146 memlimit_set(uint64_t new_memlimit)
148 if (new_memlimit == 0)
149 memlimit_set_percentage(40);
151 memlimit = new_memlimit;
157 /// \brief Convert a string to uint64_t
159 /// This is rudely copied from src/xz/util.c and modified a little. :-(
161 /// \param max Return value when the string "max" was specified.
164 str_to_uint64(const char *value, uint64_t max)
168 // Accept special value "max".
169 if (strcmp(value, "max") == 0)
172 if (*value < '0' || *value > '9') {
173 my_errorf("%s: Value is not a non-negative decimal integer",
180 if (result > (UINT64_MAX - 9) / 10)
184 result += *value - '0';
186 } while (*value >= '0' && *value <= '9');
188 if (*value != '\0') {
190 static const struct {
199 { "GB", 1000000000 },
204 { "Gi", 1073741824 },
205 { "GiB", 1073741824 }
208 uint32_t multiplier = 0;
209 for (size_t i = 0; i < ARRAY_SIZE(suffixes); ++i) {
210 if (strcmp(value, suffixes[i].name) == 0) {
211 multiplier = suffixes[i].multiplier;
216 if (multiplier == 0) {
217 my_errorf("%s: Invalid suffix", value);
221 // Don't overflow here either.
222 if (result > UINT64_MAX / multiplier)
225 result *= multiplier;
232 /// Parses command line options.
234 parse_options(int argc, char **argv)
236 static const char short_opts[] = "cdkfM:hqQV";
237 static const struct option long_opts[] = {
238 { "stdout", no_argument, NULL, 'c' },
239 { "to-stdout", no_argument, NULL, 'c' },
240 { "decompress", no_argument, NULL, 'd' },
241 { "uncompress", no_argument, NULL, 'd' },
242 { "force", no_argument, NULL, 'f' },
243 { "keep", no_argument, NULL, 'k' },
244 { "memory", required_argument, NULL, 'M' },
245 { "quiet", no_argument, NULL, 'q' },
246 { "no-warn", no_argument, NULL, 'Q' },
247 { "help", no_argument, NULL, 'h' },
248 { "version", no_argument, NULL, 'V' },
254 while ((c = getopt_long(argc, argv, short_opts, long_opts, NULL))
265 // Support specifying the limit as a percentage of
266 // installed physical RAM.
267 const size_t len = strlen(optarg);
268 if (len > 0 && optarg[len - 1] == '%') {
269 // Memory limit is a percentage of total
271 optarg[len - 1] = '\0';
272 const uint64_t percentage
273 = str_to_uint64(optarg, 100);
274 if (percentage < 1 || percentage > 100) {
275 my_errorf("Percentage must be in "
276 "the range [1, 100]");
280 memlimit_set_percentage(percentage);
282 memlimit_set(str_to_uint64(
283 optarg, UINT64_MAX));
290 if (display_errors > 0)
311 uncompress(lzma_stream *strm, FILE *file, const char *filename)
315 // Initialize the decoder
317 ret = lzma_alone_decoder(strm, memlimit);
319 ret = lzma_stream_decoder(strm, memlimit, LZMA_CONCATENATED);
322 // The only reasonable error here is LZMA_MEM_ERROR.
323 // FIXME: Maybe also LZMA_MEMLIMIT_ERROR in future?
324 if (ret != LZMA_OK) {
325 my_errorf("%s", ret == LZMA_MEM_ERROR ? strerror(ENOMEM)
326 : "Internal program error (bug)");
330 // Input and output buffers
331 uint8_t in_buf[BUFSIZ];
332 uint8_t out_buf[BUFSIZ];
335 strm->next_out = out_buf;
336 strm->avail_out = BUFSIZ;
338 lzma_action action = LZMA_RUN;
341 if (strm->avail_in == 0) {
342 strm->next_in = in_buf;
343 strm->avail_in = fread(in_buf, 1, BUFSIZ, file);
346 // POSIX says that fread() sets errno if
347 // an error occurred. ferror() doesn't
349 my_errorf("%s: Error reading input file: %s",
350 filename, strerror(errno));
355 // When using LZMA_CONCATENATED, we need to tell
356 // liblzma when it has got all the input.
358 action = LZMA_FINISH;
362 ret = lzma_code(strm, action);
364 // Write and check write error before checking decoder error.
365 // This way as much data as possible gets written to output
366 // even if decoder detected an error.
367 if (strm->avail_out == 0 || ret != LZMA_OK) {
368 const size_t write_size = BUFSIZ - strm->avail_out;
370 if (fwrite(out_buf, 1, write_size, stdout)
372 // Wouldn't be a surprise if writing to stderr
373 // would fail too but at least try to show an
375 my_errorf("Cannot write to standard output: "
376 "%s", strerror(errno));
380 strm->next_out = out_buf;
381 strm->avail_out = BUFSIZ;
384 if (ret != LZMA_OK) {
385 if (ret == LZMA_STREAM_END) {
387 // Check that there's no trailing garbage.
388 if (strm->avail_in != 0
389 || fread(in_buf, 1, 1, file)
392 ret = LZMA_DATA_ERROR;
396 // lzma_stream_decoder() already guarantees
397 // that there's no trailing garbage.
398 assert(strm->avail_in == 0);
399 assert(action == LZMA_FINISH);
408 msg = strerror(ENOMEM);
411 case LZMA_MEMLIMIT_ERROR:
412 msg = "Memory usage limit reached";
415 case LZMA_FORMAT_ERROR:
416 msg = "File format not recognized";
419 case LZMA_OPTIONS_ERROR:
420 // FIXME: Better message?
421 msg = "Unsupported compression options";
424 case LZMA_DATA_ERROR:
425 msg = "File is corrupt";
429 msg = "Unexpected end of input";
433 msg = "Internal program error (bug)";
437 my_errorf("%s: %s", filename, msg);
445 main(int argc, char **argv)
447 // Set the argv0 global so that we can print the command name in
448 // error and help messages.
451 // Set the default memory usage limit. This is needed before parsing
452 // the command line arguments.
455 // Parse the command line options.
456 parse_options(argc, argv);
458 // The same lzma_stream is used for all files that we decode. This way
459 // we don't need to reallocate memory for every file if they use same
460 // compression settings.
461 lzma_stream strm = LZMA_STREAM_INIT;
463 // Some systems require setting stdin and stdout to binary mode.
465 setmode(fileno(stdin), O_BINARY);
466 setmode(fileno(stdout), O_BINARY);
469 if (optind == argc) {
470 // No filenames given, decode from stdin.
471 uncompress(&strm, stdin, "(stdin)");
473 // Loop through the filenames given on the command line.
475 // "-" indicates stdin.
476 if (strcmp(argv[optind], "-") == 0) {
477 uncompress(&strm, stdin, "(stdin)");
479 FILE *file = fopen(argv[optind], "rb");
481 my_errorf("%s: %s", argv[optind],
486 uncompress(&strm, file, argv[optind]);
489 } while (++optind < argc);
493 // Free the memory only when debugging. Freeing wastes some time,
494 // but allows detecting possible memory leaks with Valgrind.