trace: handle NULL argument in trace_disable()
[git] / trace.c
1 /*
2  * GIT - The information manager from hell
3  *
4  * Copyright (C) 2000-2002 Michael R. Elkins <me@mutt.org>
5  * Copyright (C) 2002-2004 Oswald Buddenhagen <ossi@users.sf.net>
6  * Copyright (C) 2004 Theodore Y. Ts'o <tytso@mit.edu>
7  * Copyright (C) 2006 Mike McCormack
8  * Copyright (C) 2006 Christian Couder
9  *
10  *  This program is free software; you can redistribute it and/or modify
11  *  it under the terms of the GNU General Public License as published by
12  *  the Free Software Foundation; either version 2 of the License, or
13  *  (at your option) any later version.
14  *
15  *  This program is distributed in the hope that it will be useful,
16  *  but WITHOUT ANY WARRANTY; without even the implied warranty of
17  *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
18  *  GNU General Public License for more details.
19  *
20  *  You should have received a copy of the GNU General Public License
21  *  along with this program; if not, write to the Free Software
22  *  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
23  */
24
25 #include "cache.h"
26 #include "quote.h"
27
28 /*
29  * "Normalize" a key argument by converting NULL to our trace_default,
30  * and otherwise passing through the value. All caller-facing functions
31  * should normalize their inputs in this way, though most get it
32  * for free by calling get_trace_fd() (directly or indirectly).
33  */
34 static void normalize_trace_key(struct trace_key **key)
35 {
36         static struct trace_key trace_default = { "GIT_TRACE" };
37         if (!*key)
38                 *key = &trace_default;
39 }
40
41 /* Get a trace file descriptor from "key" env variable. */
42 static int get_trace_fd(struct trace_key *key)
43 {
44         const char *trace;
45
46         normalize_trace_key(&key);
47
48         /* don't open twice */
49         if (key->initialized)
50                 return key->fd;
51
52         trace = getenv(key->key);
53
54         if (!trace || !strcmp(trace, "") ||
55             !strcmp(trace, "0") || !strcasecmp(trace, "false"))
56                 key->fd = 0;
57         else if (!strcmp(trace, "1") || !strcasecmp(trace, "true"))
58                 key->fd = STDERR_FILENO;
59         else if (strlen(trace) == 1 && isdigit(*trace))
60                 key->fd = atoi(trace);
61         else if (is_absolute_path(trace)) {
62                 int fd = open(trace, O_WRONLY | O_APPEND | O_CREAT, 0666);
63                 if (fd == -1) {
64                         fprintf(stderr,
65                                 "Could not open '%s' for tracing: %s\n"
66                                 "Defaulting to tracing on stderr...\n",
67                                 trace, strerror(errno));
68                         key->fd = STDERR_FILENO;
69                 } else {
70                         key->fd = fd;
71                         key->need_close = 1;
72                 }
73         } else {
74                 fprintf(stderr, "What does '%s' for %s mean?\n"
75                         "If you want to trace into a file, then please set "
76                         "%s to an absolute pathname (starting with /).\n"
77                         "Defaulting to tracing on stderr...\n",
78                         trace, key->key, key->key);
79                 key->fd = STDERR_FILENO;
80         }
81
82         key->initialized = 1;
83         return key->fd;
84 }
85
86 void trace_disable(struct trace_key *key)
87 {
88         normalize_trace_key(&key);
89
90         if (key->need_close)
91                 close(key->fd);
92         key->fd = 0;
93         key->initialized = 1;
94         key->need_close = 0;
95 }
96
97 static const char err_msg[] = "Could not trace into fd given by "
98         "GIT_TRACE environment variable";
99
100 static int prepare_trace_line(const char *file, int line,
101                               struct trace_key *key, struct strbuf *buf)
102 {
103         static struct trace_key trace_bare = TRACE_KEY_INIT(BARE);
104         struct timeval tv;
105         struct tm tm;
106         time_t secs;
107
108         if (!trace_want(key))
109                 return 0;
110
111         set_try_to_free_routine(NULL);  /* is never reset */
112
113         /* unit tests may want to disable additional trace output */
114         if (trace_want(&trace_bare))
115                 return 1;
116
117         /* print current timestamp */
118         gettimeofday(&tv, NULL);
119         secs = tv.tv_sec;
120         localtime_r(&secs, &tm);
121         strbuf_addf(buf, "%02d:%02d:%02d.%06ld ", tm.tm_hour, tm.tm_min,
122                     tm.tm_sec, (long) tv.tv_usec);
123
124 #ifdef HAVE_VARIADIC_MACROS
125         /* print file:line */
126         strbuf_addf(buf, "%s:%d ", file, line);
127         /* align trace output (column 40 catches most files names in git) */
128         while (buf->len < 40)
129                 strbuf_addch(buf, ' ');
130 #endif
131
132         return 1;
133 }
134
135 void trace_verbatim(struct trace_key *key, const void *buf, unsigned len)
136 {
137         if (!trace_want(key))
138                 return;
139         write_or_whine_pipe(get_trace_fd(key), buf, len, err_msg);
140 }
141
142 static void print_trace_line(struct trace_key *key, struct strbuf *buf)
143 {
144         strbuf_complete_line(buf);
145
146         write_or_whine_pipe(get_trace_fd(key), buf->buf, buf->len, err_msg);
147         strbuf_release(buf);
148 }
149
150 static void trace_vprintf_fl(const char *file, int line, struct trace_key *key,
151                              const char *format, va_list ap)
152 {
153         struct strbuf buf = STRBUF_INIT;
154
155         if (!prepare_trace_line(file, line, key, &buf))
156                 return;
157
158         strbuf_vaddf(&buf, format, ap);
159         print_trace_line(key, &buf);
160 }
161
162 static void trace_argv_vprintf_fl(const char *file, int line,
163                                   const char **argv, const char *format,
164                                   va_list ap)
165 {
166         struct strbuf buf = STRBUF_INIT;
167
168         if (!prepare_trace_line(file, line, NULL, &buf))
169                 return;
170
171         strbuf_vaddf(&buf, format, ap);
172
173         sq_quote_argv(&buf, argv, 0);
174         print_trace_line(NULL, &buf);
175 }
176
177 void trace_strbuf_fl(const char *file, int line, struct trace_key *key,
178                      const struct strbuf *data)
179 {
180         struct strbuf buf = STRBUF_INIT;
181
182         if (!prepare_trace_line(file, line, key, &buf))
183                 return;
184
185         strbuf_addbuf(&buf, data);
186         print_trace_line(key, &buf);
187 }
188
189 static struct trace_key trace_perf_key = TRACE_KEY_INIT(PERFORMANCE);
190
191 static void trace_performance_vprintf_fl(const char *file, int line,
192                                          uint64_t nanos, const char *format,
193                                          va_list ap)
194 {
195         struct strbuf buf = STRBUF_INIT;
196
197         if (!prepare_trace_line(file, line, &trace_perf_key, &buf))
198                 return;
199
200         strbuf_addf(&buf, "performance: %.9f s", (double) nanos / 1000000000);
201
202         if (format && *format) {
203                 strbuf_addstr(&buf, ": ");
204                 strbuf_vaddf(&buf, format, ap);
205         }
206
207         print_trace_line(&trace_perf_key, &buf);
208 }
209
210 #ifndef HAVE_VARIADIC_MACROS
211
212 void trace_printf(const char *format, ...)
213 {
214         va_list ap;
215         va_start(ap, format);
216         trace_vprintf_fl(NULL, 0, NULL, format, ap);
217         va_end(ap);
218 }
219
220 void trace_printf_key(struct trace_key *key, const char *format, ...)
221 {
222         va_list ap;
223         va_start(ap, format);
224         trace_vprintf_fl(NULL, 0, key, format, ap);
225         va_end(ap);
226 }
227
228 void trace_argv_printf(const char **argv, const char *format, ...)
229 {
230         va_list ap;
231         va_start(ap, format);
232         trace_argv_vprintf_fl(NULL, 0, argv, format, ap);
233         va_end(ap);
234 }
235
236 void trace_strbuf(struct trace_key *key, const struct strbuf *data)
237 {
238         trace_strbuf_fl(NULL, 0, key, data);
239 }
240
241 void trace_performance(uint64_t nanos, const char *format, ...)
242 {
243         va_list ap;
244         va_start(ap, format);
245         trace_performance_vprintf_fl(NULL, 0, nanos, format, ap);
246         va_end(ap);
247 }
248
249 void trace_performance_since(uint64_t start, const char *format, ...)
250 {
251         va_list ap;
252         va_start(ap, format);
253         trace_performance_vprintf_fl(NULL, 0, getnanotime() - start,
254                                      format, ap);
255         va_end(ap);
256 }
257
258 #else
259
260 void trace_printf_key_fl(const char *file, int line, struct trace_key *key,
261                          const char *format, ...)
262 {
263         va_list ap;
264         va_start(ap, format);
265         trace_vprintf_fl(file, line, key, format, ap);
266         va_end(ap);
267 }
268
269 void trace_argv_printf_fl(const char *file, int line, const char **argv,
270                           const char *format, ...)
271 {
272         va_list ap;
273         va_start(ap, format);
274         trace_argv_vprintf_fl(file, line, argv, format, ap);
275         va_end(ap);
276 }
277
278 void trace_performance_fl(const char *file, int line, uint64_t nanos,
279                               const char *format, ...)
280 {
281         va_list ap;
282         va_start(ap, format);
283         trace_performance_vprintf_fl(file, line, nanos, format, ap);
284         va_end(ap);
285 }
286
287 #endif /* HAVE_VARIADIC_MACROS */
288
289
290 static const char *quote_crnl(const char *path)
291 {
292         static struct strbuf new_path = STRBUF_INIT;
293
294         if (!path)
295                 return NULL;
296
297         strbuf_reset(&new_path);
298
299         while (*path) {
300                 switch (*path) {
301                 case '\\': strbuf_addstr(&new_path, "\\\\"); break;
302                 case '\n': strbuf_addstr(&new_path, "\\n"); break;
303                 case '\r': strbuf_addstr(&new_path, "\\r"); break;
304                 default:
305                         strbuf_addch(&new_path, *path);
306                 }
307                 path++;
308         }
309         return new_path.buf;
310 }
311
312 /* FIXME: move prefix to startup_info struct and get rid of this arg */
313 void trace_repo_setup(const char *prefix)
314 {
315         static struct trace_key key = TRACE_KEY_INIT(SETUP);
316         const char *git_work_tree;
317         char *cwd;
318
319         if (!trace_want(&key))
320                 return;
321
322         cwd = xgetcwd();
323
324         if (!(git_work_tree = get_git_work_tree()))
325                 git_work_tree = "(null)";
326
327         if (!prefix)
328                 prefix = "(null)";
329
330         trace_printf_key(&key, "setup: git_dir: %s\n", quote_crnl(get_git_dir()));
331         trace_printf_key(&key, "setup: git_common_dir: %s\n", quote_crnl(get_git_common_dir()));
332         trace_printf_key(&key, "setup: worktree: %s\n", quote_crnl(git_work_tree));
333         trace_printf_key(&key, "setup: cwd: %s\n", quote_crnl(cwd));
334         trace_printf_key(&key, "setup: prefix: %s\n", quote_crnl(prefix));
335
336         free(cwd);
337 }
338
339 int trace_want(struct trace_key *key)
340 {
341         return !!get_trace_fd(key);
342 }
343
344 #if defined(HAVE_CLOCK_GETTIME) && defined(HAVE_CLOCK_MONOTONIC)
345
346 static inline uint64_t highres_nanos(void)
347 {
348         struct timespec ts;
349         if (clock_gettime(CLOCK_MONOTONIC, &ts))
350                 return 0;
351         return (uint64_t) ts.tv_sec * 1000000000 + ts.tv_nsec;
352 }
353
354 #elif defined (GIT_WINDOWS_NATIVE)
355
356 static inline uint64_t highres_nanos(void)
357 {
358         static uint64_t high_ns, scaled_low_ns;
359         static int scale;
360         LARGE_INTEGER cnt;
361
362         if (!scale) {
363                 if (!QueryPerformanceFrequency(&cnt))
364                         return 0;
365
366                 /* high_ns = number of ns per cnt.HighPart */
367                 high_ns = (1000000000LL << 32) / (uint64_t) cnt.QuadPart;
368
369                 /*
370                  * Number of ns per cnt.LowPart is 10^9 / frequency (or
371                  * high_ns >> 32). For maximum precision, we scale this factor
372                  * so that it just fits within 32 bit (i.e. won't overflow if
373                  * multiplied with cnt.LowPart).
374                  */
375                 scaled_low_ns = high_ns;
376                 scale = 32;
377                 while (scaled_low_ns >= 0x100000000LL) {
378                         scaled_low_ns >>= 1;
379                         scale--;
380                 }
381         }
382
383         /* if QPF worked on initialization, we expect QPC to work as well */
384         QueryPerformanceCounter(&cnt);
385
386         return (high_ns * cnt.HighPart) +
387                ((scaled_low_ns * cnt.LowPart) >> scale);
388 }
389
390 #else
391 # define highres_nanos() 0
392 #endif
393
394 static inline uint64_t gettimeofday_nanos(void)
395 {
396         struct timeval tv;
397         gettimeofday(&tv, NULL);
398         return (uint64_t) tv.tv_sec * 1000000000 + tv.tv_usec * 1000;
399 }
400
401 /*
402  * Returns nanoseconds since the epoch (01/01/1970), for performance tracing
403  * (i.e. favoring high precision over wall clock time accuracy).
404  */
405 uint64_t getnanotime(void)
406 {
407         static uint64_t offset;
408         if (offset > 1) {
409                 /* initialization succeeded, return offset + high res time */
410                 return offset + highres_nanos();
411         } else if (offset == 1) {
412                 /* initialization failed, fall back to gettimeofday */
413                 return gettimeofday_nanos();
414         } else {
415                 /* initialize offset if high resolution timer works */
416                 uint64_t now = gettimeofday_nanos();
417                 uint64_t highres = highres_nanos();
418                 if (highres)
419                         offset = now - highres;
420                 else
421                         offset = 1;
422                 return now;
423         }
424 }
425
426 static uint64_t command_start_time;
427 static struct strbuf command_line = STRBUF_INIT;
428
429 static void print_command_performance_atexit(void)
430 {
431         trace_performance_since(command_start_time, "git command:%s",
432                                 command_line.buf);
433 }
434
435 void trace_command_performance(const char **argv)
436 {
437         if (!trace_want(&trace_perf_key))
438                 return;
439
440         if (!command_start_time)
441                 atexit(print_command_performance_atexit);
442
443         strbuf_reset(&command_line);
444         sq_quote_argv(&command_line, argv, 0);
445         command_start_time = getnanotime();
446 }