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