]> icculus.org git repositories - icculus/xz.git/blob - src/xz/process.c
xz message handling improvements
[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 (1-9)
38 static size_t preset_number = 7;
39
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.
42 // FIXME
43 static bool preset_default = true;
44
45 /// Integrity check type
46 static lzma_check check = LZMA_CHECK_CRC64;
47
48
49 extern void
50 coder_set_check(lzma_check new_check)
51 {
52         check = new_check;
53         return;
54 }
55
56
57 extern void
58 coder_set_preset(size_t new_preset)
59 {
60         preset_number = new_preset;
61         preset_default = false;
62         return;
63 }
64
65
66 extern void
67 coder_add_filter(lzma_vli id, void *options)
68 {
69         if (filters_count == LZMA_FILTERS_MAX)
70                 message_fatal(_("Maximum number of filters is four"));
71
72         filters[filters_count].id = id;
73         filters[filters_count].options = options;
74         ++filters_count;
75
76         return;
77 }
78
79
80 extern void
81 coder_set_compression_settings(void)
82 {
83         // Options for LZMA1 or LZMA2 in case we are using a preset.
84         static lzma_options_lzma opt_lzma;
85
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 "
95                                         "is discouraged."));
96                         message(V_WARNING, _("The exact options of the "
97                                         "presets may vary between software "
98                                         "versions."));
99                 }
100
101                 // Get the preset for LZMA1 or LZMA2.
102                 if (lzma_lzma_preset(&opt_lzma, preset_number))
103                         message_bug();
104
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;
109                 filters_count = 1;
110         }
111
112         // Terminate the filter options array.
113         filters[filters_count].id = LZMA_VLI_UNKNOWN;
114
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 "
120                                 "is supported"));
121
122         // Print the selected filter chain.
123         message_filters(V_DEBUG, filters);
124
125         // If using --format=raw, we can be decoding. The memusage function
126         // also validates the filter chain and the options used for the
127         // filters.
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();
133         } else {
134                 memory_usage = lzma_memusage_decoder(filters);
135                 memory_limit = hardware_memlimit_decoder();
136         }
137
138         if (memory_usage == UINT64_MAX)
139                 message_fatal("Unsupported filter chain or filter options");
140
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));
146
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 "
155                                                 "filter preset"));
156
157                         if (lzma_lzma_preset(&opt_lzma, --preset_number))
158                                 message_bug();
159
160                         memory_usage = lzma_memusage_encoder(filters);
161                 }
162         } else {
163                 if (memory_usage > memory_limit)
164                         message_fatal(_("Memory usage limit is too small "
165                                         "for the given filter setup"));
166         }
167
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)
173                 thread_limit = 1;
174
175         if (opt_threads > thread_limit)
176                 opt_threads = thread_limit;
177
178         return;
179 }
180
181
182 static bool
183 coder_init(void)
184 {
185         lzma_ret ret = LZMA_PROG_ERROR;
186
187         if (opt_mode == MODE_COMPRESS) {
188                 switch (opt_format) {
189                 case FORMAT_AUTO:
190                         // args.c ensures this.
191                         assert(0);
192                         break;
193
194                 case FORMAT_XZ:
195                         ret = lzma_stream_encoder(&strm, filters, check);
196                         break;
197
198                 case FORMAT_LZMA:
199                         ret = lzma_alone_encoder(&strm, filters[0].options);
200                         break;
201
202                 case FORMAT_RAW:
203                         ret = lzma_raw_encoder(&strm, filters);
204                         break;
205                 }
206         } else {
207                 const uint32_t flags = LZMA_TELL_UNSUPPORTED_CHECK
208                                 | LZMA_CONCATENATED;
209
210                 switch (opt_format) {
211                 case FORMAT_AUTO:
212                         ret = lzma_auto_decoder(&strm,
213                                         hardware_memlimit_decoder(), flags);
214                         break;
215
216                 case FORMAT_XZ:
217                         ret = lzma_stream_decoder(&strm,
218                                         hardware_memlimit_decoder(), flags);
219                         break;
220
221                 case FORMAT_LZMA:
222                         ret = lzma_alone_decoder(&strm,
223                                         hardware_memlimit_decoder());
224                         break;
225
226                 case FORMAT_RAW:
227                         // Memory usage has already been checked in args.c.
228                         // FIXME Comment
229                         ret = lzma_raw_decoder(&strm, filters);
230                         break;
231                 }
232         }
233
234         if (ret != LZMA_OK) {
235                 if (ret == LZMA_MEM_ERROR)
236                         message_error("%s", message_strm(LZMA_MEM_ERROR));
237                 else
238                         message_bug();
239
240                 return true;
241         }
242
243         return false;
244 }
245
246
247 static bool
248 coder_run(file_pair *pair)
249 {
250         // Buffers to hold input and output data.
251         uint8_t in_buf[IO_BUFFER_SIZE];
252         uint8_t out_buf[IO_BUFFER_SIZE];
253
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);
258
259         lzma_action action = LZMA_RUN;
260         lzma_ret ret;
261
262         strm.avail_in = 0;
263         strm.next_out = out_buf;
264         strm.avail_out = IO_BUFFER_SIZE;
265
266         while (!user_abort) {
267                 // Fill the input buffer if it is empty and we haven't reached
268                 // end of file yet.
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);
272
273                         if (strm.avail_in == SIZE_MAX)
274                                 break;
275
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.
279                         if (pair->src_eof)
280                                 action = LZMA_FINISH;
281                 }
282
283                 // Let liblzma do the actual work.
284                 ret = lzma_code(&strm, action);
285
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))
290                                 return false;
291
292                         strm.next_out = out_buf;
293                         strm.avail_out = IO_BUFFER_SIZE;
294                 }
295
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;
301
302                         if (stop) {
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
307                                 // message.
308                                 //
309                                 // FIXME: What if something goes wrong
310                                 // after this?
311                                 message_progress_end(strm.total_in,
312                                                 strm.total_out,
313                                                 ret == LZMA_STREAM_END);
314
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
322                                                         - strm.avail_out))
323                                         return false;
324                         }
325
326                         if (ret == LZMA_STREAM_END) {
327                                 // Check that there is no trailing garbage.
328                                 // This is needed for LZMA_Alone and raw
329                                 // streams.
330                                 if (strm.avail_in == 0 && (pair->src_eof
331                                                 || io_read(pair, in_buf, 1)
332                                                         == 0)) {
333                                         assert(pair->src_eof);
334                                         return true;
335                                 }
336
337                                 // FIXME: What about io_read() failing?
338
339                                 // We hadn't reached the end of the file.
340                                 ret = LZMA_DATA_ERROR;
341                                 assert(stop);
342                         }
343
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.
347                         if (stop) {
348                                 message_error("%s: %s", pair->src_name,
349                                                 message_strm(ret));
350                         } else {
351                                 message_warning("%s: %s", pair->src_name,
352                                                 message_strm(ret));
353
354                                 // When compressing, all possible errors set
355                                 // stop to true.
356                                 assert(opt_mode != MODE_COMPRESS);
357                         }
358
359                         if (ret == LZMA_MEMLIMIT_ERROR) {
360                                 // Figure out how much memory it would have
361                                 // actually needed.
362                                 uint64_t memusage = lzma_memusage(&strm);
363                                 uint64_t memlimit
364                                                 = hardware_memlimit_decoder();
365
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)
371                                                 / (1024 * 1024);
372                                 memlimit /= 1024 * 1024;
373
374                                 message_error(_("Limit was %'" PRIu64 " MiB, "
375                                                 "but %'" PRIu64 " MiB would "
376                                                 "have been needed"),
377                                                 memlimit, memusage);
378                         }
379
380                         if (stop)
381                                 return false;
382                 }
383
384                 // Show progress information if --verbose was specified and
385                 // stderr is a terminal.
386                 message_progress_update(strm.total_in, strm.total_out);
387         }
388
389         return false;
390 }
391
392
393 extern void
394 process_file(const char *filename)
395 {
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)
400                 return;
401
402         // Try to open the input and output files.
403         file_pair *pair = io_open(filename);
404         if (pair == NULL)
405                 return;
406
407         // Do the actual coding.
408         const bool success = coder_run(pair);
409
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);
413
414         return;
415 }