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