gdb_server: Log both incoming and outgoing GDB packets
[openocd.git] / src / helper / log.c
blob36b59fe77198bd528ca81da56be12140a92a05d6
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 ***************************************************************************/
25 #ifdef HAVE_CONFIG_H
26 #include "config.h"
27 #endif
29 #include "log.h"
30 #include "command.h"
31 #include "replacements.h"
32 #include "time_support.h"
34 #include <stdarg.h>
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
44 int debug_level = LOG_LVL_INFO;
46 static FILE *log_output;
47 static struct log_callback *log_callbacks;
49 static int64_t last_time;
50 static int64_t current_time;
52 static int64_t start;
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: "
63 static int count;
65 /* forward the log to the listeners */
66 static void log_forward(const char *file, unsigned line, const char *function, const char *string)
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;
78 /* The log_puts() serves two somewhat different goals:
80 * - logging
81 * - feeding low-level info to the user in GDB or Telnet
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).
88 static void log_puts(enum log_levels level,
89 const char *file,
90 int line,
91 const char *function,
92 const char *string)
94 char *f;
96 if (!log_output) {
97 /* log_init() not called yet; print on stderr */
98 fputs(string, stderr);
99 fflush(stderr);
100 return;
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;
110 f = strrchr(file, '/');
111 if (f != NULL)
112 file = f + 1;
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);
137 } else {
138 /* Empty strings are sent to log callbacks to keep e.g. gdbserver alive, here we do
139 *nothing. */
142 fflush(log_output);
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);
149 void log_printf(enum log_levels level,
150 const char *file,
151 unsigned line,
152 const char *function,
153 const char *format,
154 ...)
156 char *string;
157 va_list ap;
159 count++;
160 if (level > debug_level)
161 return;
163 va_start(ap, format);
165 string = alloc_vprintf(format, ap);
166 if (string != NULL) {
167 log_puts(level, file, line, function, string);
168 free(string);
171 va_end(ap);
174 void log_vprintf_lf(enum log_levels level, const char *file, unsigned line,
175 const char *function, const char *format, va_list args)
177 char *tmp;
179 count++;
181 if (level > debug_level)
182 return;
184 tmp = alloc_vprintf(format, args);
186 if (!tmp)
187 return;
190 * Note: alloc_vprintf() guarantees that the buffer is at least one
191 * character longer.
193 strcat(tmp, "\n");
194 log_puts(level, file, line, function, tmp);
195 free(tmp);
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 ...)
205 va_list ap;
207 va_start(ap, format);
208 log_vprintf_lf(level, file, line, function, format, ap);
209 va_end(ap);
212 COMMAND_HANDLER(handle_debug_level_command)
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;
221 debug_level = new_level;
222 } else if (CMD_ARGC > 1)
223 return ERROR_COMMAND_SYNTAX_ERROR;
225 command_print(CMD, "debug_level: %i", debug_level);
227 return ERROR_OK;
230 COMMAND_HANDLER(handle_log_output_command)
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);
237 log_output = stderr;
238 LOG_DEBUG("set log_output to default");
239 return ERROR_OK;
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;
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);
251 log_output = file;
252 LOG_DEBUG("set log_output to \"%s\"", CMD_ARGV[0]);
253 return ERROR_OK;
256 return ERROR_COMMAND_SYNTAX_ERROR;
259 static const struct command_registration log_command_handlers[] = {
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\"]",
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",
277 COMMAND_REGISTRATION_DONE
280 int log_register_commands(struct command_context *cmd_ctx)
282 return register_commands(cmd_ctx, NULL, log_command_handlers);
285 void log_init(void)
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 (ERROR_OK == retval &&
294 debug_level >= LOG_LVL_SILENT &&
295 debug_level <= LOG_LVL_DEBUG_IO)
296 debug_level = value;
299 if (log_output == NULL)
300 log_output = stderr;
302 start = last_time = timeval_ms();
305 int set_log_output(struct command_context *cmd_ctx, FILE *output)
307 log_output = output;
308 return ERROR_OK;
311 /* add/remove log callback handler */
312 int log_add_callback(log_callback_fn fn, void *priv)
314 struct log_callback *cb;
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;
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;
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;
334 return ERROR_OK;
337 int log_remove_callback(log_callback_fn fn, void *priv)
339 struct log_callback *cb, **p;
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;
349 /* no such item */
350 return ERROR_COMMAND_SYNTAX_ERROR;
353 /* return allocated string w/printf() result */
354 char *alloc_vprintf(const char *fmt, va_list ap)
356 va_list ap_copy;
357 int len;
358 char *string;
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);
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;
373 /* do the real work */
374 vsnprintf(string, len + 1, fmt, ap);
376 return string;
379 char *alloc_printf(const char *format, ...)
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;
389 /* Code must return to the server loop before 1000ms has returned or invoke
390 * this function.
392 * The GDB connection will time out if it spends >2000ms and you'll get nasty
393 * error messages from GDB:
395 * Ignoring packet error, continuing...
396 * Reply contains invalid hex digit 116
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.
403 * This function will send a keep alive packet if >500ms has passed since last time
404 * it was invoked.
406 * Note that this function can be invoked often, so it needs to be relatively
407 * fast when invoked more often than every 500ms.
410 #define KEEP_ALIVE_KICK_TIME_MS 500
411 #define KEEP_ALIVE_TIMEOUT_MS 1000
413 static void gdb_timeout_warning(int64_t delta_time)
415 extern int gdb_actual_connections;
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);
432 void keep_alive(void)
434 current_time = timeval_ms();
436 int64_t delta_time = current_time - last_time;
438 if (delta_time > KEEP_ALIVE_TIMEOUT_MS) {
439 last_time = current_time;
441 gdb_timeout_warning(delta_time);
444 if (delta_time > KEEP_ALIVE_KICK_TIME_MS) {
445 last_time = current_time;
447 /* this will keep the GDB connection alive */
448 LOG_USER_N("%s", "");
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.
455 * These functions should be invoked at a well defined spot in server.c
460 /* reset keep alive timer without sending message */
461 void kept_alive(void)
463 current_time = timeval_ms();
465 int64_t delta_time = current_time - last_time;
467 last_time = current_time;
469 if (delta_time > KEEP_ALIVE_TIMEOUT_MS)
470 gdb_timeout_warning(delta_time);
473 /* if we sleep for extended periods of time, we must invoke keep_alive() intermittently */
474 void alive_sleep(uint64_t ms)
476 uint64_t napTime = 10;
477 for (uint64_t i = 0; i < ms; i += napTime) {
478 uint64_t sleep_a_bit = ms - i;
479 if (sleep_a_bit > napTime)
480 sleep_a_bit = napTime;
482 usleep(sleep_a_bit * 1000);
483 keep_alive();
487 void busy_sleep(uint64_t ms)
489 uint64_t then = timeval_ms();
490 while (timeval_ms() - then < ms) {
492 * busy wait
497 /* Maximum size of socket error message retrieved from operation system */
498 #define MAX_SOCKET_ERR_MSG_LENGTH 256
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)
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
523 * Find the first non-printable character in the char buffer, return a pointer to it.
524 * If no such character exists, return NULL.
526 char *find_nonprint_char(char *buf, unsigned buf_len)
528 for (unsigned int i = 0; i < buf_len; i++) {
529 if (!isprint(buf[i]))
530 return buf + i;
532 return NULL;