]> icculus.org git repositories - icculus/xz.git/blob - src/xzdec/xzdec.c
A few grammar fixes.
[icculus/xz.git] / src / xzdec / xzdec.c
1 ///////////////////////////////////////////////////////////////////////////////
2 //
3 /// \file       xzdec.c
4 /// \brief      Simple single-threaded tool to uncompress .xz or .lzma files
5 //
6 //  Author:     Lasse Collin
7 //
8 //  This file has been put into the public domain.
9 //  You can do whatever you want with this file.
10 //
11 ///////////////////////////////////////////////////////////////////////////////
12
13 #include "sysdefs.h"
14 #include "lzma.h"
15
16 #include <stdarg.h>
17 #include <errno.h>
18 #include <stdio.h>
19 #include <unistd.h>
20
21 #ifdef DOSLIKE
22 #       include <fcntl.h>
23 #       include <io.h>
24 #endif
25
26 #include "getopt.h"
27 #include "physmem.h"
28
29
30 #ifdef LZMADEC
31 #       define TOOL_FORMAT "lzma"
32 #else
33 #       define TOOL_FORMAT "xz"
34 #endif
35
36
37 /// Number of bytes to use memory at maximum
38 static uint64_t memlimit;
39
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;
43
44 /// Program name to be shown in error messages
45 static const char *argv0;
46
47
48 static void lzma_attribute((format(printf, 1, 2)))
49 my_errorf(const char *fmt, ...)
50 {
51         va_list ap;
52         va_start(ap, fmt);
53
54         if (display_errors) {
55                 fprintf(stderr, "%s: ", argv0);
56                 vfprintf(stderr, fmt, ap);
57                 fprintf(stderr, "\n");
58         }
59
60         va_end(ap);
61         return;
62 }
63
64
65 static void lzma_attribute((noreturn))
66 my_exit(void)
67 {
68         int status = EXIT_SUCCESS;
69
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);
74
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("Writing to standard output failed: %s", fclose_err
80                                 ? strerror(errno) : "Unknown error");
81                 status = EXIT_FAILURE;
82         }
83
84         exit(status);
85 }
86
87
88 static void lzma_attribute((noreturn))
89 help(void)
90 {
91         printf(
92 "Usage: %s [OPTION]... [FILE]...\n"
93 "Uncompress files in the ." TOOL_FORMAT " format to the standard output.\n"
94 "\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"
103 "\n"
104 "With no FILE, or when FILE is -, read standard input.\n"
105 "\n"
106 "On this system and configuration, this program will use a maximum of roughly\n"
107 "%" PRIu64 " MiB RAM.\n"
108 "\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));
112         my_exit();
113 }
114
115
116 static void lzma_attribute((noreturn))
117 version(void)
118 {
119         printf(TOOL_FORMAT "dec (" PACKAGE_NAME ") " LZMA_VERSION_STRING "\n"
120                         "liblzma %s\n", lzma_version_string());
121
122         my_exit();
123 }
124
125
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.
128 static void
129 memlimit_set_percentage(uint32_t percentage)
130 {
131         uint64_t mem = physmem();
132
133         // If we cannot determine the amount of RAM, assume 32 MiB.
134         if (mem == 0)
135                 mem = UINT64_C(32) * 1024 * 1024;
136
137         memlimit = percentage * mem / 100;
138         return;
139 }
140
141
142 /// Set the memory usage limit to give number of bytes. Zero is a special
143 /// value to indicate the default limit.
144 static void
145 memlimit_set(uint64_t new_memlimit)
146 {
147         if (new_memlimit == 0)
148                 memlimit_set_percentage(40);
149         else
150                 memlimit = new_memlimit;
151
152         return;
153 }
154
155
156 /// \brief      Convert a string to uint64_t
157 ///
158 /// This is rudely copied from src/xz/util.c and modified a little. :-(
159 ///
160 /// \param      max     Return value when the string "max" was specified.
161 ///
162 static uint64_t
163 str_to_uint64(const char *value, uint64_t max)
164 {
165         uint64_t result = 0;
166
167         // Accept special value "max".
168         if (strcmp(value, "max") == 0)
169                 return max;
170
171         if (*value < '0' || *value > '9') {
172                 my_errorf("%s: Value is not a non-negative decimal integer",
173                                 value);
174                 exit(EXIT_FAILURE);
175         }
176
177         do {
178                 // Don't overflow.
179                 if (result > (UINT64_MAX - 9) / 10)
180                         return UINT64_MAX;
181
182                 result *= 10;
183                 result += *value - '0';
184                 ++value;
185         } while (*value >= '0' && *value <= '9');
186
187         if (*value != '\0') {
188                 // Look for suffix.
189                 static const struct {
190                         const char name[4];
191                         uint32_t multiplier;
192                 } suffixes[] = {
193                         { "k",   1000 },
194                         { "kB",  1000 },
195                         { "M",   1000000 },
196                         { "MB",  1000000 },
197                         { "G",   1000000000 },
198                         { "GB",  1000000000 },
199                         { "Ki",  1024 },
200                         { "KiB", 1024 },
201                         { "Mi",  1048576 },
202                         { "MiB", 1048576 },
203                         { "Gi",  1073741824 },
204                         { "GiB", 1073741824 }
205                 };
206
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;
211                                 break;
212                         }
213                 }
214
215                 if (multiplier == 0) {
216                         my_errorf("%s: Invalid suffix", value);
217                         exit(EXIT_FAILURE);
218                 }
219
220                 // Don't overflow here either.
221                 if (result > UINT64_MAX / multiplier)
222                         result = UINT64_MAX;
223                 else
224                         result *= multiplier;
225         }
226
227         return result;
228 }
229
230
231 /// Parses command line options.
232 static void
233 parse_options(int argc, char **argv)
234 {
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' },
247                 { NULL,           0,                   NULL, 0   }
248         };
249
250         int c;
251
252         while ((c = getopt_long(argc, argv, short_opts, long_opts, NULL))
253                         != -1) {
254                 switch (c) {
255                 case 'c':
256                 case 'd':
257                 case 'k':
258                 case 'Q':
259                         break;
260
261                 case 'M': {
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
267                                 // installed RAM.
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]");
274                                         exit(EXIT_FAILURE);
275                                 }
276
277                                 memlimit_set_percentage(percentage);
278                         } else {
279                                 memlimit_set(str_to_uint64(
280                                                 optarg, UINT64_MAX));
281                         }
282
283                         break;
284                 }
285
286                 case 'q':
287                         if (display_errors > 0)
288                                 --display_errors;
289
290                         break;
291
292                 case 'h':
293                         help();
294
295                 case 'V':
296                         version();
297
298                 default:
299                         exit(EXIT_FAILURE);
300                 }
301         }
302
303         return;
304 }
305
306
307 static void
308 uncompress(lzma_stream *strm, FILE *file, const char *filename)
309 {
310         lzma_ret ret;
311
312         // Initialize the decoder
313 #ifdef LZMADEC
314         ret = lzma_alone_decoder(strm, memlimit);
315 #else
316         ret = lzma_stream_decoder(strm, memlimit, LZMA_CONCATENATED);
317 #endif
318
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 error (bug)");
324                 exit(EXIT_FAILURE);
325         }
326
327         // Input and output buffers
328         uint8_t in_buf[BUFSIZ];
329         uint8_t out_buf[BUFSIZ];
330
331         strm->avail_in = 0;
332         strm->next_out = out_buf;
333         strm->avail_out = BUFSIZ;
334
335         lzma_action action = LZMA_RUN;
336
337         while (true) {
338                 if (strm->avail_in == 0) {
339                         strm->next_in = in_buf;
340                         strm->avail_in = fread(in_buf, 1, BUFSIZ, file);
341
342                         if (ferror(file)) {
343                                 // POSIX says that fread() sets errno if
344                                 // an error occurred. ferror() doesn't
345                                 // touch errno.
346                                 my_errorf("%s: Error reading input file: %s",
347                                                 filename, strerror(errno));
348                                 exit(EXIT_FAILURE);
349                         }
350
351 #ifndef LZMADEC
352                         // When using LZMA_CONCATENATED, we need to tell
353                         // liblzma when it has got all the input.
354                         if (feof(file))
355                                 action = LZMA_FINISH;
356 #endif
357                 }
358
359                 ret = lzma_code(strm, action);
360
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;
366
367                         if (fwrite(out_buf, 1, write_size, stdout)
368                                         != write_size) {
369                                 // Wouldn't be a surprise if writing to stderr
370                                 // would fail too but at least try to show an
371                                 // error message.
372                                 my_errorf("Cannot write to standard output: "
373                                                 "%s", strerror(errno));
374                                 exit(EXIT_FAILURE);
375                         }
376
377                         strm->next_out = out_buf;
378                         strm->avail_out = BUFSIZ;
379                 }
380
381                 if (ret != LZMA_OK) {
382                         if (ret == LZMA_STREAM_END) {
383 #ifdef LZMADEC
384                                 // Check that there's no trailing garbage.
385                                 if (strm->avail_in != 0
386                                                 || fread(in_buf, 1, 1, file)
387                                                         != 0
388                                                 || !feof(file))
389                                         ret = LZMA_DATA_ERROR;
390                                 else
391                                         return;
392 #else
393                                 // lzma_stream_decoder() already guarantees
394                                 // that there's no trailing garbage.
395                                 assert(strm->avail_in == 0);
396                                 assert(action == LZMA_FINISH);
397                                 assert(feof(file));
398                                 return;
399 #endif
400                         }
401
402                         const char *msg;
403                         switch (ret) {
404                         case LZMA_MEM_ERROR:
405                                 msg = strerror(ENOMEM);
406                                 break;
407
408                         case LZMA_MEMLIMIT_ERROR:
409                                 msg = "Memory usage limit reached";
410                                 break;
411
412                         case LZMA_FORMAT_ERROR:
413                                 msg = "File format not recognized";
414                                 break;
415
416                         case LZMA_OPTIONS_ERROR:
417                                 // FIXME: Better message?
418                                 msg = "Unsupported compression options";
419                                 break;
420
421                         case LZMA_DATA_ERROR:
422                                 msg = "File is corrupt";
423                                 break;
424
425                         case LZMA_BUF_ERROR:
426                                 msg = "Unexpected end of input";
427                                 break;
428
429                         default:
430                                 msg = "Internal error (bug)";
431                                 break;
432                         }
433
434                         my_errorf("%s: %s", filename, msg);
435                         exit(EXIT_FAILURE);
436                 }
437         }
438 }
439
440
441 int
442 main(int argc, char **argv)
443 {
444         // Set the argv0 global so that we can print the command name in
445         // error and help messages.
446         argv0 = argv[0];
447
448         // Set the default memory usage limit. This is needed before parsing
449         // the command line arguments.
450         memlimit_set(0);
451
452         // Parse the command line options.
453         parse_options(argc, argv);
454
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;
459
460         // Some systems require setting stdin and stdout to binary mode.
461 #ifdef DOSLIKE
462         setmode(fileno(stdin), O_BINARY);
463         setmode(fileno(stdout), O_BINARY);
464 #endif
465
466         if (optind == argc) {
467                 // No filenames given, decode from stdin.
468                 uncompress(&strm, stdin, "(stdin)");
469         } else {
470                 // Loop through the filenames given on the command line.
471                 do {
472                         // "-" indicates stdin.
473                         if (strcmp(argv[optind], "-") == 0) {
474                                 uncompress(&strm, stdin, "(stdin)");
475                         } else {
476                                 FILE *file = fopen(argv[optind], "rb");
477                                 if (file == NULL) {
478                                         my_errorf("%s: %s", argv[optind],
479                                                         strerror(errno));
480                                         exit(EXIT_FAILURE);
481                                 }
482
483                                 uncompress(&strm, file, argv[optind]);
484                                 fclose(file);
485                         }
486                 } while (++optind < argc);
487         }
488
489 #ifndef NDEBUG
490         // Free the memory only when debugging. Freeing wastes some time,
491         // but allows detecting possible memory leaks with Valgrind.
492         lzma_end(&strm);
493 #endif
494
495         my_exit();
496 }