aboutsummaryrefslogtreecommitdiffstats
path: root/vweprintf.c
blob: f68455351f696ac52dadda8f40e3f3f904fa9c10 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
/* See LICENSE file for copyright and license details. */
#include "common.h"
#ifndef TEST

#if defined(__clang__)
# pragma clang diagnostic ignored "-Wformat-nonliteral"
#endif


extern char *argv0;


int libsimple_default_failure_exit = 1;
void (*libsimple_eprintf_preprint)(void) = NULL;
void (*libsimple_eprintf_postprint)(void) = NULL;


void
libsimple_vweprintf(const char *fmt, va_list ap)
{
	int saved_errno = errno, r;
	const char *end = strchr(fmt, '\0');
	const char *prefix1 = argv0;
	const char *prefix2 = ": ";
	const char *suffix1 = "";
	const char *suffix2 = "";
	const char *suffix3 = "";
	char *message = NULL;
	va_list ap1;
	va_list ap2;

	if (!argv0 || !strncmp(fmt, "usage: ", sizeof("usage: ") - 1))
		prefix1 = prefix2 = "";

	va_copy(ap1, ap);
	va_copy(ap2, ap);
	r = vsnprintf(NULL, 0, fmt, ap1);
	if (0 <= r && r < 8096) {
#if defined(__clang__)
# pragma clang diagnostic push
# pragma clang diagnostic ignored "-Walloca"
#endif
		message = alloca((size_t)r + 1);
		vsprintf(message, fmt, ap2);
#if defined(__clang__)
# pragma clang diagnostic pop
#endif
	}
	va_end(ap2);
	va_end(ap1);

	if (!*fmt) {
		suffix1 = strerror(saved_errno);
		suffix2 = "\n";
	} else if (end[-1] == ':') {
		suffix1 = " ";
		suffix2 = strerror(saved_errno);
		suffix3 = "\n";
	} else if (end[-1] != '\n') {
		suffix1 = "\n";
	}

	if (libsimple_eprintf_preprint)
		libsimple_eprintf_preprint();
	if (message) {
		/* This is to avoid mangling when multiple processes are writting. */
		fprintf(stderr, "%s%s%s%s%s%s", prefix1, prefix2, message, suffix1, suffix2, suffix3);
	} else {
		fprintf(stderr, "%s%s", prefix1, prefix2);
		vfprintf(stderr, fmt, ap);
		fprintf(stderr, "%s%s%s", suffix1, suffix2, suffix3);
	}
	if (libsimple_eprintf_postprint)
		libsimple_eprintf_postprint();

	errno = saved_errno;
}


#else
#include "test.h"

int
main(void)
{
	return 0; /* Tested via libsimple_weprintf */
}

#endif