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