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