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