log: drop global current_time
[fw/openocd] / src / helper / log.c
1 /***************************************************************************
2  *   Copyright (C) 2005 by Dominic Rath                                    *
3  *   Dominic.Rath@gmx.de                                                   *
4  *                                                                         *
5  *   Copyright (C) 2007-2010 Ã˜yvind Harboe                                 *
6  *   oyvind.harboe@zylin.com                                               *
7  *                                                                         *
8  *   Copyright (C) 2008 by Spencer Oliver                                  *
9  *   spen@spen-soft.co.uk                                                  *
10  *                                                                         *
11  *   This program is free software; you can redistribute it and/or modify  *
12  *   it under the terms of the GNU General Public License as published by  *
13  *   the Free Software Foundation; either version 2 of the License, or     *
14  *   (at your option) any later version.                                   *
15  *                                                                         *
16  *   This program is distributed in the hope that it will be useful,       *
17  *   but WITHOUT ANY WARRANTY; without even the implied warranty of        *
18  *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the         *
19  *   GNU General Public License for more details.                          *
20  *                                                                         *
21  *   You should have received a copy of the GNU General Public License     *
22  *   along with this program.  If not, see <http://www.gnu.org/licenses/>. *
23  ***************************************************************************/
24
25 #ifdef HAVE_CONFIG_H
26 #include "config.h"
27 #endif
28
29 #include "log.h"
30 #include "command.h"
31 #include "replacements.h"
32 #include "time_support.h"
33
34 #include <stdarg.h>
35
36 #ifdef _DEBUG_FREE_SPACE_
37 #ifdef HAVE_MALLOC_H
38 #include <malloc.h>
39 #else
40 #error "malloc.h is required to use --enable-malloc-logging"
41 #endif
42 #endif
43
44 int debug_level = LOG_LVL_INFO;
45
46 static FILE *log_output;
47 static struct log_callback *log_callbacks;
48
49 static int64_t last_time;
50
51 static int64_t start;
52
53 static const char * const log_strings[6] = {
54         "User : ",
55         "Error: ",
56         "Warn : ",      /* want a space after each colon, all same width, colons aligned */
57         "Info : ",
58         "Debug: ",
59         "Debug: "
60 };
61
62 static int count;
63
64 /* forward the log to the listeners */
65 static void log_forward(const char *file, unsigned line, const char *function, const char *string)
66 {
67         struct log_callback *cb, *next;
68         cb = log_callbacks;
69         /* DANGER!!!! the log callback can remove itself!!!! */
70         while (cb) {
71                 next = cb->next;
72                 cb->fn(cb->priv, file, line, function, string);
73                 cb = next;
74         }
75 }
76
77 /* The log_puts() serves two somewhat different goals:
78  *
79  * - logging
80  * - feeding low-level info to the user in GDB or Telnet
81  *
82  * The latter dictates that strings without newline are not logged, lest there
83  * will be *MANY log lines when sending one char at the time(e.g.
84  * target_request.c).
85  *
86  */
87 static void log_puts(enum log_levels level,
88         const char *file,
89         int line,
90         const char *function,
91         const char *string)
92 {
93         char *f;
94
95         if (!log_output) {
96                 /* log_init() not called yet; print on stderr */
97                 fputs(string, stderr);
98                 fflush(stderr);
99                 return;
100         }
101
102         if (level == LOG_LVL_OUTPUT) {
103                 /* do not prepend any headers, just print out what we were given and return */
104                 fputs(string, log_output);
105                 fflush(log_output);
106                 return;
107         }
108
109         f = strrchr(file, '/');
110         if (f)
111                 file = f + 1;
112
113         if (strlen(string) > 0) {
114                 if (debug_level >= LOG_LVL_DEBUG) {
115                         /* print with count and time information */
116                         int64_t t = timeval_ms() - start;
117 #ifdef _DEBUG_FREE_SPACE_
118                         struct mallinfo info;
119                         info = mallinfo();
120 #endif
121                         fprintf(log_output, "%s%d %" PRId64 " %s:%d %s()"
122 #ifdef _DEBUG_FREE_SPACE_
123                                 " %d"
124 #endif
125                                 ": %s", log_strings[level + 1], count, t, file, line, function,
126 #ifdef _DEBUG_FREE_SPACE_
127                                 info.fordblks,
128 #endif
129                                 string);
130                 } else {
131                         /* if we are using gdb through pipes then we do not want any output
132                          * to the pipe otherwise we get repeated strings */
133                         fprintf(log_output, "%s%s",
134                                 (level > LOG_LVL_USER) ? log_strings[level + 1] : "", string);
135                 }
136         } else {
137                 /* Empty strings are sent to log callbacks to keep e.g. gdbserver alive, here we do
138                  *nothing. */
139         }
140
141         fflush(log_output);
142
143         /* Never forward LOG_LVL_DEBUG, too verbose and they can be found in the log if need be */
144         if (level <= LOG_LVL_INFO)
145                 log_forward(file, line, function, string);
146 }
147
148 void log_printf(enum log_levels level,
149         const char *file,
150         unsigned line,
151         const char *function,
152         const char *format,
153         ...)
154 {
155         char *string;
156         va_list ap;
157
158         count++;
159         if (level > debug_level)
160                 return;
161
162         va_start(ap, format);
163
164         string = alloc_vprintf(format, ap);
165         if (string) {
166                 log_puts(level, file, line, function, string);
167                 free(string);
168         }
169
170         va_end(ap);
171 }
172
173 void log_vprintf_lf(enum log_levels level, const char *file, unsigned line,
174                 const char *function, const char *format, va_list args)
175 {
176         char *tmp;
177
178         count++;
179
180         if (level > debug_level)
181                 return;
182
183         tmp = alloc_vprintf(format, args);
184
185         if (!tmp)
186                 return;
187
188         /*
189          * Note: alloc_vprintf() guarantees that the buffer is at least one
190          * character longer.
191          */
192         strcat(tmp, "\n");
193         log_puts(level, file, line, function, tmp);
194         free(tmp);
195 }
196
197 void log_printf_lf(enum log_levels level,
198         const char *file,
199         unsigned line,
200         const char *function,
201         const char *format,
202         ...)
203 {
204         va_list ap;
205
206         va_start(ap, format);
207         log_vprintf_lf(level, file, line, function, format, ap);
208         va_end(ap);
209 }
210
211 COMMAND_HANDLER(handle_debug_level_command)
212 {
213         if (CMD_ARGC == 1) {
214                 int new_level;
215                 COMMAND_PARSE_NUMBER(int, CMD_ARGV[0], new_level);
216                 if ((new_level > LOG_LVL_DEBUG_IO) || (new_level < LOG_LVL_SILENT)) {
217                         LOG_ERROR("level must be between %d and %d", LOG_LVL_SILENT, LOG_LVL_DEBUG_IO);
218                         return ERROR_COMMAND_SYNTAX_ERROR;
219                 }
220                 debug_level = new_level;
221         } else if (CMD_ARGC > 1)
222                 return ERROR_COMMAND_SYNTAX_ERROR;
223
224         command_print(CMD, "debug_level: %i", debug_level);
225
226         return ERROR_OK;
227 }
228
229 COMMAND_HANDLER(handle_log_output_command)
230 {
231         if (CMD_ARGC == 0 || (CMD_ARGC == 1 && strcmp(CMD_ARGV[0], "default") == 0)) {
232                 if (log_output != stderr && log_output) {
233                         /* Close previous log file, if it was open and wasn't stderr. */
234                         fclose(log_output);
235                 }
236                 log_output = stderr;
237                 LOG_DEBUG("set log_output to default");
238                 return ERROR_OK;
239         }
240         if (CMD_ARGC == 1) {
241                 FILE *file = fopen(CMD_ARGV[0], "w");
242                 if (!file) {
243                         LOG_ERROR("failed to open output log '%s'", CMD_ARGV[0]);
244                         return ERROR_FAIL;
245                 }
246                 if (log_output != stderr && log_output) {
247                         /* Close previous log file, if it was open and wasn't stderr. */
248                         fclose(log_output);
249                 }
250                 log_output = file;
251                 LOG_DEBUG("set log_output to \"%s\"", CMD_ARGV[0]);
252                 return ERROR_OK;
253         }
254
255         return ERROR_COMMAND_SYNTAX_ERROR;
256 }
257
258 static const struct command_registration log_command_handlers[] = {
259         {
260                 .name = "log_output",
261                 .handler = handle_log_output_command,
262                 .mode = COMMAND_ANY,
263                 .help = "redirect logging to a file (default: stderr)",
264                 .usage = "[file_name | \"default\"]",
265         },
266         {
267                 .name = "debug_level",
268                 .handler = handle_debug_level_command,
269                 .mode = COMMAND_ANY,
270                 .help = "Sets the verbosity level of debugging output. "
271                         "0 shows errors only; 1 adds warnings; "
272                         "2 (default) adds other info; 3 adds debugging; "
273                         "4 adds extra verbose debugging.",
274                 .usage = "number",
275         },
276         COMMAND_REGISTRATION_DONE
277 };
278
279 int log_register_commands(struct command_context *cmd_ctx)
280 {
281         return register_commands(cmd_ctx, NULL, log_command_handlers);
282 }
283
284 void log_init(void)
285 {
286         /* set defaults for daemon configuration,
287          * if not set by cmdline or cfgfile */
288         char *debug_env = getenv("OPENOCD_DEBUG_LEVEL");
289         if (debug_env) {
290                 int value;
291                 int retval = parse_int(debug_env, &value);
292                 if (retval == ERROR_OK &&
293                                 debug_level >= LOG_LVL_SILENT &&
294                                 debug_level <= LOG_LVL_DEBUG_IO)
295                                 debug_level = value;
296         }
297
298         if (!log_output)
299                 log_output = stderr;
300
301         start = last_time = timeval_ms();
302 }
303
304 void log_exit(void)
305 {
306         if (log_output && log_output != stderr) {
307                 /* Close log file, if it was open and wasn't stderr. */
308                 fclose(log_output);
309         }
310         log_output = NULL;
311 }
312
313 int set_log_output(struct command_context *cmd_ctx, FILE *output)
314 {
315         log_output = output;
316         return ERROR_OK;
317 }
318
319 /* add/remove log callback handler */
320 int log_add_callback(log_callback_fn fn, void *priv)
321 {
322         struct log_callback *cb;
323
324         /* prevent the same callback to be registered more than once, just for sure */
325         for (cb = log_callbacks; cb; cb = cb->next) {
326                 if (cb->fn == fn && cb->priv == priv)
327                         return ERROR_COMMAND_SYNTAX_ERROR;
328         }
329
330         /* alloc memory, it is safe just to return in case of an error, no need for the caller to
331          *check this */
332         cb = malloc(sizeof(struct log_callback));
333         if (!cb)
334                 return ERROR_BUF_TOO_SMALL;
335
336         /* add item to the beginning of the linked list */
337         cb->fn = fn;
338         cb->priv = priv;
339         cb->next = log_callbacks;
340         log_callbacks = cb;
341
342         return ERROR_OK;
343 }
344
345 int log_remove_callback(log_callback_fn fn, void *priv)
346 {
347         struct log_callback *cb, **p;
348
349         for (p = &log_callbacks; (cb = *p); p = &(*p)->next) {
350                 if (cb->fn == fn && cb->priv == priv) {
351                         *p = cb->next;
352                         free(cb);
353                         return ERROR_OK;
354                 }
355         }
356
357         /* no such item */
358         return ERROR_COMMAND_SYNTAX_ERROR;
359 }
360
361 /* return allocated string w/printf() result */
362 char *alloc_vprintf(const char *fmt, va_list ap)
363 {
364         va_list ap_copy;
365         int len;
366         char *string;
367
368         /* determine the length of the buffer needed */
369         va_copy(ap_copy, ap);
370         len = vsnprintf(NULL, 0, fmt, ap_copy);
371         va_end(ap_copy);
372
373         /* allocate and make room for terminating zero. */
374         /* FIXME: The old version always allocated at least one byte extra and
375          * other code depend on that. They should be probably be fixed, but for
376          * now reserve the extra byte. */
377         string = malloc(len + 2);
378         if (!string)
379                 return NULL;
380
381         /* do the real work */
382         vsnprintf(string, len + 1, fmt, ap);
383
384         return string;
385 }
386
387 char *alloc_printf(const char *format, ...)
388 {
389         char *string;
390         va_list ap;
391         va_start(ap, format);
392         string = alloc_vprintf(format, ap);
393         va_end(ap);
394         return string;
395 }
396
397 /* Code must return to the server loop before 1000ms has returned or invoke
398  * this function.
399  *
400  * The GDB connection will time out if it spends >2000ms and you'll get nasty
401  * error messages from GDB:
402  *
403  * Ignoring packet error, continuing...
404  * Reply contains invalid hex digit 116
405  *
406  * While it is possible use "set remotetimeout" to more than the default 2000ms
407  * in GDB, OpenOCD guarantees that it sends keep-alive packages on the
408  * GDB protocol and it is a bug in OpenOCD not to either return to the server
409  * loop or invoke keep_alive() every 1000ms.
410  *
411  * This function will send a keep alive packet if >500ms has passed since last time
412  * it was invoked.
413  *
414  * Note that this function can be invoked often, so it needs to be relatively
415  * fast when invoked more often than every 500ms.
416  *
417  */
418 #define KEEP_ALIVE_KICK_TIME_MS  500
419 #define KEEP_ALIVE_TIMEOUT_MS   1000
420
421 static void gdb_timeout_warning(int64_t delta_time)
422 {
423         extern int gdb_actual_connections;
424
425         if (gdb_actual_connections)
426                 LOG_WARNING("keep_alive() was not invoked in the "
427                         "%d ms timelimit. GDB alive packet not "
428                         "sent! (%" PRId64 " ms). Workaround: increase "
429                         "\"set remotetimeout\" in GDB",
430                         KEEP_ALIVE_TIMEOUT_MS,
431                         delta_time);
432         else
433                 LOG_DEBUG("keep_alive() was not invoked in the "
434                         "%d ms timelimit (%" PRId64 " ms). This may cause "
435                         "trouble with GDB connections.",
436                         KEEP_ALIVE_TIMEOUT_MS,
437                         delta_time);
438 }
439
440 void keep_alive(void)
441 {
442         int64_t current_time = timeval_ms();
443         int64_t delta_time = current_time - last_time;
444
445         if (delta_time > KEEP_ALIVE_TIMEOUT_MS) {
446                 last_time = current_time;
447
448                 gdb_timeout_warning(delta_time);
449         }
450
451         if (delta_time > KEEP_ALIVE_KICK_TIME_MS) {
452                 last_time = current_time;
453
454                 /* this will keep the GDB connection alive */
455                 LOG_USER_N("%s", "");
456
457                 /* DANGER!!!! do not add code to invoke e.g. target event processing,
458                  * jim timer processing, etc. it can cause infinite recursion +
459                  * jim event callbacks need to happen at a well defined time,
460                  * not anywhere keep_alive() is invoked.
461                  *
462                  * These functions should be invoked at a well defined spot in server.c
463                  */
464         }
465 }
466
467 /* reset keep alive timer without sending message */
468 void kept_alive(void)
469 {
470         int64_t current_time = timeval_ms();
471
472         int64_t delta_time = current_time - last_time;
473
474         last_time = current_time;
475
476         if (delta_time > KEEP_ALIVE_TIMEOUT_MS)
477                 gdb_timeout_warning(delta_time);
478 }
479
480 /* if we sleep for extended periods of time, we must invoke keep_alive() intermittently */
481 void alive_sleep(uint64_t ms)
482 {
483         uint64_t nap_time = 10;
484         for (uint64_t i = 0; i < ms; i += nap_time) {
485                 uint64_t sleep_a_bit = ms - i;
486                 if (sleep_a_bit > nap_time)
487                         sleep_a_bit = nap_time;
488
489                 usleep(sleep_a_bit * 1000);
490                 keep_alive();
491         }
492 }
493
494 void busy_sleep(uint64_t ms)
495 {
496         uint64_t then = timeval_ms();
497         while (timeval_ms() - then < ms) {
498                 /*
499                  * busy wait
500                  */
501         }
502 }
503
504 /* Maximum size of socket error message retrieved from operation system */
505 #define MAX_SOCKET_ERR_MSG_LENGTH 256
506
507 /* Provide log message for the last socket error.
508    Uses errno on *nix and WSAGetLastError() on Windows */
509 void log_socket_error(const char *socket_desc)
510 {
511         int error_code;
512 #ifdef _WIN32
513         error_code = WSAGetLastError();
514         char error_message[MAX_SOCKET_ERR_MSG_LENGTH];
515         error_message[0] = '\0';
516         DWORD retval = FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM, NULL, error_code, 0,
517                 error_message, MAX_SOCKET_ERR_MSG_LENGTH, NULL);
518         error_message[MAX_SOCKET_ERR_MSG_LENGTH - 1] = '\0';
519         const bool have_message = (retval != 0) && (error_message[0] != '\0');
520         LOG_ERROR("Error on socket '%s': WSAGetLastError==%d%s%s.", socket_desc, error_code,
521                 (have_message ? ", message: " : ""),
522                 (have_message ? error_message : ""));
523 #else
524         error_code = errno;
525         LOG_ERROR("Error on socket '%s': errno==%d, message: %s.", socket_desc, error_code, strerror(error_code));
526 #endif
527 }
528
529 /**
530  * Find the first non-printable character in the char buffer, return a pointer to it.
531  * If no such character exists, return NULL.
532  */
533 char *find_nonprint_char(char *buf, unsigned buf_len)
534 {
535         for (unsigned int i = 0; i < buf_len; i++) {
536                 if (!isprint(buf[i]))
537                         return buf + i;
538         }
539         return NULL;
540 }