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.
 
 
 
 
 
 

3862 lines
107 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. * Copyright (C) 2011 by Broadcom Corporation *
  12. * Evan Hunter - ehunter@broadcom.com *
  13. * *
  14. * Copyright (C) ST-Ericsson SA 2011 *
  15. * michel.jaouen@stericsson.com : smp minimum support *
  16. * *
  17. * Copyright (C) 2013 Andes Technology *
  18. * Hsiangkai Wang <hkwang@andestech.com> *
  19. * *
  20. * Copyright (C) 2013 Franck Jullien *
  21. * elec4fun@gmail.com *
  22. * *
  23. * This program is free software; you can redistribute it and/or modify *
  24. * it under the terms of the GNU General Public License as published by *
  25. * the Free Software Foundation; either version 2 of the License, or *
  26. * (at your option) any later version. *
  27. * *
  28. * This program is distributed in the hope that it will be useful, *
  29. * but WITHOUT ANY WARRANTY; without even the implied warranty of *
  30. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
  31. * GNU General Public License for more details. *
  32. * *
  33. * You should have received a copy of the GNU General Public License *
  34. * along with this program. If not, see <http://www.gnu.org/licenses/>. *
  35. ***************************************************************************/
  36. #ifdef HAVE_CONFIG_H
  37. #include "config.h"
  38. #endif
  39. #include <target/breakpoints.h>
  40. #include <target/target_request.h>
  41. #include <target/register.h>
  42. #include <target/target.h>
  43. #include <target/target_type.h>
  44. #include <target/semihosting_common.h>
  45. #include "server.h"
  46. #include <flash/nor/core.h>
  47. #include "gdb_server.h"
  48. #include <target/image.h>
  49. #include <jtag/jtag.h>
  50. #include "rtos/rtos.h"
  51. #include "target/smp.h"
  52. /**
  53. * @file
  54. * GDB server implementation.
  55. *
  56. * This implements the GDB Remote Serial Protocol, over TCP connections,
  57. * giving GDB access to the JTAG or other hardware debugging facilities
  58. * found in most modern embedded processors.
  59. */
  60. struct target_desc_format {
  61. char *tdesc;
  62. uint32_t tdesc_length;
  63. };
  64. /* private connection data for GDB */
  65. struct gdb_connection {
  66. char buffer[GDB_BUFFER_SIZE + 1]; /* Extra byte for null-termination */
  67. char *buf_p;
  68. int buf_cnt;
  69. bool ctrl_c;
  70. enum target_state frontend_state;
  71. struct image *vflash_image;
  72. bool closed;
  73. bool busy;
  74. int noack_mode;
  75. /* set flag to true if you want the next stepi to return immediately.
  76. * allowing GDB to pick up a fresh set of register values from the target
  77. * without modifying the target state. */
  78. bool sync;
  79. /* We delay reporting memory write errors until next step/continue or memory
  80. * write. This improves performance of gdb load significantly as the GDB packet
  81. * can be replied immediately and a new GDB packet will be ready without delay
  82. * (ca. 10% or so...). */
  83. bool mem_write_error;
  84. /* with extended-remote it seems we need to better emulate attach/detach.
  85. * what this means is we reply with a W stop reply after a kill packet,
  86. * normally we reply with a S reply via gdb_last_signal_packet.
  87. * as a side note this behaviour only effects gdb > 6.8 */
  88. bool attached;
  89. /* set when extended protocol is used */
  90. bool extended_protocol;
  91. /* temporarily used for target description support */
  92. struct target_desc_format target_desc;
  93. /* temporarily used for thread list support */
  94. char *thread_list;
  95. };
  96. #if 0
  97. #define _DEBUG_GDB_IO_
  98. #endif
  99. static struct gdb_connection *current_gdb_connection;
  100. static int gdb_breakpoint_override;
  101. static enum breakpoint_type gdb_breakpoint_override_type;
  102. static int gdb_error(struct connection *connection, int retval);
  103. static char *gdb_port;
  104. static char *gdb_port_next;
  105. static void gdb_log_callback(void *priv, const char *file, unsigned line,
  106. const char *function, const char *string);
  107. static void gdb_sig_halted(struct connection *connection);
  108. /* number of gdb connections, mainly to suppress gdb related debugging spam
  109. * in helper/log.c when no gdb connections are actually active */
  110. int gdb_actual_connections;
  111. /* set if we are sending a memory map to gdb
  112. * via qXfer:memory-map:read packet */
  113. /* enabled by default*/
  114. static int gdb_use_memory_map = 1;
  115. /* enabled by default*/
  116. static int gdb_flash_program = 1;
  117. /* if set, data aborts cause an error to be reported in memory read packets
  118. * see the code in gdb_read_memory_packet() for further explanations.
  119. * Disabled by default.
  120. */
  121. static int gdb_report_data_abort;
  122. /* If set, errors when accessing registers are reported to gdb. Disabled by
  123. * default. */
  124. static int gdb_report_register_access_error;
  125. /* set if we are sending target descriptions to gdb
  126. * via qXfer:features:read packet */
  127. /* enabled by default */
  128. static int gdb_use_target_description = 1;
  129. /* current processing free-run type, used by file-I/O */
  130. static char gdb_running_type;
  131. static int gdb_last_signal(struct target *target)
  132. {
  133. switch (target->debug_reason) {
  134. case DBG_REASON_DBGRQ:
  135. return 0x2; /* SIGINT */
  136. case DBG_REASON_BREAKPOINT:
  137. case DBG_REASON_WATCHPOINT:
  138. case DBG_REASON_WPTANDBKPT:
  139. return 0x05; /* SIGTRAP */
  140. case DBG_REASON_SINGLESTEP:
  141. return 0x05; /* SIGTRAP */
  142. case DBG_REASON_EXC_CATCH:
  143. return 0x05;
  144. case DBG_REASON_NOTHALTED:
  145. return 0x0; /* no signal... shouldn't happen */
  146. default:
  147. LOG_USER("undefined debug reason %d - target needs reset",
  148. target->debug_reason);
  149. return 0x0;
  150. }
  151. }
  152. static int check_pending(struct connection *connection,
  153. int timeout_s, int *got_data)
  154. {
  155. /* a non-blocking socket will block if there is 0 bytes available on the socket,
  156. * but return with as many bytes as are available immediately
  157. */
  158. struct timeval tv;
  159. fd_set read_fds;
  160. struct gdb_connection *gdb_con = connection->priv;
  161. int t;
  162. if (!got_data)
  163. got_data = &t;
  164. *got_data = 0;
  165. if (gdb_con->buf_cnt > 0) {
  166. *got_data = 1;
  167. return ERROR_OK;
  168. }
  169. FD_ZERO(&read_fds);
  170. FD_SET(connection->fd, &read_fds);
  171. tv.tv_sec = timeout_s;
  172. tv.tv_usec = 0;
  173. if (socket_select(connection->fd + 1, &read_fds, NULL, NULL, &tv) == 0) {
  174. /* This can typically be because a "monitor" command took too long
  175. * before printing any progress messages
  176. */
  177. if (timeout_s > 0)
  178. return ERROR_GDB_TIMEOUT;
  179. else
  180. return ERROR_OK;
  181. }
  182. *got_data = FD_ISSET(connection->fd, &read_fds) != 0;
  183. return ERROR_OK;
  184. }
  185. static int gdb_get_char_inner(struct connection *connection, int *next_char)
  186. {
  187. struct gdb_connection *gdb_con = connection->priv;
  188. int retval = ERROR_OK;
  189. #ifdef _DEBUG_GDB_IO_
  190. char *debug_buffer;
  191. #endif
  192. for (;; ) {
  193. if (connection->service->type != CONNECTION_TCP)
  194. gdb_con->buf_cnt = read(connection->fd, gdb_con->buffer, GDB_BUFFER_SIZE);
  195. else {
  196. retval = check_pending(connection, 1, NULL);
  197. if (retval != ERROR_OK)
  198. return retval;
  199. gdb_con->buf_cnt = read_socket(connection->fd,
  200. gdb_con->buffer,
  201. GDB_BUFFER_SIZE);
  202. }
  203. if (gdb_con->buf_cnt > 0)
  204. break;
  205. if (gdb_con->buf_cnt == 0) {
  206. gdb_con->closed = true;
  207. return ERROR_SERVER_REMOTE_CLOSED;
  208. }
  209. #ifdef _WIN32
  210. errno = WSAGetLastError();
  211. switch (errno) {
  212. case WSAEWOULDBLOCK:
  213. usleep(1000);
  214. break;
  215. case WSAECONNABORTED:
  216. gdb_con->closed = true;
  217. return ERROR_SERVER_REMOTE_CLOSED;
  218. case WSAECONNRESET:
  219. gdb_con->closed = true;
  220. return ERROR_SERVER_REMOTE_CLOSED;
  221. default:
  222. LOG_ERROR("read: %d", errno);
  223. exit(-1);
  224. }
  225. #else
  226. switch (errno) {
  227. case EAGAIN:
  228. usleep(1000);
  229. break;
  230. case ECONNABORTED:
  231. gdb_con->closed = true;
  232. return ERROR_SERVER_REMOTE_CLOSED;
  233. case ECONNRESET:
  234. gdb_con->closed = true;
  235. return ERROR_SERVER_REMOTE_CLOSED;
  236. default:
  237. LOG_ERROR("read: %s", strerror(errno));
  238. gdb_con->closed = true;
  239. return ERROR_SERVER_REMOTE_CLOSED;
  240. }
  241. #endif
  242. }
  243. #ifdef _DEBUG_GDB_IO_
  244. debug_buffer = strndup(gdb_con->buffer, gdb_con->buf_cnt);
  245. LOG_DEBUG("received '%s'", debug_buffer);
  246. free(debug_buffer);
  247. #endif
  248. gdb_con->buf_p = gdb_con->buffer;
  249. gdb_con->buf_cnt--;
  250. *next_char = *(gdb_con->buf_p++);
  251. if (gdb_con->buf_cnt > 0)
  252. connection->input_pending = true;
  253. else
  254. connection->input_pending = false;
  255. #ifdef _DEBUG_GDB_IO_
  256. LOG_DEBUG("returned char '%c' (0x%2.2x)", *next_char, *next_char);
  257. #endif
  258. return retval;
  259. }
  260. /**
  261. * The cool thing about this fn is that it allows buf_p and buf_cnt to be
  262. * held in registers in the inner loop.
  263. *
  264. * For small caches and embedded systems this is important!
  265. */
  266. static inline int gdb_get_char_fast(struct connection *connection,
  267. int *next_char, char **buf_p, int *buf_cnt)
  268. {
  269. int retval = ERROR_OK;
  270. if ((*buf_cnt)-- > 0) {
  271. *next_char = **buf_p;
  272. (*buf_p)++;
  273. if (*buf_cnt > 0)
  274. connection->input_pending = true;
  275. else
  276. connection->input_pending = false;
  277. #ifdef _DEBUG_GDB_IO_
  278. LOG_DEBUG("returned char '%c' (0x%2.2x)", *next_char, *next_char);
  279. #endif
  280. return ERROR_OK;
  281. }
  282. struct gdb_connection *gdb_con = connection->priv;
  283. gdb_con->buf_p = *buf_p;
  284. gdb_con->buf_cnt = *buf_cnt;
  285. retval = gdb_get_char_inner(connection, next_char);
  286. *buf_p = gdb_con->buf_p;
  287. *buf_cnt = gdb_con->buf_cnt;
  288. return retval;
  289. }
  290. static int gdb_get_char(struct connection *connection, int *next_char)
  291. {
  292. struct gdb_connection *gdb_con = connection->priv;
  293. return gdb_get_char_fast(connection, next_char, &gdb_con->buf_p, &gdb_con->buf_cnt);
  294. }
  295. static int gdb_putback_char(struct connection *connection, int last_char)
  296. {
  297. struct gdb_connection *gdb_con = connection->priv;
  298. if (gdb_con->buf_p > gdb_con->buffer) {
  299. *(--gdb_con->buf_p) = last_char;
  300. gdb_con->buf_cnt++;
  301. } else
  302. LOG_ERROR("BUG: couldn't put character back");
  303. return ERROR_OK;
  304. }
  305. /* The only way we can detect that the socket is closed is the first time
  306. * we write to it, we will fail. Subsequent write operations will
  307. * succeed. Shudder! */
  308. static int gdb_write(struct connection *connection, void *data, int len)
  309. {
  310. struct gdb_connection *gdb_con = connection->priv;
  311. if (gdb_con->closed)
  312. return ERROR_SERVER_REMOTE_CLOSED;
  313. if (connection_write(connection, data, len) == len)
  314. return ERROR_OK;
  315. gdb_con->closed = true;
  316. return ERROR_SERVER_REMOTE_CLOSED;
  317. }
  318. static void gdb_log_incoming_packet(char *packet)
  319. {
  320. if (!LOG_LEVEL_IS(LOG_LVL_DEBUG))
  321. return;
  322. /* Avoid dumping non-printable characters to the terminal */
  323. const unsigned packet_len = strlen(packet);
  324. const char *nonprint = find_nonprint_char(packet, packet_len);
  325. if (nonprint) {
  326. /* Does packet at least have a prefix that is printable?
  327. * Look within the first 50 chars of the packet. */
  328. const char *colon = memchr(packet, ':', MIN(50, packet_len));
  329. const bool packet_has_prefix = (colon);
  330. const bool packet_prefix_printable = (packet_has_prefix && nonprint > colon);
  331. if (packet_prefix_printable) {
  332. const unsigned int prefix_len = colon - packet + 1; /* + 1 to include the ':' */
  333. const unsigned int payload_len = packet_len - prefix_len;
  334. LOG_DEBUG("received packet: %.*s<binary-data-%u-bytes>", prefix_len, packet, payload_len);
  335. } else {
  336. LOG_DEBUG("received packet: <binary-data-%u-bytes>", packet_len);
  337. }
  338. } else {
  339. /* All chars printable, dump the packet as is */
  340. LOG_DEBUG("received packet: %s", packet);
  341. }
  342. }
  343. static void gdb_log_outgoing_packet(char *packet_buf, unsigned int packet_len, unsigned char checksum)
  344. {
  345. if (!LOG_LEVEL_IS(LOG_LVL_DEBUG))
  346. return;
  347. if (find_nonprint_char(packet_buf, packet_len))
  348. LOG_DEBUG("sending packet: $<binary-data-%u-bytes>#%2.2x", packet_len, checksum);
  349. else
  350. LOG_DEBUG("sending packet: $%.*s#%2.2x'", packet_len, packet_buf, checksum);
  351. }
  352. static int gdb_put_packet_inner(struct connection *connection,
  353. char *buffer, int len)
  354. {
  355. int i;
  356. unsigned char my_checksum = 0;
  357. int reply;
  358. int retval;
  359. struct gdb_connection *gdb_con = connection->priv;
  360. for (i = 0; i < len; i++)
  361. my_checksum += buffer[i];
  362. #ifdef _DEBUG_GDB_IO_
  363. /*
  364. * At this point we should have nothing in the input queue from GDB,
  365. * however sometimes '-' is sent even though we've already received
  366. * an ACK (+) for everything we've sent off.
  367. */
  368. int gotdata;
  369. for (;; ) {
  370. retval = check_pending(connection, 0, &gotdata);
  371. if (retval != ERROR_OK)
  372. return retval;
  373. if (!gotdata)
  374. break;
  375. retval = gdb_get_char(connection, &reply);
  376. if (retval != ERROR_OK)
  377. return retval;
  378. if (reply == '$') {
  379. /* fix a problem with some IAR tools */
  380. gdb_putback_char(connection, reply);
  381. LOG_DEBUG("Unexpected start of new packet");
  382. break;
  383. }
  384. LOG_WARNING("Discard unexpected char %c", reply);
  385. }
  386. #endif
  387. while (1) {
  388. gdb_log_outgoing_packet(buffer, len, my_checksum);
  389. char local_buffer[1024];
  390. local_buffer[0] = '$';
  391. if ((size_t)len + 4 <= sizeof(local_buffer)) {
  392. /* performance gain on smaller packets by only a single call to gdb_write() */
  393. memcpy(local_buffer + 1, buffer, len++);
  394. len += snprintf(local_buffer + len, sizeof(local_buffer) - len, "#%02x", my_checksum);
  395. retval = gdb_write(connection, local_buffer, len);
  396. if (retval != ERROR_OK)
  397. return retval;
  398. } else {
  399. /* larger packets are transmitted directly from caller supplied buffer
  400. * by several calls to gdb_write() to avoid dynamic allocation */
  401. snprintf(local_buffer + 1, sizeof(local_buffer) - 1, "#%02x", my_checksum);
  402. retval = gdb_write(connection, local_buffer, 1);
  403. if (retval != ERROR_OK)
  404. return retval;
  405. retval = gdb_write(connection, buffer, len);
  406. if (retval != ERROR_OK)
  407. return retval;
  408. retval = gdb_write(connection, local_buffer + 1, 3);
  409. if (retval != ERROR_OK)
  410. return retval;
  411. }
  412. if (gdb_con->noack_mode)
  413. break;
  414. retval = gdb_get_char(connection, &reply);
  415. if (retval != ERROR_OK)
  416. return retval;
  417. if (reply == '+')
  418. break;
  419. else if (reply == '-') {
  420. /* Stop sending output packets for now */
  421. log_remove_callback(gdb_log_callback, connection);
  422. LOG_WARNING("negative reply, retrying");
  423. } else if (reply == 0x3) {
  424. gdb_con->ctrl_c = true;
  425. retval = gdb_get_char(connection, &reply);
  426. if (retval != ERROR_OK)
  427. return retval;
  428. if (reply == '+')
  429. break;
  430. else if (reply == '-') {
  431. /* Stop sending output packets for now */
  432. log_remove_callback(gdb_log_callback, connection);
  433. LOG_WARNING("negative reply, retrying");
  434. } else if (reply == '$') {
  435. LOG_ERROR("GDB missing ack(1) - assumed good");
  436. gdb_putback_char(connection, reply);
  437. return ERROR_OK;
  438. } else {
  439. LOG_ERROR("unknown character(1) 0x%2.2x in reply, dropping connection", reply);
  440. gdb_con->closed = true;
  441. return ERROR_SERVER_REMOTE_CLOSED;
  442. }
  443. } else if (reply == '$') {
  444. LOG_ERROR("GDB missing ack(2) - assumed good");
  445. gdb_putback_char(connection, reply);
  446. return ERROR_OK;
  447. } else {
  448. LOG_ERROR("unknown character(2) 0x%2.2x in reply, dropping connection",
  449. reply);
  450. gdb_con->closed = true;
  451. return ERROR_SERVER_REMOTE_CLOSED;
  452. }
  453. }
  454. if (gdb_con->closed)
  455. return ERROR_SERVER_REMOTE_CLOSED;
  456. return ERROR_OK;
  457. }
  458. int gdb_put_packet(struct connection *connection, char *buffer, int len)
  459. {
  460. struct gdb_connection *gdb_con = connection->priv;
  461. gdb_con->busy = true;
  462. int retval = gdb_put_packet_inner(connection, buffer, len);
  463. gdb_con->busy = false;
  464. /* we sent some data, reset timer for keep alive messages */
  465. kept_alive();
  466. return retval;
  467. }
  468. static inline int fetch_packet(struct connection *connection,
  469. int *checksum_ok, int noack, int *len, char *buffer)
  470. {
  471. unsigned char my_checksum = 0;
  472. char checksum[3];
  473. int character;
  474. int retval = ERROR_OK;
  475. struct gdb_connection *gdb_con = connection->priv;
  476. my_checksum = 0;
  477. int count = 0;
  478. count = 0;
  479. /* move this over into local variables to use registers and give the
  480. * more freedom to optimize */
  481. char *buf_p = gdb_con->buf_p;
  482. int buf_cnt = gdb_con->buf_cnt;
  483. for (;; ) {
  484. /* The common case is that we have an entire packet with no escape chars.
  485. * We need to leave at least 2 bytes in the buffer to have
  486. * gdb_get_char() update various bits and bobs correctly.
  487. */
  488. if ((buf_cnt > 2) && ((buf_cnt + count) < *len)) {
  489. /* The compiler will struggle a bit with constant propagation and
  490. * aliasing, so we help it by showing that these values do not
  491. * change inside the loop
  492. */
  493. int i;
  494. char *buf = buf_p;
  495. int run = buf_cnt - 2;
  496. i = 0;
  497. int done = 0;
  498. while (i < run) {
  499. character = *buf++;
  500. i++;
  501. if (character == '#') {
  502. /* Danger! character can be '#' when esc is
  503. * used so we need an explicit boolean for done here. */
  504. done = 1;
  505. break;
  506. }
  507. if (character == '}') {
  508. /* data transmitted in binary mode (X packet)
  509. * uses 0x7d as escape character */
  510. my_checksum += character & 0xff;
  511. character = *buf++;
  512. i++;
  513. my_checksum += character & 0xff;
  514. buffer[count++] = (character ^ 0x20) & 0xff;
  515. } else {
  516. my_checksum += character & 0xff;
  517. buffer[count++] = character & 0xff;
  518. }
  519. }
  520. buf_p += i;
  521. buf_cnt -= i;
  522. if (done)
  523. break;
  524. }
  525. if (count > *len) {
  526. LOG_ERROR("packet buffer too small");
  527. retval = ERROR_GDB_BUFFER_TOO_SMALL;
  528. break;
  529. }
  530. retval = gdb_get_char_fast(connection, &character, &buf_p, &buf_cnt);
  531. if (retval != ERROR_OK)
  532. break;
  533. if (character == '#')
  534. break;
  535. if (character == '}') {
  536. /* data transmitted in binary mode (X packet)
  537. * uses 0x7d as escape character */
  538. my_checksum += character & 0xff;
  539. retval = gdb_get_char_fast(connection, &character, &buf_p, &buf_cnt);
  540. if (retval != ERROR_OK)
  541. break;
  542. my_checksum += character & 0xff;
  543. buffer[count++] = (character ^ 0x20) & 0xff;
  544. } else {
  545. my_checksum += character & 0xff;
  546. buffer[count++] = character & 0xff;
  547. }
  548. }
  549. gdb_con->buf_p = buf_p;
  550. gdb_con->buf_cnt = buf_cnt;
  551. if (retval != ERROR_OK)
  552. return retval;
  553. *len = count;
  554. retval = gdb_get_char(connection, &character);
  555. if (retval != ERROR_OK)
  556. return retval;
  557. checksum[0] = character;
  558. retval = gdb_get_char(connection, &character);
  559. if (retval != ERROR_OK)
  560. return retval;
  561. checksum[1] = character;
  562. checksum[2] = 0;
  563. if (!noack)
  564. *checksum_ok = (my_checksum == strtoul(checksum, NULL, 16));
  565. return ERROR_OK;
  566. }
  567. static int gdb_get_packet_inner(struct connection *connection,
  568. char *buffer, int *len)
  569. {
  570. int character;
  571. int retval;
  572. struct gdb_connection *gdb_con = connection->priv;
  573. while (1) {
  574. do {
  575. retval = gdb_get_char(connection, &character);
  576. if (retval != ERROR_OK)
  577. return retval;
  578. #ifdef _DEBUG_GDB_IO_
  579. LOG_DEBUG("character: '%c'", character);
  580. #endif
  581. switch (character) {
  582. case '$':
  583. break;
  584. case '+':
  585. /* According to the GDB documentation
  586. * (https://sourceware.org/gdb/onlinedocs/gdb/Packet-Acknowledgment.html):
  587. * "gdb sends a final `+` acknowledgment of the stub's `OK`
  588. * response, which can be safely ignored by the stub."
  589. * However OpenOCD server already is in noack mode at this
  590. * point and instead of ignoring this it was emitting a
  591. * warning. This code makes server ignore the first ACK
  592. * that will be received after going into noack mode,
  593. * warning only about subsequent ACK's. */
  594. if (gdb_con->noack_mode > 1) {
  595. LOG_WARNING("acknowledgment received, but no packet pending");
  596. } else if (gdb_con->noack_mode) {
  597. LOG_DEBUG("Received first acknowledgment after entering noack mode. Ignoring it.");
  598. gdb_con->noack_mode = 2;
  599. }
  600. break;
  601. case '-':
  602. LOG_WARNING("negative acknowledgment, but no packet pending");
  603. break;
  604. case 0x3:
  605. gdb_con->ctrl_c = true;
  606. *len = 0;
  607. return ERROR_OK;
  608. default:
  609. LOG_WARNING("ignoring character 0x%x", character);
  610. break;
  611. }
  612. } while (character != '$');
  613. int checksum_ok = 0;
  614. /* explicit code expansion here to get faster inlined code in -O3 by not
  615. * calculating checksum */
  616. if (gdb_con->noack_mode) {
  617. retval = fetch_packet(connection, &checksum_ok, 1, len, buffer);
  618. if (retval != ERROR_OK)
  619. return retval;
  620. } else {
  621. retval = fetch_packet(connection, &checksum_ok, 0, len, buffer);
  622. if (retval != ERROR_OK)
  623. return retval;
  624. }
  625. if (gdb_con->noack_mode) {
  626. /* checksum is not checked in noack mode */
  627. break;
  628. }
  629. if (checksum_ok) {
  630. retval = gdb_write(connection, "+", 1);
  631. if (retval != ERROR_OK)
  632. return retval;
  633. break;
  634. }
  635. }
  636. if (gdb_con->closed)
  637. return ERROR_SERVER_REMOTE_CLOSED;
  638. return ERROR_OK;
  639. }
  640. static int gdb_get_packet(struct connection *connection, char *buffer, int *len)
  641. {
  642. struct gdb_connection *gdb_con = connection->priv;
  643. gdb_con->busy = true;
  644. int retval = gdb_get_packet_inner(connection, buffer, len);
  645. gdb_con->busy = false;
  646. return retval;
  647. }
  648. static int gdb_output_con(struct connection *connection, const char *line)
  649. {
  650. char *hex_buffer;
  651. int bin_size;
  652. bin_size = strlen(line);
  653. hex_buffer = malloc(bin_size * 2 + 2);
  654. if (!hex_buffer)
  655. return ERROR_GDB_BUFFER_TOO_SMALL;
  656. hex_buffer[0] = 'O';
  657. size_t pkt_len = hexify(hex_buffer + 1, (const uint8_t *)line, bin_size,
  658. bin_size * 2 + 1);
  659. int retval = gdb_put_packet(connection, hex_buffer, pkt_len + 1);
  660. free(hex_buffer);
  661. return retval;
  662. }
  663. static int gdb_output(struct command_context *context, const char *line)
  664. {
  665. /* this will be dumped to the log and also sent as an O packet if possible */
  666. LOG_USER_N("%s", line);
  667. return ERROR_OK;
  668. }
  669. static void gdb_signal_reply(struct target *target, struct connection *connection)
  670. {
  671. struct gdb_connection *gdb_connection = connection->priv;
  672. char sig_reply[65];
  673. char stop_reason[32];
  674. char current_thread[25];
  675. int sig_reply_len;
  676. int signal_var;
  677. rtos_update_threads(target);
  678. if (target->debug_reason == DBG_REASON_EXIT) {
  679. sig_reply_len = snprintf(sig_reply, sizeof(sig_reply), "W00");
  680. } else {
  681. struct target *ct;
  682. if (target->rtos) {
  683. target->rtos->current_threadid = target->rtos->current_thread;
  684. target->rtos->gdb_target_for_threadid(connection, target->rtos->current_threadid, &ct);
  685. } else {
  686. ct = target;
  687. }
  688. if (gdb_connection->ctrl_c) {
  689. signal_var = 0x2;
  690. } else
  691. signal_var = gdb_last_signal(ct);
  692. stop_reason[0] = '\0';
  693. if (ct->debug_reason == DBG_REASON_WATCHPOINT) {
  694. enum watchpoint_rw hit_wp_type;
  695. target_addr_t hit_wp_address;
  696. if (watchpoint_hit(ct, &hit_wp_type, &hit_wp_address) == ERROR_OK) {
  697. switch (hit_wp_type) {
  698. case WPT_WRITE:
  699. snprintf(stop_reason, sizeof(stop_reason),
  700. "watch:%08" TARGET_PRIxADDR ";", hit_wp_address);
  701. break;
  702. case WPT_READ:
  703. snprintf(stop_reason, sizeof(stop_reason),
  704. "rwatch:%08" TARGET_PRIxADDR ";", hit_wp_address);
  705. break;
  706. case WPT_ACCESS:
  707. snprintf(stop_reason, sizeof(stop_reason),
  708. "awatch:%08" TARGET_PRIxADDR ";", hit_wp_address);
  709. break;
  710. default:
  711. break;
  712. }
  713. }
  714. }
  715. current_thread[0] = '\0';
  716. if (target->rtos)
  717. snprintf(current_thread, sizeof(current_thread), "thread:%" PRIx64 ";",
  718. target->rtos->current_thread);
  719. sig_reply_len = snprintf(sig_reply, sizeof(sig_reply), "T%2.2x%s%s",
  720. signal_var, stop_reason, current_thread);
  721. gdb_connection->ctrl_c = false;
  722. }
  723. gdb_put_packet(connection, sig_reply, sig_reply_len);
  724. gdb_connection->frontend_state = TARGET_HALTED;
  725. }
  726. static void gdb_fileio_reply(struct target *target, struct connection *connection)
  727. {
  728. struct gdb_connection *gdb_connection = connection->priv;
  729. char fileio_command[256];
  730. int command_len;
  731. bool program_exited = false;
  732. if (strcmp(target->fileio_info->identifier, "open") == 0)
  733. sprintf(fileio_command, "F%s,%" PRIx64 "/%" PRIx64 ",%" PRIx64 ",%" PRIx64, target->fileio_info->identifier,
  734. target->fileio_info->param_1,
  735. target->fileio_info->param_2 + 1, /* len + trailing zero */
  736. target->fileio_info->param_3,
  737. target->fileio_info->param_4);
  738. else if (strcmp(target->fileio_info->identifier, "close") == 0)
  739. sprintf(fileio_command, "F%s,%" PRIx64, target->fileio_info->identifier,
  740. target->fileio_info->param_1);
  741. else if (strcmp(target->fileio_info->identifier, "read") == 0)
  742. sprintf(fileio_command, "F%s,%" PRIx64 ",%" PRIx64 ",%" PRIx64, target->fileio_info->identifier,
  743. target->fileio_info->param_1,
  744. target->fileio_info->param_2,
  745. target->fileio_info->param_3);
  746. else if (strcmp(target->fileio_info->identifier, "write") == 0)
  747. sprintf(fileio_command, "F%s,%" PRIx64 ",%" PRIx64 ",%" PRIx64, target->fileio_info->identifier,
  748. target->fileio_info->param_1,
  749. target->fileio_info->param_2,
  750. target->fileio_info->param_3);
  751. else if (strcmp(target->fileio_info->identifier, "lseek") == 0)
  752. sprintf(fileio_command, "F%s,%" PRIx64 ",%" PRIx64 ",%" PRIx64, target->fileio_info->identifier,
  753. target->fileio_info->param_1,
  754. target->fileio_info->param_2,
  755. target->fileio_info->param_3);
  756. else if (strcmp(target->fileio_info->identifier, "rename") == 0)
  757. sprintf(fileio_command, "F%s,%" PRIx64 "/%" PRIx64 ",%" PRIx64 "/%" PRIx64, target->fileio_info->identifier,
  758. target->fileio_info->param_1,
  759. target->fileio_info->param_2 + 1, /* len + trailing zero */
  760. target->fileio_info->param_3,
  761. target->fileio_info->param_4 + 1); /* len + trailing zero */
  762. else if (strcmp(target->fileio_info->identifier, "unlink") == 0)
  763. sprintf(fileio_command, "F%s,%" PRIx64 "/%" PRIx64, target->fileio_info->identifier,
  764. target->fileio_info->param_1,
  765. target->fileio_info->param_2 + 1); /* len + trailing zero */
  766. else if (strcmp(target->fileio_info->identifier, "stat") == 0)
  767. sprintf(fileio_command, "F%s,%" PRIx64 "/%" PRIx64 ",%" PRIx64, target->fileio_info->identifier,
  768. target->fileio_info->param_1,
  769. target->fileio_info->param_2,
  770. target->fileio_info->param_3);
  771. else if (strcmp(target->fileio_info->identifier, "fstat") == 0)
  772. sprintf(fileio_command, "F%s,%" PRIx64 ",%" PRIx64, target->fileio_info->identifier,
  773. target->fileio_info->param_1,
  774. target->fileio_info->param_2);
  775. else if (strcmp(target->fileio_info->identifier, "gettimeofday") == 0)
  776. sprintf(fileio_command, "F%s,%" PRIx64 ",%" PRIx64, target->fileio_info->identifier,
  777. target->fileio_info->param_1,
  778. target->fileio_info->param_2);
  779. else if (strcmp(target->fileio_info->identifier, "isatty") == 0)
  780. sprintf(fileio_command, "F%s,%" PRIx64, target->fileio_info->identifier,
  781. target->fileio_info->param_1);
  782. else if (strcmp(target->fileio_info->identifier, "system") == 0)
  783. sprintf(fileio_command, "F%s,%" PRIx64 "/%" PRIx64, target->fileio_info->identifier,
  784. target->fileio_info->param_1,
  785. target->fileio_info->param_2 + 1); /* len + trailing zero */
  786. else if (strcmp(target->fileio_info->identifier, "exit") == 0) {
  787. /* If target hits exit syscall, report to GDB the program is terminated.
  788. * In addition, let target run its own exit syscall handler. */
  789. program_exited = true;
  790. sprintf(fileio_command, "W%02" PRIx64, target->fileio_info->param_1);
  791. } else {
  792. LOG_DEBUG("Unknown syscall: %s", target->fileio_info->identifier);
  793. /* encounter unknown syscall, continue */
  794. gdb_connection->frontend_state = TARGET_RUNNING;
  795. target_resume(target, 1, 0x0, 0, 0);
  796. return;
  797. }
  798. command_len = strlen(fileio_command);
  799. gdb_put_packet(connection, fileio_command, command_len);
  800. if (program_exited) {
  801. /* Use target_resume() to let target run its own exit syscall handler. */
  802. gdb_connection->frontend_state = TARGET_RUNNING;
  803. target_resume(target, 1, 0x0, 0, 0);
  804. } else {
  805. gdb_connection->frontend_state = TARGET_HALTED;
  806. rtos_update_threads(target);
  807. }
  808. }
  809. static void gdb_frontend_halted(struct target *target, struct connection *connection)
  810. {
  811. struct gdb_connection *gdb_connection = connection->priv;
  812. /* In the GDB protocol when we are stepping or continuing execution,
  813. * we have a lingering reply. Upon receiving a halted event
  814. * when we have that lingering packet, we reply to the original
  815. * step or continue packet.
  816. *
  817. * Executing monitor commands can bring the target in and
  818. * out of the running state so we'll see lots of TARGET_EVENT_XXX
  819. * that are to be ignored.
  820. */
  821. if (gdb_connection->frontend_state == TARGET_RUNNING) {
  822. /* stop forwarding log packets! */
  823. log_remove_callback(gdb_log_callback, connection);
  824. /* check fileio first */
  825. if (target_get_gdb_fileio_info(target, target->fileio_info) == ERROR_OK)
  826. gdb_fileio_reply(target, connection);
  827. else
  828. gdb_signal_reply(target, connection);
  829. }
  830. }
  831. static int gdb_target_callback_event_handler(struct target *target,
  832. enum target_event event, void *priv)
  833. {
  834. struct connection *connection = priv;
  835. struct gdb_service *gdb_service = connection->service->priv;
  836. if (gdb_service->target != target)
  837. return ERROR_OK;
  838. switch (event) {
  839. case TARGET_EVENT_GDB_HALT:
  840. gdb_frontend_halted(target, connection);
  841. break;
  842. case TARGET_EVENT_HALTED:
  843. target_call_event_callbacks(target, TARGET_EVENT_GDB_END);
  844. break;
  845. default:
  846. break;
  847. }
  848. return ERROR_OK;
  849. }
  850. static int gdb_new_connection(struct connection *connection)
  851. {
  852. struct gdb_connection *gdb_connection = malloc(sizeof(struct gdb_connection));
  853. struct target *target;
  854. int retval;
  855. int initial_ack;
  856. target = get_target_from_connection(connection);
  857. connection->priv = gdb_connection;
  858. connection->cmd_ctx->current_target = target;
  859. /* initialize gdb connection information */
  860. gdb_connection->buf_p = gdb_connection->buffer;
  861. gdb_connection->buf_cnt = 0;
  862. gdb_connection->ctrl_c = false;
  863. gdb_connection->frontend_state = TARGET_HALTED;
  864. gdb_connection->vflash_image = NULL;
  865. gdb_connection->closed = false;
  866. gdb_connection->busy = false;
  867. gdb_connection->noack_mode = 0;
  868. gdb_connection->sync = false;
  869. gdb_connection->mem_write_error = false;
  870. gdb_connection->attached = true;
  871. gdb_connection->extended_protocol = false;
  872. gdb_connection->target_desc.tdesc = NULL;
  873. gdb_connection->target_desc.tdesc_length = 0;
  874. gdb_connection->thread_list = NULL;
  875. /* send ACK to GDB for debug request */
  876. gdb_write(connection, "+", 1);
  877. /* output goes through gdb connection */
  878. command_set_output_handler(connection->cmd_ctx, gdb_output, connection);
  879. /* we must remove all breakpoints registered to the target as a previous
  880. * GDB session could leave dangling breakpoints if e.g. communication
  881. * timed out.
  882. */
  883. breakpoint_clear_target(target);
  884. watchpoint_clear_target(target);
  885. /* remove the initial ACK from the incoming buffer */
  886. retval = gdb_get_char(connection, &initial_ack);
  887. if (retval != ERROR_OK)
  888. return retval;
  889. /* FIX!!!??? would we actually ever receive a + here???
  890. * Not observed.
  891. */
  892. if (initial_ack != '+')
  893. gdb_putback_char(connection, initial_ack);
  894. target_call_event_callbacks(target, TARGET_EVENT_GDB_ATTACH);
  895. if (target->rtos) {
  896. /* clean previous rtos session if supported*/
  897. if (target->rtos->type->clean)
  898. target->rtos->type->clean(target);
  899. /* update threads */
  900. rtos_update_threads(target);
  901. }
  902. if (gdb_use_memory_map) {
  903. /* Connect must fail if the memory map can't be set up correctly.
  904. *
  905. * This will cause an auto_probe to be invoked, which is either
  906. * a no-op or it will fail when the target isn't ready(e.g. not halted).
  907. */
  908. for (unsigned int i = 0; i < flash_get_bank_count(); i++) {
  909. struct flash_bank *p;
  910. p = get_flash_bank_by_num_noprobe(i);
  911. if (p->target != target)
  912. continue;
  913. retval = get_flash_bank_by_num(i, &p);
  914. if (retval != ERROR_OK) {
  915. LOG_ERROR("Connect failed. Consider setting up a gdb-attach event for the target "
  916. "to prepare target for GDB connect, or use 'gdb_memory_map disable'.");
  917. return retval;
  918. }
  919. }
  920. }
  921. gdb_actual_connections++;
  922. log_printf_lf(all_targets->next ? LOG_LVL_INFO : LOG_LVL_DEBUG,
  923. __FILE__, __LINE__, __func__,
  924. "New GDB Connection: %d, Target %s, state: %s",
  925. gdb_actual_connections,
  926. target_name(target),
  927. target_state_name(target));
  928. if (!target_was_examined(target)) {
  929. LOG_ERROR("Target %s not examined yet, refuse gdb connection %d!",
  930. target_name(target), gdb_actual_connections);
  931. gdb_actual_connections--;
  932. return ERROR_TARGET_NOT_EXAMINED;
  933. }
  934. if (target->state != TARGET_HALTED)
  935. LOG_WARNING("GDB connection %d on target %s not halted",
  936. gdb_actual_connections, target_name(target));
  937. /* DANGER! If we fail subsequently, we must remove this handler,
  938. * otherwise we occasionally see crashes as the timer can invoke the
  939. * callback fn.
  940. *
  941. * register callback to be informed about target events */
  942. target_register_event_callback(gdb_target_callback_event_handler, connection);
  943. return ERROR_OK;
  944. }
  945. static int gdb_connection_closed(struct connection *connection)
  946. {
  947. struct target *target;
  948. struct gdb_connection *gdb_connection = connection->priv;
  949. target = get_target_from_connection(connection);
  950. /* we're done forwarding messages. Tear down callback before
  951. * cleaning up connection.
  952. */
  953. log_remove_callback(gdb_log_callback, connection);
  954. gdb_actual_connections--;
  955. LOG_DEBUG("GDB Close, Target: %s, state: %s, gdb_actual_connections=%d",
  956. target_name(target),
  957. target_state_name(target),
  958. gdb_actual_connections);
  959. /* see if an image built with vFlash commands is left */
  960. if (gdb_connection->vflash_image) {
  961. image_close(gdb_connection->vflash_image);
  962. free(gdb_connection->vflash_image);
  963. gdb_connection->vflash_image = NULL;
  964. }
  965. /* if this connection registered a debug-message receiver delete it */
  966. delete_debug_msg_receiver(connection->cmd_ctx, target);
  967. free(connection->priv);
  968. connection->priv = NULL;
  969. target_unregister_event_callback(gdb_target_callback_event_handler, connection);
  970. target_call_event_callbacks(target, TARGET_EVENT_GDB_END);
  971. target_call_event_callbacks(target, TARGET_EVENT_GDB_DETACH);
  972. return ERROR_OK;
  973. }
  974. static void gdb_send_error(struct connection *connection, uint8_t the_error)
  975. {
  976. char err[4];
  977. snprintf(err, 4, "E%2.2X", the_error);
  978. gdb_put_packet(connection, err, 3);
  979. }
  980. static int gdb_last_signal_packet(struct connection *connection,
  981. char const *packet, int packet_size)
  982. {
  983. struct target *target = get_target_from_connection(connection);
  984. struct gdb_connection *gdb_con = connection->priv;
  985. char sig_reply[4];
  986. int signal_var;
  987. if (!gdb_con->attached) {
  988. /* if we are here we have received a kill packet
  989. * reply W stop reply otherwise gdb gets very unhappy */
  990. gdb_put_packet(connection, "W00", 3);
  991. return ERROR_OK;
  992. }
  993. signal_var = gdb_last_signal(target);
  994. snprintf(sig_reply, 4, "S%2.2x", signal_var);
  995. gdb_put_packet(connection, sig_reply, 3);
  996. return ERROR_OK;
  997. }
  998. static inline int gdb_reg_pos(struct target *target, int pos, int len)
  999. {
  1000. if (target->endianness == TARGET_LITTLE_ENDIAN)
  1001. return pos;
  1002. else
  1003. return len - 1 - pos;
  1004. }
  1005. /* Convert register to string of bytes. NB! The # of bits in the
  1006. * register might be non-divisible by 8(a byte), in which
  1007. * case an entire byte is shown.
  1008. *
  1009. * NB! the format on the wire is the target endianness
  1010. *
  1011. * The format of reg->value is little endian
  1012. *
  1013. */
  1014. static void gdb_str_to_target(struct target *target,
  1015. char *tstr, struct reg *reg)
  1016. {
  1017. int i;
  1018. uint8_t *buf;
  1019. int buf_len;
  1020. buf = reg->value;
  1021. buf_len = DIV_ROUND_UP(reg->size, 8);
  1022. for (i = 0; i < buf_len; i++) {
  1023. int j = gdb_reg_pos(target, i, buf_len);
  1024. tstr += sprintf(tstr, "%02x", buf[j]);
  1025. }
  1026. }
  1027. /* copy over in register buffer */
  1028. static void gdb_target_to_reg(struct target *target,
  1029. char const *tstr, int str_len, uint8_t *bin)
  1030. {
  1031. if (str_len % 2) {
  1032. LOG_ERROR("BUG: gdb value with uneven number of characters encountered");
  1033. exit(-1);
  1034. }
  1035. int i;
  1036. for (i = 0; i < str_len; i += 2) {
  1037. unsigned t;
  1038. if (sscanf(tstr + i, "%02x", &t) != 1) {
  1039. LOG_ERROR("BUG: unable to convert register value");
  1040. exit(-1);
  1041. }
  1042. int j = gdb_reg_pos(target, i/2, str_len/2);
  1043. bin[j] = t;
  1044. }
  1045. }
  1046. static int gdb_get_registers_packet(struct connection *connection,
  1047. char const *packet, int packet_size)
  1048. {
  1049. struct target *target = get_target_from_connection(connection);
  1050. struct reg **reg_list;
  1051. int reg_list_size;
  1052. int retval;
  1053. int reg_packet_size = 0;
  1054. char *reg_packet;
  1055. char *reg_packet_p;
  1056. int i;
  1057. #ifdef _DEBUG_GDB_IO_
  1058. LOG_DEBUG("-");
  1059. #endif
  1060. if ((target->rtos) && (rtos_get_gdb_reg_list(connection) == ERROR_OK))
  1061. return ERROR_OK;
  1062. retval = target_get_gdb_reg_list(target, &reg_list, &reg_list_size,
  1063. REG_CLASS_GENERAL);
  1064. if (retval != ERROR_OK)
  1065. return gdb_error(connection, retval);
  1066. for (i = 0; i < reg_list_size; i++) {
  1067. if (!reg_list[i] || reg_list[i]->exist == false || reg_list[i]->hidden)
  1068. continue;
  1069. reg_packet_size += DIV_ROUND_UP(reg_list[i]->size, 8) * 2;
  1070. }
  1071. assert(reg_packet_size > 0);
  1072. reg_packet = malloc(reg_packet_size + 1); /* plus one for string termination null */
  1073. if (!reg_packet)
  1074. return ERROR_FAIL;
  1075. reg_packet_p = reg_packet;
  1076. for (i = 0; i < reg_list_size; i++) {
  1077. if (!reg_list[i] || reg_list[i]->exist == false || reg_list[i]->hidden)
  1078. continue;
  1079. if (!reg_list[i]->valid) {
  1080. retval = reg_list[i]->type->get(reg_list[i]);
  1081. if (retval != ERROR_OK && gdb_report_register_access_error) {
  1082. LOG_DEBUG("Couldn't get register %s.", reg_list[i]->name);
  1083. free(reg_packet);
  1084. free(reg_list);
  1085. return gdb_error(connection, retval);
  1086. }
  1087. }
  1088. gdb_str_to_target(target, reg_packet_p, reg_list[i]);
  1089. reg_packet_p += DIV_ROUND_UP(reg_list[i]->size, 8) * 2;
  1090. }
  1091. #ifdef _DEBUG_GDB_IO_
  1092. {
  1093. char *reg_packet_p_debug;
  1094. reg_packet_p_debug = strndup(reg_packet, reg_packet_size);
  1095. LOG_DEBUG("reg_packet: %s", reg_packet_p_debug);
  1096. free(reg_packet_p_debug);
  1097. }
  1098. #endif
  1099. gdb_put_packet(connection, reg_packet, reg_packet_size);
  1100. free(reg_packet);
  1101. free(reg_list);
  1102. return ERROR_OK;
  1103. }
  1104. static int gdb_set_registers_packet(struct connection *connection,
  1105. char const *packet, int packet_size)
  1106. {
  1107. struct target *target = get_target_from_connection(connection);
  1108. int i;
  1109. struct reg **reg_list;
  1110. int reg_list_size;
  1111. int retval;
  1112. char const *packet_p;
  1113. #ifdef _DEBUG_GDB_IO_
  1114. LOG_DEBUG("-");
  1115. #endif
  1116. /* skip command character */
  1117. packet++;
  1118. packet_size--;
  1119. if (packet_size % 2) {
  1120. LOG_WARNING("GDB set_registers packet with uneven characters received, dropping connection");
  1121. return ERROR_SERVER_REMOTE_CLOSED;
  1122. }
  1123. retval = target_get_gdb_reg_list(target, &reg_list, &reg_list_size,
  1124. REG_CLASS_GENERAL);
  1125. if (retval != ERROR_OK)
  1126. return gdb_error(connection, retval);
  1127. packet_p = packet;
  1128. for (i = 0; i < reg_list_size; i++) {
  1129. uint8_t *bin_buf;
  1130. int chars = (DIV_ROUND_UP(reg_list[i]->size, 8) * 2);
  1131. if (packet_p + chars > packet + packet_size)
  1132. LOG_ERROR("BUG: register packet is too small for registers");
  1133. bin_buf = malloc(DIV_ROUND_UP(reg_list[i]->size, 8));
  1134. gdb_target_to_reg(target, packet_p, chars, bin_buf);
  1135. retval = reg_list[i]->type->set(reg_list[i], bin_buf);
  1136. if (retval != ERROR_OK && gdb_report_register_access_error) {
  1137. LOG_DEBUG("Couldn't set register %s.", reg_list[i]->name);
  1138. free(reg_list);
  1139. free(bin_buf);
  1140. return gdb_error(connection, retval);
  1141. }
  1142. /* advance packet pointer */
  1143. packet_p += chars;
  1144. free(bin_buf);
  1145. }
  1146. /* free struct reg *reg_list[] array allocated by get_gdb_reg_list */
  1147. free(reg_list);
  1148. gdb_put_packet(connection, "OK", 2);
  1149. return ERROR_OK;
  1150. }
  1151. static int gdb_get_register_packet(struct connection *connection,
  1152. char const *packet, int packet_size)
  1153. {
  1154. struct target *target = get_target_from_connection(connection);
  1155. char *reg_packet;
  1156. int reg_num = strtoul(packet + 1, NULL, 16);
  1157. struct reg **reg_list;
  1158. int reg_list_size;
  1159. int retval;
  1160. #ifdef _DEBUG_GDB_IO_
  1161. LOG_DEBUG("-");
  1162. #endif
  1163. if ((target->rtos) && (rtos_get_gdb_reg(connection, reg_num) == ERROR_OK))
  1164. return ERROR_OK;
  1165. retval = target_get_gdb_reg_list_noread(target, &reg_list, &reg_list_size,
  1166. REG_CLASS_ALL);
  1167. if (retval != ERROR_OK)
  1168. return gdb_error(connection, retval);
  1169. if (reg_list_size <= reg_num) {
  1170. LOG_ERROR("gdb requested a non-existing register");
  1171. return ERROR_SERVER_REMOTE_CLOSED;
  1172. }
  1173. if (!reg_list[reg_num]->valid) {
  1174. retval = reg_list[reg_num]->type->get(reg_list[reg_num]);
  1175. if (retval != ERROR_OK && gdb_report_register_access_error) {
  1176. LOG_DEBUG("Couldn't get register %s.", reg_list[reg_num]->name);
  1177. free(reg_list);
  1178. return gdb_error(connection, retval);
  1179. }
  1180. }
  1181. reg_packet = calloc(DIV_ROUND_UP(reg_list[reg_num]->size, 8) * 2 + 1, 1); /* plus one for string termination null */
  1182. gdb_str_to_target(target, reg_packet, reg_list[reg_num]);
  1183. gdb_put_packet(connection, reg_packet, DIV_ROUND_UP(reg_list[reg_num]->size, 8) * 2);
  1184. free(reg_list);
  1185. free(reg_packet);
  1186. return ERROR_OK;
  1187. }
  1188. static int gdb_set_register_packet(struct connection *connection,
  1189. char const *packet, int packet_size)
  1190. {
  1191. struct target *target = get_target_from_connection(connection);
  1192. char *separator;
  1193. int reg_num = strtoul(packet + 1, &separator, 16);
  1194. struct reg **reg_list;
  1195. int reg_list_size;
  1196. int retval;
  1197. #ifdef _DEBUG_GDB_IO_
  1198. LOG_DEBUG("-");
  1199. #endif
  1200. if (*separator != '=') {
  1201. LOG_ERROR("GDB 'set register packet', but no '=' following the register number");
  1202. return ERROR_SERVER_REMOTE_CLOSED;
  1203. }
  1204. size_t chars = strlen(separator + 1);
  1205. uint8_t *bin_buf = malloc(chars / 2);
  1206. gdb_target_to_reg(target, separator + 1, chars, bin_buf);
  1207. if ((target->rtos) &&
  1208. (rtos_set_reg(connection, reg_num, bin_buf) == ERROR_OK)) {
  1209. free(bin_buf);
  1210. gdb_put_packet(connection, "OK", 2);
  1211. return ERROR_OK;
  1212. }
  1213. retval = target_get_gdb_reg_list_noread(target, &reg_list, &reg_list_size,
  1214. REG_CLASS_ALL);
  1215. if (retval != ERROR_OK) {
  1216. free(bin_buf);
  1217. return gdb_error(connection, retval);
  1218. }
  1219. if (reg_list_size <= reg_num) {
  1220. LOG_ERROR("gdb requested a non-existing register");
  1221. free(bin_buf);
  1222. free(reg_list);
  1223. return ERROR_SERVER_REMOTE_CLOSED;
  1224. }
  1225. if (chars != (DIV_ROUND_UP(reg_list[reg_num]->size, 8) * 2)) {
  1226. LOG_ERROR("gdb sent %zu bits for a %" PRIu32 "-bit register (%s)",
  1227. chars * 4, reg_list[reg_num]->size, reg_list[reg_num]->name);
  1228. free(bin_buf);
  1229. free(reg_list);
  1230. return ERROR_SERVER_REMOTE_CLOSED;
  1231. }
  1232. gdb_target_to_reg(target, separator + 1, chars, bin_buf);
  1233. retval = reg_list[reg_num]->type->set(reg_list[reg_num], bin_buf);
  1234. if (retval != ERROR_OK && gdb_report_register_access_error) {
  1235. LOG_DEBUG("Couldn't set register %s.", reg_list[reg_num]->name);
  1236. free(bin_buf);
  1237. free(reg_list);
  1238. return gdb_error(connection, retval);
  1239. }
  1240. gdb_put_packet(connection, "OK", 2);
  1241. free(bin_buf);
  1242. free(reg_list);
  1243. return ERROR_OK;
  1244. }
  1245. /* No attempt is made to translate the "retval" to
  1246. * GDB speak. This has to be done at the calling
  1247. * site as no mapping really exists.
  1248. */
  1249. static int gdb_error(struct connection *connection, int retval)
  1250. {
  1251. LOG_DEBUG("Reporting %i to GDB as generic error", retval);
  1252. gdb_send_error(connection, EFAULT);
  1253. return ERROR_OK;
  1254. }
  1255. /* We don't have to worry about the default 2 second timeout for GDB packets,
  1256. * because GDB breaks up large memory reads into smaller reads.
  1257. */
  1258. static int gdb_read_memory_packet(struct connection *connection,
  1259. char const *packet, int packet_size)
  1260. {
  1261. struct target *target = get_target_from_connection(connection);
  1262. char *separator;
  1263. uint64_t addr = 0;
  1264. uint32_t len = 0;
  1265. uint8_t *buffer;
  1266. char *hex_buffer;
  1267. int retval = ERROR_OK;
  1268. /* skip command character */
  1269. packet++;
  1270. addr = strtoull(packet, &separator, 16);
  1271. if (*separator != ',') {
  1272. LOG_ERROR("incomplete read memory packet received, dropping connection");
  1273. return ERROR_SERVER_REMOTE_CLOSED;
  1274. }
  1275. len = strtoul(separator + 1, NULL, 16);
  1276. if (!len) {
  1277. LOG_WARNING("invalid read memory packet received (len == 0)");
  1278. gdb_put_packet(connection, "", 0);
  1279. return ERROR_OK;
  1280. }
  1281. buffer = malloc(len);
  1282. LOG_DEBUG("addr: 0x%16.16" PRIx64 ", len: 0x%8.8" PRIx32 "", addr, len);
  1283. retval = ERROR_NOT_IMPLEMENTED;
  1284. if (target->rtos)
  1285. retval = rtos_read_buffer(target, addr, len, buffer);
  1286. if (retval == ERROR_NOT_IMPLEMENTED)
  1287. retval = target_read_buffer(target, addr, len, buffer);
  1288. if ((retval != ERROR_OK) && !gdb_report_data_abort) {
  1289. /* TODO : Here we have to lie and send back all zero's lest stack traces won't work.
  1290. * At some point this might be fixed in GDB, in which case this code can be removed.
  1291. *
  1292. * OpenOCD developers are acutely aware of this problem, but there is nothing
  1293. * gained by involving the user in this problem that hopefully will get resolved
  1294. * eventually
  1295. *
  1296. * http://sourceware.org/cgi-bin/gnatsweb.pl? \
  1297. * cmd = view%20audit-trail&database = gdb&pr = 2395
  1298. *
  1299. * For now, the default is to fix up things to make current GDB versions work.
  1300. * This can be overwritten using the gdb_report_data_abort <'enable'|'disable'> command.
  1301. */
  1302. memset(buffer, 0, len);
  1303. retval = ERROR_OK;
  1304. }
  1305. if (retval == ERROR_OK) {
  1306. hex_buffer = malloc(len * 2 + 1);
  1307. size_t pkt_len = hexify(hex_buffer, buffer, len, len * 2 + 1);
  1308. gdb_put_packet(connection, hex_buffer, pkt_len);
  1309. free(hex_buffer);
  1310. } else
  1311. retval = gdb_error(connection, retval);
  1312. free(buffer);
  1313. return retval;
  1314. }
  1315. static int gdb_write_memory_packet(struct connection *connection,
  1316. char const *packet, int packet_size)
  1317. {
  1318. struct target *target = get_target_from_connection(connection);
  1319. char *separator;
  1320. uint64_t addr = 0;
  1321. uint32_t len = 0;
  1322. uint8_t *buffer;
  1323. int retval;
  1324. /* skip command character */
  1325. packet++;
  1326. addr = strtoull(packet, &separator, 16);
  1327. if (*separator != ',') {
  1328. LOG_ERROR("incomplete write memory packet received, dropping connection");
  1329. return ERROR_SERVER_REMOTE_CLOSED;
  1330. }
  1331. len = strtoul(separator + 1, &separator, 16);
  1332. if (*(separator++) != ':') {
  1333. LOG_ERROR("incomplete write memory packet received, dropping connection");
  1334. return ERROR_SERVER_REMOTE_CLOSED;
  1335. }
  1336. buffer = malloc(len);
  1337. LOG_DEBUG("addr: 0x%" PRIx64 ", len: 0x%8.8" PRIx32 "", addr, len);
  1338. if (unhexify(buffer, separator, len) != len)
  1339. LOG_ERROR("unable to decode memory packet");
  1340. retval = ERROR_NOT_IMPLEMENTED;
  1341. if (target->rtos)
  1342. retval = rtos_write_buffer(target, addr, len, buffer);
  1343. if (retval == ERROR_NOT_IMPLEMENTED)
  1344. retval = target_write_buffer(target, addr, len, buffer);
  1345. if (retval == ERROR_OK)
  1346. gdb_put_packet(connection, "OK", 2);
  1347. else
  1348. retval = gdb_error(connection, retval);
  1349. free(buffer);
  1350. return retval;
  1351. }
  1352. static int gdb_write_memory_binary_packet(struct connection *connection,
  1353. char const *packet, int packet_size)
  1354. {
  1355. struct target *target = get_target_from_connection(connection);
  1356. char *separator;
  1357. uint64_t addr = 0;
  1358. uint32_t len = 0;
  1359. int retval = ERROR_OK;
  1360. /* Packets larger than fast_limit bytes will be acknowledged instantly on
  1361. * the assumption that we're in a download and it's important to go as fast
  1362. * as possible. */
  1363. uint32_t fast_limit = 8;
  1364. /* skip command character */
  1365. packet++;
  1366. addr = strtoull(packet, &separator, 16);
  1367. if (*separator != ',') {
  1368. LOG_ERROR("incomplete write memory binary packet received, dropping connection");
  1369. return ERROR_SERVER_REMOTE_CLOSED;
  1370. }
  1371. len = strtoul(separator + 1, &separator, 16);
  1372. if (*(separator++) != ':') {
  1373. LOG_ERROR("incomplete write memory binary packet received, dropping connection");
  1374. return ERROR_SERVER_REMOTE_CLOSED;
  1375. }
  1376. struct gdb_connection *gdb_connection = connection->priv;
  1377. if (gdb_connection->mem_write_error)
  1378. retval = ERROR_FAIL;
  1379. if (retval == ERROR_OK) {
  1380. if (len >= fast_limit) {
  1381. /* By replying the packet *immediately* GDB will send us a new packet
  1382. * while we write the last one to the target.
  1383. * We only do this for larger writes, so that users who do something like:
  1384. * p *((int*)0xdeadbeef)=8675309
  1385. * will get immediate feedback that that write failed.
  1386. */
  1387. gdb_put_packet(connection, "OK", 2);
  1388. }
  1389. } else {
  1390. retval = gdb_error(connection, retval);
  1391. /* now that we have reported the memory write error, we can clear the condition */
  1392. gdb_connection->mem_write_error = false;
  1393. if (retval != ERROR_OK)
  1394. return retval;
  1395. }
  1396. if (len) {
  1397. LOG_DEBUG("addr: 0x%" PRIx64 ", len: 0x%8.8" PRIx32 "", addr, len);
  1398. retval = ERROR_NOT_IMPLEMENTED;
  1399. if (target->rtos)
  1400. retval = rtos_write_buffer(target, addr, len, (uint8_t *)separator);
  1401. if (retval == ERROR_NOT_IMPLEMENTED)
  1402. retval = target_write_buffer(target, addr, len, (uint8_t *)separator);
  1403. if (retval != ERROR_OK)
  1404. gdb_connection->mem_write_error = true;
  1405. }
  1406. if (len < fast_limit) {
  1407. if (retval != ERROR_OK) {
  1408. gdb_error(connection, retval);
  1409. gdb_connection->mem_write_error = false;
  1410. } else {
  1411. gdb_put_packet(connection, "OK", 2);
  1412. }
  1413. }
  1414. return ERROR_OK;
  1415. }
  1416. static int gdb_step_continue_packet(struct connection *connection,
  1417. char const *packet, int packet_size)
  1418. {
  1419. struct target *target = get_target_from_connection(connection);
  1420. int current = 0;
  1421. uint64_t address = 0x0;
  1422. int retval = ERROR_OK;
  1423. LOG_DEBUG("-");
  1424. if (packet_size > 1)
  1425. address = strtoull(packet + 1, NULL, 16);
  1426. else
  1427. current = 1;
  1428. gdb_running_type = packet[0];
  1429. if (packet[0] == 'c') {
  1430. LOG_DEBUG("continue");
  1431. /* resume at current address, don't handle breakpoints, not debugging */
  1432. retval = target_resume(target, current, address, 0, 0);
  1433. } else if (packet[0] == 's') {
  1434. LOG_DEBUG("step");
  1435. /* step at current or address, don't handle breakpoints */
  1436. retval = target_step(target, current, address, 0);
  1437. }
  1438. return retval;
  1439. }
  1440. static int gdb_breakpoint_watchpoint_packet(struct connection *connection,
  1441. char const *packet, int packet_size)
  1442. {
  1443. struct target *target = get_target_from_connection(connection);
  1444. int type;
  1445. enum breakpoint_type bp_type = BKPT_SOFT /* dummy init to avoid warning */;
  1446. enum watchpoint_rw wp_type = WPT_READ /* dummy init to avoid warning */;
  1447. uint64_t address;
  1448. uint32_t size;
  1449. char *separator;
  1450. int retval;
  1451. LOG_DEBUG("[%s]", target_name(target));
  1452. type = strtoul(packet + 1, &separator, 16);
  1453. if (type == 0) /* memory breakpoint */
  1454. bp_type = BKPT_SOFT;
  1455. else if (type == 1) /* hardware breakpoint */
  1456. bp_type = BKPT_HARD;
  1457. else if (type == 2) /* write watchpoint */
  1458. wp_type = WPT_WRITE;
  1459. else if (type == 3) /* read watchpoint */
  1460. wp_type = WPT_READ;
  1461. else if (type == 4) /* access watchpoint */
  1462. wp_type = WPT_ACCESS;
  1463. else {
  1464. LOG_ERROR("invalid gdb watch/breakpoint type(%d), dropping connection", type);
  1465. return ERROR_SERVER_REMOTE_CLOSED;
  1466. }
  1467. if (gdb_breakpoint_override && ((bp_type == BKPT_SOFT) || (bp_type == BKPT_HARD)))
  1468. bp_type = gdb_breakpoint_override_type;
  1469. if (*separator != ',') {
  1470. LOG_ERROR("incomplete breakpoint/watchpoint packet received, dropping connection");
  1471. return ERROR_SERVER_REMOTE_CLOSED;
  1472. }
  1473. address = strtoull(separator + 1, &separator, 16);
  1474. if (*separator != ',') {
  1475. LOG_ERROR("incomplete breakpoint/watchpoint packet received, dropping connection");
  1476. return ERROR_SERVER_REMOTE_CLOSED;
  1477. }
  1478. size = strtoul(separator + 1, &separator, 16);
  1479. switch (type) {
  1480. case 0:
  1481. case 1:
  1482. if (packet[0] == 'Z') {
  1483. retval = breakpoint_add(target, address, size, bp_type);
  1484. if (retval != ERROR_OK) {
  1485. retval = gdb_error(connection, retval);
  1486. if (retval != ERROR_OK)
  1487. return retval;
  1488. } else
  1489. gdb_put_packet(connection, "OK", 2);
  1490. } else {
  1491. breakpoint_remove(target, address);
  1492. gdb_put_packet(connection, "OK", 2);
  1493. }
  1494. break;
  1495. case 2:
  1496. case 3:
  1497. case 4:
  1498. {
  1499. if (packet[0] == 'Z') {
  1500. retval = watchpoint_add(target, address, size, wp_type, 0, 0xffffffffu);
  1501. if (retval != ERROR_OK) {
  1502. retval = gdb_error(connection, retval);
  1503. if (retval != ERROR_OK)
  1504. return retval;
  1505. } else
  1506. gdb_put_packet(connection, "OK", 2);
  1507. } else {
  1508. watchpoint_remove(target, address);
  1509. gdb_put_packet(connection, "OK", 2);
  1510. }
  1511. break;
  1512. }
  1513. default:
  1514. break;
  1515. }
  1516. return ERROR_OK;
  1517. }
  1518. /* print out a string and allocate more space as needed,
  1519. * mainly used for XML at this point
  1520. */
  1521. static __attribute__ ((format (PRINTF_ATTRIBUTE_FORMAT, 5, 6))) void xml_printf(int *retval,
  1522. char **xml, int *pos, int *size, const char *fmt, ...)
  1523. {
  1524. if (*retval != ERROR_OK)
  1525. return;
  1526. int first = 1;
  1527. for (;; ) {
  1528. if ((!*xml) || (!first)) {
  1529. /* start by 0 to exercise all the code paths.
  1530. * Need minimum 2 bytes to fit 1 char and 0 terminator. */
  1531. *size = *size * 2 + 2;
  1532. char *t = *xml;
  1533. *xml = realloc(*xml, *size);
  1534. if (!*xml) {
  1535. free(t);
  1536. *retval = ERROR_SERVER_REMOTE_CLOSED;
  1537. return;
  1538. }
  1539. }
  1540. va_list ap;
  1541. int ret;
  1542. va_start(ap, fmt);
  1543. ret = vsnprintf(*xml + *pos, *size - *pos, fmt, ap);
  1544. va_end(ap);
  1545. if ((ret > 0) && ((ret + 1) < *size - *pos)) {
  1546. *pos += ret;
  1547. return;
  1548. }
  1549. /* there was just enough or not enough space, allocate more. */
  1550. first = 0;
  1551. }
  1552. }
  1553. static int decode_xfer_read(char const *buf, char **annex, int *ofs, unsigned int *len)
  1554. {
  1555. /* Locate the annex. */
  1556. const char *annex_end = strchr(buf, ':');
  1557. if (!annex_end)
  1558. return ERROR_FAIL;
  1559. /* After the read marker and annex, qXfer looks like a
  1560. * traditional 'm' packet. */
  1561. char *separator;
  1562. *ofs = strtoul(annex_end + 1, &separator, 16);
  1563. if (*separator != ',')
  1564. return ERROR_FAIL;
  1565. *len = strtoul(separator + 1, NULL, 16);
  1566. /* Extract the annex if needed */
  1567. if (annex) {
  1568. *annex = strndup(buf, annex_end - buf);
  1569. if (!*annex)
  1570. return ERROR_FAIL;
  1571. }
  1572. return ERROR_OK;
  1573. }
  1574. static int compare_bank(const void *a, const void *b)
  1575. {
  1576. struct flash_bank *b1, *b2;
  1577. b1 = *((struct flash_bank **)a);
  1578. b2 = *((struct flash_bank **)b);
  1579. if (b1->base == b2->base)
  1580. return 0;
  1581. else if (b1->base > b2->base)
  1582. return 1;
  1583. else
  1584. return -1;
  1585. }
  1586. static int gdb_memory_map(struct connection *connection,
  1587. char const *packet, int packet_size)
  1588. {
  1589. /* We get away with only specifying flash here. Regions that are not
  1590. * specified are treated as if we provided no memory map(if not we
  1591. * could detect the holes and mark them as RAM).
  1592. * Normally we only execute this code once, but no big deal if we
  1593. * have to regenerate it a couple of times.
  1594. */
  1595. struct target *target = get_target_from_connection(connection);
  1596. struct flash_bank *p;
  1597. char *xml = NULL;
  1598. int size = 0;
  1599. int pos = 0;
  1600. int retval = ERROR_OK;
  1601. struct flash_bank **banks;
  1602. int offset;
  1603. int length;
  1604. char *separator;
  1605. target_addr_t ram_start = 0;
  1606. unsigned int target_flash_banks = 0;
  1607. /* skip command character */
  1608. packet += 23;
  1609. offset = strtoul(packet, &separator, 16);
  1610. length = strtoul(separator + 1, &separator, 16);
  1611. xml_printf(&retval, &xml, &pos, &size, "<memory-map>\n");
  1612. /* Sort banks in ascending order. We need to report non-flash
  1613. * memory as ram (or rather read/write) by default for GDB, since
  1614. * it has no concept of non-cacheable read/write memory (i/o etc).
  1615. */
  1616. banks = malloc(sizeof(struct flash_bank *)*flash_get_bank_count());
  1617. for (unsigned int i = 0; i < flash_get_bank_count(); i++) {
  1618. p = get_flash_bank_by_num_noprobe(i);
  1619. if (p->target != target)
  1620. continue;
  1621. retval = get_flash_bank_by_num(i, &p);
  1622. if (retval != ERROR_OK) {
  1623. free(banks);
  1624. gdb_error(connection, retval);
  1625. return retval;
  1626. }
  1627. banks[target_flash_banks++] = p;
  1628. }
  1629. qsort(banks, target_flash_banks, sizeof(struct flash_bank *),
  1630. compare_bank);
  1631. for (unsigned int i = 0; i < target_flash_banks; i++) {
  1632. unsigned sector_size = 0;
  1633. unsigned group_len = 0;
  1634. p = banks[i];
  1635. if (ram_start < p->base)
  1636. xml_printf(&retval, &xml, &pos, &size,
  1637. "<memory type=\"ram\" start=\"" TARGET_ADDR_FMT "\" "
  1638. "length=\"" TARGET_ADDR_FMT "\"/>\n",
  1639. ram_start, p->base - ram_start);
  1640. /* Report adjacent groups of same-size sectors. So for
  1641. * example top boot CFI flash will list an initial region
  1642. * with several large sectors (maybe 128KB) and several
  1643. * smaller ones at the end (maybe 32KB). STR7 will have
  1644. * regions with 8KB, 32KB, and 64KB sectors; etc.
  1645. */
  1646. for (unsigned int j = 0; j < p->num_sectors; j++) {
  1647. /* Maybe start a new group of sectors. */
  1648. if (sector_size == 0) {
  1649. if (p->sectors[j].offset + p->sectors[j].size > p->size) {
  1650. LOG_WARNING("The flash sector at offset 0x%08" PRIx32
  1651. " overflows the end of %s bank.",
  1652. p->sectors[j].offset, p->name);
  1653. LOG_WARNING("The rest of bank will not show in gdb memory map.");
  1654. break;
  1655. }
  1656. target_addr_t start;
  1657. start = p->base + p->sectors[j].offset;
  1658. xml_printf(&retval, &xml, &pos, &size,
  1659. "<memory type=\"flash\" "
  1660. "start=\"" TARGET_ADDR_FMT "\" ",
  1661. start);
  1662. sector_size = p->sectors[j].size;
  1663. group_len = sector_size;
  1664. } else {
  1665. group_len += sector_size; /* equal to p->sectors[j].size */
  1666. }
  1667. /* Does this finish a group of sectors?
  1668. * If not, continue an already-started group.
  1669. */
  1670. if (j < p->num_sectors - 1
  1671. && p->sectors[j + 1].size == sector_size
  1672. && p->sectors[j + 1].offset == p->sectors[j].offset + sector_size
  1673. && p->sectors[j + 1].offset + p->sectors[j + 1].size <= p->size)
  1674. continue;
  1675. xml_printf(&retval, &xml, &pos, &size,
  1676. "length=\"0x%x\">\n"
  1677. "<property name=\"blocksize\">"
  1678. "0x%x</property>\n"
  1679. "</memory>\n",
  1680. group_len,
  1681. sector_size);
  1682. sector_size = 0;
  1683. }
  1684. ram_start = p->base + p->size;
  1685. }
  1686. if (ram_start != 0)
  1687. xml_printf(&retval, &xml, &pos, &size,
  1688. "<memory type=\"ram\" start=\"" TARGET_ADDR_FMT "\" "
  1689. "length=\"" TARGET_ADDR_FMT "\"/>\n",
  1690. ram_start, target_address_max(target) - ram_start + 1);
  1691. /* ELSE a flash chip could be at the very end of the address space, in
  1692. * which case ram_start will be precisely 0 */
  1693. free(banks);
  1694. xml_printf(&retval, &xml, &pos, &size, "</memory-map>\n");
  1695. if (retval != ERROR_OK) {
  1696. free(xml);
  1697. gdb_error(connection, retval);
  1698. return retval;
  1699. }
  1700. if (offset + length > pos)
  1701. length = pos - offset;
  1702. char *t = malloc(length + 1);
  1703. t[0] = 'l';
  1704. memcpy(t + 1, xml + offset, length);
  1705. gdb_put_packet(connection, t, length + 1);
  1706. free(t);
  1707. free(xml);
  1708. return ERROR_OK;
  1709. }
  1710. static const char *gdb_get_reg_type_name(enum reg_type type)
  1711. {
  1712. switch (type) {
  1713. case REG_TYPE_BOOL:
  1714. return "bool";
  1715. case REG_TYPE_INT:
  1716. return "int";
  1717. case REG_TYPE_INT8:
  1718. return "int8";
  1719. case REG_TYPE_INT16:
  1720. return "int16";
  1721. case REG_TYPE_INT32:
  1722. return "int32";
  1723. case REG_TYPE_INT64:
  1724. return "int64";
  1725. case REG_TYPE_INT128:
  1726. return "int128";
  1727. case REG_TYPE_UINT:
  1728. return "uint";
  1729. case REG_TYPE_UINT8:
  1730. return "uint8";
  1731. case REG_TYPE_UINT16:
  1732. return "uint16";
  1733. case REG_TYPE_UINT32:
  1734. return "uint32";
  1735. case REG_TYPE_UINT64:
  1736. return "uint64";
  1737. case REG_TYPE_UINT128:
  1738. return "uint128";
  1739. case REG_TYPE_CODE_PTR:
  1740. return "code_ptr";
  1741. case REG_TYPE_DATA_PTR:
  1742. return "data_ptr";
  1743. case REG_TYPE_FLOAT:
  1744. return "float";
  1745. case REG_TYPE_IEEE_SINGLE:
  1746. return "ieee_single";
  1747. case REG_TYPE_IEEE_DOUBLE:
  1748. return "ieee_double";
  1749. case REG_TYPE_ARCH_DEFINED:
  1750. return "int"; /* return arbitrary string to avoid compile warning. */
  1751. }
  1752. return "int"; /* "int" as default value */
  1753. }
  1754. static int lookup_add_arch_defined_types(char const **arch_defined_types_list[], const char *type_id,
  1755. int *num_arch_defined_types)
  1756. {
  1757. int tbl_sz = *num_arch_defined_types;
  1758. if (type_id && (strcmp(type_id, ""))) {
  1759. for (int j = 0; j < (tbl_sz + 1); j++) {
  1760. if (!((*arch_defined_types_list)[j])) {
  1761. (*arch_defined_types_list)[tbl_sz++] = type_id;
  1762. *arch_defined_types_list = realloc(*arch_defined_types_list,
  1763. sizeof(char *) * (tbl_sz + 1));
  1764. (*arch_defined_types_list)[tbl_sz] = NULL;
  1765. *num_arch_defined_types = tbl_sz;
  1766. return 1;
  1767. } else {
  1768. if (!strcmp((*arch_defined_types_list)[j], type_id))
  1769. return 0;
  1770. }
  1771. }
  1772. }
  1773. return -1;
  1774. }
  1775. static int gdb_generate_reg_type_description(struct target *target,
  1776. char **tdesc, int *pos, int *size, struct reg_data_type *type,
  1777. char const **arch_defined_types_list[], int *num_arch_defined_types)
  1778. {
  1779. int retval = ERROR_OK;
  1780. if (type->type_class == REG_TYPE_CLASS_VECTOR) {
  1781. struct reg_data_type *data_type = type->reg_type_vector->type;
  1782. if (data_type->type == REG_TYPE_ARCH_DEFINED) {
  1783. if (lookup_add_arch_defined_types(arch_defined_types_list, data_type->id,
  1784. num_arch_defined_types))
  1785. gdb_generate_reg_type_description(target, tdesc, pos, size, data_type,
  1786. arch_defined_types_list,
  1787. num_arch_defined_types);
  1788. }
  1789. /* <vector id="id" type="type" count="count"/> */
  1790. xml_printf(&retval, tdesc, pos, size,
  1791. "<vector id=\"%s\" type=\"%s\" count=\"%" PRIu32 "\"/>\n",
  1792. type->id, type->reg_type_vector->type->id,
  1793. type->reg_type_vector->count);
  1794. } else if (type->type_class == REG_TYPE_CLASS_UNION) {
  1795. struct reg_data_type_union_field *field;
  1796. field = type->reg_type_union->fields;
  1797. while (field) {
  1798. struct reg_data_type *data_type = field->type;
  1799. if (data_type->type == REG_TYPE_ARCH_DEFINED) {
  1800. if (lookup_add_arch_defined_types(arch_defined_types_list, data_type->id,
  1801. num_arch_defined_types))
  1802. gdb_generate_reg_type_description(target, tdesc, pos, size, data_type,
  1803. arch_defined_types_list,
  1804. num_arch_defined_types);
  1805. }
  1806. field = field->next;
  1807. }
  1808. /* <union id="id">
  1809. * <field name="name" type="type"/> ...
  1810. * </union> */
  1811. xml_printf(&retval, tdesc, pos, size,
  1812. "<union id=\"%s\">\n",
  1813. type->id);
  1814. field = type->reg_type_union->fields;
  1815. while (field) {
  1816. xml_printf(&retval, tdesc, pos, size,
  1817. "<field name=\"%s\" type=\"%s\"/>\n",
  1818. field->name, field->type->id);
  1819. field = field->next;
  1820. }
  1821. xml_printf(&retval, tdesc, pos, size,
  1822. "</union>\n");
  1823. } else if (type->type_class == REG_TYPE_CLASS_STRUCT) {
  1824. struct reg_data_type_struct_field *field;
  1825. field = type->reg_type_struct->fields;
  1826. if (field->use_bitfields) {
  1827. /* <struct id="id" size="size">
  1828. * <field name="name" start="start" end="end"/> ...
  1829. * </struct> */
  1830. xml_printf(&retval, tdesc, pos, size,
  1831. "<struct id=\"%s\" size=\"%" PRIu32 "\">\n",
  1832. type->id, type->reg_type_struct->size);
  1833. while (field) {
  1834. xml_printf(&retval, tdesc, pos, size,
  1835. "<field name=\"%s\" start=\"%" PRIu32 "\" end=\"%" PRIu32 "\" type=\"%s\" />\n",
  1836. field->name, field->bitfield->start, field->bitfield->end,
  1837. gdb_get_reg_type_name(field->bitfield->type));
  1838. field = field->next;
  1839. }
  1840. } else {
  1841. while (field) {
  1842. struct reg_data_type *data_type = field->type;
  1843. if (data_type->type == REG_TYPE_ARCH_DEFINED) {
  1844. if (lookup_add_arch_defined_types(arch_defined_types_list, data_type->id,
  1845. num_arch_defined_types))
  1846. gdb_generate_reg_type_description(target, tdesc, pos, size, data_type,
  1847. arch_defined_types_list,
  1848. num_arch_defined_types);
  1849. }
  1850. }
  1851. /* <struct id="id">
  1852. * <field name="name" type="type"/> ...
  1853. * </struct> */
  1854. xml_printf(&retval, tdesc, pos, size,
  1855. "<struct id=\"%s\">\n",
  1856. type->id);
  1857. while (field) {
  1858. xml_printf(&retval, tdesc, pos, size,
  1859. "<field name=\"%s\" type=\"%s\"/>\n",
  1860. field->name, field->type->id);
  1861. field = field->next;
  1862. }
  1863. }
  1864. xml_printf(&retval, tdesc, pos, size,
  1865. "</struct>\n");
  1866. } else if (type->type_class == REG_TYPE_CLASS_FLAGS) {
  1867. /* <flags id="id" size="size">
  1868. * <field name="name" start="start" end="end"/> ...
  1869. * </flags> */
  1870. xml_printf(&retval, tdesc, pos, size,
  1871. "<flags id=\"%s\" size=\"%" PRIu32 "\">\n",
  1872. type->id, type->reg_type_flags->size);
  1873. struct reg_data_type_flags_field *field;
  1874. field = type->reg_type_flags->fields;
  1875. while (field) {
  1876. xml_printf(&retval, tdesc, pos, size,
  1877. "<field name=\"%s\" start=\"%" PRIu32 "\" end=\"%" PRIu32 "\" type=\"%s\" />\n",
  1878. field->name, field->bitfield->start, field->bitfield->end,
  1879. gdb_get_reg_type_name(field->bitfield->type));
  1880. field = field->next;
  1881. }
  1882. xml_printf(&retval, tdesc, pos, size,
  1883. "</flags>\n");
  1884. }
  1885. return ERROR_OK;
  1886. }
  1887. /* Get a list of available target registers features. feature_list must
  1888. * be freed by caller.
  1889. */
  1890. static int get_reg_features_list(struct target *target, char const **feature_list[], int *feature_list_size,
  1891. struct reg **reg_list, int reg_list_size)
  1892. {
  1893. int tbl_sz = 0;
  1894. /* Start with only one element */
  1895. *feature_list = calloc(1, sizeof(char *));
  1896. for (int i = 0; i < reg_list_size; i++) {
  1897. if (reg_list[i]->exist == false || reg_list[i]->hidden)
  1898. continue;
  1899. if (reg_list[i]->feature
  1900. && reg_list[i]->feature->name
  1901. && (strcmp(reg_list[i]->feature->name, ""))) {
  1902. /* We found a feature, check if the feature is already in the
  1903. * table. If not, allocate a new entry for the table and
  1904. * put the new feature in it.
  1905. */
  1906. for (int j = 0; j < (tbl_sz + 1); j++) {
  1907. if (!((*feature_list)[j])) {
  1908. (*feature_list)[tbl_sz++] = reg_list[i]->feature->name;
  1909. *feature_list = realloc(*feature_list, sizeof(char *) * (tbl_sz + 1));
  1910. (*feature_list)[tbl_sz] = NULL;
  1911. break;
  1912. } else {
  1913. if (!strcmp((*feature_list)[j], reg_list[i]->feature->name))
  1914. break;
  1915. }
  1916. }
  1917. }
  1918. }
  1919. if (feature_list_size)
  1920. *feature_list_size = tbl_sz;
  1921. return ERROR_OK;
  1922. }
  1923. static int gdb_generate_target_description(struct target *target, char **tdesc_out)
  1924. {
  1925. int retval = ERROR_OK;
  1926. struct reg **reg_list = NULL;
  1927. int reg_list_size;
  1928. char const *architecture;
  1929. char const **features = NULL;
  1930. int feature_list_size = 0;
  1931. char *tdesc = NULL;
  1932. int pos = 0;
  1933. int size = 0;
  1934. retval = target_get_gdb_reg_list_noread(target, &reg_list,
  1935. &reg_list_size, REG_CLASS_ALL);
  1936. if (retval != ERROR_OK) {
  1937. LOG_ERROR("get register list failed");
  1938. retval = ERROR_FAIL;
  1939. goto error;
  1940. }
  1941. if (reg_list_size <= 0) {
  1942. LOG_ERROR("get register list failed");
  1943. retval = ERROR_FAIL;
  1944. goto error;
  1945. }
  1946. /* Get a list of available target registers features */
  1947. retval = get_reg_features_list(target, &features, &feature_list_size, reg_list, reg_list_size);
  1948. if (retval != ERROR_OK) {
  1949. LOG_ERROR("Can't get the registers feature list");
  1950. retval = ERROR_FAIL;
  1951. goto error;
  1952. }
  1953. /* If we found some features associated with registers, create sections */
  1954. int current_feature = 0;
  1955. xml_printf(&retval, &tdesc, &pos, &size,
  1956. "<?xml version=\"1.0\"?>\n"
  1957. "<!DOCTYPE target SYSTEM \"gdb-target.dtd\">\n"
  1958. "<target version=\"1.0\">\n");
  1959. /* generate architecture element if supported by target */
  1960. architecture = target_get_gdb_arch(target);
  1961. if (architecture)
  1962. xml_printf(&retval, &tdesc, &pos, &size,
  1963. "<architecture>%s</architecture>\n", architecture);
  1964. /* generate target description according to register list */
  1965. if (features) {
  1966. while (features[current_feature]) {
  1967. char const **arch_defined_types = NULL;
  1968. int num_arch_defined_types = 0;
  1969. arch_defined_types = calloc(1, sizeof(char *));
  1970. xml_printf(&retval, &tdesc, &pos, &size,
  1971. "<feature name=\"%s\">\n",
  1972. features[current_feature]);
  1973. int i;
  1974. for (i = 0; i < reg_list_size; i++) {
  1975. if (reg_list[i]->exist == false || reg_list[i]->hidden)
  1976. continue;
  1977. if (strcmp(reg_list[i]->feature->name, features[current_feature]))
  1978. continue;
  1979. const char *type_str;
  1980. if (reg_list[i]->reg_data_type) {
  1981. if (reg_list[i]->reg_data_type->type == REG_TYPE_ARCH_DEFINED) {
  1982. /* generate <type... first, if there are architecture-defined types. */
  1983. if (lookup_add_arch_defined_types(&arch_defined_types,
  1984. reg_list[i]->reg_data_type->id,
  1985. &num_arch_defined_types))
  1986. gdb_generate_reg_type_description(target, &tdesc, &pos, &size,
  1987. reg_list[i]->reg_data_type,
  1988. &arch_defined_types,
  1989. &num_arch_defined_types);
  1990. type_str = reg_list[i]->reg_data_type->id;
  1991. } else {
  1992. /* predefined type */
  1993. type_str = gdb_get_reg_type_name(
  1994. reg_list[i]->reg_data_type->type);
  1995. }
  1996. } else {
  1997. /* Default type is "int" */
  1998. type_str = "int";
  1999. }
  2000. xml_printf(&retval, &tdesc, &pos, &size,
  2001. "<reg name=\"%s\"", reg_list[i]->name);
  2002. xml_printf(&retval, &tdesc, &pos, &size,
  2003. " bitsize=\"%" PRIu32 "\"", reg_list[i]->size);
  2004. xml_printf(&retval, &tdesc, &pos, &size,
  2005. " regnum=\"%" PRIu32 "\"", reg_list[i]->number);
  2006. if (reg_list[i]->caller_save)
  2007. xml_printf(&retval, &tdesc, &pos, &size,
  2008. " save-restore=\"yes\"");
  2009. else
  2010. xml_printf(&retval, &tdesc, &pos, &size,
  2011. " save-restore=\"no\"");
  2012. xml_printf(&retval, &tdesc, &pos, &size,
  2013. " type=\"%s\"", type_str);
  2014. if (reg_list[i]->group)
  2015. xml_printf(&retval, &tdesc, &pos, &size,
  2016. " group=\"%s\"", reg_list[i]->group);
  2017. xml_printf(&retval, &tdesc, &pos, &size,
  2018. "/>\n");
  2019. }
  2020. xml_printf(&retval, &tdesc, &pos, &size,
  2021. "</feature>\n");
  2022. current_feature++;
  2023. free(arch_defined_types);
  2024. }
  2025. }
  2026. xml_printf(&retval, &tdesc, &pos, &size,
  2027. "</target>\n");
  2028. error:
  2029. free(features);
  2030. free(reg_list);
  2031. if (retval == ERROR_OK)
  2032. *tdesc_out = tdesc;
  2033. else
  2034. free(tdesc);
  2035. return retval;
  2036. }
  2037. static int gdb_get_target_description_chunk(struct target *target, struct target_desc_format *target_desc,
  2038. char **chunk, int32_t offset, uint32_t length)
  2039. {
  2040. if (!target_desc) {
  2041. LOG_ERROR("Unable to Generate Target Description");
  2042. return ERROR_FAIL;
  2043. }
  2044. char *tdesc = target_desc->tdesc;
  2045. uint32_t tdesc_length = target_desc->tdesc_length;
  2046. if (!tdesc) {
  2047. int retval = gdb_generate_target_description(target, &tdesc);
  2048. if (retval != ERROR_OK) {
  2049. LOG_ERROR("Unable to Generate Target Description");
  2050. return ERROR_FAIL;
  2051. }
  2052. tdesc_length = strlen(tdesc);
  2053. }
  2054. char transfer_type;
  2055. if (length < (tdesc_length - offset))
  2056. transfer_type = 'm';
  2057. else
  2058. transfer_type = 'l';
  2059. *chunk = malloc(length + 2);
  2060. if (!*chunk) {
  2061. LOG_ERROR("Unable to allocate memory");
  2062. return ERROR_FAIL;
  2063. }
  2064. (*chunk)[0] = transfer_type;
  2065. if (transfer_type == 'm') {
  2066. strncpy((*chunk) + 1, tdesc + offset, length);
  2067. (*chunk)[1 + length] = '\0';
  2068. } else {
  2069. strncpy((*chunk) + 1, tdesc + offset, tdesc_length - offset);
  2070. (*chunk)[1 + (tdesc_length - offset)] = '\0';
  2071. /* After gdb-server sends out last chunk, invalidate tdesc. */
  2072. free(tdesc);
  2073. tdesc = NULL;
  2074. tdesc_length = 0;
  2075. }
  2076. target_desc->tdesc = tdesc;
  2077. target_desc->tdesc_length = tdesc_length;
  2078. return ERROR_OK;
  2079. }
  2080. static int gdb_target_description_supported(struct target *target, int *supported)
  2081. {
  2082. int retval = ERROR_OK;
  2083. struct reg **reg_list = NULL;
  2084. int reg_list_size = 0;
  2085. char const **features = NULL;
  2086. int feature_list_size = 0;
  2087. char const *architecture = target_get_gdb_arch(target);
  2088. retval = target_get_gdb_reg_list_noread(target, &reg_list,
  2089. &reg_list_size, REG_CLASS_ALL);
  2090. if (retval != ERROR_OK) {
  2091. LOG_ERROR("get register list failed");
  2092. goto error;
  2093. }
  2094. if (reg_list_size <= 0) {
  2095. LOG_ERROR("get register list failed");
  2096. retval = ERROR_FAIL;
  2097. goto error;
  2098. }
  2099. /* Get a list of available target registers features */
  2100. retval = get_reg_features_list(target, &features, &feature_list_size, reg_list, reg_list_size);
  2101. if (retval != ERROR_OK) {
  2102. LOG_ERROR("Can't get the registers feature list");
  2103. goto error;
  2104. }
  2105. if (supported) {
  2106. if (architecture || feature_list_size)
  2107. *supported = 1;
  2108. else
  2109. *supported = 0;
  2110. }
  2111. error:
  2112. free(features);
  2113. free(reg_list);
  2114. return retval;
  2115. }
  2116. static int gdb_generate_thread_list(struct target *target, char **thread_list_out)
  2117. {
  2118. struct rtos *rtos = target->rtos;
  2119. int retval = ERROR_OK;
  2120. char *thread_list = NULL;
  2121. int pos = 0;
  2122. int size = 0;
  2123. xml_printf(&retval, &thread_list, &pos, &size,
  2124. "<?xml version=\"1.0\"?>\n"
  2125. "<threads>\n");
  2126. if (rtos) {
  2127. for (int i = 0; i < rtos->thread_count; i++) {
  2128. struct thread_detail *thread_detail = &rtos->thread_details[i];
  2129. if (!thread_detail->exists)
  2130. continue;
  2131. xml_printf(&retval, &thread_list, &pos, &size,
  2132. "<thread id=\"%" PRIx64 "\">", thread_detail->threadid);
  2133. if (thread_detail->thread_name_str)
  2134. xml_printf(&retval, &thread_list, &pos, &size,
  2135. "Name: %s", thread_detail->thread_name_str);
  2136. if (thread_detail->extra_info_str) {
  2137. if (thread_detail->thread_name_str)
  2138. xml_printf(&retval, &thread_list, &pos, &size,
  2139. ", ");
  2140. xml_printf(&retval, &thread_list, &pos, &size,
  2141. "%s", thread_detail->extra_info_str);
  2142. }
  2143. xml_printf(&retval, &thread_list, &pos, &size,
  2144. "</thread>\n");
  2145. }
  2146. }
  2147. xml_printf(&retval, &thread_list, &pos, &size,
  2148. "</threads>\n");
  2149. if (retval == ERROR_OK)
  2150. *thread_list_out = thread_list;
  2151. else
  2152. free(thread_list);
  2153. return retval;
  2154. }
  2155. static int gdb_get_thread_list_chunk(struct target *target, char **thread_list,
  2156. char **chunk, int32_t offset, uint32_t length)
  2157. {
  2158. if (!*thread_list) {
  2159. int retval = gdb_generate_thread_list(target, thread_list);
  2160. if (retval != ERROR_OK) {
  2161. LOG_ERROR("Unable to Generate Thread List");
  2162. return ERROR_FAIL;
  2163. }
  2164. }
  2165. size_t thread_list_length = strlen(*thread_list);
  2166. char transfer_type;
  2167. length = MIN(length, thread_list_length - offset);
  2168. if (length < (thread_list_length - offset))
  2169. transfer_type = 'm';
  2170. else
  2171. transfer_type = 'l';
  2172. *chunk = malloc(length + 2 + 3);
  2173. /* Allocating extra 3 bytes prevents false positive valgrind report
  2174. * of strlen(chunk) word access:
  2175. * Invalid read of size 4
  2176. * Address 0x4479934 is 44 bytes inside a block of size 45 alloc'd */
  2177. if (!*chunk) {
  2178. LOG_ERROR("Unable to allocate memory");
  2179. return ERROR_FAIL;
  2180. }
  2181. (*chunk)[0] = transfer_type;
  2182. strncpy((*chunk) + 1, (*thread_list) + offset, length);
  2183. (*chunk)[1 + length] = '\0';
  2184. /* After gdb-server sends out last chunk, invalidate thread list. */
  2185. if (transfer_type == 'l') {
  2186. free(*thread_list);
  2187. *thread_list = NULL;
  2188. }
  2189. return ERROR_OK;
  2190. }
  2191. static int gdb_query_packet(struct connection *connection,
  2192. char const *packet, int packet_size)
  2193. {
  2194. struct command_context *cmd_ctx = connection->cmd_ctx;
  2195. struct gdb_connection *gdb_connection = connection->priv;
  2196. struct target *target = get_target_from_connection(connection);
  2197. if (strncmp(packet, "qRcmd,", 6) == 0) {
  2198. if (packet_size > 6) {
  2199. char *cmd;
  2200. cmd = malloc((packet_size - 6) / 2 + 1);
  2201. size_t len = unhexify((uint8_t *)cmd, packet + 6, (packet_size - 6) / 2);
  2202. cmd[len] = 0;
  2203. /* We want to print all debug output to GDB connection */
  2204. log_add_callback(gdb_log_callback, connection);
  2205. target_call_timer_callbacks_now();
  2206. /* some commands need to know the GDB connection, make note of current
  2207. * GDB connection. */
  2208. current_gdb_connection = gdb_connection;
  2209. command_run_line(cmd_ctx, cmd);
  2210. current_gdb_connection = NULL;
  2211. target_call_timer_callbacks_now();
  2212. log_remove_callback(gdb_log_callback, connection);
  2213. free(cmd);
  2214. }
  2215. gdb_put_packet(connection, "OK", 2);
  2216. return ERROR_OK;
  2217. } else if (strncmp(packet, "qCRC:", 5) == 0) {
  2218. if (packet_size > 5) {
  2219. int retval;
  2220. char gdb_reply[10];
  2221. char *separator;
  2222. uint32_t checksum;
  2223. target_addr_t addr = 0;
  2224. uint32_t len = 0;
  2225. /* skip command character */
  2226. packet += 5;
  2227. addr = strtoull(packet, &separator, 16);
  2228. if (*separator != ',') {
  2229. LOG_ERROR("incomplete read memory packet received, dropping connection");
  2230. return ERROR_SERVER_REMOTE_CLOSED;
  2231. }
  2232. len = strtoul(separator + 1, NULL, 16);
  2233. retval = target_checksum_memory(target, addr, len, &checksum);
  2234. if (retval == ERROR_OK) {
  2235. snprintf(gdb_reply, 10, "C%8.8" PRIx32 "", checksum);
  2236. gdb_put_packet(connection, gdb_reply, 9);
  2237. } else {
  2238. retval = gdb_error(connection, retval);
  2239. if (retval != ERROR_OK)
  2240. return retval;
  2241. }
  2242. return ERROR_OK;
  2243. }
  2244. } else if (strncmp(packet, "qSupported", 10) == 0) {
  2245. /* we currently support packet size and qXfer:memory-map:read (if enabled)
  2246. * qXfer:features:read is supported for some targets */
  2247. int retval = ERROR_OK;
  2248. char *buffer = NULL;
  2249. int pos = 0;
  2250. int size = 0;
  2251. int gdb_target_desc_supported = 0;
  2252. /* we need to test that the target supports target descriptions */
  2253. retval = gdb_target_description_supported(target, &gdb_target_desc_supported);
  2254. if (retval != ERROR_OK) {
  2255. LOG_INFO("Failed detecting Target Description Support, disabling");
  2256. gdb_target_desc_supported = 0;
  2257. }
  2258. /* support may be disabled globally */
  2259. if (gdb_use_target_description == 0) {
  2260. if (gdb_target_desc_supported)
  2261. LOG_WARNING("Target Descriptions Supported, but disabled");
  2262. gdb_target_desc_supported = 0;
  2263. }
  2264. xml_printf(&retval,
  2265. &buffer,
  2266. &pos,
  2267. &size,
  2268. "PacketSize=%x;qXfer:memory-map:read%c;qXfer:features:read%c;qXfer:threads:read+;QStartNoAckMode+;vContSupported+",
  2269. GDB_BUFFER_SIZE,
  2270. ((gdb_use_memory_map == 1) && (flash_get_bank_count() > 0)) ? '+' : '-',
  2271. (gdb_target_desc_supported == 1) ? '+' : '-');
  2272. if (retval != ERROR_OK) {
  2273. gdb_send_error(connection, 01);
  2274. return ERROR_OK;
  2275. }
  2276. gdb_put_packet(connection, buffer, strlen(buffer));
  2277. free(buffer);
  2278. return ERROR_OK;
  2279. } else if ((strncmp(packet, "qXfer:memory-map:read::", 23) == 0)
  2280. && (flash_get_bank_count() > 0))
  2281. return gdb_memory_map(connection, packet, packet_size);
  2282. else if (strncmp(packet, "qXfer:features:read:", 20) == 0) {
  2283. char *xml = NULL;
  2284. int retval = ERROR_OK;
  2285. int offset;
  2286. unsigned int length;
  2287. /* skip command character */
  2288. packet += 20;
  2289. if (decode_xfer_read(packet, NULL, &offset, &length) < 0) {
  2290. gdb_send_error(connection, 01);
  2291. return ERROR_OK;
  2292. }
  2293. /* Target should prepare correct target description for annex.
  2294. * The first character of returned xml is 'm' or 'l'. 'm' for
  2295. * there are *more* chunks to transfer. 'l' for it is the *last*
  2296. * chunk of target description.
  2297. */
  2298. retval = gdb_get_target_description_chunk(target, &gdb_connection->target_desc,
  2299. &xml, offset, length);
  2300. if (retval != ERROR_OK) {
  2301. gdb_error(connection, retval);
  2302. return retval;
  2303. }
  2304. gdb_put_packet(connection, xml, strlen(xml));
  2305. free(xml);
  2306. return ERROR_OK;
  2307. } else if (strncmp(packet, "qXfer:threads:read:", 19) == 0) {
  2308. char *xml = NULL;
  2309. int retval = ERROR_OK;
  2310. int offset;
  2311. unsigned int length;
  2312. /* skip command character */
  2313. packet += 19;
  2314. if (decode_xfer_read(packet, NULL, &offset, &length) < 0) {
  2315. gdb_send_error(connection, 01);
  2316. return ERROR_OK;
  2317. }
  2318. /* Target should prepare correct thread list for annex.
  2319. * The first character of returned xml is 'm' or 'l'. 'm' for
  2320. * there are *more* chunks to transfer. 'l' for it is the *last*
  2321. * chunk of target description.
  2322. */
  2323. retval = gdb_get_thread_list_chunk(target, &gdb_connection->thread_list,
  2324. &xml, offset, length);
  2325. if (retval != ERROR_OK) {
  2326. gdb_error(connection, retval);
  2327. return retval;
  2328. }
  2329. gdb_put_packet(connection, xml, strlen(xml));
  2330. free(xml);
  2331. return ERROR_OK;
  2332. } else if (strncmp(packet, "QStartNoAckMode", 15) == 0) {
  2333. gdb_connection->noack_mode = 1;
  2334. gdb_put_packet(connection, "OK", 2);
  2335. return ERROR_OK;
  2336. }
  2337. gdb_put_packet(connection, "", 0);
  2338. return ERROR_OK;
  2339. }
  2340. static bool gdb_handle_vcont_packet(struct connection *connection, const char *packet, int packet_size)
  2341. {
  2342. struct gdb_connection *gdb_connection = connection->priv;
  2343. struct target *target = get_target_from_connection(connection);
  2344. const char *parse = packet;
  2345. int retval;
  2346. /* query for vCont supported */
  2347. if (parse[0] == '?') {
  2348. if (target->type->step) {
  2349. /* gdb doesn't accept c without C and s without S */
  2350. gdb_put_packet(connection, "vCont;c;C;s;S", 13);
  2351. return true;
  2352. }
  2353. return false;
  2354. }
  2355. if (parse[0] == ';') {
  2356. ++parse;
  2357. --packet_size;
  2358. }
  2359. /* simple case, a continue packet */
  2360. if (parse[0] == 'c') {
  2361. gdb_running_type = 'c';
  2362. LOG_DEBUG("target %s continue", target_name(target));
  2363. log_add_callback(gdb_log_callback, connection);
  2364. retval = target_resume(target, 1, 0, 0, 0);
  2365. if (retval == ERROR_TARGET_NOT_HALTED)
  2366. LOG_INFO("target %s was not halted when resume was requested", target_name(target));
  2367. /* poll target in an attempt to make its internal state consistent */
  2368. if (retval != ERROR_OK) {
  2369. retval = target_poll(target);
  2370. if (retval != ERROR_OK)
  2371. LOG_DEBUG("error polling target %s after failed resume", target_name(target));
  2372. }
  2373. /*
  2374. * We don't report errors to gdb here, move frontend_state to
  2375. * TARGET_RUNNING to stay in sync with gdb's expectation of the
  2376. * target state
  2377. */
  2378. gdb_connection->frontend_state = TARGET_RUNNING;
  2379. target_call_event_callbacks(target, TARGET_EVENT_GDB_START);
  2380. return true;
  2381. }
  2382. /* single-step or step-over-breakpoint */
  2383. if (parse[0] == 's') {
  2384. gdb_running_type = 's';
  2385. bool fake_step = false;
  2386. if (strncmp(parse, "s:", 2) == 0) {
  2387. struct target *ct = target;
  2388. int current_pc = 1;
  2389. int64_t thread_id;
  2390. char *endp;
  2391. parse += 2;
  2392. packet_size -= 2;
  2393. thread_id = strtoll(parse, &endp, 16);
  2394. if (endp) {
  2395. packet_size -= endp - parse;
  2396. parse = endp;
  2397. }
  2398. if (target->rtos) {
  2399. /* FIXME: why is this necessary? rtos state should be up-to-date here already! */
  2400. rtos_update_threads(target);
  2401. target->rtos->gdb_target_for_threadid(connection, thread_id, &ct);
  2402. /*
  2403. * check if the thread to be stepped is the current rtos thread
  2404. * if not, we must fake the step
  2405. */
  2406. if (target->rtos->current_thread != thread_id)
  2407. fake_step = true;
  2408. }
  2409. if (parse[0] == ';') {
  2410. ++parse;
  2411. --packet_size;
  2412. if (parse[0] == 'c') {
  2413. parse += 1;
  2414. /* check if thread-id follows */
  2415. if (parse[0] == ':') {
  2416. int64_t tid;
  2417. parse += 1;
  2418. tid = strtoll(parse, &endp, 16);
  2419. if (tid == thread_id) {
  2420. /*
  2421. * Special case: only step a single thread (core),
  2422. * keep the other threads halted. Currently, only
  2423. * aarch64 target understands it. Other target types don't
  2424. * care (nobody checks the actual value of 'current')
  2425. * and it doesn't really matter. This deserves
  2426. * a symbolic constant and a formal interface documentation
  2427. * at a later time.
  2428. */
  2429. LOG_DEBUG("request to step current core only");
  2430. /* uncomment after checking that indeed other targets are safe */
  2431. /*current_pc = 2;*/
  2432. }
  2433. }
  2434. }
  2435. }
  2436. LOG_DEBUG("target %s single-step thread %"PRIx64, target_name(ct), thread_id);
  2437. log_add_callback(gdb_log_callback, connection);
  2438. target_call_event_callbacks(ct, TARGET_EVENT_GDB_START);
  2439. /*
  2440. * work around an annoying gdb behaviour: when the current thread
  2441. * is changed in gdb, it assumes that the target can follow and also
  2442. * make the thread current. This is an assumption that cannot hold
  2443. * for a real target running a multi-threading OS. We just fake
  2444. * the step to not trigger an internal error in gdb. See
  2445. * https://sourceware.org/bugzilla/show_bug.cgi?id=22925 for details
  2446. */
  2447. if (fake_step) {
  2448. int sig_reply_len;
  2449. char sig_reply[128];
  2450. LOG_DEBUG("fake step thread %"PRIx64, thread_id);
  2451. sig_reply_len = snprintf(sig_reply, sizeof(sig_reply),
  2452. "T05thread:%016"PRIx64";", thread_id);
  2453. gdb_put_packet(connection, sig_reply, sig_reply_len);
  2454. log_remove_callback(gdb_log_callback, connection);
  2455. return true;
  2456. }
  2457. /* support for gdb_sync command */
  2458. if (gdb_connection->sync) {
  2459. gdb_connection->sync = false;
  2460. if (ct->state == TARGET_HALTED) {
  2461. LOG_DEBUG("stepi ignored. GDB will now fetch the register state "
  2462. "from the target.");
  2463. gdb_sig_halted(connection);
  2464. log_remove_callback(gdb_log_callback, connection);
  2465. } else
  2466. gdb_connection->frontend_state = TARGET_RUNNING;
  2467. return true;
  2468. }
  2469. retval = target_step(ct, current_pc, 0, 0);
  2470. if (retval == ERROR_TARGET_NOT_HALTED)
  2471. LOG_INFO("target %s was not halted when step was requested", target_name(ct));
  2472. /* if step was successful send a reply back to gdb */
  2473. if (retval == ERROR_OK) {
  2474. retval = target_poll(ct);
  2475. if (retval != ERROR_OK)
  2476. LOG_DEBUG("error polling target %s after successful step", target_name(ct));
  2477. /* send back signal information */
  2478. gdb_signal_reply(ct, connection);
  2479. /* stop forwarding log packets! */
  2480. log_remove_callback(gdb_log_callback, connection);
  2481. } else
  2482. gdb_connection->frontend_state = TARGET_RUNNING;
  2483. } else {
  2484. LOG_ERROR("Unknown vCont packet");
  2485. return false;
  2486. }
  2487. return true;
  2488. }
  2489. return false;
  2490. }
  2491. static char *next_hex_encoded_field(const char **str, char sep)
  2492. {
  2493. size_t hexlen;
  2494. const char *hex = *str;
  2495. if (hex[0] == '\0')
  2496. return NULL;
  2497. const char *end = strchr(hex, sep);
  2498. if (!end)
  2499. hexlen = strlen(hex);
  2500. else
  2501. hexlen = end - hex;
  2502. *str = hex + hexlen + 1;
  2503. if (hexlen % 2 != 0) {
  2504. /* Malformed hex data */
  2505. return NULL;
  2506. }
  2507. size_t count = hexlen / 2;
  2508. char *decoded = malloc(count + 1);
  2509. if (!decoded)
  2510. return NULL;
  2511. size_t converted = unhexify((void *)decoded, hex, count);
  2512. if (converted != count) {
  2513. free(decoded);
  2514. return NULL;
  2515. }
  2516. decoded[count] = '\0';
  2517. return decoded;
  2518. }
  2519. /* handle extended restart packet */
  2520. static void gdb_restart_inferior(struct connection *connection, const char *packet, int packet_size)
  2521. {
  2522. struct gdb_connection *gdb_con = connection->priv;
  2523. struct target *target = get_target_from_connection(connection);
  2524. breakpoint_clear_target(target);
  2525. watchpoint_clear_target(target);
  2526. command_run_linef(connection->cmd_ctx, "ocd_gdb_restart %s",
  2527. target_name(target));
  2528. /* set connection as attached after reset */
  2529. gdb_con->attached = true;
  2530. /* info rtos parts */
  2531. gdb_thread_packet(connection, packet, packet_size);
  2532. }
  2533. static bool gdb_handle_vrun_packet(struct connection *connection, const char *packet, int packet_size)
  2534. {
  2535. struct target *target = get_target_from_connection(connection);
  2536. const char *parse = packet;
  2537. /* Skip "vRun" */
  2538. parse += 4;
  2539. if (parse[0] != ';')
  2540. return false;
  2541. parse++;
  2542. /* Skip first field "filename"; don't know what to do with it. */
  2543. free(next_hex_encoded_field(&parse, ';'));
  2544. char *cmdline = next_hex_encoded_field(&parse, ';');
  2545. char *arg;
  2546. while (cmdline && (arg = next_hex_encoded_field(&parse, ';')) != NULL) {
  2547. char *new_cmdline = alloc_printf("%s %s", cmdline, arg);
  2548. free(cmdline);
  2549. free(arg);
  2550. cmdline = new_cmdline;
  2551. }
  2552. if (cmdline) {
  2553. if (target->semihosting) {
  2554. LOG_INFO("GDB set inferior command line to '%s'", cmdline);
  2555. free(target->semihosting->cmdline);
  2556. target->semihosting->cmdline = cmdline;
  2557. } else {
  2558. LOG_INFO("GDB set inferior command line to '%s' but semihosting is unavailable", cmdline);
  2559. free(cmdline);
  2560. }
  2561. }
  2562. gdb_restart_inferior(connection, packet, packet_size);
  2563. gdb_put_packet(connection, "S00", 3);
  2564. return true;
  2565. }
  2566. static int gdb_v_packet(struct connection *connection,
  2567. char const *packet, int packet_size)
  2568. {
  2569. struct gdb_connection *gdb_connection = connection->priv;
  2570. int result;
  2571. struct target *target = get_target_from_connection(connection);
  2572. if (strncmp(packet, "vCont", 5) == 0) {
  2573. bool handled;
  2574. packet += 5;
  2575. packet_size -= 5;
  2576. handled = gdb_handle_vcont_packet(connection, packet, packet_size);
  2577. if (!handled)
  2578. gdb_put_packet(connection, "", 0);
  2579. return ERROR_OK;
  2580. }
  2581. if (strncmp(packet, "vRun", 4) == 0) {
  2582. bool handled;
  2583. handled = gdb_handle_vrun_packet(connection, packet, packet_size);
  2584. if (!handled)
  2585. gdb_put_packet(connection, "", 0);
  2586. return ERROR_OK;
  2587. }
  2588. /* if flash programming disabled - send a empty reply */
  2589. if (gdb_flash_program == 0) {
  2590. gdb_put_packet(connection, "", 0);
  2591. return ERROR_OK;
  2592. }
  2593. if (strncmp(packet, "vFlashErase:", 12) == 0) {
  2594. unsigned long addr;
  2595. unsigned long length;
  2596. char const *parse = packet + 12;
  2597. if (*parse == '\0') {
  2598. LOG_ERROR("incomplete vFlashErase packet received, dropping connection");
  2599. return ERROR_SERVER_REMOTE_CLOSED;
  2600. }
  2601. addr = strtoul(parse, (char **)&parse, 16);
  2602. if (*(parse++) != ',' || *parse == '\0') {
  2603. LOG_ERROR("incomplete vFlashErase packet received, dropping connection");
  2604. return ERROR_SERVER_REMOTE_CLOSED;
  2605. }
  2606. length = strtoul(parse, (char **)&parse, 16);
  2607. if (*parse != '\0') {
  2608. LOG_ERROR("incomplete vFlashErase packet received, dropping connection");
  2609. return ERROR_SERVER_REMOTE_CLOSED;
  2610. }
  2611. /* assume all sectors need erasing - stops any problems
  2612. * when flash_write is called multiple times */
  2613. flash_set_dirty();
  2614. /* perform any target specific operations before the erase */
  2615. target_call_event_callbacks(target,
  2616. TARGET_EVENT_GDB_FLASH_ERASE_START);
  2617. /* vFlashErase:addr,length messages require region start and
  2618. * end to be "block" aligned ... if padding is ever needed,
  2619. * GDB will have become dangerously confused.
  2620. */
  2621. result = flash_erase_address_range(target, false, addr,
  2622. length);
  2623. /* perform any target specific operations after the erase */
  2624. target_call_event_callbacks(target,
  2625. TARGET_EVENT_GDB_FLASH_ERASE_END);
  2626. /* perform erase */
  2627. if (result != ERROR_OK) {
  2628. /* GDB doesn't evaluate the actual error number returned,
  2629. * treat a failed erase as an I/O error
  2630. */
  2631. gdb_send_error(connection, EIO);
  2632. LOG_ERROR("flash_erase returned %i", result);
  2633. } else
  2634. gdb_put_packet(connection, "OK", 2);
  2635. return ERROR_OK;
  2636. }
  2637. if (strncmp(packet, "vFlashWrite:", 12) == 0) {
  2638. int retval;
  2639. unsigned long addr;
  2640. unsigned long length;
  2641. char const *parse = packet + 12;
  2642. if (*parse == '\0') {
  2643. LOG_ERROR("incomplete vFlashErase packet received, dropping connection");
  2644. return ERROR_SERVER_REMOTE_CLOSED;
  2645. }
  2646. addr = strtoul(parse, (char **)&parse, 16);
  2647. if (*(parse++) != ':') {
  2648. LOG_ERROR("incomplete vFlashErase packet received, dropping connection");
  2649. return ERROR_SERVER_REMOTE_CLOSED;
  2650. }
  2651. length = packet_size - (parse - packet);
  2652. /* create a new image if there isn't already one */
  2653. if (!gdb_connection->vflash_image) {
  2654. gdb_connection->vflash_image = malloc(sizeof(struct image));
  2655. image_open(gdb_connection->vflash_image, "", "build");
  2656. }
  2657. /* create new section with content from packet buffer */
  2658. retval = image_add_section(gdb_connection->vflash_image,
  2659. addr, length, 0x0, (uint8_t const *)parse);
  2660. if (retval != ERROR_OK)
  2661. return retval;
  2662. gdb_put_packet(connection, "OK", 2);
  2663. return ERROR_OK;
  2664. }
  2665. if (strncmp(packet, "vFlashDone", 10) == 0) {
  2666. uint32_t written;
  2667. /* process the flashing buffer. No need to erase as GDB
  2668. * always issues a vFlashErase first. */
  2669. target_call_event_callbacks(target,
  2670. TARGET_EVENT_GDB_FLASH_WRITE_START);
  2671. result = flash_write(target, gdb_connection->vflash_image,
  2672. &written, false);
  2673. target_call_event_callbacks(target,
  2674. TARGET_EVENT_GDB_FLASH_WRITE_END);
  2675. if (result != ERROR_OK) {
  2676. if (result == ERROR_FLASH_DST_OUT_OF_BANK)
  2677. gdb_put_packet(connection, "E.memtype", 9);
  2678. else
  2679. gdb_send_error(connection, EIO);
  2680. } else {
  2681. LOG_DEBUG("wrote %u bytes from vFlash image to flash", (unsigned)written);
  2682. gdb_put_packet(connection, "OK", 2);
  2683. }
  2684. image_close(gdb_connection->vflash_image);
  2685. free(gdb_connection->vflash_image);
  2686. gdb_connection->vflash_image = NULL;
  2687. return ERROR_OK;
  2688. }
  2689. gdb_put_packet(connection, "", 0);
  2690. return ERROR_OK;
  2691. }
  2692. static int gdb_detach(struct connection *connection)
  2693. {
  2694. /*
  2695. * Only reply "OK" to GDB
  2696. * it will close the connection and this will trigger a call to
  2697. * gdb_connection_closed() that will in turn trigger the event
  2698. * TARGET_EVENT_GDB_DETACH
  2699. */
  2700. return gdb_put_packet(connection, "OK", 2);
  2701. }
  2702. /* The format of 'F' response packet is
  2703. * Fretcode,errno,Ctrl-C flag;call-specific attachment
  2704. */
  2705. static int gdb_fileio_response_packet(struct connection *connection,
  2706. char const *packet, int packet_size)
  2707. {
  2708. struct target *target = get_target_from_connection(connection);
  2709. char *separator;
  2710. char *parsing_point;
  2711. int fileio_retcode = strtoul(packet + 1, &separator, 16);
  2712. int fileio_errno = 0;
  2713. bool fileio_ctrl_c = false;
  2714. int retval;
  2715. LOG_DEBUG("-");
  2716. if (*separator == ',') {
  2717. parsing_point = separator + 1;
  2718. fileio_errno = strtoul(parsing_point, &separator, 16);
  2719. if (*separator == ',') {
  2720. if (*(separator + 1) == 'C') {
  2721. /* TODO: process ctrl-c */
  2722. fileio_ctrl_c = true;
  2723. }
  2724. }
  2725. }
  2726. LOG_DEBUG("File-I/O response, retcode: 0x%x, errno: 0x%x, ctrl-c: %s",
  2727. fileio_retcode, fileio_errno, fileio_ctrl_c ? "true" : "false");
  2728. retval = target_gdb_fileio_end(target, fileio_retcode, fileio_errno, fileio_ctrl_c);
  2729. if (retval != ERROR_OK)
  2730. return ERROR_FAIL;
  2731. /* After File-I/O ends, keep continue or step */
  2732. if (gdb_running_type == 'c')
  2733. retval = target_resume(target, 1, 0x0, 0, 0);
  2734. else if (gdb_running_type == 's')
  2735. retval = target_step(target, 1, 0x0, 0);
  2736. else
  2737. retval = ERROR_FAIL;
  2738. if (retval != ERROR_OK)
  2739. return ERROR_FAIL;
  2740. return ERROR_OK;
  2741. }
  2742. static void gdb_log_callback(void *priv, const char *file, unsigned line,
  2743. const char *function, const char *string)
  2744. {
  2745. struct connection *connection = priv;
  2746. struct gdb_connection *gdb_con = connection->priv;
  2747. if (gdb_con->busy) {
  2748. /* do not reply this using the O packet */
  2749. return;
  2750. }
  2751. gdb_output_con(connection, string);
  2752. }
  2753. static void gdb_sig_halted(struct connection *connection)
  2754. {
  2755. char sig_reply[4];
  2756. snprintf(sig_reply, 4, "T%2.2x", 2);
  2757. gdb_put_packet(connection, sig_reply, 3);
  2758. }
  2759. static int gdb_input_inner(struct connection *connection)
  2760. {
  2761. /* Do not allocate this on the stack */
  2762. static char gdb_packet_buffer[GDB_BUFFER_SIZE + 1]; /* Extra byte for null-termination */
  2763. struct target *target;
  2764. char const *packet = gdb_packet_buffer;
  2765. int packet_size;
  2766. int retval;
  2767. struct gdb_connection *gdb_con = connection->priv;
  2768. static bool warn_use_ext;
  2769. target = get_target_from_connection(connection);
  2770. /* drain input buffer. If one of the packets fail, then an error
  2771. * packet is replied, if applicable.
  2772. *
  2773. * This loop will terminate and the error code is returned.
  2774. *
  2775. * The calling fn will check if this error is something that
  2776. * can be recovered from, or if the connection must be closed.
  2777. *
  2778. * If the error is recoverable, this fn is called again to
  2779. * drain the rest of the buffer.
  2780. */
  2781. do {
  2782. packet_size = GDB_BUFFER_SIZE;
  2783. retval = gdb_get_packet(connection, gdb_packet_buffer, &packet_size);
  2784. if (retval != ERROR_OK)
  2785. return retval;
  2786. /* terminate with zero */
  2787. gdb_packet_buffer[packet_size] = '\0';
  2788. gdb_log_incoming_packet(gdb_packet_buffer);
  2789. if (packet_size > 0) {
  2790. retval = ERROR_OK;
  2791. switch (packet[0]) {
  2792. case 'T': /* Is thread alive? */
  2793. gdb_thread_packet(connection, packet, packet_size);
  2794. break;
  2795. case 'H': /* Set current thread ( 'c' for step and continue,
  2796. * 'g' for all other operations ) */
  2797. gdb_thread_packet(connection, packet, packet_size);
  2798. break;
  2799. case 'q':
  2800. case 'Q':
  2801. retval = gdb_thread_packet(connection, packet, packet_size);
  2802. if (retval == GDB_THREAD_PACKET_NOT_CONSUMED)
  2803. retval = gdb_query_packet(connection, packet, packet_size);
  2804. break;
  2805. case 'g':
  2806. retval = gdb_get_registers_packet(connection, packet, packet_size);
  2807. break;
  2808. case 'G':
  2809. retval = gdb_set_registers_packet(connection, packet, packet_size);
  2810. break;
  2811. case 'p':
  2812. retval = gdb_get_register_packet(connection, packet, packet_size);
  2813. break;
  2814. case 'P':
  2815. retval = gdb_set_register_packet(connection, packet, packet_size);
  2816. break;
  2817. case 'm':
  2818. retval = gdb_read_memory_packet(connection, packet, packet_size);
  2819. break;
  2820. case 'M':
  2821. retval = gdb_write_memory_packet(connection, packet, packet_size);
  2822. break;
  2823. case 'z':
  2824. case 'Z':
  2825. retval = gdb_breakpoint_watchpoint_packet(connection, packet, packet_size);
  2826. break;
  2827. case '?':
  2828. gdb_last_signal_packet(connection, packet, packet_size);
  2829. /* '?' is sent after the eventual '!' */
  2830. if (!warn_use_ext && !gdb_con->extended_protocol) {
  2831. warn_use_ext = true;
  2832. LOG_WARNING("Prefer GDB command \"target extended-remote :%s\" instead of \"target remote :%s\"",
  2833. connection->service->port, connection->service->port);
  2834. }
  2835. break;
  2836. case 'c':
  2837. case 's':
  2838. {
  2839. gdb_thread_packet(connection, packet, packet_size);
  2840. log_add_callback(gdb_log_callback, connection);
  2841. if (gdb_con->mem_write_error) {
  2842. LOG_ERROR("Memory write failure!");
  2843. /* now that we have reported the memory write error,
  2844. * we can clear the condition */
  2845. gdb_con->mem_write_error = false;
  2846. }
  2847. bool nostep = false;
  2848. bool already_running = false;
  2849. if (target->state == TARGET_RUNNING) {
  2850. LOG_WARNING("WARNING! The target is already running. "
  2851. "All changes GDB did to registers will be discarded! "
  2852. "Waiting for target to halt.");
  2853. already_running = true;
  2854. } else if (target->state != TARGET_HALTED) {
  2855. LOG_WARNING("The target is not in the halted nor running stated, "
  2856. "stepi/continue ignored.");
  2857. nostep = true;
  2858. } else if ((packet[0] == 's') && gdb_con->sync) {
  2859. /* Hmm..... when you issue a continue in GDB, then a "stepi" is
  2860. * sent by GDB first to OpenOCD, thus defeating the check to
  2861. * make only the single stepping have the sync feature...
  2862. */
  2863. nostep = true;
  2864. LOG_DEBUG("stepi ignored. GDB will now fetch the register state "
  2865. "from the target.");
  2866. }
  2867. gdb_con->sync = false;
  2868. if (!already_running && nostep) {
  2869. /* Either the target isn't in the halted state, then we can't
  2870. * step/continue. This might be early setup, etc.
  2871. *
  2872. * Or we want to allow GDB to pick up a fresh set of
  2873. * register values without modifying the target state.
  2874. *
  2875. */
  2876. gdb_sig_halted(connection);
  2877. /* stop forwarding log packets! */
  2878. log_remove_callback(gdb_log_callback, connection);
  2879. } else {
  2880. /* We're running/stepping, in which case we can
  2881. * forward log output until the target is halted
  2882. */
  2883. gdb_con->frontend_state = TARGET_RUNNING;
  2884. target_call_event_callbacks(target, TARGET_EVENT_GDB_START);
  2885. if (!already_running) {
  2886. /* Here we don't want packet processing to stop even if this fails,
  2887. * so we use a local variable instead of retval. */
  2888. retval = gdb_step_continue_packet(connection, packet, packet_size);
  2889. if (retval != ERROR_OK) {
  2890. /* we'll never receive a halted
  2891. * condition... issue a false one..
  2892. */
  2893. gdb_frontend_halted(target, connection);
  2894. }
  2895. }
  2896. }
  2897. }
  2898. break;
  2899. case 'v':
  2900. retval = gdb_v_packet(connection, packet, packet_size);
  2901. break;
  2902. case 'D':
  2903. retval = gdb_detach(connection);
  2904. break;
  2905. case 'X':
  2906. retval = gdb_write_memory_binary_packet(connection, packet, packet_size);
  2907. if (retval != ERROR_OK)
  2908. return retval;
  2909. break;
  2910. case 'k':
  2911. if (gdb_con->extended_protocol) {
  2912. gdb_con->attached = false;
  2913. break;
  2914. }
  2915. gdb_put_packet(connection, "OK", 2);
  2916. return ERROR_SERVER_REMOTE_CLOSED;
  2917. case '!':
  2918. /* handle extended remote protocol */
  2919. gdb_con->extended_protocol = true;
  2920. gdb_put_packet(connection, "OK", 2);
  2921. break;
  2922. case 'R':
  2923. /* handle extended restart packet */
  2924. gdb_restart_inferior(connection, packet, packet_size);
  2925. break;
  2926. case 'j':
  2927. /* packet supported only by smp target i.e cortex_a.c*/
  2928. /* handle smp packet replying coreid played to gbd */
  2929. gdb_read_smp_packet(connection, packet, packet_size);
  2930. break;
  2931. case 'J':
  2932. /* packet supported only by smp target i.e cortex_a.c */
  2933. /* handle smp packet setting coreid to be played at next
  2934. * resume to gdb */
  2935. gdb_write_smp_packet(connection, packet, packet_size);
  2936. break;
  2937. case 'F':
  2938. /* File-I/O extension */
  2939. /* After gdb uses host-side syscall to complete target file
  2940. * I/O, gdb sends host-side syscall return value to target
  2941. * by 'F' packet.
  2942. * The format of 'F' response packet is
  2943. * Fretcode,errno,Ctrl-C flag;call-specific attachment
  2944. */
  2945. gdb_con->frontend_state = TARGET_RUNNING;
  2946. log_add_callback(gdb_log_callback, connection);
  2947. gdb_fileio_response_packet(connection, packet, packet_size);
  2948. break;
  2949. default:
  2950. /* ignore unknown packets */
  2951. LOG_DEBUG("ignoring 0x%2.2x packet", packet[0]);
  2952. gdb_put_packet(connection, "", 0);
  2953. break;
  2954. }
  2955. /* if a packet handler returned an error, exit input loop */
  2956. if (retval != ERROR_OK)
  2957. return retval;
  2958. }
  2959. if (gdb_con->ctrl_c) {
  2960. if (target->state == TARGET_RUNNING) {
  2961. struct target *t = target;
  2962. if (target->rtos)
  2963. target->rtos->gdb_target_for_threadid(connection, target->rtos->current_threadid, &t);
  2964. retval = target_halt(t);
  2965. if (retval == ERROR_OK)
  2966. retval = target_poll(t);
  2967. if (retval != ERROR_OK)
  2968. target_call_event_callbacks(target, TARGET_EVENT_GDB_HALT);
  2969. gdb_con->ctrl_c = false;
  2970. } else {
  2971. LOG_INFO("The target is not running when halt was requested, stopping GDB.");
  2972. target_call_event_callbacks(target, TARGET_EVENT_GDB_HALT);
  2973. }
  2974. }
  2975. } while (gdb_con->buf_cnt > 0);
  2976. return ERROR_OK;
  2977. }
  2978. static int gdb_input(struct connection *connection)
  2979. {
  2980. int retval = gdb_input_inner(connection);
  2981. struct gdb_connection *gdb_con = connection->priv;
  2982. if (retval == ERROR_SERVER_REMOTE_CLOSED)
  2983. return retval;
  2984. /* logging does not propagate the error, yet can set the gdb_con->closed flag */
  2985. if (gdb_con->closed)
  2986. return ERROR_SERVER_REMOTE_CLOSED;
  2987. /* we'll recover from any other errors(e.g. temporary timeouts, etc.) */
  2988. return ERROR_OK;
  2989. }
  2990. static int gdb_target_start(struct target *target, const char *port)
  2991. {
  2992. struct gdb_service *gdb_service;
  2993. int ret;
  2994. gdb_service = malloc(sizeof(struct gdb_service));
  2995. if (!gdb_service)
  2996. return -ENOMEM;
  2997. LOG_INFO("starting gdb server for %s on %s", target_name(target), port);
  2998. gdb_service->target = target;
  2999. gdb_service->core[0] = -1;
  3000. gdb_service->core[1] = -1;
  3001. target->gdb_service = gdb_service;
  3002. ret = add_service("gdb",
  3003. port, target->gdb_max_connections, &gdb_new_connection, &gdb_input,
  3004. &gdb_connection_closed, gdb_service);
  3005. /* initialize all targets gdb service with the same pointer */
  3006. {
  3007. struct target_list *head;
  3008. struct target *curr;
  3009. head = target->head;
  3010. while (head != (struct target_list *)NULL) {
  3011. curr = head->target;
  3012. if (curr != target)
  3013. curr->gdb_service = gdb_service;
  3014. head = head->next;
  3015. }
  3016. }
  3017. return ret;
  3018. }
  3019. static int gdb_target_add_one(struct target *target)
  3020. {
  3021. /* one gdb instance per smp list */
  3022. if ((target->smp) && (target->gdb_service))
  3023. return ERROR_OK;
  3024. /* skip targets that cannot handle a gdb connections (e.g. mem_ap) */
  3025. if (!target_supports_gdb_connection(target)) {
  3026. LOG_DEBUG("skip gdb server for target %s", target_name(target));
  3027. return ERROR_OK;
  3028. }
  3029. if (target->gdb_port_override) {
  3030. if (strcmp(target->gdb_port_override, "disabled") == 0) {
  3031. LOG_INFO("gdb port disabled");
  3032. return ERROR_OK;
  3033. }
  3034. return gdb_target_start(target, target->gdb_port_override);
  3035. }
  3036. if (strcmp(gdb_port, "disabled") == 0) {
  3037. LOG_INFO("gdb port disabled");
  3038. return ERROR_OK;
  3039. }
  3040. int retval = gdb_target_start(target, gdb_port_next);
  3041. if (retval == ERROR_OK) {
  3042. /* save the port number so can be queried with
  3043. * $target_name cget -gdb-port
  3044. */
  3045. target->gdb_port_override = strdup(gdb_port_next);
  3046. long portnumber;
  3047. /* If we can parse the port number
  3048. * then we increment the port number for the next target.
  3049. */
  3050. char *end;
  3051. portnumber = strtol(gdb_port_next, &end, 0);
  3052. if (!*end) {
  3053. if (parse_long(gdb_port_next, &portnumber) == ERROR_OK) {
  3054. free(gdb_port_next);
  3055. if (portnumber) {
  3056. gdb_port_next = alloc_printf("%ld", portnumber+1);
  3057. } else {
  3058. /* Don't increment if gdb_port is 0, since we're just
  3059. * trying to allocate an unused port. */
  3060. gdb_port_next = strdup("0");
  3061. }
  3062. }
  3063. }
  3064. }
  3065. return retval;
  3066. }
  3067. int gdb_target_add_all(struct target *target)
  3068. {
  3069. if (!target) {
  3070. LOG_WARNING("gdb services need one or more targets defined");
  3071. return ERROR_OK;
  3072. }
  3073. while (target) {
  3074. int retval = gdb_target_add_one(target);
  3075. if (retval != ERROR_OK)
  3076. return retval;
  3077. target = target->next;
  3078. }
  3079. return ERROR_OK;
  3080. }
  3081. COMMAND_HANDLER(handle_gdb_sync_command)
  3082. {
  3083. if (CMD_ARGC != 0)
  3084. return ERROR_COMMAND_SYNTAX_ERROR;
  3085. if (!current_gdb_connection) {
  3086. command_print(CMD,
  3087. "gdb_sync command can only be run from within gdb using \"monitor gdb_sync\"");
  3088. return ERROR_FAIL;
  3089. }
  3090. current_gdb_connection->sync = true;
  3091. return ERROR_OK;
  3092. }
  3093. /* daemon configuration command gdb_port */
  3094. COMMAND_HANDLER(handle_gdb_port_command)
  3095. {
  3096. int retval = CALL_COMMAND_HANDLER(server_pipe_command, &gdb_port);
  3097. if (retval == ERROR_OK) {
  3098. free(gdb_port_next);
  3099. gdb_port_next = strdup(gdb_port);
  3100. }
  3101. return retval;
  3102. }
  3103. COMMAND_HANDLER(handle_gdb_memory_map_command)
  3104. {
  3105. if (CMD_ARGC != 1)
  3106. return ERROR_COMMAND_SYNTAX_ERROR;
  3107. COMMAND_PARSE_ENABLE(CMD_ARGV[0], gdb_use_memory_map);
  3108. return ERROR_OK;
  3109. }
  3110. COMMAND_HANDLER(handle_gdb_flash_program_command)
  3111. {
  3112. if (CMD_ARGC != 1)
  3113. return ERROR_COMMAND_SYNTAX_ERROR;
  3114. COMMAND_PARSE_ENABLE(CMD_ARGV[0], gdb_flash_program);
  3115. return ERROR_OK;
  3116. }
  3117. COMMAND_HANDLER(handle_gdb_report_data_abort_command)
  3118. {
  3119. if (CMD_ARGC != 1)
  3120. return ERROR_COMMAND_SYNTAX_ERROR;
  3121. COMMAND_PARSE_ENABLE(CMD_ARGV[0], gdb_report_data_abort);
  3122. return ERROR_OK;
  3123. }
  3124. COMMAND_HANDLER(handle_gdb_report_register_access_error)
  3125. {
  3126. if (CMD_ARGC != 1)
  3127. return ERROR_COMMAND_SYNTAX_ERROR;
  3128. COMMAND_PARSE_ENABLE(CMD_ARGV[0], gdb_report_register_access_error);
  3129. return ERROR_OK;
  3130. }
  3131. /* gdb_breakpoint_override */
  3132. COMMAND_HANDLER(handle_gdb_breakpoint_override_command)
  3133. {
  3134. if (CMD_ARGC == 0) {
  3135. /* nothing */
  3136. } else if (CMD_ARGC == 1) {
  3137. gdb_breakpoint_override = 1;
  3138. if (strcmp(CMD_ARGV[0], "hard") == 0)
  3139. gdb_breakpoint_override_type = BKPT_HARD;
  3140. else if (strcmp(CMD_ARGV[0], "soft") == 0)
  3141. gdb_breakpoint_override_type = BKPT_SOFT;
  3142. else if (strcmp(CMD_ARGV[0], "disable") == 0)
  3143. gdb_breakpoint_override = 0;
  3144. } else
  3145. return ERROR_COMMAND_SYNTAX_ERROR;
  3146. if (gdb_breakpoint_override)
  3147. LOG_USER("force %s breakpoints",
  3148. (gdb_breakpoint_override_type == BKPT_HARD) ? "hard" : "soft");
  3149. else
  3150. LOG_USER("breakpoint type is not overridden");
  3151. return ERROR_OK;
  3152. }
  3153. COMMAND_HANDLER(handle_gdb_target_description_command)
  3154. {
  3155. if (CMD_ARGC != 1)
  3156. return ERROR_COMMAND_SYNTAX_ERROR;
  3157. COMMAND_PARSE_ENABLE(CMD_ARGV[0], gdb_use_target_description);
  3158. return ERROR_OK;
  3159. }
  3160. COMMAND_HANDLER(handle_gdb_save_tdesc_command)
  3161. {
  3162. char *tdesc;
  3163. uint32_t tdesc_length;
  3164. struct target *target = get_current_target(CMD_CTX);
  3165. int retval = gdb_generate_target_description(target, &tdesc);
  3166. if (retval != ERROR_OK) {
  3167. LOG_ERROR("Unable to Generate Target Description");
  3168. return ERROR_FAIL;
  3169. }
  3170. tdesc_length = strlen(tdesc);
  3171. struct fileio *fileio;
  3172. size_t size_written;
  3173. char *tdesc_filename = alloc_printf("%s.xml", target_type_name(target));
  3174. if (!tdesc_filename) {
  3175. retval = ERROR_FAIL;
  3176. goto out;
  3177. }
  3178. retval = fileio_open(&fileio, tdesc_filename, FILEIO_WRITE, FILEIO_TEXT);
  3179. if (retval != ERROR_OK) {
  3180. LOG_ERROR("Can't open %s for writing", tdesc_filename);
  3181. goto out;
  3182. }
  3183. retval = fileio_write(fileio, tdesc_length, tdesc, &size_written);
  3184. fileio_close(fileio);
  3185. if (retval != ERROR_OK)
  3186. LOG_ERROR("Error while writing the tdesc file");
  3187. out:
  3188. free(tdesc_filename);
  3189. free(tdesc);
  3190. return retval;
  3191. }
  3192. static const struct command_registration gdb_command_handlers[] = {
  3193. {
  3194. .name = "gdb_sync",
  3195. .handler = handle_gdb_sync_command,
  3196. .mode = COMMAND_ANY,
  3197. .help = "next stepi will return immediately allowing "
  3198. "GDB to fetch register state without affecting "
  3199. "target state",
  3200. .usage = ""
  3201. },
  3202. {
  3203. .name = "gdb_port",
  3204. .handler = handle_gdb_port_command,
  3205. .mode = COMMAND_CONFIG,
  3206. .help = "Normally gdb listens to a TCP/IP port. Each subsequent GDB "
  3207. "server listens for the next port number after the "
  3208. "base port number specified. "
  3209. "No arguments reports GDB port. \"pipe\" means listen to stdin "
  3210. "output to stdout, an integer is base port number, \"disabled\" disables "
  3211. "port. Any other string is are interpreted as named pipe to listen to. "
  3212. "Output pipe is the same name as input pipe, but with 'o' appended.",
  3213. .usage = "[port_num]",
  3214. },
  3215. {
  3216. .name = "gdb_memory_map",
  3217. .handler = handle_gdb_memory_map_command,
  3218. .mode = COMMAND_CONFIG,
  3219. .help = "enable or disable memory map",
  3220. .usage = "('enable'|'disable')"
  3221. },
  3222. {
  3223. .name = "gdb_flash_program",
  3224. .handler = handle_gdb_flash_program_command,
  3225. .mode = COMMAND_CONFIG,
  3226. .help = "enable or disable flash program",
  3227. .usage = "('enable'|'disable')"
  3228. },
  3229. {
  3230. .name = "gdb_report_data_abort",
  3231. .handler = handle_gdb_report_data_abort_command,
  3232. .mode = COMMAND_CONFIG,
  3233. .help = "enable or disable reporting data aborts",
  3234. .usage = "('enable'|'disable')"
  3235. },
  3236. {
  3237. .name = "gdb_report_register_access_error",
  3238. .handler = handle_gdb_report_register_access_error,
  3239. .mode = COMMAND_CONFIG,
  3240. .help = "enable or disable reporting register access errors",
  3241. .usage = "('enable'|'disable')"
  3242. },
  3243. {
  3244. .name = "gdb_breakpoint_override",
  3245. .handler = handle_gdb_breakpoint_override_command,
  3246. .mode = COMMAND_ANY,
  3247. .help = "Display or specify type of breakpoint "
  3248. "to be used by gdb 'break' commands.",
  3249. .usage = "('hard'|'soft'|'disable')"
  3250. },
  3251. {
  3252. .name = "gdb_target_description",
  3253. .handler = handle_gdb_target_description_command,
  3254. .mode = COMMAND_CONFIG,
  3255. .help = "enable or disable target description",
  3256. .usage = "('enable'|'disable')"
  3257. },
  3258. {
  3259. .name = "gdb_save_tdesc",
  3260. .handler = handle_gdb_save_tdesc_command,
  3261. .mode = COMMAND_EXEC,
  3262. .help = "Save the target description file",
  3263. .usage = "",
  3264. },
  3265. COMMAND_REGISTRATION_DONE
  3266. };
  3267. int gdb_register_commands(struct command_context *cmd_ctx)
  3268. {
  3269. gdb_port = strdup("3333");
  3270. gdb_port_next = strdup("3333");
  3271. return register_commands(cmd_ctx, NULL, gdb_command_handlers);
  3272. }
  3273. void gdb_service_free(void)
  3274. {
  3275. free(gdb_port);
  3276. free(gdb_port_next);
  3277. }