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