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