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 " -M, --memory=NUM use NUM bytes of memory at maximum (0 means default)\n"
99 " -q, --quiet specify *twice* to suppress errors\n"
100 " -Q, --no-warn (ignored)\n"
101 " -h, --help display this help and exit\n"
102 " -V, --version display the version number and exit\n"
104 "With no FILE, or when FILE is -, read standard input.\n"
106 "On this system and configuration, this program will use at maximum of roughly\n"
107 "%" PRIu64 " MiB RAM.\n"
109 "Report bugs to <" PACKAGE_BUGREPORT "> (in English or Finnish).\n"
110 PACKAGE_NAME " home page: <" PACKAGE_HOMEPAGE ">\n",
111 argv0, memlimit / (1024 * 1024));
116 static void lzma_attribute((noreturn))
119 printf(TOOL_FORMAT "dec (" PACKAGE_NAME ") " LZMA_VERSION_STRING "\n"
120 "liblzma %s\n", lzma_version_string());
126 /// Find out the amount of physical memory (RAM) in the system, and set
127 /// the memory usage limit to the given percentage of RAM.
129 memlimit_set_percentage(uint32_t percentage)
131 uint64_t mem = physmem();
133 // If we cannot determine the amount of RAM, assume 32 MiB.
135 mem = UINT64_C(32) * 1024 * 1024;
137 memlimit = percentage * mem / 100;
142 /// Set the memory usage limit to give number of bytes. Zero is a special
143 /// value to indicate the default limit.
145 memlimit_set(uint64_t new_memlimit)
147 if (new_memlimit == 0)
148 memlimit_set_percentage(40);
150 memlimit = new_memlimit;
156 /// \brief Convert a string to uint64_t
158 /// This is rudely copied from src/xz/util.c and modified a little. :-(
160 /// \param max Return value when the string "max" was specified.
163 str_to_uint64(const char *value, uint64_t max)
167 // Accept special value "max".
168 if (strcmp(value, "max") == 0)
171 if (*value < '0' || *value > '9') {
172 my_errorf("%s: Value is not a non-negative decimal integer",
179 if (result > (UINT64_MAX - 9) / 10)
183 result += *value - '0';
185 } while (*value >= '0' && *value <= '9');
187 if (*value != '\0') {
189 static const struct {
198 { "GB", 1000000000 },
203 { "Gi", 1073741824 },
204 { "GiB", 1073741824 }
207 uint32_t multiplier = 0;
208 for (size_t i = 0; i < ARRAY_SIZE(suffixes); ++i) {
209 if (strcmp(value, suffixes[i].name) == 0) {
210 multiplier = suffixes[i].multiplier;
215 if (multiplier == 0) {
216 my_errorf("%s: Invalid suffix", value);
220 // Don't overflow here either.
221 if (result > UINT64_MAX / multiplier)
224 result *= multiplier;
231 /// Parses command line options.
233 parse_options(int argc, char **argv)
235 static const char short_opts[] = "cdkM:hqQV";
236 static const struct option long_opts[] = {
237 { "stdout", no_argument, NULL, 'c' },
238 { "to-stdout", no_argument, NULL, 'c' },
239 { "decompress", no_argument, NULL, 'd' },
240 { "uncompress", no_argument, NULL, 'd' },
241 { "keep", no_argument, NULL, 'k' },
242 { "memory", required_argument, NULL, 'M' },
243 { "quiet", no_argument, NULL, 'q' },
244 { "no-warn", no_argument, NULL, 'Q' },
245 { "help", no_argument, NULL, 'h' },
246 { "version", no_argument, NULL, 'V' },
252 while ((c = getopt_long(argc, argv, short_opts, long_opts, NULL))
262 // Support specifying the limit as a percentage of
263 // installed physical RAM.
264 const size_t len = strlen(optarg);
265 if (len > 0 && optarg[len - 1] == '%') {
266 // Memory limit is a percentage of total
268 optarg[len - 1] = '\0';
269 const uint64_t percentage
270 = str_to_uint64(optarg, 100);
271 if (percentage < 1 || percentage > 100) {
272 my_errorf("Percentage must be in "
273 "the range [1, 100]");
277 memlimit_set_percentage(percentage);
279 memlimit_set(str_to_uint64(
280 optarg, UINT64_MAX));
287 if (display_errors > 0)
308 uncompress(lzma_stream *strm, FILE *file, const char *filename)
312 // Initialize the decoder
314 ret = lzma_alone_decoder(strm, memlimit);
316 ret = lzma_stream_decoder(strm, memlimit, LZMA_CONCATENATED);
319 // The only reasonable error here is LZMA_MEM_ERROR.
320 // FIXME: Maybe also LZMA_MEMLIMIT_ERROR in future?
321 if (ret != LZMA_OK) {
322 my_errorf("%s", ret == LZMA_MEM_ERROR ? strerror(ENOMEM)
323 : "Internal program error (bug)");
327 // Input and output buffers
328 uint8_t in_buf[BUFSIZ];
329 uint8_t out_buf[BUFSIZ];
332 strm->next_out = out_buf;
333 strm->avail_out = BUFSIZ;
335 lzma_action action = LZMA_RUN;
338 if (strm->avail_in == 0) {
339 strm->next_in = in_buf;
340 strm->avail_in = fread(in_buf, 1, BUFSIZ, file);
343 // POSIX says that fread() sets errno if
344 // an error occurred. ferror() doesn't
346 my_errorf("%s: Error reading input file: %s",
347 filename, strerror(errno));
352 // When using LZMA_CONCATENATED, we need to tell
353 // liblzma when it has got all the input.
355 action = LZMA_FINISH;
359 ret = lzma_code(strm, action);
361 // Write and check write error before checking decoder error.
362 // This way as much data as possible gets written to output
363 // even if decoder detected an error.
364 if (strm->avail_out == 0 || ret != LZMA_OK) {
365 const size_t write_size = BUFSIZ - strm->avail_out;
367 if (fwrite(out_buf, 1, write_size, stdout)
369 // Wouldn't be a surprise if writing to stderr
370 // would fail too but at least try to show an
372 my_errorf("Cannot write to standard output: "
373 "%s", strerror(errno));
377 strm->next_out = out_buf;
378 strm->avail_out = BUFSIZ;
381 if (ret != LZMA_OK) {
382 if (ret == LZMA_STREAM_END) {
384 // Check that there's no trailing garbage.
385 if (strm->avail_in != 0
386 || fread(in_buf, 1, 1, file)
389 ret = LZMA_DATA_ERROR;
393 // lzma_stream_decoder() already guarantees
394 // that there's no trailing garbage.
395 assert(strm->avail_in == 0);
396 assert(action == LZMA_FINISH);
405 msg = strerror(ENOMEM);
408 case LZMA_MEMLIMIT_ERROR:
409 msg = "Memory usage limit reached";
412 case LZMA_FORMAT_ERROR:
413 msg = "File format not recognized";
416 case LZMA_OPTIONS_ERROR:
417 // FIXME: Better message?
418 msg = "Unsupported compression options";
421 case LZMA_DATA_ERROR:
422 msg = "File is corrupt";
426 msg = "Unexpected end of input";
430 msg = "Internal program error (bug)";
434 my_errorf("%s: %s", filename, msg);
442 main(int argc, char **argv)
444 // Set the argv0 global so that we can print the command name in
445 // error and help messages.
448 // Set the default memory usage limit. This is needed before parsing
449 // the command line arguments.
452 // Parse the command line options.
453 parse_options(argc, argv);
455 // The same lzma_stream is used for all files that we decode. This way
456 // we don't need to reallocate memory for every file if they use same
457 // compression settings.
458 lzma_stream strm = LZMA_STREAM_INIT;
460 // Some systems require setting stdin and stdout to binary mode.
462 setmode(fileno(stdin), O_BINARY);
463 setmode(fileno(stdout), O_BINARY);
466 if (optind == argc) {
467 // No filenames given, decode from stdin.
468 uncompress(&strm, stdin, "(stdin)");
470 // Loop through the filenames given on the command line.
472 // "-" indicates stdin.
473 if (strcmp(argv[optind], "-") == 0) {
474 uncompress(&strm, stdin, "(stdin)");
476 FILE *file = fopen(argv[optind], "rb");
478 my_errorf("%s: %s", argv[optind],
483 uncompress(&strm, file, argv[optind]);
486 } while (++optind < argc);
490 // Free the memory only when debugging. Freeing wastes some time,
491 // but allows detecting possible memory leaks with Valgrind.