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