You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 
 
 

534 lines
14 KiB

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