]> icculus.org git repositories - icculus/xz.git/blob - src/xz/message.c
Various changes.
[icculus/xz.git] / src / xz / message.c
1 ///////////////////////////////////////////////////////////////////////////////
2 //
3 /// \file       message.c
4 /// \brief      Printing messages to stderr
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 #ifdef HAVE_SYS_TIME_H
16 #       include <sys/time.h>
17 #endif
18
19 #include <stdarg.h>
20
21
22 /// Number of the current file
23 static unsigned int files_pos = 0;
24
25 /// Total number of input files; zero if unknown.
26 static unsigned int files_total;
27
28 /// Verbosity level
29 static enum message_verbosity verbosity = V_WARNING;
30
31 /// Filename which we will print with the verbose messages
32 static const char *filename;
33
34 /// True once the a filename has been printed to stderr as part of progress
35 /// message. If automatic progress updating isn't enabled, this becomes true
36 /// after the first progress message has been printed due to user sending
37 /// SIGINFO, SIGUSR1, or SIGALRM. Once this variable is true, we will print
38 /// an empty line before the next filename to make the output more readable.
39 static bool first_filename_printed = false;
40
41 /// This is set to true when we have printed the current filename to stderr
42 /// as part of a progress message. This variable is useful only if not
43 /// updating progress automatically: if user sends many SIGINFO, SIGUSR1, or
44 /// SIGALRM signals, we won't print the name of the same file multiple times.
45 static bool current_filename_printed = false;
46
47 /// True if we should print progress indicator and update it automatically
48 /// if also verbose >= V_VERBOSE.
49 static bool progress_automatic;
50
51 /// True if message_progress_start() has been called but
52 /// message_progress_end() hasn't been called yet.
53 static bool progress_started = false;
54
55 /// This is true when a progress message was printed and the cursor is still
56 /// on the same line with the progress message. In that case, a newline has
57 /// to be printed before any error messages.
58 static bool progress_active = false;
59
60 /// Pointer to lzma_stream used to do the encoding or decoding.
61 static lzma_stream *progress_strm;
62
63 /// Expected size of the input stream is needed to show completion percentage
64 /// and estimate remaining time.
65 static uint64_t expected_in_size;
66
67 /// Time when we started processing the file
68 static uint64_t start_time;
69
70
71 // Use alarm() and SIGALRM when they are supported. This has two minor
72 // advantages over the alternative of polling gettimeofday():
73 //  - It is possible for the user to send SIGINFO, SIGUSR1, or SIGALRM to
74 //    get intermediate progress information even when --verbose wasn't used
75 //    or stderr is not a terminal.
76 //  - alarm() + SIGALRM seems to have slightly less overhead than polling
77 //    gettimeofday().
78 #ifdef SIGALRM
79
80 /// The signal handler for SIGALRM sets this to true. It is set back to false
81 /// once the progress message has been updated.
82 static volatile sig_atomic_t progress_needs_updating = false;
83
84 /// Signal handler for SIGALRM
85 static void
86 progress_signal_handler(int sig lzma_attribute((unused)))
87 {
88         progress_needs_updating = true;
89         return;
90 }
91
92 #else
93
94 /// This is true when progress message printing is wanted. Using the same
95 /// variable name as above to avoid some ifdefs.
96 static bool progress_needs_updating = false;
97
98 /// Elapsed time when the next progress message update should be done.
99 static uint64_t progress_next_update;
100
101 #endif
102
103
104 /// Get the current time as microseconds since epoch
105 static uint64_t
106 my_time(void)
107 {
108         struct timeval tv;
109         gettimeofday(&tv, NULL);
110         return (uint64_t)(tv.tv_sec) * UINT64_C(1000000) + tv.tv_usec;
111 }
112
113
114 /// Wrapper for snprintf() to help constructing a string in pieces.
115 static void lzma_attribute((format(printf, 3, 4)))
116 my_snprintf(char **pos, size_t *left, const char *fmt, ...)
117 {
118         va_list ap;
119         va_start(ap, fmt);
120         const int len = vsnprintf(*pos, *left, fmt, ap);
121         va_end(ap);
122
123         // If an error occurred, we want the caller to think that the whole
124         // buffer was used. This way no more data will be written to the
125         // buffer. We don't need better error handling here.
126         if (len < 0 || (size_t)(len) >= *left) {
127                 *left = 0;
128         } else {
129                 *pos += len;
130                 *left -= len;
131         }
132
133         return;
134 }
135
136
137 extern void
138 message_init(void)
139 {
140         // If --verbose is used, we use a progress indicator if and only
141         // if stderr is a terminal. If stderr is not a terminal, we print
142         // verbose information only after finishing the file. As a special
143         // exception, even if --verbose was not used, user can send SIGALRM
144         // to make us print progress information once without automatic
145         // updating.
146         progress_automatic = isatty(STDERR_FILENO);
147
148         // Commented out because COLUMNS is rarely exported to environment.
149         // Most users have at least 80 columns anyway, let's think something
150         // fancy here if enough people complain.
151 /*
152         if (progress_automatic) {
153                 // stderr is a terminal. Check the COLUMNS environment
154                 // variable to see if the terminal is wide enough. If COLUMNS
155                 // doesn't exist or it has some unparseable value, we assume
156                 // that the terminal is wide enough.
157                 const char *columns_str = getenv("COLUMNS");
158                 if (columns_str != NULL) {
159                         char *endptr;
160                         const long columns = strtol(columns_str, &endptr, 10);
161                         if (*endptr != '\0' || columns < 80)
162                                 progress_automatic = false;
163                 }
164         }
165 */
166
167 #ifdef SIGALRM
168         // At least DJGPP lacks SA_RESTART. It's not essential for us (the
169         // rest of the code can handle interrupted system calls), so just
170         // define it zero.
171 #       ifndef SA_RESTART
172 #               define SA_RESTART 0
173 #       endif
174         // Establish the signal handlers which set a flag to tell us that
175         // progress info should be updated. Since these signals don't
176         // require any quick action, we set SA_RESTART.
177         static const int sigs[] = {
178 #ifdef SIGALRM
179                 SIGALRM,
180 #endif
181 #ifdef SIGINFO
182                 SIGINFO,
183 #endif
184 #ifdef SIGUSR1
185                 SIGUSR1,
186 #endif
187         };
188
189         struct sigaction sa;
190         sigemptyset(&sa.sa_mask);
191         sa.sa_flags = SA_RESTART;
192         sa.sa_handler = &progress_signal_handler;
193
194         for (size_t i = 0; i < ARRAY_SIZE(sigs); ++i)
195                 if (sigaction(sigs[i], &sa, NULL))
196                         message_signal_handler();
197 #endif
198
199         return;
200 }
201
202
203 extern void
204 message_verbosity_increase(void)
205 {
206         if (verbosity < V_DEBUG)
207                 ++verbosity;
208
209         return;
210 }
211
212
213 extern void
214 message_verbosity_decrease(void)
215 {
216         if (verbosity > V_SILENT)
217                 --verbosity;
218
219         return;
220 }
221
222
223 extern enum message_verbosity
224 message_verbosity_get(void)
225 {
226         return verbosity;
227 }
228
229
230 extern void
231 message_set_files(unsigned int files)
232 {
233         files_total = files;
234         return;
235 }
236
237
238 /// Prints the name of the current file if it hasn't been printed already,
239 /// except if we are processing exactly one stream from stdin to stdout.
240 /// I think it looks nicer to not print "(stdin)" when --verbose is used
241 /// in a pipe and no other files are processed.
242 static void
243 print_filename(void)
244 {
245         if (!current_filename_printed
246                         && (files_total != 1 || filename != stdin_filename)) {
247                 signals_block();
248
249                 // If a file was already processed, put an empty line
250                 // before the next filename to improve readability.
251                 if (first_filename_printed)
252                         fputc('\n', stderr);
253
254                 first_filename_printed = true;
255                 current_filename_printed = true;
256
257                 // If we don't know how many files there will be due
258                 // to usage of --files or --files0.
259                 if (files_total == 0)
260                         fprintf(stderr, "%s (%u)\n", filename,
261                                         files_pos);
262                 else
263                         fprintf(stderr, "%s (%u/%u)\n", filename,
264                                         files_pos, files_total);
265
266                 signals_unblock();
267         }
268
269         return;
270 }
271
272
273 extern void
274 message_progress_start(
275                 lzma_stream *strm, const char *src_name, uint64_t in_size)
276 {
277         // Store the pointer to the lzma_stream used to do the coding.
278         // It is needed to find out the position in the stream.
279         progress_strm = strm;
280
281         // Store the processing start time of the file and its expected size.
282         // If we aren't printing any statistics, then these are unused. But
283         // since it is possible that the user sends us a signal to show
284         // statistics, we need to have these available anyway.
285         start_time = my_time();
286         filename = src_name;
287         expected_in_size = in_size;
288
289         // Indicate that progress info may need to be printed before
290         // printing error messages.
291         progress_started = true;
292
293         // Indicate the name of this file hasn't been printed to
294         // stderr yet.
295         current_filename_printed = false;
296
297         // Start numbering the files starting from one.
298         ++files_pos;
299
300         // If progress indicator is wanted, print the filename and possibly
301         // the file count now.
302         if (verbosity >= V_VERBOSE && progress_automatic) {
303                 // Print the filename to stderr if that is appropriate with
304                 // the current settings.
305                 print_filename();
306
307                 // Start the timer to display the first progress message
308                 // after one second. An alternative would be to show the
309                 // first message almost immediatelly, but delaying by one
310                 // second looks better to me, since extremely early
311                 // progress info is pretty much useless.
312 #ifdef SIGALRM
313                 // First disable a possibly existing alarm.
314                 alarm(0);
315                 progress_needs_updating = false;
316                 alarm(1);
317 #else
318                 progress_needs_updating = true;
319                 progress_next_update = 1000000;
320 #endif
321         }
322
323         return;
324 }
325
326
327 /// Make the string indicating completion percentage.
328 static const char *
329 progress_percentage(uint64_t in_pos, bool final)
330 {
331         static char buf[sizeof("100.0 %")];
332
333         double percentage;
334
335         if (final) {
336                 // Use floating point conversion of snprintf() also for
337                 // 100.0 % instead of fixed string, because the decimal
338                 // separator isn't a dot in all locales.
339                 percentage = 100.0;
340         } else {
341                 // If the size of the input file is unknown or the size told us is
342                 // clearly wrong since we have processed more data than the alleged
343                 // size of the file, show a static string indicating that we have
344                 // no idea of the completion percentage.
345                 if (expected_in_size == 0 || in_pos > expected_in_size)
346                         return "--- %";
347
348                 // Never show 100.0 % before we actually are finished.
349                 percentage = (double)(in_pos) / (double)(expected_in_size)
350                                 * 99.9;
351         }
352
353         snprintf(buf, sizeof(buf), "%.1f %%", percentage);
354
355         return buf;
356 }
357
358
359 static void
360 progress_sizes_helper(char **pos, size_t *left, uint64_t value, bool final)
361 {
362         // Allow high precision only for the final message, since it looks
363         // stupid for in-progress information.
364         if (final) {
365                 // A maximum of four digits are allowed for exact byte count.
366                 if (value < 10000) {
367                         my_snprintf(pos, left, "%s B",
368                                         uint64_to_str(value, 0));
369                         return;
370                 }
371
372                 // A maximum of five significant digits are allowed for KiB.
373                 if (value < UINT64_C(10239900)) {
374                         my_snprintf(pos, left, "%s KiB", double_to_str(
375                                         (double)(value) / 1024.0));
376                         return;
377                 }
378         }
379
380         // Otherwise we use MiB.
381         my_snprintf(pos, left, "%s MiB",
382                         double_to_str((double)(value) / (1024.0 * 1024.0)));
383
384         return;
385 }
386
387
388 /// Make the string containing the amount of input processed, amount of
389 /// output produced, and the compression ratio.
390 static const char *
391 progress_sizes(uint64_t compressed_pos, uint64_t uncompressed_pos, bool final)
392 {
393         // This is enough to hold sizes up to about 99 TiB if thousand
394         // separator is used, or about 1 PiB without thousand separator.
395         // After that the progress indicator will look a bit silly, since
396         // the compression ratio no longer fits with three decimal places.
397         static char buf[44];
398
399         char *pos = buf;
400         size_t left = sizeof(buf);
401
402         // Print the sizes. If this the final message, use more reasonable
403         // units than MiB if the file was small.
404         progress_sizes_helper(&pos, &left, compressed_pos, final);
405         my_snprintf(&pos, &left, " / ");
406         progress_sizes_helper(&pos, &left, uncompressed_pos, final);
407
408         // Avoid division by zero. If we cannot calculate the ratio, set
409         // it to some nice number greater than 10.0 so that it gets caught
410         // in the next if-clause.
411         const double ratio = uncompressed_pos > 0
412                         ? (double)(compressed_pos) / (double)(uncompressed_pos)
413                         : 16.0;
414
415         // If the ratio is very bad, just indicate that it is greater than
416         // 9.999. This way the length of the ratio field stays fixed.
417         if (ratio > 9.999)
418                 snprintf(pos, left, " > %.3f", 9.999);
419         else
420                 snprintf(pos, left, " = %.3f", ratio);
421
422         return buf;
423 }
424
425
426 /// Make the string containing the processing speed of uncompressed data.
427 static const char *
428 progress_speed(uint64_t uncompressed_pos, uint64_t elapsed)
429 {
430         // Don't print the speed immediatelly, since the early values look
431         // like somewhat random.
432         if (elapsed < 3000000)
433                 return "";
434
435         static const char unit[][8] = {
436                 "KiB/s",
437                 "MiB/s",
438                 "GiB/s",
439         };
440
441         size_t unit_index = 0;
442
443         // Calculate the speed as KiB/s.
444         double speed = (double)(uncompressed_pos)
445                         / ((double)(elapsed) * (1024.0 / 1e6));
446
447         // Adjust the unit of the speed if needed.
448         while (speed > 999.0) {
449                 speed /= 1024.0;
450                 if (++unit_index == ARRAY_SIZE(unit))
451                         return ""; // Way too fast ;-)
452         }
453
454         // Use decimal point only if the number is small. Examples:
455         //  - 0.1 KiB/s
456         //  - 9.9 KiB/s
457         //  - 99 KiB/s
458         //  - 999 KiB/s
459         static char buf[sizeof("999 GiB/s")];
460         snprintf(buf, sizeof(buf), "%.*f %s",
461                         speed > 9.9 ? 0 : 1, speed, unit[unit_index]);
462         return buf;
463 }
464
465
466 /// Make a string indicating elapsed or remaining time. The format is either
467 /// M:SS or H:MM:SS depending on if the time is an hour or more.
468 static const char *
469 progress_time(uint64_t useconds)
470 {
471         // 9999 hours = 416 days
472         static char buf[sizeof("9999:59:59")];
473
474         uint32_t seconds = useconds / 1000000;
475
476         // Don't show anything if the time is zero or ridiculously big.
477         if (seconds == 0 || seconds > ((9999 * 60) + 59) * 60 + 59)
478                 return "";
479
480         uint32_t minutes = seconds / 60;
481         seconds %= 60;
482
483         if (minutes >= 60) {
484                 const uint32_t hours = minutes / 60;
485                 minutes %= 60;
486                 snprintf(buf, sizeof(buf),
487                                 "%" PRIu32 ":%02" PRIu32 ":%02" PRIu32,
488                                 hours, minutes, seconds);
489         } else {
490                 snprintf(buf, sizeof(buf), "%" PRIu32 ":%02" PRIu32,
491                                 minutes, seconds);
492         }
493
494         return buf;
495 }
496
497
498 /// Make the string to contain the estimated remaining time, or if the amount
499 /// of input isn't known, how much time has elapsed.
500 static const char *
501 progress_remaining(uint64_t in_pos, uint64_t elapsed)
502 {
503         // Show the amount of time spent so far when making an estimate of
504         // remaining time wouldn't be reasonable:
505         //  - Input size is unknown.
506         //  - Input has grown bigger since we started (de)compressing.
507         //  - We haven't processed much data yet, so estimate would be
508         //    too inaccurate.
509         //  - Only a few seconds has passed since we started (de)compressing,
510         //    so estimate would be too inaccurate.
511         if (expected_in_size == 0 || in_pos > expected_in_size
512                         || in_pos < (UINT64_C(1) << 19) || elapsed < 8000000)
513                 return progress_time(elapsed);
514
515         // Calculate the estimate. Don't give an estimate of zero seconds,
516         // since it is possible that all the input has been already passed
517         // to the library, but there is still quite a bit of output pending.
518         uint32_t remaining = (double)(expected_in_size - in_pos)
519                         * ((double)(elapsed) / 1e6) / (double)(in_pos);
520         if (remaining < 1)
521                 remaining = 1;
522
523         static char buf[sizeof("9 h 55 min")];
524
525         // Select appropriate precision for the estimated remaining time.
526         if (remaining <= 10) {
527                 // A maximum of 10 seconds remaining.
528                 // Show the number of seconds as is.
529                 snprintf(buf, sizeof(buf), "%" PRIu32 " s", remaining);
530
531         } else if (remaining <= 50) {
532                 // A maximum of 50 seconds remaining.
533                 // Round up to the next multiple of five seconds.
534                 remaining = (remaining + 4) / 5 * 5;
535                 snprintf(buf, sizeof(buf), "%" PRIu32 " s", remaining);
536
537         } else if (remaining <= 590) {
538                 // A maximum of 9 minutes and 50 seconds remaining.
539                 // Round up to the next multiple of ten seconds.
540                 remaining = (remaining + 9) / 10 * 10;
541                 snprintf(buf, sizeof(buf), "%" PRIu32 " min %" PRIu32 " s",
542                                 remaining / 60, remaining % 60);
543
544         } else if (remaining <= 59 * 60) {
545                 // A maximum of 59 minutes remaining.
546                 // Round up to the next multiple of a minute.
547                 remaining = (remaining + 59) / 60;
548                 snprintf(buf, sizeof(buf), "%" PRIu32 " min", remaining);
549
550         } else if (remaining <= 9 * 3600 + 50 * 60) {
551                 // A maximum of 9 hours and 50 minutes left.
552                 // Round up to the next multiple of ten minutes.
553                 remaining = (remaining + 599) / 600 * 10;
554                 snprintf(buf, sizeof(buf), "%" PRIu32 " h %" PRIu32 " min",
555                                 remaining / 60, remaining % 60);
556
557         } else if (remaining <= 23 * 3600) {
558                 // A maximum of 23 hours remaining.
559                 // Round up to the next multiple of an hour.
560                 remaining = (remaining + 3599) / 3600;
561                 snprintf(buf, sizeof(buf), "%" PRIu32 " h", remaining);
562
563         } else if (remaining <= 9 * 24 * 3600 + 23 * 3600) {
564                 // A maximum of 9 days and 23 hours remaining.
565                 // Round up to the next multiple of an hour.
566                 remaining = (remaining + 3599) / 3600;
567                 snprintf(buf, sizeof(buf), "%" PRIu32 " d %" PRIu32 " h",
568                                 remaining / 24, remaining % 24);
569
570         } else if (remaining <= 999 * 24 * 3600) {
571                 // A maximum of 999 days remaining. ;-)
572                 // Round up to the next multiple of a day.
573                 remaining = (remaining + 24 * 3600 - 1) / (24 * 3600);
574                 snprintf(buf, sizeof(buf), "%" PRIu32 " d", remaining);
575
576         } else {
577                 // The estimated remaining time is so big that it's better
578                 // that we just show the elapsed time.
579                 return progress_time(elapsed);
580         }
581
582         return buf;
583 }
584
585
586 /// Calculate the elapsed time as microseconds.
587 static uint64_t
588 progress_elapsed(void)
589 {
590         return my_time() - start_time;
591 }
592
593
594 /// Get information about position in the stream. This is currently simple,
595 /// but it will become more complicated once we have multithreading support.
596 static void
597 progress_pos(uint64_t *in_pos,
598                 uint64_t *compressed_pos, uint64_t *uncompressed_pos)
599 {
600         *in_pos = progress_strm->total_in;
601
602         if (opt_mode == MODE_COMPRESS) {
603                 *compressed_pos = progress_strm->total_out;
604                 *uncompressed_pos = progress_strm->total_in;
605         } else {
606                 *compressed_pos = progress_strm->total_in;
607                 *uncompressed_pos = progress_strm->total_out;
608         }
609
610         return;
611 }
612
613
614 extern void
615 message_progress_update(void)
616 {
617         if (!progress_needs_updating)
618                 return;
619
620         // Calculate how long we have been processing this file.
621         const uint64_t elapsed = progress_elapsed();
622
623 #ifndef SIGALRM
624         if (progress_next_update > elapsed)
625                 return;
626
627         progress_next_update = elapsed + 1000000;
628 #endif
629
630         // Get our current position in the stream.
631         uint64_t in_pos;
632         uint64_t compressed_pos;
633         uint64_t uncompressed_pos;
634         progress_pos(&in_pos, &compressed_pos, &uncompressed_pos);
635
636         // Block signals so that fprintf() doesn't get interrupted.
637         signals_block();
638
639         // Print the filename if it hasn't been printed yet.
640         print_filename();
641
642         // Print the actual progress message. The idea is that there is at
643         // least three spaces between the fields in typical situations, but
644         // even in rare situations there is at least one space.
645         fprintf(stderr, "  %7s %43s   %9s   %10s\r",
646                 progress_percentage(in_pos, false),
647                 progress_sizes(compressed_pos, uncompressed_pos, false),
648                 progress_speed(uncompressed_pos, elapsed),
649                 progress_remaining(in_pos, elapsed));
650
651 #ifdef SIGALRM
652         // Updating the progress info was finished. Reset
653         // progress_needs_updating to wait for the next SIGALRM.
654         //
655         // NOTE: This has to be done before alarm(1) or with (very) bad
656         // luck we could be setting this to false after the alarm has already
657         // been triggered.
658         progress_needs_updating = false;
659
660         if (verbosity >= V_VERBOSE && progress_automatic) {
661                 // Mark that the progress indicator is active, so if an error
662                 // occurs, the error message gets printed cleanly.
663                 progress_active = true;
664
665                 // Restart the timer so that progress_needs_updating gets
666                 // set to true after about one second.
667                 alarm(1);
668         } else {
669                 // The progress message was printed because user had sent us
670                 // SIGALRM. In this case, each progress message is printed
671                 // on its own line.
672                 fputc('\n', stderr);
673         }
674 #else
675         // When SIGALRM isn't supported and we get here, it's always due to
676         // automatic progress update. We set progress_active here too like
677         // described above.
678         assert(verbosity >= V_VERBOSE);
679         assert(progress_automatic);
680         progress_active = true;
681 #endif
682
683         signals_unblock();
684
685         return;
686 }
687
688
689 static void
690 progress_flush(bool finished)
691 {
692         if (!progress_started || verbosity < V_VERBOSE)
693                 return;
694
695         uint64_t in_pos;
696         uint64_t compressed_pos;
697         uint64_t uncompressed_pos;
698         progress_pos(&in_pos, &compressed_pos, &uncompressed_pos);
699
700         // Avoid printing intermediate progress info if some error occurs
701         // in the beginning of the stream. (If something goes wrong later in
702         // the stream, it is sometimes useful to tell the user where the
703         // error approximately occurred, especially if the error occurs
704         // after a time-consuming operation.)
705         if (!finished && !progress_active
706                         && (compressed_pos == 0 || uncompressed_pos == 0))
707                 return;
708
709         progress_active = false;
710
711         const uint64_t elapsed = progress_elapsed();
712         const char *elapsed_str = progress_time(elapsed);
713
714         signals_block();
715
716         // When using the auto-updating progress indicator, the final
717         // statistics are printed in the same format as the progress
718         // indicator itself.
719         if (progress_automatic) {
720                 // Using floating point conversion for the percentage instead
721                 // of static "100.0 %" string, because the decimal separator
722                 // isn't a dot in all locales.
723                 fprintf(stderr, "  %7s %43s   %9s   %10s\n",
724                         progress_percentage(in_pos, finished),
725                         progress_sizes(compressed_pos, uncompressed_pos, true),
726                         progress_speed(uncompressed_pos, elapsed),
727                         elapsed_str);
728         } else {
729                 // The filename is always printed.
730                 fprintf(stderr, "%s: ", filename);
731
732                 // Percentage is printed only if we didn't finish yet.
733                 // FIXME: This may look weird when size of the input
734                 // isn't known.
735                 if (!finished)
736                         fprintf(stderr, "%s, ",
737                                         progress_percentage(in_pos, false));
738
739                 // Size information is always printed.
740                 fprintf(stderr, "%s", progress_sizes(
741                                 compressed_pos, uncompressed_pos, true));
742
743                 // The speed and elapsed time aren't always shown.
744                 const char *speed = progress_speed(uncompressed_pos, elapsed);
745                 if (speed[0] != '\0')
746                         fprintf(stderr, ", %s", speed);
747
748                 if (elapsed_str[0] != '\0')
749                         fprintf(stderr, ", %s", elapsed_str);
750
751                 fputc('\n', stderr);
752         }
753
754         signals_unblock();
755
756         return;
757 }
758
759
760 extern void
761 message_progress_end(bool success)
762 {
763         assert(progress_started);
764         progress_flush(success);
765         progress_started = false;
766         return;
767 }
768
769
770 static void
771 vmessage(enum message_verbosity v, const char *fmt, va_list ap)
772 {
773         if (v <= verbosity) {
774                 signals_block();
775
776                 progress_flush(false);
777
778                 fprintf(stderr, "%s: ", progname);
779                 vfprintf(stderr, fmt, ap);
780                 fputc('\n', stderr);
781
782                 signals_unblock();
783         }
784
785         return;
786 }
787
788
789 extern void
790 message(enum message_verbosity v, const char *fmt, ...)
791 {
792         va_list ap;
793         va_start(ap, fmt);
794         vmessage(v, fmt, ap);
795         va_end(ap);
796         return;
797 }
798
799
800 extern void
801 message_warning(const char *fmt, ...)
802 {
803         va_list ap;
804         va_start(ap, fmt);
805         vmessage(V_WARNING, fmt, ap);
806         va_end(ap);
807
808         set_exit_status(E_WARNING);
809         return;
810 }
811
812
813 extern void
814 message_error(const char *fmt, ...)
815 {
816         va_list ap;
817         va_start(ap, fmt);
818         vmessage(V_ERROR, fmt, ap);
819         va_end(ap);
820
821         set_exit_status(E_ERROR);
822         return;
823 }
824
825
826 extern void
827 message_fatal(const char *fmt, ...)
828 {
829         va_list ap;
830         va_start(ap, fmt);
831         vmessage(V_ERROR, fmt, ap);
832         va_end(ap);
833
834         tuklib_exit(E_ERROR, E_ERROR, false);
835 }
836
837
838 extern void
839 message_bug(void)
840 {
841         message_fatal(_("Internal error (bug)"));
842 }
843
844
845 extern void
846 message_signal_handler(void)
847 {
848         message_fatal(_("Cannot establish signal handlers"));
849 }
850
851
852 extern const char *
853 message_strm(lzma_ret code)
854 {
855         switch (code) {
856         case LZMA_NO_CHECK:
857                 return _("No integrity check; not verifying file integrity");
858
859         case LZMA_UNSUPPORTED_CHECK:
860                 return _("Unsupported type of integrity check; "
861                                 "not verifying file integrity");
862
863         case LZMA_MEM_ERROR:
864                 return strerror(ENOMEM);
865
866         case LZMA_MEMLIMIT_ERROR:
867                 return _("Memory usage limit reached");
868
869         case LZMA_FORMAT_ERROR:
870                 return _("File format not recognized");
871
872         case LZMA_OPTIONS_ERROR:
873                 return _("Unsupported options");
874
875         case LZMA_DATA_ERROR:
876                 return _("Compressed data is corrupt");
877
878         case LZMA_BUF_ERROR:
879                 return _("Unexpected end of input");
880
881         case LZMA_OK:
882         case LZMA_STREAM_END:
883         case LZMA_GET_CHECK:
884         case LZMA_PROG_ERROR:
885                 return _("Internal error (bug)");
886         }
887
888         return NULL;
889 }
890
891
892 extern void
893 message_filters(enum message_verbosity v, const lzma_filter *filters)
894 {
895         if (v > verbosity)
896                 return;
897
898         fprintf(stderr, _("%s: Filter chain:"), progname);
899
900         for (size_t i = 0; filters[i].id != LZMA_VLI_UNKNOWN; ++i) {
901                 fprintf(stderr, " --");
902
903                 switch (filters[i].id) {
904                 case LZMA_FILTER_LZMA1:
905                 case LZMA_FILTER_LZMA2: {
906                         const lzma_options_lzma *opt = filters[i].options;
907                         const char *mode;
908                         const char *mf;
909
910                         switch (opt->mode) {
911                         case LZMA_MODE_FAST:
912                                 mode = "fast";
913                                 break;
914
915                         case LZMA_MODE_NORMAL:
916                                 mode = "normal";
917                                 break;
918
919                         default:
920                                 mode = "UNKNOWN";
921                                 break;
922                         }
923
924                         switch (opt->mf) {
925                         case LZMA_MF_HC3:
926                                 mf = "hc3";
927                                 break;
928
929                         case LZMA_MF_HC4:
930                                 mf = "hc4";
931                                 break;
932
933                         case LZMA_MF_BT2:
934                                 mf = "bt2";
935                                 break;
936
937                         case LZMA_MF_BT3:
938                                 mf = "bt3";
939                                 break;
940
941                         case LZMA_MF_BT4:
942                                 mf = "bt4";
943                                 break;
944
945                         default:
946                                 mf = "UNKNOWN";
947                                 break;
948                         }
949
950                         fprintf(stderr, "lzma%c=dict=%" PRIu32
951                                         ",lc=%" PRIu32 ",lp=%" PRIu32
952                                         ",pb=%" PRIu32
953                                         ",mode=%s,nice=%" PRIu32 ",mf=%s"
954                                         ",depth=%" PRIu32,
955                                         filters[i].id == LZMA_FILTER_LZMA2
956                                                 ? '2' : '1',
957                                         opt->dict_size,
958                                         opt->lc, opt->lp, opt->pb,
959                                         mode, opt->nice_len, mf, opt->depth);
960                         break;
961                 }
962
963                 case LZMA_FILTER_X86:
964                         fprintf(stderr, "x86");
965                         break;
966
967                 case LZMA_FILTER_POWERPC:
968                         fprintf(stderr, "powerpc");
969                         break;
970
971                 case LZMA_FILTER_IA64:
972                         fprintf(stderr, "ia64");
973                         break;
974
975                 case LZMA_FILTER_ARM:
976                         fprintf(stderr, "arm");
977                         break;
978
979                 case LZMA_FILTER_ARMTHUMB:
980                         fprintf(stderr, "armthumb");
981                         break;
982
983                 case LZMA_FILTER_SPARC:
984                         fprintf(stderr, "sparc");
985                         break;
986
987                 case LZMA_FILTER_DELTA: {
988                         const lzma_options_delta *opt = filters[i].options;
989                         fprintf(stderr, "delta=dist=%" PRIu32, opt->dist);
990                         break;
991                 }
992
993                 default:
994                         fprintf(stderr, "UNKNOWN");
995                         break;
996                 }
997         }
998
999         fputc('\n', stderr);
1000         return;
1001 }
1002
1003
1004 extern void
1005 message_try_help(void)
1006 {
1007         // Print this with V_WARNING instead of V_ERROR to prevent it from
1008         // showing up when --quiet has been specified.
1009         message(V_WARNING, _("Try `%s --help' for more information."),
1010                         progname);
1011         return;
1012 }
1013
1014
1015 extern void
1016 message_version(void)
1017 {
1018         // It is possible that liblzma version is different than the command
1019         // line tool version, so print both.
1020         printf("xz (" PACKAGE_NAME ") " LZMA_VERSION_STRING "\n");
1021         printf("liblzma %s\n", lzma_version_string());
1022         tuklib_exit(E_SUCCESS, E_ERROR, verbosity != V_SILENT);
1023 }
1024
1025
1026 extern void
1027 message_help(bool long_help)
1028 {
1029         printf(_("Usage: %s [OPTION]... [FILE]...\n"
1030                         "Compress or decompress FILEs in the .xz format.\n\n"),
1031                         progname);
1032
1033         puts(_("Mandatory arguments to long options are mandatory for "
1034                         "short options too.\n"));
1035
1036         if (long_help)
1037                 puts(_(" Operation mode:\n"));
1038
1039         puts(_(
1040 "  -z, --compress      force compression\n"
1041 "  -d, --decompress    force decompression\n"
1042 "  -t, --test          test compressed file integrity\n"
1043 "  -l, --list          list information about files"));
1044
1045         if (long_help)
1046                 puts(_("\n Operation modifiers:\n"));
1047
1048         puts(_(
1049 "  -k, --keep          keep (don't delete) input files\n"
1050 "  -f, --force         force overwrite of output file and (de)compress links\n"
1051 "  -c, --stdout        write to standard output and don't delete input files"));
1052
1053         if (long_help)
1054                 puts(_(
1055 "  -S, --suffix=.SUF   use the suffix `.SUF' on compressed files\n"
1056 "      --files=[FILE]  read filenames to process from FILE; if FILE is\n"
1057 "                      omitted, filenames are read from the standard input;\n"
1058 "                      filenames must be terminated with the newline character\n"
1059 "      --files0=[FILE] like --files but use the null character as terminator"));
1060
1061         if (long_help) {
1062                 puts(_("\n Basic file format and compression options:\n"));
1063                 puts(_(
1064 "  -F, --format=FMT    file format to encode or decode; possible values are\n"
1065 "                      `auto' (default), `xz', `lzma', and `raw'\n"
1066 "  -C, --check=CHECK   integrity check type: `crc32', `crc64' (default),\n"
1067 "                      or `sha256'"));
1068         }
1069
1070         puts(_(
1071 "  -0 .. -9            compression preset; 0-2 fast compression, 3-5 good\n"
1072 "                      compression, 6-9 excellent compression; default is 6"));
1073
1074         puts(_(
1075 "  -e, --extreme       use more CPU time when encoding to increase compression\n"
1076 "                      ratio without increasing memory usage of the decoder"));
1077
1078         if (long_help)
1079                 puts(_(
1080 "  -M, --memory=NUM    use roughly NUM bytes of memory at maximum; 0 indicates\n"
1081 "                      the default setting, which depends on the operation mode\n"
1082 "                      and the amount of physical memory (RAM)"));
1083
1084         if (long_help) {
1085                 puts(_(
1086 "\n Custom filter chain for compression (alternative for using presets):"));
1087
1088 #if defined(HAVE_ENCODER_LZMA1) || defined(HAVE_DECODER_LZMA1) \
1089                 || defined(HAVE_ENCODER_LZMA2) || defined(HAVE_DECODER_LZMA2)
1090                 puts(_(
1091 "\n"
1092 "  --lzma1[=OPTS]      LZMA1 or LZMA2; OPTS is a comma-separated list of zero or\n"
1093 "  --lzma2[=OPTS]      more of the following options (valid values; default):\n"
1094 "                        preset=NUM reset options to preset number NUM (0-9)\n"
1095 "                        dict=NUM   dictionary size (4KiB - 1536MiB; 8MiB)\n"
1096 "                        lc=NUM     number of literal context bits (0-4; 3)\n"
1097 "                        lp=NUM     number of literal position bits (0-4; 0)\n"
1098 "                        pb=NUM     number of position bits (0-4; 2)\n"
1099 "                        mode=MODE  compression mode (fast, normal; normal)\n"
1100 "                        nice=NUM   nice length of a match (2-273; 64)\n"
1101 "                        mf=NAME    match finder (hc3, hc4, bt2, bt3, bt4; bt4)\n"
1102 "                        depth=NUM  maximum search depth; 0=automatic (default)"));
1103 #endif
1104
1105                 puts(_(
1106 "\n"
1107 "  --x86[=OPTS]        x86 BCJ filter\n"
1108 "  --powerpc[=OPTS]    PowerPC BCJ filter (big endian only)\n"
1109 "  --ia64[=OPTS]       IA64 (Itanium) BCJ filter\n"
1110 "  --arm[=OPTS]        ARM BCJ filter (little endian only)\n"
1111 "  --armthumb[=OPTS]   ARM-Thumb BCJ filter (little endian only)\n"
1112 "  --sparc[=OPTS]      SPARC BCJ filter\n"
1113 "                      Valid OPTS for all BCJ filters:\n"
1114 "                        start=NUM  start offset for conversions (default=0)"));
1115
1116 #if defined(HAVE_ENCODER_DELTA) || defined(HAVE_DECODER_DELTA)
1117                 puts(_(
1118 "\n"
1119 "  --delta[=OPTS]      Delta filter; valid OPTS (valid values; default):\n"
1120 "                        dist=NUM   distance between bytes being subtracted\n"
1121 "                                   from each other (1-256; 1)"));
1122 #endif
1123
1124 #if defined(HAVE_ENCODER_SUBBLOCK) || defined(HAVE_DECODER_SUBBLOCK)
1125                 puts(_(
1126 "\n"
1127 "  --subblock[=OPTS]   Subblock filter; valid OPTS (valid values; default):\n"
1128 "                        size=NUM   number of bytes of data per subblock\n"
1129 "                                   (1 - 256Mi; 4Ki)\n"
1130 "                        rle=NUM    run-length encoder chunk size (0-256; 0)"));
1131 #endif
1132         }
1133
1134         if (long_help)
1135                 puts(_("\n Other options:\n"));
1136
1137         puts(_(
1138 "  -q, --quiet         suppress warnings; specify twice to suppress errors too\n"
1139 "  -v, --verbose       be verbose; specify twice for even more verbose"));
1140
1141         if (long_help)
1142                 puts(_(
1143 "  -Q, --no-warn       make warnings not affect the exit status"));
1144
1145         if (long_help)
1146                 puts(_(
1147 "\n"
1148 "  -h, --help          display the short help (lists only the basic options)\n"
1149 "  -H, --long-help     display this long help"));
1150         else
1151                 puts(_(
1152 "  -h, --help          display this short help\n"
1153 "  -H, --long-help     display the long help (lists also the advanced options)"));
1154
1155         puts(_(
1156 "  -V, --version       display the version number"));
1157
1158         puts(_("\nWith no FILE, or when FILE is -, read standard input.\n"));
1159
1160         if (long_help) {
1161                 printf(_(
1162 "On this system and configuration, this program will use a maximum of roughly\n"
1163 "%s MiB RAM and "), uint64_to_str(hardware_memlimit_get() / (1024 * 1024), 0));
1164                 printf(N_("one thread.\n\n", "%s threads.\n\n",
1165                                 hardware_threadlimit_get()),
1166                                 uint64_to_str(hardware_threadlimit_get(), 0));
1167         }
1168
1169         printf(_("Report bugs to <%s> (in English or Finnish).\n"),
1170                         PACKAGE_BUGREPORT);
1171         printf(_("%s home page: <%s>\n"), PACKAGE_NAME, PACKAGE_HOMEPAGE);
1172
1173         tuklib_exit(E_SUCCESS, E_ERROR, verbosity != V_SILENT);
1174 }