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