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