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