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