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