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 #if defined(HAVE_MALLINFO) || defined(HAVE_MALLINFO2)
28 #include <malloc.h>
29 #endif
30 
32 
33 static FILE *log_output;
34 static struct log_callback *log_callbacks;
35 
36 static int64_t last_time;
37 
38 static int64_t start;
39 
40 static const char * const log_strings[7] = {
41  "User : ",
42  "Error: ",
43  "Warn : ", /* want a space after each colon, all same width, colons aligned */
44  "Info : ",
45  "Debug: ",
46  "Debug: ",
47  "Debug: ", /* corresponds to LOG_LVL_DEBUG_USB */
48 };
49 
50 static unsigned int count;
51 
52 /* forward the log to the listeners */
53 static void log_forward(const char *file, unsigned int line, const char *function, const char *string)
54 {
55  struct log_callback *cb, *next;
56  cb = log_callbacks;
57  /* DANGER!!!! the log callback can remove itself!!!! */
58  while (cb) {
59  next = cb->next;
60  cb->fn(cb->priv, file, line, function, string);
61  cb = next;
62  }
63 }
64 
65 /* The log_puts() serves two somewhat different goals:
66  *
67  * - logging
68  * - feeding low-level info to the user in GDB or Telnet
69  *
70  * The latter dictates that strings without newline are not logged, lest there
71  * will be *MANY log lines when sending one char at the time(e.g.
72  * target_request.c).
73  *
74  */
75 static void log_puts(enum log_levels level,
76  const char *file,
77  int line,
78  const char *function,
79  const char *string)
80 {
81  char *f;
82 
83  if (!log_output) {
84  /* log_init() not called yet; print on stderr */
85  fputs(string, stderr);
86  fflush(stderr);
87  return;
88  }
89 
90  if (level == LOG_LVL_OUTPUT) {
91  /* do not prepend any headers, just print out what we were given and return */
92  fputs(string, log_output);
93  fflush(log_output);
94  return;
95  }
96 
97  f = strrchr(file, '/');
98  if (f)
99  file = f + 1;
100 
102  /* print with count and time information */
103  int64_t t = timeval_ms() - start;
104 
105 #if defined(HAVE_MALLINFO) || defined(HAVE_MALLINFO2)
106  const int should_use_mallinfo = LOG_LEVEL_IS(LOG_LVL_DEBUG_MALLOC);
107 
108  if (should_use_mallinfo) {
109 #ifdef HAVE_MALLINFO2
110  struct mallinfo2 info = mallinfo2();
111 #else
112  struct mallinfo info = mallinfo();
113 #endif
114 
115  fprintf(log_output, "%s%u %" PRId64 " %s:%d %s()"
116 #ifdef HAVE_MALLINFO2
117  " %zu"
118 #else
119  " %d"
120 #endif
121  ": %s", log_strings[level + 1], count, t, file, line, function,
122  info.fordblks,
123  string);
124  }
125 #else
126  const int should_use_mallinfo = 0;
127 #endif
128  if (!should_use_mallinfo) {
129  fprintf(log_output, "%s%u %" PRId64 " %s:%d %s()"
130  ": %s", log_strings[level + 1], count, t, file, line, function,
131  string);
132  }
133  } else {
134  /* if we are using gdb through pipes then we do not want any output
135  * to the pipe otherwise we get repeated strings */
136  fprintf(log_output, "%s%s",
137  (level > LOG_LVL_USER) ? log_strings[level + 1] : "", string);
138  }
139 
140  fflush(log_output);
141 
142  /* Never forward LOG_LVL_DEBUG, too verbose and they can be found in the log if need be */
143  if (level <= LOG_LVL_INFO)
144  log_forward(file, line, function, string);
145 }
146 
147 void log_printf(enum log_levels level,
148  const char *file,
149  unsigned int line,
150  const char *function,
151  const char *format,
152  ...)
153 {
154  char *string;
155  va_list ap;
156 
157  if (level > debug_level)
158  return;
159 
160  count++;
161 
162  va_start(ap, format);
163 
164  string = alloc_vprintf(format, ap);
165  if (string) {
166  log_puts(level, file, line, function, string);
167  free(string);
168  }
169 
170  va_end(ap);
171 }
172 
173 void log_vprintf_lf(enum log_levels level, const char *file, unsigned int line,
174  const char *function, const char *format, va_list args)
175 {
176  char *tmp;
177 
178  if (level > debug_level)
179  return;
180 
181  count++;
182 
183  tmp = alloc_vprintf(format, args);
184 
185  if (!tmp)
186  return;
187 
188  /*
189  * Note: alloc_vprintf() guarantees that the buffer is at least one
190  * character longer.
191  */
192  strcat(tmp, "\n");
193  log_puts(level, file, line, function, tmp);
194  free(tmp);
195 }
196 
197 void log_printf_lf(enum log_levels level,
198  const char *file,
199  unsigned int line,
200  const char *function,
201  const char *format,
202  ...)
203 {
204  va_list ap;
205 
206  va_start(ap, format);
207  log_vprintf_lf(level, file, line, function, format, ap);
208  va_end(ap);
209 }
210 
211 COMMAND_HANDLER(handle_debug_level_command)
212 {
213  if (!CMD_ARGC) {
214  command_print(CMD, "%i", debug_level);
215  } else if (CMD_ARGC == 1) {
216  int new_level;
217  COMMAND_PARSE_NUMBER(int, CMD_ARGV[0], new_level);
218  if (new_level > LOG_LVL_DEBUG_USB || new_level < LOG_LVL_SILENT) {
219  command_print(CMD, "level must be between %d and %d", LOG_LVL_SILENT, LOG_LVL_DEBUG_USB);
221  }
222  debug_level = new_level;
223  } else {
225  }
226 
227  return ERROR_OK;
228 }
229 
230 COMMAND_HANDLER(handle_log_output_command)
231 {
232  if (CMD_ARGC > 1)
234 
235  FILE *file;
236  if (CMD_ARGC == 1 && strcmp(CMD_ARGV[0], "default") != 0) {
237  file = fopen(CMD_ARGV[0], "w");
238  if (!file) {
239  command_print(CMD, "failed to open output log \"%s\"", CMD_ARGV[0]);
240  return ERROR_FAIL;
241  }
242  command_print(CMD, "set log_output to \"%s\"", CMD_ARGV[0]);
243  } else {
244  file = stderr;
245  command_print(CMD, "set log_output to default");
246  }
247 
248  if (log_output != stderr && log_output) {
249  /* Close previous log file, if it was open and wasn't stderr. */
250  fclose(log_output);
251  }
252  log_output = file;
253  return ERROR_OK;
254 }
255 
256 static const struct command_registration log_command_handlers[] = {
257  {
258  .name = "log_output",
259  .handler = handle_log_output_command,
260  .mode = COMMAND_ANY,
261  .help = "redirect logging to a file (default: stderr)",
262  .usage = "[file_name | 'default']",
263  },
264  {
265  .name = "debug_level",
266  .handler = handle_debug_level_command,
267  .mode = COMMAND_ANY,
268  .help = "Sets or display the verbosity level of debugging output. "
269  "0 shows errors only; 1 adds warnings; "
270  "2 (default) adds other info; 3 adds debugging; "
271  "4 adds extra verbose debugging.",
272  .usage = "[number]",
273  },
275 };
276 
278 {
279  return register_commands(cmd_ctx, NULL, log_command_handlers);
280 }
281 
282 void log_init(void)
283 {
284  /* set defaults for daemon configuration,
285  * if not set by cmdline or cfgfile */
286  char *debug_env = getenv("OPENOCD_DEBUG_LEVEL");
287  if (debug_env) {
288  int value;
289  int retval = parse_int(debug_env, &value);
290  if (retval == ERROR_OK
293  debug_level = value;
294  }
295 
296  if (!log_output)
297  log_output = stderr;
298 
299  start = last_time = timeval_ms();
300 }
301 
302 void log_exit(void)
303 {
304  if (log_output && log_output != stderr) {
305  /* Close log file, if it was open and wasn't stderr. */
306  fclose(log_output);
307  }
308  log_output = NULL;
309 }
310 
311 /* add/remove log callback handler */
313 {
314  struct log_callback *cb;
315 
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)
320  }
321 
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)
326  return ERROR_BUF_TOO_SMALL;
327 
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;
333 
334  return ERROR_OK;
335 }
336 
338 {
339  struct log_callback *cb, **p;
340 
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;
346  }
347  }
348 
349  /* no such item */
351 }
352 
353 /* return allocated string w/printf() result */
354 char *alloc_vprintf(const char *fmt, va_list ap)
355 {
356  va_list ap_copy;
357  int len;
358  char *string;
359 
360  assert(fmt);
361 
362  /* determine the length of the buffer needed */
363  va_copy(ap_copy, ap);
364  len = vsnprintf(NULL, 0, fmt, ap_copy);
365  va_end(ap_copy);
366 
367  /* allocate and make room for terminating zero. */
368  /* FIXME: The old version always allocated at least one byte extra and
369  * other code depend on that. They should be probably be fixed, but for
370  * now reserve the extra byte. Apparently the last user of such hack is
371  * log_vprintf_lf() that adds a trailing newline. */
372  string = malloc(len + 2);
373  if (!string)
374  return NULL;
375 
376  /* do the real work */
377  vsnprintf(string, len + 1, fmt, ap);
378 
379  return string;
380 }
381 
382 char *alloc_printf(const char *format, ...)
383 {
384  char *string;
385  va_list ap;
386  va_start(ap, format);
387  string = alloc_vprintf(format, ap);
388  va_end(ap);
389  return string;
390 }
391 
392 /* Code must return to the server loop before 1000ms has returned or invoke
393  * this function.
394  *
395  * The GDB connection will time out if it spends >2000ms and you'll get nasty
396  * error messages from GDB:
397  *
398  * Ignoring packet error, continuing...
399  * Reply contains invalid hex digit 116
400  *
401  * While it is possible use "set remotetimeout" to more than the default 2000ms
402  * in GDB, OpenOCD guarantees that it sends keep-alive packages on the
403  * GDB protocol and it is a bug in OpenOCD not to either return to the server
404  * loop or invoke keep_alive() every 1000ms.
405  *
406  * This function will send a keep alive packet if >500ms has passed since last time
407  * it was invoked.
408  *
409  * Note that this function can be invoked often, so it needs to be relatively
410  * fast when invoked more often than every 500ms.
411  *
412  */
413 #define KEEP_ALIVE_KICK_TIME_MS 500
414 #define KEEP_ALIVE_TIMEOUT_MS 1000
415 
416 static void gdb_timeout_warning(int64_t delta_time)
417 {
419  LOG_WARNING("keep_alive() was not invoked in the "
420  "%d ms timelimit. GDB alive packet not "
421  "sent! (%" PRId64 " ms). Workaround: increase "
422  "\"set remotetimeout\" in GDB",
424  delta_time);
425  else
426  LOG_DEBUG("keep_alive() was not invoked in the "
427  "%d ms timelimit (%" PRId64 " ms). This may cause "
428  "trouble with GDB connections.",
430  delta_time);
431 }
432 
433 void keep_alive(void)
434 {
435  int64_t current_time = timeval_ms();
436  int64_t delta_time = current_time - last_time;
437 
438  if (delta_time > KEEP_ALIVE_TIMEOUT_MS) {
439  last_time = current_time;
440 
441  gdb_timeout_warning(delta_time);
442  }
443 
444  if (delta_time > KEEP_ALIVE_KICK_TIME_MS) {
445  last_time = current_time;
446 
447  /* this will keep the GDB connection alive */
449 
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.
454  *
455  * These functions should be invoked at a well defined spot in server.c
456  */
457  }
458 }
459 
460 /* reset keep alive timer without sending message */
461 void kept_alive(void)
462 {
463  int64_t current_time = timeval_ms();
464 
465  int64_t delta_time = current_time - last_time;
466 
467  last_time = current_time;
468 
469  if (delta_time > KEEP_ALIVE_TIMEOUT_MS)
470  gdb_timeout_warning(delta_time);
471 }
472 
473 /* if we sleep for extended periods of time, we must invoke keep_alive() intermittently */
474 void alive_sleep(uint64_t ms)
475 {
476  uint64_t nap_time = 10;
477  for (uint64_t i = 0; i < ms; i += nap_time) {
478  uint64_t sleep_a_bit = ms - i;
479  if (sleep_a_bit > nap_time)
480  sleep_a_bit = nap_time;
481 
482  usleep(sleep_a_bit * 1000);
483  keep_alive();
484  }
485 }
486 
487 void busy_sleep(uint64_t ms)
488 {
489  uint64_t then = timeval_ms();
490  while (timeval_ms() - then < ms) {
491  /*
492  * busy wait
493  */
494  }
495 }
496 
497 /* Maximum size of socket error message retrieved from operation system */
498 #define MAX_SOCKET_ERR_MSG_LENGTH 256
499 
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)
503 {
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
520 }
521 
526 const char *find_nonprint_char(const char *buf, unsigned int buf_len)
527 {
528  for (unsigned int i = 0; i < buf_len; i++) {
529  if (!isprint(buf[i]))
530  return buf + i;
531  }
532  return NULL;
533 }
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:4234
int log_remove_callback(log_callback_fn fn, void *priv)
Definition: log.c:337
int log_register_commands(struct command_context *cmd_ctx)
Definition: log.c:277
static unsigned int count
Definition: log.c:50
void log_printf_lf(enum log_levels level, const char *file, unsigned int line, const char *function, const char *format,...)
Definition: log.c:197
void log_init(void)
Initialize logging module.
Definition: log.c:282
void log_printf(enum log_levels level, const char *file, unsigned int line, const char *function, const char *format,...)
Definition: log.c:147
int log_add_callback(log_callback_fn fn, void *priv)
Definition: log.c:312
static const struct command_registration log_command_handlers[]
Definition: log.c:256
char * alloc_vprintf(const char *fmt, va_list ap)
Definition: log.c:354
static void gdb_timeout_warning(int64_t delta_time)
Definition: log.c:416
static const char *const log_strings[7]
Definition: log.c:40
int debug_level
Definition: log.c:31
void alive_sleep(uint64_t ms)
Definition: log.c:474
static void log_forward(const char *file, unsigned int line, const char *function, const char *string)
Definition: log.c:53
void busy_sleep(uint64_t ms)
Definition: log.c:487
static struct log_callback * log_callbacks
Definition: log.c:34
void keep_alive(void)
Definition: log.c:433
static int64_t start
Definition: log.c:38
COMMAND_HANDLER(handle_debug_level_command)
Definition: log.c:211
static FILE * log_output
Definition: log.c:33
void log_socket_error(const char *socket_desc)
Definition: log.c:502
void log_exit(void)
Definition: log.c:302
#define MAX_SOCKET_ERR_MSG_LENGTH
Definition: log.c:498
#define KEEP_ALIVE_TIMEOUT_MS
Definition: log.c:414
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:173
void kept_alive(void)
Definition: log.c:461
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:526
#define KEEP_ALIVE_KICK_TIME_MS
Definition: log.c:413
static int64_t last_time
Definition: log.c:36
char * alloc_printf(const char *format,...)
Definition: log.c:382
static void log_puts(enum log_levels level, const char *file, int line, const char *function, const char *string)
Definition: log.c:75
void(* log_callback_fn)(void *priv, const char *file, unsigned int line, const char *function, const char *string)
Definition: log.h:88
#define LOG_WARNING(expr ...)
Definition: log.h:144
#define ERROR_FAIL
Definition: log.h:188
#define ERROR_BUF_TOO_SMALL
Definition: log.h:184
#define LOG_ERROR(expr ...)
Definition: log.h:147
#define LOG_LEVEL_IS(FOO)
Definition: log.h:112
#define LOG_DEBUG(expr ...)
Definition: log.h:124
#define ERROR_OK
Definition: log.h:182
log_levels
Definition: log.h:48
@ LOG_LVL_DEBUG_MALLOC
Definition: log.h:60
@ LOG_LVL_OUTPUT
Definition: log.h:50
@ LOG_LVL_DEBUG_USB
Definition: log.h:59
@ LOG_LVL_INFO
Definition: log.h:54
@ LOG_LVL_USER
Definition: log.h:51
@ LOG_LVL_DEBUG
Definition: log.h:55
@ LOG_LVL_DEBUG_IO
Definition: log.h:56
@ LOG_LVL_SILENT
Definition: log.h:49
void server_keep_clients_alive(void)
Definition: server.c:423
const char * name
Definition: command.h:239
struct log_callback * next
Definition: log.h:94
void * priv
Definition: log.h:93
log_callback_fn fn
Definition: log.h:92
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