1 ///////////////////////////////////////////////////////////////////////////////
4 /// \brief Compresses or uncompresses a file
6 // Copyright (C) 2007 Lasse Collin
8 // This program is free software; you can redistribute it and/or
9 // modify it under the terms of the GNU Lesser General Public
10 // License as published by the Free Software Foundation; either
11 // version 2.1 of the License, or (at your option) any later version.
13 // This program is distributed in the hope that it will be useful,
14 // but WITHOUT ANY WARRANTY; without even the implied warranty of
15 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
16 // Lesser General Public License for more details.
18 ///////////////////////////////////////////////////////////////////////////////
23 enum operation_mode opt_mode = MODE_COMPRESS;
25 enum format_type opt_format = FORMAT_AUTO;
28 /// Stream used to communicate with liblzma
29 static lzma_stream strm = LZMA_STREAM_INIT;
31 /// Filters needed for all encoding all formats, and also decoding in raw data
32 static lzma_filter filters[LZMA_FILTERS_MAX + 1];
34 /// Number of filters. Zero indicates that we are using a preset.
35 static size_t filters_count = 0;
37 /// Number of the preset (1-9)
38 static size_t preset_number = 7;
40 /// Indicate if no preset has been given. In that case, we will auto-adjust
41 /// the compression preset so that it doesn't use too much RAM.
43 static bool preset_default = true;
45 /// Integrity check type
46 static lzma_check check = LZMA_CHECK_CRC64;
50 coder_set_check(lzma_check new_check)
58 coder_set_preset(size_t new_preset)
60 preset_number = new_preset;
61 preset_default = false;
67 coder_add_filter(lzma_vli id, void *options)
69 if (filters_count == LZMA_FILTERS_MAX)
70 message_fatal(_("Maximum number of filters is four"));
72 filters[filters_count].id = id;
73 filters[filters_count].options = options;
81 coder_set_compression_settings(void)
83 // Options for LZMA1 or LZMA2 in case we are using a preset.
84 static lzma_options_lzma opt_lzma;
86 if (filters_count == 0) {
87 // We are using a preset. This is not a good idea in raw mode
88 // except when playing around with things. Different versions
89 // of this software may use different options in presets, and
90 // thus make uncompressing the raw data difficult.
91 if (opt_format == FORMAT_RAW) {
92 // The message is shown only if warnings are allowed
93 // but the exit status isn't changed.
94 message(V_WARNING, _("Using a preset in raw mode "
96 message(V_WARNING, _("The exact options of the "
97 "presets may vary between software "
101 // Get the preset for LZMA1 or LZMA2.
102 if (lzma_lzma_preset(&opt_lzma, preset_number))
105 // Use LZMA2 except with --format=lzma we use LZMA1.
106 filters[0].id = opt_format == FORMAT_LZMA
107 ? LZMA_FILTER_LZMA1 : LZMA_FILTER_LZMA2;
108 filters[0].options = &opt_lzma;
112 // Terminate the filter options array.
113 filters[filters_count].id = LZMA_VLI_UNKNOWN;
115 // If we are using the LZMA_Alone format, allow exactly one filter
116 // which has to be LZMA.
117 if (opt_format == FORMAT_LZMA && (filters_count != 1
118 || filters[0].id != LZMA_FILTER_LZMA1))
119 message_fatal(_("With --format=lzma only the LZMA1 filter "
122 // Print the selected filter chain.
123 message_filters(V_DEBUG, filters);
125 // If using --format=raw, we can be decoding. The memusage function
126 // also validates the filter chain and the options used for the
128 uint64_t memory_usage;
129 uint64_t memory_limit;
130 if (opt_mode == MODE_COMPRESS) {
131 memory_usage = lzma_memusage_encoder(filters);
132 memory_limit = hardware_memlimit_encoder();
134 memory_usage = lzma_memusage_decoder(filters);
135 memory_limit = hardware_memlimit_decoder();
138 if (memory_usage == UINT64_MAX)
139 message_fatal("Unsupported filter chain or filter options");
141 // Print memory usage info.
142 message(V_DEBUG, _("%" PRIu64 " MiB of memory is required per thread, "
143 "limit is %" PRIu64 " MiB"),
144 memory_usage / (1024 * 1024),
145 memory_limit / (1024 * 1024));
147 if (preset_default) {
148 // When no preset was explicitly requested, we use the default
149 // preset only if the memory usage limit allows. Otherwise we
150 // select a lower preset automatically.
151 while (memory_usage > memory_limit) {
152 if (preset_number == 1)
153 message_fatal(_("Memory usage limit is too "
154 "small for any internal "
157 if (lzma_lzma_preset(&opt_lzma, --preset_number))
160 memory_usage = lzma_memusage_encoder(filters);
163 if (memory_usage > memory_limit)
164 message_fatal(_("Memory usage limit is too small "
165 "for the given filter setup"));
168 // Limit the number of worker threads so that memory usage
169 // limit isn't exceeded.
170 assert(memory_usage > 0);
171 size_t thread_limit = memory_limit / memory_usage;
172 if (thread_limit == 0)
175 if (opt_threads > thread_limit)
176 opt_threads = thread_limit;
185 lzma_ret ret = LZMA_PROG_ERROR;
187 if (opt_mode == MODE_COMPRESS) {
188 switch (opt_format) {
190 // args.c ensures this.
195 ret = lzma_stream_encoder(&strm, filters, check);
199 ret = lzma_alone_encoder(&strm, filters[0].options);
203 ret = lzma_raw_encoder(&strm, filters);
207 const uint32_t flags = LZMA_TELL_UNSUPPORTED_CHECK
210 switch (opt_format) {
212 ret = lzma_auto_decoder(&strm,
213 hardware_memlimit_decoder(), flags);
217 ret = lzma_stream_decoder(&strm,
218 hardware_memlimit_decoder(), flags);
222 ret = lzma_alone_decoder(&strm,
223 hardware_memlimit_decoder());
227 // Memory usage has already been checked in args.c.
229 ret = lzma_raw_decoder(&strm, filters);
234 if (ret != LZMA_OK) {
235 if (ret == LZMA_MEM_ERROR)
236 message_error("%s", message_strm(LZMA_MEM_ERROR));
248 coder_run(file_pair *pair)
250 // Buffers to hold input and output data.
251 uint8_t in_buf[IO_BUFFER_SIZE];
252 uint8_t out_buf[IO_BUFFER_SIZE];
254 // Initialize the progress indicator.
255 const uint64_t in_size = pair->src_st.st_size <= (off_t)(0)
256 ? 0 : (uint64_t)(pair->src_st.st_size);
257 message_progress_start(pair->src_name, in_size);
259 lzma_action action = LZMA_RUN;
263 strm.next_out = out_buf;
264 strm.avail_out = IO_BUFFER_SIZE;
266 while (!user_abort) {
267 // Fill the input buffer if it is empty and we haven't reached
269 if (strm.avail_in == 0 && !pair->src_eof) {
270 strm.next_in = in_buf;
271 strm.avail_in = io_read(pair, in_buf, IO_BUFFER_SIZE);
273 if (strm.avail_in == SIZE_MAX)
276 // Encoder needs to know when we have given all the
277 // input to it. The decoders need to know it too when
278 // we are using LZMA_CONCATENATED.
280 action = LZMA_FINISH;
283 // Let liblzma do the actual work.
284 ret = lzma_code(&strm, action);
286 // Write out if the output buffer became full.
287 if (strm.avail_out == 0) {
288 if (opt_mode != MODE_TEST && io_write(pair, out_buf,
289 IO_BUFFER_SIZE - strm.avail_out))
292 strm.next_out = out_buf;
293 strm.avail_out = IO_BUFFER_SIZE;
296 if (ret != LZMA_OK) {
297 // Determine if the return value indicates that we
298 // won't continue coding.
299 const bool stop = ret != LZMA_NO_CHECK
300 && ret != LZMA_UNSUPPORTED_CHECK;
303 // First print the final progress info.
304 // This way the user sees more accurately
305 // where the error occurred. Note that we
306 // print this *before* the possible error
309 // FIXME: What if something goes wrong
311 message_progress_end(strm.total_in,
313 ret == LZMA_STREAM_END);
315 // Write the remaining bytes even if something
316 // went wrong, because that way the user gets
317 // as much data as possible, which can be good
318 // when trying to get at least some useful
319 // data out of damaged files.
320 if (opt_mode != MODE_TEST && io_write(pair,
321 out_buf, IO_BUFFER_SIZE
326 if (ret == LZMA_STREAM_END) {
327 // Check that there is no trailing garbage.
328 // This is needed for LZMA_Alone and raw
330 if (strm.avail_in == 0 && (pair->src_eof
331 || io_read(pair, in_buf, 1)
333 assert(pair->src_eof);
337 // FIXME: What about io_read() failing?
339 // We hadn't reached the end of the file.
340 ret = LZMA_DATA_ERROR;
344 // If we get here and stop is true, something went
345 // wrong and we print an error. Otherwise it's just
346 // a warning and coding can continue.
348 message_error("%s: %s", pair->src_name,
351 message_warning("%s: %s", pair->src_name,
354 // When compressing, all possible errors set
356 assert(opt_mode != MODE_COMPRESS);
359 if (ret == LZMA_MEMLIMIT_ERROR) {
360 // Figure out how much memory it would have
362 uint64_t memusage = lzma_memusage(&strm);
364 = hardware_memlimit_decoder();
366 // Round the memory limit down and usage up.
367 // This way we don't display a ridiculous
368 // message like "Limit was 9 MiB, but 9 MiB
369 // would have been needed".
370 memusage = (memusage + 1024 * 1024 - 1)
372 memlimit /= 1024 * 1024;
374 message_error(_("Limit was %'" PRIu64 " MiB, "
375 "but %'" PRIu64 " MiB would "
384 // Show progress information if --verbose was specified and
385 // stderr is a terminal.
386 message_progress_update(strm.total_in, strm.total_out);
394 process_file(const char *filename)
396 // First try initializing the coder. If it fails, it's useless to try
397 // opening the file. Check also for user_abort just in case if we had
398 // got a signal while initializing the coder.
399 if (coder_init() || user_abort)
402 // Try to open the input and output files.
403 file_pair *pair = io_open(filename);
407 // Do the actual coding.
408 const bool success = coder_run(pair);
410 // Close the file pair. It needs to know if coding was successful to
411 // know if the source or target file should be unlinked.
412 io_close(pair, success);