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