]> icculus.org git repositories - icculus/xz.git/blob - src/xz/process.c
Put the interesting parts of XZ Utils into the public domain.
[icculus/xz.git] / src / xz / process.c
1 ///////////////////////////////////////////////////////////////////////////////
2 //
3 /// \file       process.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 enum operation_mode opt_mode = MODE_COMPRESS;
17
18 enum format_type opt_format = FORMAT_AUTO;
19
20
21 /// Stream used to communicate with liblzma
22 static lzma_stream strm = LZMA_STREAM_INIT;
23
24 /// Filters needed for all encoding all formats, and also decoding in raw data
25 static lzma_filter filters[LZMA_FILTERS_MAX + 1];
26
27 /// Number of filters. Zero indicates that we are using a preset.
28 static size_t filters_count = 0;
29
30 /// Number of the preset (0-9)
31 static size_t preset_number = 6;
32
33 /// True if we should auto-adjust the compression settings to use less memory
34 /// if memory usage limit is too low for the original settings.
35 static bool auto_adjust = true;
36
37 /// Indicate if no preset has been explicitly given. In that case, if we need
38 /// to auto-adjust for lower memory usage, we won't print a warning.
39 static bool preset_default = true;
40
41 /// If a preset is used (no custom filter chain) and preset_extreme is true,
42 /// a significantly slower compression is used to achieve slightly better
43 /// compression ratio.
44 static bool preset_extreme = false;
45
46 /// Integrity check type
47 #ifdef HAVE_CHECK_CRC64
48 static lzma_check check = LZMA_CHECK_CRC64;
49 #else
50 static lzma_check check = LZMA_CHECK_CRC32;
51 #endif
52
53
54 extern void
55 coder_set_check(lzma_check new_check)
56 {
57         check = new_check;
58         return;
59 }
60
61
62 extern void
63 coder_set_preset(size_t new_preset)
64 {
65         preset_number = new_preset;
66         preset_default = false;
67         return;
68 }
69
70
71 extern void
72 coder_set_extreme(void)
73 {
74         preset_extreme = true;
75         return;
76 }
77
78
79 extern void
80 coder_add_filter(lzma_vli id, void *options)
81 {
82         if (filters_count == LZMA_FILTERS_MAX)
83                 message_fatal(_("Maximum number of filters is four"));
84
85         filters[filters_count].id = id;
86         filters[filters_count].options = options;
87         ++filters_count;
88
89         return;
90 }
91
92
93 static void lzma_attribute((noreturn))
94 memlimit_too_small(uint64_t memory_usage, uint64_t memory_limit)
95 {
96         message_fatal(_("Memory usage limit (%" PRIu64 " MiB) is too small "
97                         "for the given filter setup (%" PRIu64 " MiB)"),
98                         memory_limit >> 20, memory_usage >> 20);
99 }
100
101
102 extern void
103 coder_set_compression_settings(void)
104 {
105         // Options for LZMA1 or LZMA2 in case we are using a preset.
106         static lzma_options_lzma opt_lzma;
107
108         if (filters_count == 0) {
109                 // We are using a preset. This is not a good idea in raw mode
110                 // except when playing around with things. Different versions
111                 // of this software may use different options in presets, and
112                 // thus make uncompressing the raw data difficult.
113                 if (opt_format == FORMAT_RAW) {
114                         // The message is shown only if warnings are allowed
115                         // but the exit status isn't changed.
116                         message(V_WARNING, _("Using a preset in raw mode "
117                                         "is discouraged."));
118                         message(V_WARNING, _("The exact options of the "
119                                         "presets may vary between software "
120                                         "versions."));
121                 }
122
123                 // Get the preset for LZMA1 or LZMA2.
124                 if (preset_extreme)
125                         preset_number |= LZMA_PRESET_EXTREME;
126
127                 if (lzma_lzma_preset(&opt_lzma, preset_number))
128                         message_bug();
129
130                 // Use LZMA2 except with --format=lzma we use LZMA1.
131                 filters[0].id = opt_format == FORMAT_LZMA
132                                 ? LZMA_FILTER_LZMA1 : LZMA_FILTER_LZMA2;
133                 filters[0].options = &opt_lzma;
134                 filters_count = 1;
135         } else {
136                 preset_default = false;
137         }
138
139         // Terminate the filter options array.
140         filters[filters_count].id = LZMA_VLI_UNKNOWN;
141
142         // If we are using the LZMA_Alone format, allow exactly one filter
143         // which has to be LZMA.
144         if (opt_format == FORMAT_LZMA && (filters_count != 1
145                         || filters[0].id != LZMA_FILTER_LZMA1))
146                 message_fatal(_("With --format=lzma only the LZMA1 filter "
147                                 "is supported"));
148
149         // Print the selected filter chain.
150         message_filters(V_DEBUG, filters);
151
152         // If using --format=raw, we can be decoding. The memusage function
153         // also validates the filter chain and the options used for the
154         // filters.
155         uint64_t memory_usage;
156         uint64_t memory_limit;
157         if (opt_mode == MODE_COMPRESS) {
158                 memory_usage = lzma_raw_encoder_memusage(filters);
159                 memory_limit = hardware_memlimit_encoder();
160         } else {
161                 memory_usage = lzma_raw_decoder_memusage(filters);
162                 memory_limit = hardware_memlimit_decoder();
163         }
164
165         if (memory_usage == UINT64_MAX)
166                 message_fatal("Unsupported filter chain or filter options");
167
168         // Print memory usage info.
169         message(V_DEBUG, _("%'" PRIu64 " MiB (%'" PRIu64 " B) of memory is "
170                         "required per thread, "
171                         "limit is %'" PRIu64 " MiB (%'" PRIu64 " B)"),
172                         memory_usage >> 20, memory_usage,
173                         memory_limit >> 20, memory_limit);
174
175         if (memory_usage > memory_limit) {
176                 // If --no-auto-adjust was used or we didn't find LZMA1 or
177                 // LZMA2 as the last filter, give an error immediatelly.
178                 // --format=raw implies --no-auto-adjust.
179                 if (!auto_adjust || opt_format == FORMAT_RAW)
180                         memlimit_too_small(memory_usage, memory_limit);
181
182                 assert(opt_mode == MODE_COMPRESS);
183
184                 // Look for the last filter if it is LZMA2 or LZMA1, so
185                 // we can make it use less RAM. With other filters we don't
186                 // know what to do.
187                 size_t i = 0;
188                 while (filters[i].id != LZMA_FILTER_LZMA2
189                                 && filters[i].id != LZMA_FILTER_LZMA1) {
190                         if (filters[i].id == LZMA_VLI_UNKNOWN)
191                                 memlimit_too_small(memory_usage, memory_limit);
192
193                         ++i;
194                 }
195
196                 // Decrease the dictionary size until we meet the memory
197                 // usage limit. First round down to full mebibytes.
198                 lzma_options_lzma *opt = filters[i].options;
199                 const uint32_t orig_dict_size = opt->dict_size;
200                 opt->dict_size &= ~((UINT32_C(1) << 20) - 1);
201                 while (true) {
202                         // If it is below 1 MiB, auto-adjusting failed. We
203                         // could be more sophisticated and scale it down even
204                         // more, but let's see if many complain about this
205                         // version.
206                         //
207                         // FIXME: Displays the scaled memory usage instead
208                         // of the original.
209                         if (opt->dict_size < (UINT32_C(1) << 20))
210                                 memlimit_too_small(memory_usage, memory_limit);
211
212                         memory_usage = lzma_raw_encoder_memusage(filters);
213                         if (memory_usage == UINT64_MAX)
214                                 message_bug();
215
216                         // Accept it if it is low enough.
217                         if (memory_usage <= memory_limit)
218                                 break;
219
220                         // Otherwise 1 MiB down and try again. I hope this
221                         // isn't too slow method for cases where the original
222                         // dict_size is very big.
223                         opt->dict_size -= UINT32_C(1) << 20;
224                 }
225
226                 // Tell the user that we decreased the dictionary size.
227                 // However, omit the message if no preset or custom chain
228                 // was given. FIXME: Always warn?
229                 if (!preset_default)
230                         message(V_WARNING, "Adjusted LZMA%c dictionary size "
231                                         "from %'" PRIu32 " MiB to "
232                                         "%'" PRIu32 " MiB to not exceed "
233                                         "the memory usage limit of "
234                                         "%'" PRIu64 " MiB",
235                                         filters[i].id == LZMA_FILTER_LZMA2
236                                                 ? '2' : '1',
237                                         orig_dict_size >> 20,
238                                         opt->dict_size >> 20,
239                                         memory_limit >> 20);
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         return;
255 }
256
257
258 static bool
259 coder_init(void)
260 {
261         lzma_ret ret = LZMA_PROG_ERROR;
262
263         if (opt_mode == MODE_COMPRESS) {
264                 switch (opt_format) {
265                 case FORMAT_AUTO:
266                         // args.c ensures this.
267                         assert(0);
268                         break;
269
270                 case FORMAT_XZ:
271                         ret = lzma_stream_encoder(&strm, filters, check);
272                         break;
273
274                 case FORMAT_LZMA:
275                         ret = lzma_alone_encoder(&strm, filters[0].options);
276                         break;
277
278                 case FORMAT_RAW:
279                         ret = lzma_raw_encoder(&strm, filters);
280                         break;
281                 }
282         } else {
283                 const uint32_t flags = LZMA_TELL_UNSUPPORTED_CHECK
284                                 | LZMA_CONCATENATED;
285
286                 switch (opt_format) {
287                 case FORMAT_AUTO:
288                         ret = lzma_auto_decoder(&strm,
289                                         hardware_memlimit_decoder(), flags);
290                         break;
291
292                 case FORMAT_XZ:
293                         ret = lzma_stream_decoder(&strm,
294                                         hardware_memlimit_decoder(), flags);
295                         break;
296
297                 case FORMAT_LZMA:
298                         ret = lzma_alone_decoder(&strm,
299                                         hardware_memlimit_decoder());
300                         break;
301
302                 case FORMAT_RAW:
303                         // Memory usage has already been checked in
304                         // coder_set_compression_settings().
305                         ret = lzma_raw_decoder(&strm, filters);
306                         break;
307                 }
308         }
309
310         if (ret != LZMA_OK) {
311                 if (ret == LZMA_MEM_ERROR)
312                         message_error("%s", message_strm(LZMA_MEM_ERROR));
313                 else
314                         message_bug();
315
316                 return true;
317         }
318
319         return false;
320 }
321
322
323 static bool
324 coder_run(file_pair *pair)
325 {
326         // Buffers to hold input and output data.
327         uint8_t in_buf[IO_BUFFER_SIZE];
328         uint8_t out_buf[IO_BUFFER_SIZE];
329
330         // Initialize the progress indicator.
331         const uint64_t in_size = pair->src_st.st_size <= (off_t)(0)
332                         ? 0 : (uint64_t)(pair->src_st.st_size);
333         message_progress_start(&strm, pair->src_name, in_size);
334
335         lzma_action action = LZMA_RUN;
336         lzma_ret ret;
337         bool success = false; // Assume that something goes wrong.
338
339         strm.avail_in = 0;
340         strm.next_out = out_buf;
341         strm.avail_out = IO_BUFFER_SIZE;
342
343         while (!user_abort) {
344                 // Fill the input buffer if it is empty and we haven't reached
345                 // end of file yet.
346                 if (strm.avail_in == 0 && !pair->src_eof) {
347                         strm.next_in = in_buf;
348                         strm.avail_in = io_read(pair, in_buf, IO_BUFFER_SIZE);
349
350                         if (strm.avail_in == SIZE_MAX)
351                                 break;
352
353                         // Encoder needs to know when we have given all the
354                         // input to it. The decoders need to know it too when
355                         // we are using LZMA_CONCATENATED.
356                         if (pair->src_eof)
357                                 action = LZMA_FINISH;
358                 }
359
360                 // Let liblzma do the actual work.
361                 ret = lzma_code(&strm, action);
362
363                 // Write out if the output buffer became full.
364                 if (strm.avail_out == 0) {
365                         if (opt_mode != MODE_TEST && io_write(pair, out_buf,
366                                         IO_BUFFER_SIZE - strm.avail_out))
367                                 break;
368
369                         strm.next_out = out_buf;
370                         strm.avail_out = IO_BUFFER_SIZE;
371                 }
372
373                 if (ret != LZMA_OK) {
374                         // Determine if the return value indicates that we
375                         // won't continue coding.
376                         const bool stop = ret != LZMA_NO_CHECK
377                                         && ret != LZMA_UNSUPPORTED_CHECK;
378
379                         if (stop) {
380                                 // Write the remaining bytes even if something
381                                 // went wrong, because that way the user gets
382                                 // as much data as possible, which can be good
383                                 // when trying to get at least some useful
384                                 // data out of damaged files.
385                                 if (opt_mode != MODE_TEST && io_write(pair,
386                                                 out_buf, IO_BUFFER_SIZE
387                                                         - strm.avail_out))
388                                         break;
389                         }
390
391                         if (ret == LZMA_STREAM_END) {
392                                 // Check that there is no trailing garbage.
393                                 // This is needed for LZMA_Alone and raw
394                                 // streams.
395                                 if (strm.avail_in == 0 && !pair->src_eof) {
396                                         // Try reading one more byte.
397                                         // Hopefully we don't get any more
398                                         // input, and thus pair->src_eof
399                                         // becomes true.
400                                         strm.avail_in = io_read(
401                                                         pair, in_buf, 1);
402                                         if (strm.avail_in == SIZE_MAX)
403                                                 break;
404
405                                         assert(strm.avail_in == 0
406                                                         || strm.avail_in == 1);
407                                 }
408
409                                 if (strm.avail_in == 0) {
410                                         assert(pair->src_eof);
411                                         success = true;
412                                         break;
413                                 }
414
415                                 // We hadn't reached the end of the file.
416                                 ret = LZMA_DATA_ERROR;
417                                 assert(stop);
418                         }
419
420                         // If we get here and stop is true, something went
421                         // wrong and we print an error. Otherwise it's just
422                         // a warning and coding can continue.
423                         if (stop) {
424                                 message_error("%s: %s", pair->src_name,
425                                                 message_strm(ret));
426                         } else {
427                                 message_warning("%s: %s", pair->src_name,
428                                                 message_strm(ret));
429
430                                 // When compressing, all possible errors set
431                                 // stop to true.
432                                 assert(opt_mode != MODE_COMPRESS);
433                         }
434
435                         if (ret == LZMA_MEMLIMIT_ERROR) {
436                                 // Figure out how much memory it would have
437                                 // actually needed.
438                                 uint64_t memusage = lzma_memusage(&strm);
439                                 uint64_t memlimit
440                                                 = hardware_memlimit_decoder();
441
442                                 // Round the memory limit down and usage up.
443                                 // This way we don't display a ridiculous
444                                 // message like "Limit was 9 MiB, but 9 MiB
445                                 // would have been needed".
446                                 memusage = (memusage + 1024 * 1024 - 1)
447                                                 / (1024 * 1024);
448                                 memlimit /= 1024 * 1024;
449
450                                 message_error(_("Limit was %'" PRIu64 " MiB, "
451                                                 "but %'" PRIu64 " MiB would "
452                                                 "have been needed"),
453                                                 memlimit, memusage);
454                         }
455
456                         if (stop)
457                                 break;
458                 }
459
460                 // Show progress information under certain conditions.
461                 message_progress_update();
462         }
463
464         message_progress_end(success);
465
466         return success;
467 }
468
469
470 extern void
471 process_file(const char *filename)
472 {
473         // First try initializing the coder. If it fails, it's useless to try
474         // opening the file. Check also for user_abort just in case if we had
475         // got a signal while initializing the coder.
476         if (coder_init() || user_abort)
477                 return;
478
479         // Try to open the input and output files.
480         file_pair *pair = io_open(filename);
481         if (pair == NULL)
482                 return;
483
484         // Do the actual coding.
485         const bool success = coder_run(pair);
486
487         // Close the file pair. It needs to know if coding was successful to
488         // know if the source or target file should be unlinked.
489         io_close(pair, success);
490
491         return;
492 }