1 /* SPDX-License-Identifier: GPL-2.0-or-later */
3 /***************************************************************************
4 * Copyright (C) 2005 by Dominic Rath *
5 * Dominic.Rath@gmx.de *
7 * Copyright (C) 2007-2010 Øyvind Harboe *
8 * oyvind.harboe@zylin.com *
10 * Copyright (C) 2008 by Spencer Oliver *
11 * spen@spen-soft.co.uk *
12 ***************************************************************************/
20 #include "replacements.h"
21 #include "time_support.h"
22 #include <server/server.h>
26 #ifdef _DEBUG_FREE_SPACE_
30 #error "malloc.h is required to use --enable-malloc-logging"
34 int debug_level = LOG_LVL_INFO;
36 static FILE *log_output;
37 static struct log_callback *log_callbacks;
39 static int64_t last_time;
43 static const char * const log_strings[6] = {
46 "Warn : ", /* want a space after each colon, all same width, colons aligned */
54 /* forward the log to the listeners */
55 static void log_forward(const char *file, unsigned line, const char *function, const char *string)
57 struct log_callback *cb, *next;
59 /* DANGER!!!! the log callback can remove itself!!!! */
62 cb->fn(cb->priv, file, line, function, string);
67 /* The log_puts() serves two somewhat different goals:
70 * - feeding low-level info to the user in GDB or Telnet
72 * The latter dictates that strings without newline are not logged, lest there
73 * will be *MANY log lines when sending one char at the time(e.g.
77 static void log_puts(enum log_levels level,
86 /* log_init() not called yet; print on stderr */
87 fputs(string, stderr);
92 if (level == LOG_LVL_OUTPUT) {
93 /* do not prepend any headers, just print out what we were given and return */
94 fputs(string, log_output);
99 f = strrchr(file, '/');
103 if (debug_level >= LOG_LVL_DEBUG) {
104 /* print with count and time information */
105 int64_t t = timeval_ms() - start;
106 #ifdef _DEBUG_FREE_SPACE_
107 struct mallinfo info;
110 fprintf(log_output, "%s%d %" PRId64 " %s:%d %s()"
111 #ifdef _DEBUG_FREE_SPACE_
114 ": %s", log_strings[level + 1], count, t, file, line, function,
115 #ifdef _DEBUG_FREE_SPACE_
120 /* if we are using gdb through pipes then we do not want any output
121 * to the pipe otherwise we get repeated strings */
122 fprintf(log_output, "%s%s",
123 (level > LOG_LVL_USER) ? log_strings[level + 1] : "", string);
128 /* Never forward LOG_LVL_DEBUG, too verbose and they can be found in the log if need be */
129 if (level <= LOG_LVL_INFO)
130 log_forward(file, line, function, string);
133 void log_printf(enum log_levels level,
136 const char *function,
144 if (level > debug_level)
147 va_start(ap, format);
149 string = alloc_vprintf(format, ap);
151 log_puts(level, file, line, function, string);
158 void log_vprintf_lf(enum log_levels level, const char *file, unsigned line,
159 const char *function, const char *format, va_list args)
165 if (level > debug_level)
168 tmp = alloc_vprintf(format, args);
174 * Note: alloc_vprintf() guarantees that the buffer is at least one
178 log_puts(level, file, line, function, tmp);
182 void log_printf_lf(enum log_levels level,
185 const char *function,
191 va_start(ap, format);
192 log_vprintf_lf(level, file, line, function, format, ap);
196 COMMAND_HANDLER(handle_debug_level_command)
200 COMMAND_PARSE_NUMBER(int, CMD_ARGV[0], new_level);
201 if ((new_level > LOG_LVL_DEBUG_IO) || (new_level < LOG_LVL_SILENT)) {
202 LOG_ERROR("level must be between %d and %d", LOG_LVL_SILENT, LOG_LVL_DEBUG_IO);
203 return ERROR_COMMAND_SYNTAX_ERROR;
205 debug_level = new_level;
206 } else if (CMD_ARGC > 1)
207 return ERROR_COMMAND_SYNTAX_ERROR;
209 command_print(CMD, "debug_level: %i", debug_level);
214 COMMAND_HANDLER(handle_log_output_command)
216 if (CMD_ARGC == 0 || (CMD_ARGC == 1 && strcmp(CMD_ARGV[0], "default") == 0)) {
217 if (log_output != stderr && log_output) {
218 /* Close previous log file, if it was open and wasn't stderr. */
222 LOG_DEBUG("set log_output to default");
226 FILE *file = fopen(CMD_ARGV[0], "w");
228 LOG_ERROR("failed to open output log '%s'", CMD_ARGV[0]);
231 if (log_output != stderr && log_output) {
232 /* Close previous log file, if it was open and wasn't stderr. */
236 LOG_DEBUG("set log_output to \"%s\"", CMD_ARGV[0]);
240 return ERROR_COMMAND_SYNTAX_ERROR;
243 static const struct command_registration log_command_handlers[] = {
245 .name = "log_output",
246 .handler = handle_log_output_command,
248 .help = "redirect logging to a file (default: stderr)",
249 .usage = "[file_name | \"default\"]",
252 .name = "debug_level",
253 .handler = handle_debug_level_command,
255 .help = "Sets the verbosity level of debugging output. "
256 "0 shows errors only; 1 adds warnings; "
257 "2 (default) adds other info; 3 adds debugging; "
258 "4 adds extra verbose debugging.",
261 COMMAND_REGISTRATION_DONE
264 int log_register_commands(struct command_context *cmd_ctx)
266 return register_commands(cmd_ctx, NULL, log_command_handlers);
271 /* set defaults for daemon configuration,
272 * if not set by cmdline or cfgfile */
273 char *debug_env = getenv("OPENOCD_DEBUG_LEVEL");
276 int retval = parse_int(debug_env, &value);
277 if (retval == ERROR_OK &&
278 debug_level >= LOG_LVL_SILENT &&
279 debug_level <= LOG_LVL_DEBUG_IO)
286 start = last_time = timeval_ms();
291 if (log_output && log_output != stderr) {
292 /* Close log file, if it was open and wasn't stderr. */
298 int set_log_output(struct command_context *cmd_ctx, FILE *output)
304 /* add/remove log callback handler */
305 int log_add_callback(log_callback_fn fn, void *priv)
307 struct log_callback *cb;
309 /* prevent the same callback to be registered more than once, just for sure */
310 for (cb = log_callbacks; cb; cb = cb->next) {
311 if (cb->fn == fn && cb->priv == priv)
312 return ERROR_COMMAND_SYNTAX_ERROR;
315 /* alloc memory, it is safe just to return in case of an error, no need for the caller to
317 cb = malloc(sizeof(struct log_callback));
319 return ERROR_BUF_TOO_SMALL;
321 /* add item to the beginning of the linked list */
324 cb->next = log_callbacks;
330 int log_remove_callback(log_callback_fn fn, void *priv)
332 struct log_callback *cb, **p;
334 for (p = &log_callbacks; (cb = *p); p = &(*p)->next) {
335 if (cb->fn == fn && cb->priv == priv) {
343 return ERROR_COMMAND_SYNTAX_ERROR;
346 /* return allocated string w/printf() result */
347 char *alloc_vprintf(const char *fmt, va_list ap)
353 /* determine the length of the buffer needed */
354 va_copy(ap_copy, ap);
355 len = vsnprintf(NULL, 0, fmt, ap_copy);
358 /* allocate and make room for terminating zero. */
359 /* FIXME: The old version always allocated at least one byte extra and
360 * other code depend on that. They should be probably be fixed, but for
361 * now reserve the extra byte. */
362 string = malloc(len + 2);
366 /* do the real work */
367 vsnprintf(string, len + 1, fmt, ap);
372 char *alloc_printf(const char *format, ...)
376 va_start(ap, format);
377 string = alloc_vprintf(format, ap);
382 /* Code must return to the server loop before 1000ms has returned or invoke
385 * The GDB connection will time out if it spends >2000ms and you'll get nasty
386 * error messages from GDB:
388 * Ignoring packet error, continuing...
389 * Reply contains invalid hex digit 116
391 * While it is possible use "set remotetimeout" to more than the default 2000ms
392 * in GDB, OpenOCD guarantees that it sends keep-alive packages on the
393 * GDB protocol and it is a bug in OpenOCD not to either return to the server
394 * loop or invoke keep_alive() every 1000ms.
396 * This function will send a keep alive packet if >500ms has passed since last time
399 * Note that this function can be invoked often, so it needs to be relatively
400 * fast when invoked more often than every 500ms.
403 #define KEEP_ALIVE_KICK_TIME_MS 500
404 #define KEEP_ALIVE_TIMEOUT_MS 1000
406 static void gdb_timeout_warning(int64_t delta_time)
408 extern int gdb_actual_connections;
410 if (gdb_actual_connections)
411 LOG_WARNING("keep_alive() was not invoked in the "
412 "%d ms timelimit. GDB alive packet not "
413 "sent! (%" PRId64 " ms). Workaround: increase "
414 "\"set remotetimeout\" in GDB",
415 KEEP_ALIVE_TIMEOUT_MS,
418 LOG_DEBUG("keep_alive() was not invoked in the "
419 "%d ms timelimit (%" PRId64 " ms). This may cause "
420 "trouble with GDB connections.",
421 KEEP_ALIVE_TIMEOUT_MS,
425 void keep_alive(void)
427 int64_t current_time = timeval_ms();
428 int64_t delta_time = current_time - last_time;
430 if (delta_time > KEEP_ALIVE_TIMEOUT_MS) {
431 last_time = current_time;
433 gdb_timeout_warning(delta_time);
436 if (delta_time > KEEP_ALIVE_KICK_TIME_MS) {
437 last_time = current_time;
439 /* this will keep the GDB connection alive */
440 server_keep_clients_alive();
442 /* DANGER!!!! do not add code to invoke e.g. target event processing,
443 * jim timer processing, etc. it can cause infinite recursion +
444 * jim event callbacks need to happen at a well defined time,
445 * not anywhere keep_alive() is invoked.
447 * These functions should be invoked at a well defined spot in server.c
452 /* reset keep alive timer without sending message */
453 void kept_alive(void)
455 int64_t current_time = timeval_ms();
457 int64_t delta_time = current_time - last_time;
459 last_time = current_time;
461 if (delta_time > KEEP_ALIVE_TIMEOUT_MS)
462 gdb_timeout_warning(delta_time);
465 /* if we sleep for extended periods of time, we must invoke keep_alive() intermittently */
466 void alive_sleep(uint64_t ms)
468 uint64_t nap_time = 10;
469 for (uint64_t i = 0; i < ms; i += nap_time) {
470 uint64_t sleep_a_bit = ms - i;
471 if (sleep_a_bit > nap_time)
472 sleep_a_bit = nap_time;
474 usleep(sleep_a_bit * 1000);
479 void busy_sleep(uint64_t ms)
481 uint64_t then = timeval_ms();
482 while (timeval_ms() - then < ms) {
489 /* Maximum size of socket error message retrieved from operation system */
490 #define MAX_SOCKET_ERR_MSG_LENGTH 256
492 /* Provide log message for the last socket error.
493 Uses errno on *nix and WSAGetLastError() on Windows */
494 void log_socket_error(const char *socket_desc)
498 error_code = WSAGetLastError();
499 char error_message[MAX_SOCKET_ERR_MSG_LENGTH];
500 error_message[0] = '\0';
501 DWORD retval = FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM, NULL, error_code, 0,
502 error_message, MAX_SOCKET_ERR_MSG_LENGTH, NULL);
503 error_message[MAX_SOCKET_ERR_MSG_LENGTH - 1] = '\0';
504 const bool have_message = (retval != 0) && (error_message[0] != '\0');
505 LOG_ERROR("Error on socket '%s': WSAGetLastError==%d%s%s.", socket_desc, error_code,
506 (have_message ? ", message: " : ""),
507 (have_message ? error_message : ""));
510 LOG_ERROR("Error on socket '%s': errno==%d, message: %s.", socket_desc, error_code, strerror(error_code));
515 * Find the first non-printable character in the char buffer, return a pointer to it.
516 * If no such character exists, return NULL.
518 char *find_nonprint_char(char *buf, unsigned buf_len)
520 for (unsigned int i = 0; i < buf_len; i++) {
521 if (!isprint(buf[i]))