]> icculus.org git repositories - icculus/xz.git/blob - src/xz/coder.c
Add missing error check to coder.c.
[icculus/xz.git] / src / xz / coder.c
1 ///////////////////////////////////////////////////////////////////////////////
2 //
3 /// \file       coder.c
4 /// \brief      Compresses or uncompresses a file
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 "private.h"
14
15
16 /// Return value type for coder_init().
17 enum coder_init_ret {
18         CODER_INIT_NORMAL,
19         CODER_INIT_PASSTHRU,
20         CODER_INIT_ERROR,
21 };
22
23
24 enum operation_mode opt_mode = MODE_COMPRESS;
25
26 enum format_type opt_format = FORMAT_AUTO;
27
28
29 /// Stream used to communicate with liblzma
30 static lzma_stream strm = LZMA_STREAM_INIT;
31
32 /// Filters needed for all encoding all formats, and also decoding in raw data
33 static lzma_filter filters[LZMA_FILTERS_MAX + 1];
34
35 /// Input and output buffers
36 static io_buf in_buf;
37 static io_buf out_buf;
38
39 /// Number of filters. Zero indicates that we are using a preset.
40 static size_t filters_count = 0;
41
42 /// Number of the preset (0-9)
43 static size_t preset_number = 6;
44
45 /// True if we should auto-adjust the compression settings to use less memory
46 /// if memory usage limit is too low for the original settings.
47 static bool auto_adjust = true;
48
49 /// Indicate if no preset has been explicitly given. In that case, if we need
50 /// to auto-adjust for lower memory usage, we won't print a warning.
51 static bool preset_default = true;
52
53 /// If a preset is used (no custom filter chain) and preset_extreme is true,
54 /// a significantly slower compression is used to achieve slightly better
55 /// compression ratio.
56 static bool preset_extreme = false;
57
58 /// Integrity check type
59 #ifdef HAVE_CHECK_CRC64
60 static lzma_check check = LZMA_CHECK_CRC64;
61 #else
62 static lzma_check check = LZMA_CHECK_CRC32;
63 #endif
64
65
66 extern void
67 coder_set_check(lzma_check new_check)
68 {
69         check = new_check;
70         return;
71 }
72
73
74 extern void
75 coder_set_preset(size_t new_preset)
76 {
77         preset_number = new_preset;
78         preset_default = false;
79         return;
80 }
81
82
83 extern void
84 coder_set_extreme(void)
85 {
86         preset_extreme = true;
87         return;
88 }
89
90
91 extern void
92 coder_add_filter(lzma_vli id, void *options)
93 {
94         if (filters_count == LZMA_FILTERS_MAX)
95                 message_fatal(_("Maximum number of filters is four"));
96
97         filters[filters_count].id = id;
98         filters[filters_count].options = options;
99         ++filters_count;
100
101         return;
102 }
103
104
105 static void lzma_attribute((noreturn))
106 memlimit_too_small(uint64_t memory_usage, uint64_t memory_limit)
107 {
108         message_fatal(_("Memory usage limit (%" PRIu64 " MiB) is too small "
109                         "for the given filter setup (%" PRIu64 " MiB)"),
110                         memory_limit >> 20, memory_usage >> 20);
111 }
112
113
114 extern void
115 coder_set_compression_settings(void)
116 {
117         // Options for LZMA1 or LZMA2 in case we are using a preset.
118         static lzma_options_lzma opt_lzma;
119
120         if (filters_count == 0) {
121                 // We are using a preset. This is not a good idea in raw mode
122                 // except when playing around with things. Different versions
123                 // of this software may use different options in presets, and
124                 // thus make uncompressing the raw data difficult.
125                 if (opt_format == FORMAT_RAW) {
126                         // The message is shown only if warnings are allowed
127                         // but the exit status isn't changed.
128                         message(V_WARNING, _("Using a preset in raw mode "
129                                         "is discouraged."));
130                         message(V_WARNING, _("The exact options of the "
131                                         "presets may vary between software "
132                                         "versions."));
133                 }
134
135                 // Get the preset for LZMA1 or LZMA2.
136                 if (preset_extreme)
137                         preset_number |= LZMA_PRESET_EXTREME;
138
139                 if (lzma_lzma_preset(&opt_lzma, preset_number))
140                         message_bug();
141
142                 // Use LZMA2 except with --format=lzma we use LZMA1.
143                 filters[0].id = opt_format == FORMAT_LZMA
144                                 ? LZMA_FILTER_LZMA1 : LZMA_FILTER_LZMA2;
145                 filters[0].options = &opt_lzma;
146                 filters_count = 1;
147         } else {
148                 preset_default = false;
149         }
150
151         // Terminate the filter options array.
152         filters[filters_count].id = LZMA_VLI_UNKNOWN;
153
154         // If we are using the .lzma format, allow exactly one filter
155         // which has to be LZMA1.
156         if (opt_format == FORMAT_LZMA && (filters_count != 1
157                         || filters[0].id != LZMA_FILTER_LZMA1))
158                 message_fatal(_("The .lzma format supports only "
159                                 "the LZMA1 filter"));
160
161         // If we are using the .xz format, make sure that there is no LZMA1
162         // filter to prevent LZMA_PROG_ERROR.
163         if (opt_format == FORMAT_XZ)
164                 for (size_t i = 0; i < filters_count; ++i)
165                         if (filters[i].id == LZMA_FILTER_LZMA1)
166                                 message_fatal(_("LZMA1 cannot be used "
167                                                 "with the .xz format"));
168
169         // Print the selected filter chain.
170         message_filters(V_DEBUG, filters);
171
172         // If using --format=raw, we can be decoding. The memusage function
173         // also validates the filter chain and the options used for the
174         // filters.
175         const uint64_t memory_limit = hardware_memlimit_get();
176         uint64_t memory_usage;
177         if (opt_mode == MODE_COMPRESS)
178                 memory_usage = lzma_raw_encoder_memusage(filters);
179         else
180                 memory_usage = lzma_raw_decoder_memusage(filters);
181
182         if (memory_usage == UINT64_MAX)
183                 message_fatal("Unsupported filter chain or filter options");
184
185         // Print memory usage info.
186         message(V_DEBUG, _("%s MiB (%s B) of memory is required per thread, "
187                         "limit is %s MiB (%s B)"),
188                         uint64_to_str(memory_usage >> 20, 0),
189                         uint64_to_str(memory_usage, 1),
190                         uint64_to_str(memory_limit >> 20, 2),
191                         uint64_to_str(memory_limit, 3));
192
193         if (memory_usage > memory_limit) {
194                 // If --no-auto-adjust was used or we didn't find LZMA1 or
195                 // LZMA2 as the last filter, give an error immediatelly.
196                 // --format=raw implies --no-auto-adjust.
197                 if (!auto_adjust || opt_format == FORMAT_RAW)
198                         memlimit_too_small(memory_usage, memory_limit);
199
200                 assert(opt_mode == MODE_COMPRESS);
201
202                 // Look for the last filter if it is LZMA2 or LZMA1, so
203                 // we can make it use less RAM. With other filters we don't
204                 // know what to do.
205                 size_t i = 0;
206                 while (filters[i].id != LZMA_FILTER_LZMA2
207                                 && filters[i].id != LZMA_FILTER_LZMA1) {
208                         if (filters[i].id == LZMA_VLI_UNKNOWN)
209                                 memlimit_too_small(memory_usage, memory_limit);
210
211                         ++i;
212                 }
213
214                 // Decrease the dictionary size until we meet the memory
215                 // usage limit. First round down to full mebibytes.
216                 lzma_options_lzma *opt = filters[i].options;
217                 const uint32_t orig_dict_size = opt->dict_size;
218                 opt->dict_size &= ~((UINT32_C(1) << 20) - 1);
219                 while (true) {
220                         // If it is below 1 MiB, auto-adjusting failed. We
221                         // could be more sophisticated and scale it down even
222                         // more, but let's see if many complain about this
223                         // version.
224                         //
225                         // FIXME: Displays the scaled memory usage instead
226                         // of the original.
227                         if (opt->dict_size < (UINT32_C(1) << 20))
228                                 memlimit_too_small(memory_usage, memory_limit);
229
230                         memory_usage = lzma_raw_encoder_memusage(filters);
231                         if (memory_usage == UINT64_MAX)
232                                 message_bug();
233
234                         // Accept it if it is low enough.
235                         if (memory_usage <= memory_limit)
236                                 break;
237
238                         // Otherwise 1 MiB down and try again. I hope this
239                         // isn't too slow method for cases where the original
240                         // dict_size is very big.
241                         opt->dict_size -= UINT32_C(1) << 20;
242                 }
243
244                 // Tell the user that we decreased the dictionary size.
245                 // However, omit the message if no preset or custom chain
246                 // was given. FIXME: Always warn?
247                 if (!preset_default)
248                         message(V_WARNING, "Adjusted LZMA%c dictionary size "
249                                         "from %s MiB to %s MiB to not exceed "
250                                         "the memory usage limit of %s MiB",
251                                         filters[i].id == LZMA_FILTER_LZMA2
252                                                 ? '2' : '1',
253                                         uint64_to_str(orig_dict_size >> 20, 0),
254                                         uint64_to_str(opt->dict_size >> 20, 1),
255                                         uint64_to_str(memory_limit >> 20, 2));
256         }
257
258 /*
259         // Limit the number of worker threads so that memory usage
260         // limit isn't exceeded.
261         assert(memory_usage > 0);
262         size_t thread_limit = memory_limit / memory_usage;
263         if (thread_limit == 0)
264                 thread_limit = 1;
265
266         if (opt_threads > thread_limit)
267                 opt_threads = thread_limit;
268 */
269
270         return;
271 }
272
273
274 /// Return true if the data in in_buf seems to be in the .xz format.
275 static bool
276 is_format_xz(void)
277 {
278         return strm.avail_in >= 6 && memcmp(in_buf.u8, "\3757zXZ", 6) == 0;
279 }
280
281
282 /// Return true if the data in in_buf seems to be in the .lzma format.
283 static bool
284 is_format_lzma(void)
285 {
286         // The .lzma header is 13 bytes.
287         if (strm.avail_in < 13)
288                 return false;
289
290         // Decode the LZMA1 properties.
291         lzma_filter filter = { .id = LZMA_FILTER_LZMA1 };
292         if (lzma_properties_decode(&filter, NULL, in_buf.u8, 5) != LZMA_OK)
293                 return false;
294
295         // A hack to ditch tons of false positives: We allow only dictionary
296         // sizes that are 2^n or 2^n + 2^(n-1) or UINT32_MAX. LZMA_Alone
297         // created only files with 2^n, but accepts any dictionary size.
298         // If someone complains, this will be reconsidered.
299         lzma_options_lzma *opt = filter.options;
300         const uint32_t dict_size = opt->dict_size;
301         free(opt);
302
303         if (dict_size != UINT32_MAX) {
304                 uint32_t d = dict_size - 1;
305                 d |= d >> 2;
306                 d |= d >> 3;
307                 d |= d >> 4;
308                 d |= d >> 8;
309                 d |= d >> 16;
310                 ++d;
311                 if (d != dict_size || dict_size == 0)
312                         return false;
313         }
314
315         // Another hack to ditch false positives: Assume that if the
316         // uncompressed size is known, it must be less than 256 GiB.
317         // Again, if someone complains, this will be reconsidered.
318         uint64_t uncompressed_size = 0;
319         for (size_t i = 0; i < 8; ++i)
320                 uncompressed_size |= (uint64_t)(in_buf.u8[5 + i]) << (i * 8);
321
322         if (uncompressed_size != UINT64_MAX
323                         && uncompressed_size > (UINT64_C(1) << 38))
324                 return false;
325
326         return true;
327 }
328
329
330 /// Detect the input file type (for now, this done only when decompressing),
331 /// and initialize an appropriate coder. Return value indicates if a normal
332 /// liblzma-based coder was initialized (CODER_INIT_NORMAL), if passthru
333 /// mode should be used (CODER_INIT_PASSTHRU), or if an error occurred
334 /// (CODER_INIT_ERROR).
335 static enum coder_init_ret
336 coder_init(file_pair *pair)
337 {
338         lzma_ret ret = LZMA_PROG_ERROR;
339
340         if (opt_mode == MODE_COMPRESS) {
341                 switch (opt_format) {
342                 case FORMAT_AUTO:
343                         // args.c ensures this.
344                         assert(0);
345                         break;
346
347                 case FORMAT_XZ:
348                         ret = lzma_stream_encoder(&strm, filters, check);
349                         break;
350
351                 case FORMAT_LZMA:
352                         ret = lzma_alone_encoder(&strm, filters[0].options);
353                         break;
354
355                 case FORMAT_RAW:
356                         ret = lzma_raw_encoder(&strm, filters);
357                         break;
358                 }
359         } else {
360                 const uint32_t flags = LZMA_TELL_UNSUPPORTED_CHECK
361                                 | LZMA_CONCATENATED;
362
363                 // We abuse FORMAT_AUTO to indicate unknown file format,
364                 // for which we may consider passthru mode.
365                 enum format_type init_format = FORMAT_AUTO;
366
367                 switch (opt_format) {
368                 case FORMAT_AUTO:
369                         if (is_format_xz())
370                                 init_format = FORMAT_XZ;
371                         else if (is_format_lzma())
372                                 init_format = FORMAT_LZMA;
373                         break;
374
375                 case FORMAT_XZ:
376                         if (is_format_xz())
377                                 init_format = FORMAT_XZ;
378                         break;
379
380                 case FORMAT_LZMA:
381                         if (is_format_lzma())
382                                 init_format = FORMAT_LZMA;
383                         break;
384
385                 case FORMAT_RAW:
386                         init_format = FORMAT_RAW;
387                         break;
388                 }
389
390                 switch (init_format) {
391                 case FORMAT_AUTO:
392                         // Uknown file format. If --decompress --stdout
393                         // --force have been given, then we copy the input
394                         // as is to stdout. Checking for MODE_DECOMPRESS
395                         // is needed, because we don't want to do use
396                         // passthru mode with --test.
397                         if (opt_mode == MODE_DECOMPRESS
398                                         && opt_stdout && opt_force)
399                                 return CODER_INIT_PASSTHRU;
400
401                         ret = LZMA_FORMAT_ERROR;
402                         break;
403
404                 case FORMAT_XZ:
405                         ret = lzma_stream_decoder(&strm,
406                                         hardware_memlimit_get(), flags);
407                         break;
408
409                 case FORMAT_LZMA:
410                         ret = lzma_alone_decoder(&strm,
411                                         hardware_memlimit_get());
412                         break;
413
414                 case FORMAT_RAW:
415                         // Memory usage has already been checked in
416                         // coder_set_compression_settings().
417                         ret = lzma_raw_decoder(&strm, filters);
418                         break;
419                 }
420         }
421
422         if (ret != LZMA_OK) {
423                 message_error("%s: %s", pair->src_name, message_strm(ret));
424                 return CODER_INIT_ERROR;
425         }
426
427         return CODER_INIT_NORMAL;
428 }
429
430
431 /// Compress or decompress using liblzma.
432 static bool
433 coder_normal(file_pair *pair)
434 {
435         // Encoder needs to know when we have given all the input to it.
436         // The decoders need to know it too when we are using
437         // LZMA_CONCATENATED. We need to check for src_eof here, because
438         // the first input chunk has been already read, and that may
439         // have been the only chunk we will read.
440         lzma_action action = pair->src_eof ? LZMA_FINISH : LZMA_RUN;
441
442         lzma_ret ret;
443
444         // Assume that something goes wrong.
445         bool success = false;
446
447         strm.next_out = out_buf.u8;
448         strm.avail_out = IO_BUFFER_SIZE;
449
450         while (!user_abort) {
451                 // Fill the input buffer if it is empty and we haven't reached
452                 // end of file yet.
453                 if (strm.avail_in == 0 && !pair->src_eof) {
454                         strm.next_in = in_buf.u8;
455                         strm.avail_in = io_read(
456                                         pair, &in_buf, IO_BUFFER_SIZE);
457
458                         if (strm.avail_in == SIZE_MAX)
459                                 break;
460
461                         if (pair->src_eof)
462                                 action = LZMA_FINISH;
463                 }
464
465                 // Let liblzma do the actual work.
466                 ret = lzma_code(&strm, action);
467
468                 // Write out if the output buffer became full.
469                 if (strm.avail_out == 0) {
470                         if (opt_mode != MODE_TEST && io_write(pair, &out_buf,
471                                         IO_BUFFER_SIZE - strm.avail_out))
472                                 break;
473
474                         strm.next_out = out_buf.u8;
475                         strm.avail_out = IO_BUFFER_SIZE;
476                 }
477
478                 if (ret != LZMA_OK) {
479                         // Determine if the return value indicates that we
480                         // won't continue coding.
481                         const bool stop = ret != LZMA_NO_CHECK
482                                         && ret != LZMA_UNSUPPORTED_CHECK;
483
484                         if (stop) {
485                                 // Write the remaining bytes even if something
486                                 // went wrong, because that way the user gets
487                                 // as much data as possible, which can be good
488                                 // when trying to get at least some useful
489                                 // data out of damaged files.
490                                 if (opt_mode != MODE_TEST && io_write(pair,
491                                                 &out_buf, IO_BUFFER_SIZE
492                                                         - strm.avail_out))
493                                         break;
494                         }
495
496                         if (ret == LZMA_STREAM_END) {
497                                 // Check that there is no trailing garbage.
498                                 // This is needed for LZMA_Alone and raw
499                                 // streams.
500                                 if (strm.avail_in == 0 && !pair->src_eof) {
501                                         // Try reading one more byte.
502                                         // Hopefully we don't get any more
503                                         // input, and thus pair->src_eof
504                                         // becomes true.
505                                         strm.avail_in = io_read(
506                                                         pair, &in_buf, 1);
507                                         if (strm.avail_in == SIZE_MAX)
508                                                 break;
509
510                                         assert(strm.avail_in == 0
511                                                         || strm.avail_in == 1);
512                                 }
513
514                                 if (strm.avail_in == 0) {
515                                         assert(pair->src_eof);
516                                         success = true;
517                                         break;
518                                 }
519
520                                 // We hadn't reached the end of the file.
521                                 ret = LZMA_DATA_ERROR;
522                                 assert(stop);
523                         }
524
525                         // If we get here and stop is true, something went
526                         // wrong and we print an error. Otherwise it's just
527                         // a warning and coding can continue.
528                         if (stop) {
529                                 message_error("%s: %s", pair->src_name,
530                                                 message_strm(ret));
531                         } else {
532                                 message_warning("%s: %s", pair->src_name,
533                                                 message_strm(ret));
534
535                                 // When compressing, all possible errors set
536                                 // stop to true.
537                                 assert(opt_mode != MODE_COMPRESS);
538                         }
539
540                         if (ret == LZMA_MEMLIMIT_ERROR) {
541                                 // Figure out how much memory it would have
542                                 // actually needed.
543                                 uint64_t memusage = lzma_memusage(&strm);
544                                 uint64_t memlimit = hardware_memlimit_get();
545
546                                 // Round the memory limit down and usage up.
547                                 // This way we don't display a ridiculous
548                                 // message like "Limit was 9 MiB, but 9 MiB
549                                 // would have been needed".
550                                 memusage = (memusage + 1024 * 1024 - 1)
551                                                 / (1024 * 1024);
552                                 memlimit /= 1024 * 1024;
553
554                                 message_error(_("Limit was %s MiB, "
555                                                 "but %s MiB would "
556                                                 "have been needed"),
557                                                 uint64_to_str(memlimit, 0),
558                                                 uint64_to_str(memusage, 1));
559                         }
560
561                         if (stop)
562                                 break;
563                 }
564
565                 // Show progress information under certain conditions.
566                 message_progress_update();
567         }
568
569         return success;
570 }
571
572
573 /// Copy from input file to output file without processing the data in any
574 /// way. This is used only when trying to decompress unrecognized files
575 /// with --decompress --stdout --force, so the output is always stdout.
576 static bool
577 coder_passthru(file_pair *pair)
578 {
579         while (strm.avail_in != 0) {
580                 if (user_abort)
581                         return false;
582
583                 if (io_write(pair, &in_buf, strm.avail_in))
584                         return false;
585
586                 strm.total_in += strm.avail_in;
587                 strm.total_out = strm.total_in;
588                 message_progress_update();
589
590                 strm.avail_in = io_read(pair, &in_buf, IO_BUFFER_SIZE);
591                 if (strm.avail_in == SIZE_MAX)
592                         return false;
593         }
594
595         return true;
596 }
597
598
599 extern void
600 coder_run(const char *filename)
601 {
602         // Try to open the input and output files.
603         file_pair *pair = io_open(filename);
604         if (pair == NULL)
605                 return;
606
607         // Initialize the progress indicator.
608         const uint64_t in_size = pair->src_st.st_size <= (off_t)(0)
609                         ? 0 : (uint64_t)(pair->src_st.st_size);
610         message_progress_start(&strm, pair->src_name, in_size);
611
612         // Assume that something goes wrong.
613         bool success = false;
614
615         // Read the first chunk of input data. This is needed to detect
616         // the input file type (for now, only for decompression).
617         strm.next_in = in_buf.u8;
618         strm.avail_in = io_read(pair, &in_buf, IO_BUFFER_SIZE);
619
620         if (strm.avail_in != SIZE_MAX) {
621                 switch (coder_init(pair)) {
622                 case CODER_INIT_NORMAL:
623                         success = coder_normal(pair);
624                         break;
625
626                 case CODER_INIT_PASSTHRU:
627                         success = coder_passthru(pair);
628                         break;
629
630                 case CODER_INIT_ERROR:
631                         break;
632                 }
633         }
634
635         message_progress_end(success);
636
637         // Close the file pair. It needs to know if coding was successful to
638         // know if the source or target file should be unlinked.
639         io_close(pair, success);
640
641         return;
642 }