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