]> icculus.org git repositories - icculus/xz.git/blob - src/xz/process.c
Typo fix
[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         // TODO: liblzma probably needs an API to validate the filter chain.
123
124         // If using --format=raw, we can be decoding.
125         uint64_t memory_usage;
126         uint64_t memory_limit;
127         if (opt_mode == MODE_COMPRESS) {
128                 memory_usage = lzma_memusage_encoder(filters);
129                 memory_limit = hardware_memlimit_encoder();
130         } else {
131                 memory_usage = lzma_memusage_decoder(filters);
132                 memory_limit = hardware_memlimit_decoder();
133         }
134
135         if (memory_usage == UINT64_MAX)
136                 message_bug();
137
138         if (preset_default) {
139                 // When no preset was explicitly requested, we use the default
140                 // preset only if the memory usage limit allows. Otherwise we
141                 // select a lower preset automatically.
142                 while (memory_usage > memory_limit) {
143                         if (preset_number == 1)
144                                 message_fatal(_("Memory usage limit is too "
145                                                 "small for any internal "
146                                                 "filter preset"));
147
148                         if (lzma_lzma_preset(&opt_lzma, --preset_number))
149                                 message_bug();
150
151                         memory_usage = lzma_memusage_encoder(filters);
152                 }
153         } else {
154                 if (memory_usage > memory_limit)
155                         message_fatal(_("Memory usage limit is too small "
156                                         "for the given filter setup"));
157         }
158
159         // Limit the number of worker threads so that memory usage
160         // limit isn't exceeded.
161         assert(memory_usage > 0);
162         size_t thread_limit = memory_limit / memory_usage;
163         if (thread_limit == 0)
164                 thread_limit = 1;
165
166         if (opt_threads > thread_limit)
167                 opt_threads = thread_limit;
168
169         return;
170 }
171
172
173 static bool
174 coder_init(void)
175 {
176         lzma_ret ret = LZMA_PROG_ERROR;
177
178         if (opt_mode == MODE_COMPRESS) {
179                 switch (opt_format) {
180                 case FORMAT_AUTO:
181                         // args.c ensures this.
182                         assert(0);
183                         break;
184
185                 case FORMAT_XZ:
186                         ret = lzma_stream_encoder(&strm, filters, check);
187                         break;
188
189                 case FORMAT_LZMA:
190                         ret = lzma_alone_encoder(&strm, filters[0].options);
191                         break;
192
193                 case FORMAT_RAW:
194                         ret = lzma_raw_encoder(&strm, filters);
195                         break;
196                 }
197         } else {
198                 const uint32_t flags = LZMA_TELL_UNSUPPORTED_CHECK
199                                 | LZMA_CONCATENATED;
200
201                 switch (opt_format) {
202                 case FORMAT_AUTO:
203                         ret = lzma_auto_decoder(&strm,
204                                         hardware_memlimit_decoder(), flags);
205                         break;
206
207                 case FORMAT_XZ:
208                         ret = lzma_stream_decoder(&strm,
209                                         hardware_memlimit_decoder(), flags);
210                         break;
211
212                 case FORMAT_LZMA:
213                         ret = lzma_alone_decoder(&strm,
214                                         hardware_memlimit_decoder());
215                         break;
216
217                 case FORMAT_RAW:
218                         // Memory usage has already been checked in args.c.
219                         // FIXME Comment
220                         ret = lzma_raw_decoder(&strm, filters);
221                         break;
222                 }
223         }
224
225         if (ret != LZMA_OK) {
226                 if (ret == LZMA_MEM_ERROR)
227                         message_error("%s", message_strm(LZMA_MEM_ERROR));
228                 else
229                         message_bug();
230
231                 return true;
232         }
233
234         return false;
235 }
236
237
238 static bool
239 coder_run(file_pair *pair)
240 {
241         // Buffers to hold input and output data.
242         uint8_t in_buf[IO_BUFFER_SIZE];
243         uint8_t out_buf[IO_BUFFER_SIZE];
244
245         // Initialize the progress indicator.
246         const uint64_t in_size = pair->src_st.st_size <= (off_t)(0)
247                         ? 0 : (uint64_t)(pair->src_st.st_size);
248         message_progress_start(pair->src_name, in_size);
249
250         lzma_action action = LZMA_RUN;
251         lzma_ret ret;
252
253         strm.avail_in = 0;
254         strm.next_out = out_buf;
255         strm.avail_out = IO_BUFFER_SIZE;
256
257         while (!user_abort) {
258                 // Fill the input buffer if it is empty and we haven't reached
259                 // end of file yet.
260                 if (strm.avail_in == 0 && !pair->src_eof) {
261                         strm.next_in = in_buf;
262                         strm.avail_in = io_read(pair, in_buf, IO_BUFFER_SIZE);
263
264                         if (strm.avail_in == SIZE_MAX)
265                                 break;
266
267                         // Encoder needs to know when we have given all the
268                         // input to it. The decoders need to know it too when
269                         // we are using LZMA_CONCATENATED.
270                         if (pair->src_eof)
271                                 action = LZMA_FINISH;
272                 }
273
274                 // Let liblzma do the actual work.
275                 ret = lzma_code(&strm, action);
276
277                 // Write out if the output buffer became full.
278                 if (strm.avail_out == 0) {
279                         if (opt_mode != MODE_TEST && io_write(pair, out_buf,
280                                         IO_BUFFER_SIZE - strm.avail_out))
281                                 return false;
282
283                         strm.next_out = out_buf;
284                         strm.avail_out = IO_BUFFER_SIZE;
285                 }
286
287                 if (ret != LZMA_OK) {
288                         // Determine if the return value indicates that we
289                         // won't continue coding.
290                         const bool stop = ret != LZMA_NO_CHECK
291                                         && ret != LZMA_UNSUPPORTED_CHECK;
292
293                         if (stop) {
294                                 // First print the final progress info.
295                                 // This way the user sees more accurately
296                                 // where the error occurred. Note that we
297                                 // print this *before* the possible error
298                                 // message.
299                                 //
300                                 // FIXME: What if something goes wrong
301                                 // after this?
302                                 message_progress_end(strm.total_in,
303                                                 strm.total_out,
304                                                 ret == LZMA_STREAM_END);
305
306                                 // Write the remaining bytes even if something
307                                 // went wrong, because that way the user gets
308                                 // as much data as possible, which can be good
309                                 // when trying to get at least some useful
310                                 // data out of damaged files.
311                                 if (opt_mode != MODE_TEST && io_write(pair,
312                                                 out_buf, IO_BUFFER_SIZE
313                                                         - strm.avail_out))
314                                         return false;
315                         }
316
317                         if (ret == LZMA_STREAM_END) {
318                                 // Check that there is no trailing garbage.
319                                 // This is needed for LZMA_Alone and raw
320                                 // streams.
321                                 if (strm.avail_in == 0 && (pair->src_eof
322                                                 || io_read(pair, in_buf, 1)
323                                                         == 0)) {
324                                         assert(pair->src_eof);
325                                         return true;
326                                 }
327
328                                 // FIXME: What about io_read() failing?
329
330                                 // We hadn't reached the end of the file.
331                                 ret = LZMA_DATA_ERROR;
332                                 assert(stop);
333                         }
334
335                         // If we get here and stop is true, something went
336                         // wrong and we print an error. Otherwise it's just
337                         // a warning and coding can continue.
338                         if (stop) {
339                                 message_error("%s: %s", pair->src_name,
340                                                 message_strm(ret));
341                         } else {
342                                 message_warning("%s: %s", pair->src_name,
343                                                 message_strm(ret));
344
345                                 // When compressing, all possible errors set
346                                 // stop to true.
347                                 assert(opt_mode != MODE_COMPRESS);
348                         }
349
350                         if (ret == LZMA_MEMLIMIT_ERROR) {
351                                 // Figure out how much memory would have
352                                 // actually needed.
353                                 // TODO
354                         }
355
356                         if (stop)
357                                 return false;
358                 }
359
360                 // Show progress information if --verbose was specified and
361                 // stderr is a terminal.
362                 message_progress_update(strm.total_in, strm.total_out);
363         }
364
365         return false;
366 }
367
368
369 extern void
370 process_file(const char *filename)
371 {
372         // First try initializing the coder. If it fails, it's useless to try
373         // opening the file. Check also for user_abort just in case if we had
374         // got a signal while initializing the coder.
375         if (coder_init() || user_abort)
376                 return;
377
378         // Try to open the input and output files.
379         file_pair *pair = io_open(filename);
380         if (pair == NULL)
381                 return;
382
383         // Do the actual coding.
384         const bool success = coder_run(pair);
385
386         // Close the file pair. It needs to know if coding was successful to
387         // know if the source or target file should be unlinked.
388         io_close(pair, success);
389
390         return;
391 }