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