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 /* add/remove log callback handler */
299 int log_add_callback(log_callback_fn fn
, void *priv
)
301 struct log_callback
*cb
;
303 /* prevent the same callback to be registered more than once, just for sure */
304 for (cb
= log_callbacks
; cb
; cb
= cb
->next
) {
305 if (cb
->fn
== fn
&& cb
->priv
== priv
)
306 return ERROR_COMMAND_SYNTAX_ERROR
;
309 /* alloc memory, it is safe just to return in case of an error, no need for the caller to
311 cb
= malloc(sizeof(struct log_callback
));
313 return ERROR_BUF_TOO_SMALL
;
315 /* add item to the beginning of the linked list */
318 cb
->next
= log_callbacks
;
324 int log_remove_callback(log_callback_fn fn
, void *priv
)
326 struct log_callback
*cb
, **p
;
328 for (p
= &log_callbacks
; (cb
= *p
); p
= &(*p
)->next
) {
329 if (cb
->fn
== fn
&& cb
->priv
== priv
) {
337 return ERROR_COMMAND_SYNTAX_ERROR
;
340 /* return allocated string w/printf() result */
341 char *alloc_vprintf(const char *fmt
, va_list ap
)
347 /* determine the length of the buffer needed */
348 va_copy(ap_copy
, ap
);
349 len
= vsnprintf(NULL
, 0, fmt
, ap_copy
);
352 /* allocate and make room for terminating zero. */
353 /* FIXME: The old version always allocated at least one byte extra and
354 * other code depend on that. They should be probably be fixed, but for
355 * now reserve the extra byte. */
356 string
= malloc(len
+ 2);
360 /* do the real work */
361 vsnprintf(string
, len
+ 1, fmt
, ap
);
366 char *alloc_printf(const char *format
, ...)
370 va_start(ap
, format
);
371 string
= alloc_vprintf(format
, ap
);
376 /* Code must return to the server loop before 1000ms has returned or invoke
379 * The GDB connection will time out if it spends >2000ms and you'll get nasty
380 * error messages from GDB:
382 * Ignoring packet error, continuing...
383 * Reply contains invalid hex digit 116
385 * While it is possible use "set remotetimeout" to more than the default 2000ms
386 * in GDB, OpenOCD guarantees that it sends keep-alive packages on the
387 * GDB protocol and it is a bug in OpenOCD not to either return to the server
388 * loop or invoke keep_alive() every 1000ms.
390 * This function will send a keep alive packet if >500ms has passed since last time
393 * Note that this function can be invoked often, so it needs to be relatively
394 * fast when invoked more often than every 500ms.
397 #define KEEP_ALIVE_KICK_TIME_MS 500
398 #define KEEP_ALIVE_TIMEOUT_MS 1000
400 static void gdb_timeout_warning(int64_t delta_time
)
402 extern int gdb_actual_connections
;
404 if (gdb_actual_connections
)
405 LOG_WARNING("keep_alive() was not invoked in the "
406 "%d ms timelimit. GDB alive packet not "
407 "sent! (%" PRId64
" ms). Workaround: increase "
408 "\"set remotetimeout\" in GDB",
409 KEEP_ALIVE_TIMEOUT_MS
,
412 LOG_DEBUG("keep_alive() was not invoked in the "
413 "%d ms timelimit (%" PRId64
" ms). This may cause "
414 "trouble with GDB connections.",
415 KEEP_ALIVE_TIMEOUT_MS
,
419 void keep_alive(void)
421 int64_t current_time
= timeval_ms();
422 int64_t delta_time
= current_time
- last_time
;
424 if (delta_time
> KEEP_ALIVE_TIMEOUT_MS
) {
425 last_time
= current_time
;
427 gdb_timeout_warning(delta_time
);
430 if (delta_time
> KEEP_ALIVE_KICK_TIME_MS
) {
431 last_time
= current_time
;
433 /* this will keep the GDB connection alive */
434 server_keep_clients_alive();
436 /* DANGER!!!! do not add code to invoke e.g. target event processing,
437 * jim timer processing, etc. it can cause infinite recursion +
438 * jim event callbacks need to happen at a well defined time,
439 * not anywhere keep_alive() is invoked.
441 * These functions should be invoked at a well defined spot in server.c
446 /* reset keep alive timer without sending message */
447 void kept_alive(void)
449 int64_t current_time
= timeval_ms();
451 int64_t delta_time
= current_time
- last_time
;
453 last_time
= current_time
;
455 if (delta_time
> KEEP_ALIVE_TIMEOUT_MS
)
456 gdb_timeout_warning(delta_time
);
459 /* if we sleep for extended periods of time, we must invoke keep_alive() intermittently */
460 void alive_sleep(uint64_t ms
)
462 uint64_t nap_time
= 10;
463 for (uint64_t i
= 0; i
< ms
; i
+= nap_time
) {
464 uint64_t sleep_a_bit
= ms
- i
;
465 if (sleep_a_bit
> nap_time
)
466 sleep_a_bit
= nap_time
;
468 usleep(sleep_a_bit
* 1000);
473 void busy_sleep(uint64_t ms
)
475 uint64_t then
= timeval_ms();
476 while (timeval_ms() - then
< ms
) {
483 /* Maximum size of socket error message retrieved from operation system */
484 #define MAX_SOCKET_ERR_MSG_LENGTH 256
486 /* Provide log message for the last socket error.
487 Uses errno on *nix and WSAGetLastError() on Windows */
488 void log_socket_error(const char *socket_desc
)
492 error_code
= WSAGetLastError();
493 char error_message
[MAX_SOCKET_ERR_MSG_LENGTH
];
494 error_message
[0] = '\0';
495 DWORD retval
= FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM
, NULL
, error_code
, 0,
496 error_message
, MAX_SOCKET_ERR_MSG_LENGTH
, NULL
);
497 error_message
[MAX_SOCKET_ERR_MSG_LENGTH
- 1] = '\0';
498 const bool have_message
= (retval
!= 0) && (error_message
[0] != '\0');
499 LOG_ERROR("Error on socket '%s': WSAGetLastError==%d%s%s.", socket_desc
, error_code
,
500 (have_message
? ", message: " : ""),
501 (have_message
? error_message
: ""));
504 LOG_ERROR("Error on socket '%s': errno==%d, message: %s.", socket_desc
, error_code
, strerror(error_code
));
509 * Find the first non-printable character in the char buffer, return a pointer to it.
510 * If no such character exists, return NULL.
512 char *find_nonprint_char(char *buf
, unsigned buf_len
)
514 for (unsigned int i
= 0; i
< buf_len
; i
++) {
515 if (!isprint(buf
[i
]))