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

Linking to existing account procedure

If you already have an account and want to add another login method you MUST first sign in with your existing account and then change URL to read https://review.openocd.org/login/?link to get to this page again but this time it'll work for linking. Thank you.

SSH host keys fingerprints

1024 SHA256:YKx8b7u5ZWdcbp7/4AeXNaqElP49m6QrwfXaqQGJAOk gerrit-code-review@openocd.zylin.com (DSA)
384 SHA256:jHIbSQa4REvwCFG4cq5LBlBLxmxSqelQPem/EXIrxjk gerrit-code-review@openocd.org (ECDSA)
521 SHA256:UAOPYkU9Fjtcao0Ul/Rrlnj/OsQvt+pgdYSZ4jOYdgs gerrit-code-review@openocd.org (ECDSA)
256 SHA256:A13M5QlnozFOvTllybRZH6vm7iSt0XLxbA48yfc2yfY gerrit-code-review@openocd.org (ECDSA)
256 SHA256:spYMBqEYoAOtK7yZBrcwE8ZpYt6b68Cfh9yEVetvbXg gerrit-code-review@openocd.org (ED25519)
+--[ED25519 256]--+
|=..              |
|+o..   .         |
|*.o   . .        |
|+B . . .         |
|Bo. = o S        |
|Oo.+ + =         |
|oB=.* = . o      |
| =+=.+   + E     |
|. .=o   . o      |
+----[SHA256]-----+
2048 SHA256:0Onrb7/PHjpo6iVZ7xQX2riKN83FJ3KGU0TvI0TaFG4 gerrit-code-review@openocd.zylin.com (RSA)