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