win32: plug memory leak on realloc() failure in syslog()
[git/git.git] / compat / win32 / syslog.c
CommitLineData
088d8802 1#include "../../git-compat-util.h"
088d8802
MP
2
3static HANDLE ms_eventlog;
4
5void openlog(const char *ident, int logopt, int facility)
6{
7 if (ms_eventlog)
8 return;
9
10 ms_eventlog = RegisterEventSourceA(NULL, ident);
11
12 if (!ms_eventlog)
13 warning("RegisterEventSource() failed: %lu", GetLastError());
14}
15
16void syslog(int priority, const char *fmt, ...)
17{
088d8802 18 WORD logtype;
2a6b149c 19 char *str, *pos;
088d8802
MP
20 int str_len;
21 va_list ap;
22
23 if (!ms_eventlog)
24 return;
25
26 va_start(ap, fmt);
27 str_len = vsnprintf(NULL, 0, fmt, ap);
28 va_end(ap);
29
30 if (str_len < 0) {
df8e3139 31 warning_errno("vsnprintf failed");
088d8802
MP
32 return;
33 }
34
50a6c8ef 35 str = malloc(st_add(str_len, 1));
2a6b149c 36 if (!str) {
df8e3139 37 warning_errno("malloc failed");
2a6b149c
EFL
38 return;
39 }
40
088d8802
MP
41 va_start(ap, fmt);
42 vsnprintf(str, str_len + 1, fmt, ap);
43 va_end(ap);
2a6b149c
EFL
44
45 while ((pos = strstr(str, "%1")) != NULL) {
149d8cbb 46 char *oldstr = str;
50a6c8ef 47 str = realloc(str, st_add(++str_len, 1));
2a6b149c 48 if (!str) {
149d8cbb 49 free(oldstr);
df8e3139 50 warning_errno("realloc failed");
2a6b149c
EFL
51 return;
52 }
53 memmove(pos + 2, pos + 1, strlen(pos));
54 pos[1] = ' ';
55 }
088d8802
MP
56
57 switch (priority) {
58 case LOG_EMERG:
59 case LOG_ALERT:
60 case LOG_CRIT:
61 case LOG_ERR:
62 logtype = EVENTLOG_ERROR_TYPE;
63 break;
64
65 case LOG_WARNING:
66 logtype = EVENTLOG_WARNING_TYPE;
67 break;
68
69 case LOG_NOTICE:
70 case LOG_INFO:
71 case LOG_DEBUG:
72 default:
73 logtype = EVENTLOG_INFORMATION_TYPE;
74 break;
75 }
76
77 ReportEventA(ms_eventlog, logtype, 0, 0, NULL, 1, 0,
2a6b149c
EFL
78 (const char **)&str, NULL);
79 free(str);
088d8802 80}