doc: describe tcl port consistently.
[openocd.git] / src / helper / log.c
blobe6a70a3f581f6675848e015f93058381b9bdeb7f
1 // SPDX-License-Identifier: GPL-2.0-or-later
3 /***************************************************************************
4 * Copyright (C) 2005 by Dominic Rath *
5 * Dominic.Rath@gmx.de *
6 * *
7 * Copyright (C) 2007-2010 Øyvind Harboe *
8 * oyvind.harboe@zylin.com *
9 * *
10 * Copyright (C) 2008 by Spencer Oliver *
11 * spen@spen-soft.co.uk *
12 ***************************************************************************/
14 #ifdef HAVE_CONFIG_H
15 #include "config.h"
16 #endif
18 #include "log.h"
19 #include "command.h"
20 #include "replacements.h"
21 #include "time_support.h"
22 #include <server/server.h>
24 #include <stdarg.h>
26 #ifdef _DEBUG_FREE_SPACE_
27 #ifdef HAVE_MALLOC_H
28 #include <malloc.h>
29 #else
30 #error "malloc.h is required to use --enable-malloc-logging"
31 #endif
32 #endif
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;
41 static int64_t start;
43 static const char * const log_strings[6] = {
44 "User : ",
45 "Error: ",
46 "Warn : ", /* want a space after each colon, all same width, colons aligned */
47 "Info : ",
48 "Debug: ",
49 "Debug: "
52 static int count;
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;
58 cb = log_callbacks;
59 /* DANGER!!!! the log callback can remove itself!!!! */
60 while (cb) {
61 next = cb->next;
62 cb->fn(cb->priv, file, line, function, string);
63 cb = next;
67 /* The log_puts() serves two somewhat different goals:
69 * - logging
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.
74 * target_request.c).
77 static void log_puts(enum log_levels level,
78 const char *file,
79 int line,
80 const char *function,
81 const char *string)
83 char *f;
85 if (!log_output) {
86 /* log_init() not called yet; print on stderr */
87 fputs(string, stderr);
88 fflush(stderr);
89 return;
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);
95 fflush(log_output);
96 return;
99 f = strrchr(file, '/');
100 if (f)
101 file = f + 1;
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;
108 info = mallinfo();
109 #endif
110 fprintf(log_output, "%s%d %" PRId64 " %s:%d %s()"
111 #ifdef _DEBUG_FREE_SPACE_
112 " %d"
113 #endif
114 ": %s", log_strings[level + 1], count, t, file, line, function,
115 #ifdef _DEBUG_FREE_SPACE_
116 info.fordblks,
117 #endif
118 string);
119 } else {
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);
126 fflush(log_output);
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,
134 const char *file,
135 unsigned line,
136 const char *function,
137 const char *format,
138 ...)
140 char *string;
141 va_list ap;
143 count++;
144 if (level > debug_level)
145 return;
147 va_start(ap, format);
149 string = alloc_vprintf(format, ap);
150 if (string) {
151 log_puts(level, file, line, function, string);
152 free(string);
155 va_end(ap);
158 void log_vprintf_lf(enum log_levels level, const char *file, unsigned line,
159 const char *function, const char *format, va_list args)
161 char *tmp;
163 count++;
165 if (level > debug_level)
166 return;
168 tmp = alloc_vprintf(format, args);
170 if (!tmp)
171 return;
174 * Note: alloc_vprintf() guarantees that the buffer is at least one
175 * character longer.
177 strcat(tmp, "\n");
178 log_puts(level, file, line, function, tmp);
179 free(tmp);
182 void log_printf_lf(enum log_levels level,
183 const char *file,
184 unsigned line,
185 const char *function,
186 const char *format,
187 ...)
189 va_list ap;
191 va_start(ap, format);
192 log_vprintf_lf(level, file, line, function, format, ap);
193 va_end(ap);
196 COMMAND_HANDLER(handle_debug_level_command)
198 if (CMD_ARGC == 1) {
199 int new_level;
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);
211 return ERROR_OK;
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. */
219 fclose(log_output);
221 log_output = stderr;
222 LOG_DEBUG("set log_output to default");
223 return ERROR_OK;
225 if (CMD_ARGC == 1) {
226 FILE *file = fopen(CMD_ARGV[0], "w");
227 if (!file) {
228 LOG_ERROR("failed to open output log '%s'", CMD_ARGV[0]);
229 return ERROR_FAIL;
231 if (log_output != stderr && log_output) {
232 /* Close previous log file, if it was open and wasn't stderr. */
233 fclose(log_output);
235 log_output = file;
236 LOG_DEBUG("set log_output to \"%s\"", CMD_ARGV[0]);
237 return ERROR_OK;
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,
247 .mode = COMMAND_ANY,
248 .help = "redirect logging to a file (default: stderr)",
249 .usage = "[file_name | \"default\"]",
252 .name = "debug_level",
253 .handler = handle_debug_level_command,
254 .mode = COMMAND_ANY,
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.",
259 .usage = "number",
261 COMMAND_REGISTRATION_DONE
264 int log_register_commands(struct command_context *cmd_ctx)
266 return register_commands(cmd_ctx, NULL, log_command_handlers);
269 void log_init(void)
271 /* set defaults for daemon configuration,
272 * if not set by cmdline or cfgfile */
273 char *debug_env = getenv("OPENOCD_DEBUG_LEVEL");
274 if (debug_env) {
275 int value;
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)
280 debug_level = value;
283 if (!log_output)
284 log_output = stderr;
286 start = last_time = timeval_ms();
289 void log_exit(void)
291 if (log_output && log_output != stderr) {
292 /* Close log file, if it was open and wasn't stderr. */
293 fclose(log_output);
295 log_output = NULL;
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
310 *check this */
311 cb = malloc(sizeof(struct log_callback));
312 if (!cb)
313 return ERROR_BUF_TOO_SMALL;
315 /* add item to the beginning of the linked list */
316 cb->fn = fn;
317 cb->priv = priv;
318 cb->next = log_callbacks;
319 log_callbacks = cb;
321 return ERROR_OK;
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) {
330 *p = cb->next;
331 free(cb);
332 return ERROR_OK;
336 /* no such item */
337 return ERROR_COMMAND_SYNTAX_ERROR;
340 /* return allocated string w/printf() result */
341 char *alloc_vprintf(const char *fmt, va_list ap)
343 va_list ap_copy;
344 int len;
345 char *string;
347 /* determine the length of the buffer needed */
348 va_copy(ap_copy, ap);
349 len = vsnprintf(NULL, 0, fmt, ap_copy);
350 va_end(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);
357 if (!string)
358 return NULL;
360 /* do the real work */
361 vsnprintf(string, len + 1, fmt, ap);
363 return string;
366 char *alloc_printf(const char *format, ...)
368 char *string;
369 va_list ap;
370 va_start(ap, format);
371 string = alloc_vprintf(format, ap);
372 va_end(ap);
373 return string;
376 /* Code must return to the server loop before 1000ms has returned or invoke
377 * this function.
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
391 * it was invoked.
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,
410 delta_time);
411 else
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,
416 delta_time);
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);
469 keep_alive();
473 void busy_sleep(uint64_t ms)
475 uint64_t then = timeval_ms();
476 while (timeval_ms() - then < ms) {
478 * busy wait
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)
490 int error_code;
491 #ifdef _WIN32
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 : ""));
502 #else
503 error_code = errno;
504 LOG_ERROR("Error on socket '%s': errno==%d, message: %s.", socket_desc, error_code, strerror(error_code));
505 #endif
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]))
516 return buf + i;
518 return NULL;