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  if (level > debug_level)
157  return;
158 
159  count++;
160 
161  va_start(ap, format);
162 
163  string = alloc_vprintf(format, ap);
164  if (string) {
165  log_puts(level, file, line, function, string);
166  free(string);
167  }
168 
169  va_end(ap);
170 }
171 
172 void log_vprintf_lf(enum log_levels level, const char *file, unsigned int line,
173  const char *function, const char *format, va_list args)
174 {
175  char *tmp;
176 
177  if (level > debug_level)
178  return;
179 
180  count++;
181 
182  tmp = alloc_vprintf(format, args);
183 
184  if (!tmp)
185  return;
186 
187  /*
188  * Note: alloc_vprintf() guarantees that the buffer is at least one
189  * character longer.
190  */
191  strcat(tmp, "\n");
192  log_puts(level, file, line, function, tmp);
193  free(tmp);
194 }
195 
196 void log_printf_lf(enum log_levels level,
197  const char *file,
198  unsigned int line,
199  const char *function,
200  const char *format,
201  ...)
202 {
203  va_list ap;
204 
205  va_start(ap, format);
206  log_vprintf_lf(level, file, line, function, format, ap);
207  va_end(ap);
208 }
209 
210 COMMAND_HANDLER(handle_debug_level_command)
211 {
212  if (!CMD_ARGC) {
213  command_print(CMD, "%i", debug_level);
214  } else if (CMD_ARGC == 1) {
215  int new_level;
216  COMMAND_PARSE_NUMBER(int, CMD_ARGV[0], new_level);
217  if (new_level > LOG_LVL_DEBUG_USB || new_level < LOG_LVL_SILENT) {
218  command_print(CMD, "level must be between %d and %d", LOG_LVL_SILENT, LOG_LVL_DEBUG_IO);
220  }
221  debug_level = new_level;
222  } else {
224  }
225 
226  return ERROR_OK;
227 }
228 
229 COMMAND_HANDLER(handle_log_output_command)
230 {
231  if (CMD_ARGC > 1)
233 
234  FILE *file;
235  if (CMD_ARGC == 1 && strcmp(CMD_ARGV[0], "default") != 0) {
236  file = fopen(CMD_ARGV[0], "w");
237  if (!file) {
238  command_print(CMD, "failed to open output log \"%s\"", CMD_ARGV[0]);
239  return ERROR_FAIL;
240  }
241  command_print(CMD, "set log_output to \"%s\"", CMD_ARGV[0]);
242  } else {
243  file = stderr;
244  command_print(CMD, "set log_output to default");
245  }
246 
247  if (log_output != stderr && log_output) {
248  /* Close previous log file, if it was open and wasn't stderr. */
249  fclose(log_output);
250  }
251  log_output = file;
252  return ERROR_OK;
253 }
254 
255 static const struct command_registration log_command_handlers[] = {
256  {
257  .name = "log_output",
258  .handler = handle_log_output_command,
259  .mode = COMMAND_ANY,
260  .help = "redirect logging to a file (default: stderr)",
261  .usage = "[file_name | 'default']",
262  },
263  {
264  .name = "debug_level",
265  .handler = handle_debug_level_command,
266  .mode = COMMAND_ANY,
267  .help = "Sets or display the verbosity level of debugging output. "
268  "0 shows errors only; 1 adds warnings; "
269  "2 (default) adds other info; 3 adds debugging; "
270  "4 adds extra verbose debugging.",
271  .usage = "[number]",
272  },
274 };
275 
277 {
278  return register_commands(cmd_ctx, NULL, log_command_handlers);
279 }
280 
281 void log_init(void)
282 {
283  /* set defaults for daemon configuration,
284  * if not set by cmdline or cfgfile */
285  char *debug_env = getenv("OPENOCD_DEBUG_LEVEL");
286  if (debug_env) {
287  int value;
288  int retval = parse_int(debug_env, &value);
289  if (retval == ERROR_OK
292  debug_level = value;
293  }
294 
295  if (!log_output)
296  log_output = stderr;
297 
298  start = last_time = timeval_ms();
299 }
300 
301 void log_exit(void)
302 {
303  if (log_output && log_output != stderr) {
304  /* Close log file, if it was open and wasn't stderr. */
305  fclose(log_output);
306  }
307  log_output = NULL;
308 }
309 
310 /* add/remove log callback handler */
312 {
313  struct log_callback *cb;
314 
315  /* prevent the same callback to be registered more than once, just for sure */
316  for (cb = log_callbacks; cb; cb = cb->next) {
317  if (cb->fn == fn && cb->priv == priv)
319  }
320 
321  /* alloc memory, it is safe just to return in case of an error, no need for the caller to
322  *check this */
323  cb = malloc(sizeof(struct log_callback));
324  if (!cb)
325  return ERROR_BUF_TOO_SMALL;
326 
327  /* add item to the beginning of the linked list */
328  cb->fn = fn;
329  cb->priv = priv;
330  cb->next = log_callbacks;
331  log_callbacks = cb;
332 
333  return ERROR_OK;
334 }
335 
337 {
338  struct log_callback *cb, **p;
339 
340  for (p = &log_callbacks; (cb = *p); p = &(*p)->next) {
341  if (cb->fn == fn && cb->priv == priv) {
342  *p = cb->next;
343  free(cb);
344  return ERROR_OK;
345  }
346  }
347 
348  /* no such item */
350 }
351 
352 /* return allocated string w/printf() result */
353 char *alloc_vprintf(const char *fmt, va_list ap)
354 {
355  va_list ap_copy;
356  int len;
357  char *string;
358 
359  assert(fmt);
360 
361  /* determine the length of the buffer needed */
362  va_copy(ap_copy, ap);
363  len = vsnprintf(NULL, 0, fmt, ap_copy);
364  va_end(ap_copy);
365 
366  /* allocate and make room for terminating zero. */
367  /* FIXME: The old version always allocated at least one byte extra and
368  * other code depend on that. They should be probably be fixed, but for
369  * now reserve the extra byte. Apparently the last user of such hack is
370  * log_vprintf_lf() that adds a trailing newline. */
371  string = malloc(len + 2);
372  if (!string)
373  return NULL;
374 
375  /* do the real work */
376  vsnprintf(string, len + 1, fmt, ap);
377 
378  return string;
379 }
380 
381 char *alloc_printf(const char *format, ...)
382 {
383  char *string;
384  va_list ap;
385  va_start(ap, format);
386  string = alloc_vprintf(format, ap);
387  va_end(ap);
388  return string;
389 }
390 
391 /* Code must return to the server loop before 1000ms has returned or invoke
392  * this function.
393  *
394  * The GDB connection will time out if it spends >2000ms and you'll get nasty
395  * error messages from GDB:
396  *
397  * Ignoring packet error, continuing...
398  * Reply contains invalid hex digit 116
399  *
400  * While it is possible use "set remotetimeout" to more than the default 2000ms
401  * in GDB, OpenOCD guarantees that it sends keep-alive packages on the
402  * GDB protocol and it is a bug in OpenOCD not to either return to the server
403  * loop or invoke keep_alive() every 1000ms.
404  *
405  * This function will send a keep alive packet if >500ms has passed since last time
406  * it was invoked.
407  *
408  * Note that this function can be invoked often, so it needs to be relatively
409  * fast when invoked more often than every 500ms.
410  *
411  */
412 #define KEEP_ALIVE_KICK_TIME_MS 500
413 #define KEEP_ALIVE_TIMEOUT_MS 1000
414 
415 static void gdb_timeout_warning(int64_t delta_time)
416 {
418  LOG_WARNING("keep_alive() was not invoked in the "
419  "%d ms timelimit. GDB alive packet not "
420  "sent! (%" PRId64 " ms). Workaround: increase "
421  "\"set remotetimeout\" in GDB",
423  delta_time);
424  else
425  LOG_DEBUG("keep_alive() was not invoked in the "
426  "%d ms timelimit (%" PRId64 " ms). This may cause "
427  "trouble with GDB connections.",
429  delta_time);
430 }
431 
432 void keep_alive(void)
433 {
434  int64_t current_time = timeval_ms();
435  int64_t delta_time = current_time - last_time;
436 
437  if (delta_time > KEEP_ALIVE_TIMEOUT_MS) {
438  last_time = current_time;
439 
440  gdb_timeout_warning(delta_time);
441  }
442 
443  if (delta_time > KEEP_ALIVE_KICK_TIME_MS) {
444  last_time = current_time;
445 
446  /* this will keep the GDB connection alive */
448 
449  /* DANGER!!!! do not add code to invoke e.g. target event processing,
450  * jim timer processing, etc. it can cause infinite recursion +
451  * jim event callbacks need to happen at a well defined time,
452  * not anywhere keep_alive() is invoked.
453  *
454  * These functions should be invoked at a well defined spot in server.c
455  */
456  }
457 }
458 
459 /* reset keep alive timer without sending message */
460 void kept_alive(void)
461 {
462  int64_t current_time = timeval_ms();
463 
464  int64_t delta_time = current_time - last_time;
465 
466  last_time = current_time;
467 
468  if (delta_time > KEEP_ALIVE_TIMEOUT_MS)
469  gdb_timeout_warning(delta_time);
470 }
471 
472 /* if we sleep for extended periods of time, we must invoke keep_alive() intermittently */
473 void alive_sleep(uint64_t ms)
474 {
475  uint64_t nap_time = 10;
476  for (uint64_t i = 0; i < ms; i += nap_time) {
477  uint64_t sleep_a_bit = ms - i;
478  if (sleep_a_bit > nap_time)
479  sleep_a_bit = nap_time;
480 
481  usleep(sleep_a_bit * 1000);
482  keep_alive();
483  }
484 }
485 
486 void busy_sleep(uint64_t ms)
487 {
488  uint64_t then = timeval_ms();
489  while (timeval_ms() - then < ms) {
490  /*
491  * busy wait
492  */
493  }
494 }
495 
496 /* Maximum size of socket error message retrieved from operation system */
497 #define MAX_SOCKET_ERR_MSG_LENGTH 256
498 
499 /* Provide log message for the last socket error.
500  Uses errno on *nix and WSAGetLastError() on Windows */
501 void log_socket_error(const char *socket_desc)
502 {
503  int error_code;
504 #ifdef _WIN32
505  error_code = WSAGetLastError();
506  char error_message[MAX_SOCKET_ERR_MSG_LENGTH];
507  error_message[0] = '\0';
508  DWORD retval = FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM, NULL, error_code, 0,
509  error_message, MAX_SOCKET_ERR_MSG_LENGTH, NULL);
510  error_message[MAX_SOCKET_ERR_MSG_LENGTH - 1] = '\0';
511  const bool have_message = (retval != 0) && (error_message[0] != '\0');
512  LOG_ERROR("Error on socket '%s': WSAGetLastError==%d%s%s.", socket_desc, error_code,
513  (have_message ? ", message: " : ""),
514  (have_message ? error_message : ""));
515 #else
516  error_code = errno;
517  LOG_ERROR("Error on socket '%s': errno==%d, message: %s.", socket_desc, error_code, strerror(error_code));
518 #endif
519 }
520 
525 const char *find_nonprint_char(const char *buf, unsigned int buf_len)
526 {
527  for (unsigned int i = 0; i < buf_len; i++) {
528  if (!isprint(buf[i]))
529  return buf + i;
530  }
531  return NULL;
532 }
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:336
int log_register_commands(struct command_context *cmd_ctx)
Definition: log.c:276
void log_printf_lf(enum log_levels level, const char *file, unsigned int line, const char *function, const char *format,...)
Definition: log.c:196
void log_init(void)
Initialize logging module.
Definition: log.c:281
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:311
static const struct command_registration log_command_handlers[]
Definition: log.c:255
char * alloc_vprintf(const char *fmt, va_list ap)
Definition: log.c:353
static void gdb_timeout_warning(int64_t delta_time)
Definition: log.c:415
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:473
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:486
static struct log_callback * log_callbacks
Definition: log.c:50
void keep_alive(void)
Definition: log.c:432
static int64_t start
Definition: log.c:54
COMMAND_HANDLER(handle_debug_level_command)
Definition: log.c:210
static FILE * log_output
Definition: log.c:49
void log_socket_error(const char *socket_desc)
Definition: log.c:501
void log_exit(void)
Definition: log.c:301
#define MAX_SOCKET_ERR_MSG_LENGTH
Definition: log.c:497
#define KEEP_ALIVE_TIMEOUT_MS
Definition: log.c:413
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:172
void kept_alive(void)
Definition: log.c:460
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:525
static int count
Definition: log.c:66
#define KEEP_ALIVE_KICK_TIME_MS
Definition: log.c:412
static int64_t last_time
Definition: log.c:52
char * alloc_printf(const char *format,...)
Definition: log.c:381
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