Skip to content

Commit f4c3edc

Browse files
peffgitster
authored andcommitted
vreportf: avoid intermediate buffer
When we call "die(fmt, args...)", we end up in vreportf with two pieces of information: 1. The prefix "fatal: " 2. The original fmt and va_list of args. We format item (2) into a temporary buffer, and then fprintf the prefix and the temporary buffer, along with a newline. This has the unfortunate side effect of truncating any error messages that are longer than 4096 bytes. Instead, let's use separate calls for the prefix and newline, letting us hand the item (2) directly to vfprintf. This is essentially undoing d048a96 (print warning/error/fatal messages in one shot, 2007-11-09), which tried to have the whole output end up in a single `write` call. But we can address this instead by explicitly requesting line-buffering for the output handle, and by making sure that the buffer is empty before we start (so that outputting the prefix does not cause a flush due to hitting the buffer limit). We may still break the output into two writes if the content is larger than our buffer, but there's not much we can do there; depending on the stdio implementation, that might have happened even with a single fprintf call. Signed-off-by: Jeff King <[email protected]> Signed-off-by: Junio C Hamano <[email protected]>
1 parent 3b331e9 commit f4c3edc

File tree

1 file changed

+12
-3
lines changed

1 file changed

+12
-3
lines changed

usage.c

Lines changed: 12 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -7,13 +7,21 @@
77
#include "cache.h"
88

99
static FILE *error_handle;
10+
static int tweaked_error_buffering;
1011

1112
void vreportf(const char *prefix, const char *err, va_list params)
1213
{
13-
char msg[4096];
1414
FILE *fh = error_handle ? error_handle : stderr;
15-
vsnprintf(msg, sizeof(msg), err, params);
16-
fprintf(fh, "%s%s\n", prefix, msg);
15+
16+
fflush(fh);
17+
if (!tweaked_error_buffering) {
18+
setvbuf(fh, NULL, _IOLBF, 0);
19+
tweaked_error_buffering = 1;
20+
}
21+
22+
fputs(prefix, fh);
23+
vfprintf(fh, err, params);
24+
fputc('\n', fh);
1725
}
1826

1927
static NORETURN void usage_builtin(const char *err, va_list params)
@@ -70,6 +78,7 @@ void set_die_is_recursing_routine(int (*routine)(void))
7078
void set_error_handle(FILE *fh)
7179
{
7280
error_handle = fh;
81+
tweaked_error_buffering = 0;
7382
}
7483

7584
void NORETURN usagef(const char *err, ...)

0 commit comments

Comments
 (0)