1 /***************************************************************************
2 * Copyright (C) 2005 by Dominic Rath *
3 * Dominic.Rath@gmx.de *
5 * Copyright (C) 2007-2010 Øyvind Harboe *
6 * oyvind.harboe@zylin.com *
8 * Copyright (C) 2008 by Spencer Oliver *
9 * spen@spen-soft.co.uk *
11 * Copyright (C) 2011 by Broadcom Corporation *
12 * Evan Hunter - ehunter@broadcom.com *
14 * Copyright (C) ST-Ericsson SA 2011 *
15 * michel.jaouen@stericsson.com : smp minimum support *
17 * Copyright (C) 2013 Andes Technology *
18 * Hsiangkai Wang <hkwang@andestech.com> *
20 * Copyright (C) 2013 Franck Jullien *
21 * elec4fun@gmail.com *
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. *
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. *
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 ***************************************************************************/
41 #include <target/breakpoints.h>
42 #include <target/target_request.h>
43 #include <target/register.h>
44 #include <target/target.h>
45 #include <target/target_type.h>
46 #include <target/semihosting_common.h>
48 #include <flash/nor/core.h>
49 #include "gdb_server.h"
50 #include <target/image.h>
51 #include <jtag/jtag.h>
52 #include "rtos/rtos.h"
53 #include "target/smp.h"
57 * GDB server implementation.
59 * This implements the GDB Remote Serial Protocol, over TCP connections,
60 * giving GDB access to the JTAG or other hardware debugging facilities
61 * found in most modern embedded processors.
64 struct target_desc_format {
66 uint32_t tdesc_length;
69 /* private connection data for GDB */
70 struct gdb_connection {
71 char buffer[GDB_BUFFER_SIZE + 1]; /* Extra byte for null-termination */
75 enum target_state frontend_state;
76 struct image *vflash_image;
80 /* set flag to true if you want the next stepi to return immediately.
81 * allowing GDB to pick up a fresh set of register values from the target
82 * without modifying the target state. */
84 /* We delay reporting memory write errors until next step/continue or memory
85 * write. This improves performance of gdb load significantly as the GDB packet
86 * can be replied immediately and a new GDB packet will be ready without delay
87 * (ca. 10% or so...). */
89 /* with extended-remote it seems we need to better emulate attach/detach.
90 * what this means is we reply with a W stop reply after a kill packet,
91 * normally we reply with a S reply via gdb_last_signal_packet.
92 * as a side note this behaviour only effects gdb > 6.8 */
94 /* set when extended protocol is used */
95 bool extended_protocol;
96 /* temporarily used for target description support */
97 struct target_desc_format target_desc;
98 /* temporarily used for thread list support */
103 #define _DEBUG_GDB_IO_
106 static struct gdb_connection *current_gdb_connection;
108 static int gdb_breakpoint_override;
109 static enum breakpoint_type gdb_breakpoint_override_type;
111 static int gdb_error(struct connection *connection, int retval);
112 static char *gdb_port;
113 static char *gdb_port_next;
115 static void gdb_log_callback(void *priv, const char *file, unsigned line,
116 const char *function, const char *string);
118 static void gdb_sig_halted(struct connection *connection);
120 /* number of gdb connections, mainly to suppress gdb related debugging spam
121 * in helper/log.c when no gdb connections are actually active */
122 int gdb_actual_connections;
124 /* set if we are sending a memory map to gdb
125 * via qXfer:memory-map:read packet */
126 /* enabled by default*/
127 static int gdb_use_memory_map = 1;
128 /* enabled by default*/
129 static int gdb_flash_program = 1;
131 /* if set, data aborts cause an error to be reported in memory read packets
132 * see the code in gdb_read_memory_packet() for further explanations.
133 * Disabled by default.
135 static int gdb_report_data_abort;
136 /* If set, errors when accessing registers are reported to gdb. Disabled by
138 static int gdb_report_register_access_error;
140 /* set if we are sending target descriptions to gdb
141 * via qXfer:features:read packet */
142 /* enabled by default */
143 static int gdb_use_target_description = 1;
145 /* current processing free-run type, used by file-I/O */
146 static char gdb_running_type;
148 static int gdb_last_signal(struct target *target)
150 switch (target->debug_reason) {
151 case DBG_REASON_DBGRQ:
152 return 0x2; /* SIGINT */
153 case DBG_REASON_BREAKPOINT:
154 case DBG_REASON_WATCHPOINT:
155 case DBG_REASON_WPTANDBKPT:
156 return 0x05; /* SIGTRAP */
157 case DBG_REASON_SINGLESTEP:
158 return 0x05; /* SIGTRAP */
159 case DBG_REASON_EXC_CATCH:
161 case DBG_REASON_NOTHALTED:
162 return 0x0; /* no signal... shouldn't happen */
164 LOG_USER("undefined debug reason %d - target needs reset",
165 target->debug_reason);
170 static int check_pending(struct connection *connection,
171 int timeout_s, int *got_data)
173 /* a non-blocking socket will block if there is 0 bytes available on the socket,
174 * but return with as many bytes as are available immediately
178 struct gdb_connection *gdb_con = connection->priv;
184 if (gdb_con->buf_cnt > 0) {
190 FD_SET(connection->fd, &read_fds);
192 tv.tv_sec = timeout_s;
194 if (socket_select(connection->fd + 1, &read_fds, NULL, NULL, &tv) == 0) {
195 /* This can typically be because a "monitor" command took too long
196 * before printing any progress messages
199 return ERROR_GDB_TIMEOUT;
203 *got_data = FD_ISSET(connection->fd, &read_fds) != 0;
207 static int gdb_get_char_inner(struct connection *connection, int *next_char)
209 struct gdb_connection *gdb_con = connection->priv;
210 int retval = ERROR_OK;
212 #ifdef _DEBUG_GDB_IO_
216 if (connection->service->type != CONNECTION_TCP)
217 gdb_con->buf_cnt = read(connection->fd, gdb_con->buffer, GDB_BUFFER_SIZE);
219 retval = check_pending(connection, 1, NULL);
220 if (retval != ERROR_OK)
222 gdb_con->buf_cnt = read_socket(connection->fd,
227 if (gdb_con->buf_cnt > 0)
229 if (gdb_con->buf_cnt == 0) {
230 LOG_DEBUG("GDB connection closed by the remote client");
231 gdb_con->closed = true;
232 return ERROR_SERVER_REMOTE_CLOSED;
236 errno = WSAGetLastError();
242 case WSAECONNABORTED:
243 gdb_con->closed = true;
244 return ERROR_SERVER_REMOTE_CLOSED;
246 gdb_con->closed = true;
247 return ERROR_SERVER_REMOTE_CLOSED;
249 LOG_ERROR("read: %d", errno);
258 gdb_con->closed = true;
259 return ERROR_SERVER_REMOTE_CLOSED;
261 gdb_con->closed = true;
262 return ERROR_SERVER_REMOTE_CLOSED;
264 LOG_ERROR("read: %s", strerror(errno));
265 gdb_con->closed = true;
266 return ERROR_SERVER_REMOTE_CLOSED;
271 #ifdef _DEBUG_GDB_IO_
272 debug_buffer = strndup(gdb_con->buffer, gdb_con->buf_cnt);
273 LOG_DEBUG("received '%s'", debug_buffer);
277 gdb_con->buf_p = gdb_con->buffer;
279 *next_char = *(gdb_con->buf_p++);
280 if (gdb_con->buf_cnt > 0)
281 connection->input_pending = true;
283 connection->input_pending = false;
284 #ifdef _DEBUG_GDB_IO_
285 LOG_DEBUG("returned char '%c' (0x%2.2x)", *next_char, *next_char);
292 * The cool thing about this fn is that it allows buf_p and buf_cnt to be
293 * held in registers in the inner loop.
295 * For small caches and embedded systems this is important!
297 static inline int gdb_get_char_fast(struct connection *connection,
298 int *next_char, char **buf_p, int *buf_cnt)
300 int retval = ERROR_OK;
302 if ((*buf_cnt)-- > 0) {
303 *next_char = **buf_p;
306 connection->input_pending = true;
308 connection->input_pending = false;
310 #ifdef _DEBUG_GDB_IO_
311 LOG_DEBUG("returned char '%c' (0x%2.2x)", *next_char, *next_char);
317 struct gdb_connection *gdb_con = connection->priv;
318 gdb_con->buf_p = *buf_p;
319 gdb_con->buf_cnt = *buf_cnt;
320 retval = gdb_get_char_inner(connection, next_char);
321 *buf_p = gdb_con->buf_p;
322 *buf_cnt = gdb_con->buf_cnt;
327 static int gdb_get_char(struct connection *connection, int *next_char)
329 struct gdb_connection *gdb_con = connection->priv;
330 return gdb_get_char_fast(connection, next_char, &gdb_con->buf_p, &gdb_con->buf_cnt);
333 static int gdb_putback_char(struct connection *connection, int last_char)
335 struct gdb_connection *gdb_con = connection->priv;
337 if (gdb_con->buf_p > gdb_con->buffer) {
338 *(--gdb_con->buf_p) = last_char;
341 LOG_ERROR("BUG: couldn't put character back");
346 /* The only way we can detect that the socket is closed is the first time
347 * we write to it, we will fail. Subsequent write operations will
348 * succeed. Shudder! */
349 static int gdb_write(struct connection *connection, void *data, int len)
351 struct gdb_connection *gdb_con = connection->priv;
352 if (gdb_con->closed) {
353 LOG_DEBUG("GDB socket marked as closed, cannot write to it.");
354 return ERROR_SERVER_REMOTE_CLOSED;
357 if (connection_write(connection, data, len) == len)
360 LOG_WARNING("Error writing to GDB socket. Dropping the connection.");
361 gdb_con->closed = true;
362 return ERROR_SERVER_REMOTE_CLOSED;
365 static void gdb_log_incoming_packet(char *packet)
367 if (!LOG_LEVEL_IS(LOG_LVL_DEBUG))
370 /* Avoid dumping non-printable characters to the terminal */
371 const unsigned packet_len = strlen(packet);
372 const char *nonprint = find_nonprint_char(packet, packet_len);
374 /* Does packet at least have a prefix that is printable?
375 * Look within the first 50 chars of the packet. */
376 const char *colon = memchr(packet, ':', MIN(50, packet_len));
377 const bool packet_has_prefix = (colon);
378 const bool packet_prefix_printable = (packet_has_prefix && nonprint > colon);
380 if (packet_prefix_printable) {
381 const unsigned int prefix_len = colon - packet + 1; /* + 1 to include the ':' */
382 const unsigned int payload_len = packet_len - prefix_len;
383 LOG_DEBUG("received packet: %.*s<binary-data-%u-bytes>", prefix_len, packet, payload_len);
385 LOG_DEBUG("received packet: <binary-data-%u-bytes>", packet_len);
388 /* All chars printable, dump the packet as is */
389 LOG_DEBUG("received packet: %s", packet);
393 static void gdb_log_outgoing_packet(char *packet_buf, unsigned int packet_len, unsigned char checksum)
395 if (!LOG_LEVEL_IS(LOG_LVL_DEBUG))
398 if (find_nonprint_char(packet_buf, packet_len))
399 LOG_DEBUG("sending packet: $<binary-data-%u-bytes>#%2.2x", packet_len, checksum);
401 LOG_DEBUG("sending packet: $%.*s#%2.2x'", packet_len, packet_buf, checksum);
404 static int gdb_put_packet_inner(struct connection *connection,
405 char *buffer, int len)
408 unsigned char my_checksum = 0;
411 struct gdb_connection *gdb_con = connection->priv;
413 for (i = 0; i < len; i++)
414 my_checksum += buffer[i];
416 #ifdef _DEBUG_GDB_IO_
418 * At this point we should have nothing in the input queue from GDB,
419 * however sometimes '-' is sent even though we've already received
420 * an ACK (+) for everything we've sent off.
424 retval = check_pending(connection, 0, &gotdata);
425 if (retval != ERROR_OK)
429 retval = gdb_get_char(connection, &reply);
430 if (retval != ERROR_OK)
433 /* fix a problem with some IAR tools */
434 gdb_putback_char(connection, reply);
435 LOG_DEBUG("Unexpected start of new packet");
439 LOG_WARNING("Discard unexpected char %c", reply);
444 gdb_log_outgoing_packet(buffer, len, my_checksum);
446 char local_buffer[1024];
447 local_buffer[0] = '$';
448 if ((size_t)len + 4 <= sizeof(local_buffer)) {
449 /* performance gain on smaller packets by only a single call to gdb_write() */
450 memcpy(local_buffer + 1, buffer, len++);
451 len += snprintf(local_buffer + len, sizeof(local_buffer) - len, "#%02x", my_checksum);
452 retval = gdb_write(connection, local_buffer, len);
453 if (retval != ERROR_OK)
456 /* larger packets are transmitted directly from caller supplied buffer
457 * by several calls to gdb_write() to avoid dynamic allocation */
458 snprintf(local_buffer + 1, sizeof(local_buffer) - 1, "#%02x", my_checksum);
459 retval = gdb_write(connection, local_buffer, 1);
460 if (retval != ERROR_OK)
462 retval = gdb_write(connection, buffer, len);
463 if (retval != ERROR_OK)
465 retval = gdb_write(connection, local_buffer + 1, 3);
466 if (retval != ERROR_OK)
470 if (gdb_con->noack_mode)
473 retval = gdb_get_char(connection, &reply);
474 if (retval != ERROR_OK)
479 else if (reply == '-') {
480 /* Stop sending output packets for now */
481 log_remove_callback(gdb_log_callback, connection);
482 LOG_WARNING("negative reply, retrying");
483 } else if (reply == 0x3) {
484 gdb_con->ctrl_c = true;
485 retval = gdb_get_char(connection, &reply);
486 if (retval != ERROR_OK)
490 else if (reply == '-') {
491 /* Stop sending output packets for now */
492 log_remove_callback(gdb_log_callback, connection);
493 LOG_WARNING("negative reply, retrying");
494 } else if (reply == '$') {
495 LOG_ERROR("GDB missing ack(1) - assumed good");
496 gdb_putback_char(connection, reply);
499 LOG_ERROR("unknown character(1) 0x%2.2x in reply, dropping connection", reply);
500 gdb_con->closed = true;
501 return ERROR_SERVER_REMOTE_CLOSED;
503 } else if (reply == '$') {
504 LOG_ERROR("GDB missing ack(2) - assumed good");
505 gdb_putback_char(connection, reply);
508 LOG_ERROR("unknown character(2) 0x%2.2x in reply, dropping connection",
510 gdb_con->closed = true;
511 return ERROR_SERVER_REMOTE_CLOSED;
515 return ERROR_SERVER_REMOTE_CLOSED;
520 int gdb_put_packet(struct connection *connection, char *buffer, int len)
522 struct gdb_connection *gdb_con = connection->priv;
523 gdb_con->busy = true;
524 int retval = gdb_put_packet_inner(connection, buffer, len);
525 gdb_con->busy = false;
527 /* we sent some data, reset timer for keep alive messages */
533 static inline int fetch_packet(struct connection *connection,
534 int *checksum_ok, int noack, int *len, char *buffer)
536 unsigned char my_checksum = 0;
539 int retval = ERROR_OK;
541 struct gdb_connection *gdb_con = connection->priv;
546 /* move this over into local variables to use registers and give the
547 * more freedom to optimize */
548 char *buf_p = gdb_con->buf_p;
549 int buf_cnt = gdb_con->buf_cnt;
552 /* The common case is that we have an entire packet with no escape chars.
553 * We need to leave at least 2 bytes in the buffer to have
554 * gdb_get_char() update various bits and bobs correctly.
556 if ((buf_cnt > 2) && ((buf_cnt + count) < *len)) {
557 /* The compiler will struggle a bit with constant propagation and
558 * aliasing, so we help it by showing that these values do not
559 * change inside the loop
563 int run = buf_cnt - 2;
569 if (character == '#') {
570 /* Danger! character can be '#' when esc is
571 * used so we need an explicit boolean for done here. */
576 if (character == '}') {
577 /* data transmitted in binary mode (X packet)
578 * uses 0x7d as escape character */
579 my_checksum += character & 0xff;
582 my_checksum += character & 0xff;
583 buffer[count++] = (character ^ 0x20) & 0xff;
585 my_checksum += character & 0xff;
586 buffer[count++] = character & 0xff;
595 LOG_ERROR("packet buffer too small");
596 retval = ERROR_GDB_BUFFER_TOO_SMALL;
600 retval = gdb_get_char_fast(connection, &character, &buf_p, &buf_cnt);
601 if (retval != ERROR_OK)
604 if (character == '#')
607 if (character == '}') {
608 /* data transmitted in binary mode (X packet)
609 * uses 0x7d as escape character */
610 my_checksum += character & 0xff;
612 retval = gdb_get_char_fast(connection, &character, &buf_p, &buf_cnt);
613 if (retval != ERROR_OK)
616 my_checksum += character & 0xff;
617 buffer[count++] = (character ^ 0x20) & 0xff;
619 my_checksum += character & 0xff;
620 buffer[count++] = character & 0xff;
624 gdb_con->buf_p = buf_p;
625 gdb_con->buf_cnt = buf_cnt;
627 if (retval != ERROR_OK)
632 retval = gdb_get_char(connection, &character);
633 if (retval != ERROR_OK)
635 checksum[0] = character;
636 retval = gdb_get_char(connection, &character);
637 if (retval != ERROR_OK)
639 checksum[1] = character;
643 *checksum_ok = (my_checksum == strtoul(checksum, NULL, 16));
648 static int gdb_get_packet_inner(struct connection *connection,
649 char *buffer, int *len)
653 struct gdb_connection *gdb_con = connection->priv;
657 retval = gdb_get_char(connection, &character);
658 if (retval != ERROR_OK)
661 #ifdef _DEBUG_GDB_IO_
662 LOG_DEBUG("character: '%c'", character);
669 /* According to the GDB documentation
670 * (https://sourceware.org/gdb/onlinedocs/gdb/Packet-Acknowledgment.html):
671 * "gdb sends a final `+` acknowledgment of the stub's `OK`
672 * response, which can be safely ignored by the stub."
673 * However OpenOCD server already is in noack mode at this
674 * point and instead of ignoring this it was emitting a
675 * warning. This code makes server ignore the first ACK
676 * that will be received after going into noack mode,
677 * warning only about subsequent ACK's. */
678 if (gdb_con->noack_mode > 1) {
679 LOG_WARNING("acknowledgment received, but no packet pending");
680 } else if (gdb_con->noack_mode) {
681 LOG_DEBUG("Received first acknowledgment after entering noack mode. Ignoring it.");
682 gdb_con->noack_mode = 2;
686 LOG_WARNING("negative acknowledgment, but no packet pending");
689 gdb_con->ctrl_c = true;
693 LOG_WARNING("ignoring character 0x%x", character);
696 } while (character != '$');
699 /* explicit code expansion here to get faster inlined code in -O3 by not
700 * calculating checksum */
701 if (gdb_con->noack_mode) {
702 retval = fetch_packet(connection, &checksum_ok, 1, len, buffer);
703 if (retval != ERROR_OK)
706 retval = fetch_packet(connection, &checksum_ok, 0, len, buffer);
707 if (retval != ERROR_OK)
711 if (gdb_con->noack_mode) {
712 /* checksum is not checked in noack mode */
716 retval = gdb_write(connection, "+", 1);
717 if (retval != ERROR_OK)
723 return ERROR_SERVER_REMOTE_CLOSED;
728 static int gdb_get_packet(struct connection *connection, char *buffer, int *len)
730 struct gdb_connection *gdb_con = connection->priv;
731 gdb_con->busy = true;
732 int retval = gdb_get_packet_inner(connection, buffer, len);
733 gdb_con->busy = false;
737 static int gdb_output_con(struct connection *connection, const char *line)
742 bin_size = strlen(line);
744 hex_buffer = malloc(bin_size * 2 + 2);
746 return ERROR_GDB_BUFFER_TOO_SMALL;
749 size_t pkt_len = hexify(hex_buffer + 1, (const uint8_t *)line, bin_size,
751 int retval = gdb_put_packet(connection, hex_buffer, pkt_len + 1);
757 static int gdb_output(struct command_context *context, const char *line)
759 /* this will be dumped to the log and also sent as an O packet if possible */
760 LOG_USER_N("%s", line);
764 static void gdb_signal_reply(struct target *target, struct connection *connection)
766 struct gdb_connection *gdb_connection = connection->priv;
768 char stop_reason[32];
769 char current_thread[25];
773 rtos_update_threads(target);
775 if (target->debug_reason == DBG_REASON_EXIT) {
776 sig_reply_len = snprintf(sig_reply, sizeof(sig_reply), "W00");
780 target->rtos->current_threadid = target->rtos->current_thread;
781 target->rtos->gdb_target_for_threadid(connection, target->rtos->current_threadid, &ct);
786 if (gdb_connection->ctrl_c) {
789 signal_var = gdb_last_signal(ct);
791 stop_reason[0] = '\0';
792 if (ct->debug_reason == DBG_REASON_WATCHPOINT) {
793 enum watchpoint_rw hit_wp_type;
794 target_addr_t hit_wp_address;
796 if (watchpoint_hit(ct, &hit_wp_type, &hit_wp_address) == ERROR_OK) {
798 switch (hit_wp_type) {
800 snprintf(stop_reason, sizeof(stop_reason),
801 "watch:%08" TARGET_PRIxADDR ";", hit_wp_address);
804 snprintf(stop_reason, sizeof(stop_reason),
805 "rwatch:%08" TARGET_PRIxADDR ";", hit_wp_address);
808 snprintf(stop_reason, sizeof(stop_reason),
809 "awatch:%08" TARGET_PRIxADDR ";", hit_wp_address);
817 current_thread[0] = '\0';
819 snprintf(current_thread, sizeof(current_thread), "thread:%" PRIx64 ";",
820 target->rtos->current_thread);
822 sig_reply_len = snprintf(sig_reply, sizeof(sig_reply), "T%2.2x%s%s",
823 signal_var, stop_reason, current_thread);
825 gdb_connection->ctrl_c = false;
828 gdb_put_packet(connection, sig_reply, sig_reply_len);
829 gdb_connection->frontend_state = TARGET_HALTED;
832 static void gdb_fileio_reply(struct target *target, struct connection *connection)
834 struct gdb_connection *gdb_connection = connection->priv;
835 char fileio_command[256];
837 bool program_exited = false;
839 if (strcmp(target->fileio_info->identifier, "open") == 0)
840 sprintf(fileio_command, "F%s,%" PRIx64 "/%" PRIx64 ",%" PRIx64 ",%" PRIx64, target->fileio_info->identifier,
841 target->fileio_info->param_1,
842 target->fileio_info->param_2 + 1, /* len + trailing zero */
843 target->fileio_info->param_3,
844 target->fileio_info->param_4);
845 else if (strcmp(target->fileio_info->identifier, "close") == 0)
846 sprintf(fileio_command, "F%s,%" PRIx64, target->fileio_info->identifier,
847 target->fileio_info->param_1);
848 else if (strcmp(target->fileio_info->identifier, "read") == 0)
849 sprintf(fileio_command, "F%s,%" PRIx64 ",%" PRIx64 ",%" PRIx64, target->fileio_info->identifier,
850 target->fileio_info->param_1,
851 target->fileio_info->param_2,
852 target->fileio_info->param_3);
853 else if (strcmp(target->fileio_info->identifier, "write") == 0)
854 sprintf(fileio_command, "F%s,%" PRIx64 ",%" PRIx64 ",%" PRIx64, target->fileio_info->identifier,
855 target->fileio_info->param_1,
856 target->fileio_info->param_2,
857 target->fileio_info->param_3);
858 else if (strcmp(target->fileio_info->identifier, "lseek") == 0)
859 sprintf(fileio_command, "F%s,%" PRIx64 ",%" PRIx64 ",%" PRIx64, target->fileio_info->identifier,
860 target->fileio_info->param_1,
861 target->fileio_info->param_2,
862 target->fileio_info->param_3);
863 else if (strcmp(target->fileio_info->identifier, "rename") == 0)
864 sprintf(fileio_command, "F%s,%" PRIx64 "/%" PRIx64 ",%" PRIx64 "/%" PRIx64, target->fileio_info->identifier,
865 target->fileio_info->param_1,
866 target->fileio_info->param_2 + 1, /* len + trailing zero */
867 target->fileio_info->param_3,
868 target->fileio_info->param_4 + 1); /* len + trailing zero */
869 else if (strcmp(target->fileio_info->identifier, "unlink") == 0)
870 sprintf(fileio_command, "F%s,%" PRIx64 "/%" PRIx64, target->fileio_info->identifier,
871 target->fileio_info->param_1,
872 target->fileio_info->param_2 + 1); /* len + trailing zero */
873 else if (strcmp(target->fileio_info->identifier, "stat") == 0)
874 sprintf(fileio_command, "F%s,%" PRIx64 "/%" PRIx64 ",%" PRIx64, target->fileio_info->identifier,
875 target->fileio_info->param_1,
876 target->fileio_info->param_2,
877 target->fileio_info->param_3);
878 else if (strcmp(target->fileio_info->identifier, "fstat") == 0)
879 sprintf(fileio_command, "F%s,%" PRIx64 ",%" PRIx64, target->fileio_info->identifier,
880 target->fileio_info->param_1,
881 target->fileio_info->param_2);
882 else if (strcmp(target->fileio_info->identifier, "gettimeofday") == 0)
883 sprintf(fileio_command, "F%s,%" PRIx64 ",%" PRIx64, target->fileio_info->identifier,
884 target->fileio_info->param_1,
885 target->fileio_info->param_2);
886 else if (strcmp(target->fileio_info->identifier, "isatty") == 0)
887 sprintf(fileio_command, "F%s,%" PRIx64, target->fileio_info->identifier,
888 target->fileio_info->param_1);
889 else if (strcmp(target->fileio_info->identifier, "system") == 0)
890 sprintf(fileio_command, "F%s,%" PRIx64 "/%" PRIx64, target->fileio_info->identifier,
891 target->fileio_info->param_1,
892 target->fileio_info->param_2 + 1); /* len + trailing zero */
893 else if (strcmp(target->fileio_info->identifier, "exit") == 0) {
894 /* If target hits exit syscall, report to GDB the program is terminated.
895 * In addition, let target run its own exit syscall handler. */
896 program_exited = true;
897 sprintf(fileio_command, "W%02" PRIx64, target->fileio_info->param_1);
899 LOG_DEBUG("Unknown syscall: %s", target->fileio_info->identifier);
901 /* encounter unknown syscall, continue */
902 gdb_connection->frontend_state = TARGET_RUNNING;
903 target_resume(target, 1, 0x0, 0, 0);
907 command_len = strlen(fileio_command);
908 gdb_put_packet(connection, fileio_command, command_len);
910 if (program_exited) {
911 /* Use target_resume() to let target run its own exit syscall handler. */
912 gdb_connection->frontend_state = TARGET_RUNNING;
913 target_resume(target, 1, 0x0, 0, 0);
915 gdb_connection->frontend_state = TARGET_HALTED;
916 rtos_update_threads(target);
920 static void gdb_frontend_halted(struct target *target, struct connection *connection)
922 struct gdb_connection *gdb_connection = connection->priv;
924 /* In the GDB protocol when we are stepping or continuing execution,
925 * we have a lingering reply. Upon receiving a halted event
926 * when we have that lingering packet, we reply to the original
927 * step or continue packet.
929 * Executing monitor commands can bring the target in and
930 * out of the running state so we'll see lots of TARGET_EVENT_XXX
931 * that are to be ignored.
933 if (gdb_connection->frontend_state == TARGET_RUNNING) {
934 /* stop forwarding log packets! */
935 log_remove_callback(gdb_log_callback, connection);
937 /* check fileio first */
938 if (target_get_gdb_fileio_info(target, target->fileio_info) == ERROR_OK)
939 gdb_fileio_reply(target, connection);
941 gdb_signal_reply(target, connection);
945 static int gdb_target_callback_event_handler(struct target *target,
946 enum target_event event, void *priv)
948 struct connection *connection = priv;
949 struct gdb_service *gdb_service = connection->service->priv;
951 if (gdb_service->target != target)
955 case TARGET_EVENT_GDB_HALT:
956 gdb_frontend_halted(target, connection);
958 case TARGET_EVENT_HALTED:
959 target_call_event_callbacks(target, TARGET_EVENT_GDB_END);
968 static int gdb_new_connection(struct connection *connection)
970 struct gdb_connection *gdb_connection = malloc(sizeof(struct gdb_connection));
971 struct target *target;
975 target = get_target_from_connection(connection);
976 connection->priv = gdb_connection;
977 connection->cmd_ctx->current_target = target;
979 /* initialize gdb connection information */
980 gdb_connection->buf_p = gdb_connection->buffer;
981 gdb_connection->buf_cnt = 0;
982 gdb_connection->ctrl_c = false;
983 gdb_connection->frontend_state = TARGET_HALTED;
984 gdb_connection->vflash_image = NULL;
985 gdb_connection->closed = false;
986 gdb_connection->busy = false;
987 gdb_connection->noack_mode = 0;
988 gdb_connection->sync = false;
989 gdb_connection->mem_write_error = false;
990 gdb_connection->attached = true;
991 gdb_connection->extended_protocol = false;
992 gdb_connection->target_desc.tdesc = NULL;
993 gdb_connection->target_desc.tdesc_length = 0;
994 gdb_connection->thread_list = NULL;
996 /* send ACK to GDB for debug request */
997 gdb_write(connection, "+", 1);
999 /* output goes through gdb connection */
1000 command_set_output_handler(connection->cmd_ctx, gdb_output, connection);
1002 /* we must remove all breakpoints registered to the target as a previous
1003 * GDB session could leave dangling breakpoints if e.g. communication
1006 breakpoint_clear_target(target);
1007 watchpoint_clear_target(target);
1009 /* Since version 3.95 (gdb-19990504), with the exclusion of 6.5~6.8, GDB
1010 * sends an ACK at connection with the following comment in its source code:
1011 * "Ack any packet which the remote side has already sent."
1012 * LLDB does the same since the first gdb-remote implementation.
1013 * Remove the initial ACK from the incoming buffer.
1015 retval = gdb_get_char(connection, &initial_ack);
1016 if (retval != ERROR_OK)
1019 if (initial_ack != '+')
1020 gdb_putback_char(connection, initial_ack);
1022 target_call_event_callbacks(target, TARGET_EVENT_GDB_ATTACH);
1025 /* clean previous rtos session if supported*/
1026 if (target->rtos->type->clean)
1027 target->rtos->type->clean(target);
1029 /* update threads */
1030 rtos_update_threads(target);
1033 if (gdb_use_memory_map) {
1034 /* Connect must fail if the memory map can't be set up correctly.
1036 * This will cause an auto_probe to be invoked, which is either
1037 * a no-op or it will fail when the target isn't ready(e.g. not halted).
1039 for (unsigned int i = 0; i < flash_get_bank_count(); i++) {
1040 struct flash_bank *p;
1041 p = get_flash_bank_by_num_noprobe(i);
1042 if (p->target != target)
1044 retval = get_flash_bank_by_num(i, &p);
1045 if (retval != ERROR_OK) {
1046 LOG_ERROR("Connect failed. Consider setting up a gdb-attach event for the target "
1047 "to prepare target for GDB connect, or use 'gdb_memory_map disable'.");
1053 gdb_actual_connections++;
1054 log_printf_lf(all_targets->next ? LOG_LVL_INFO : LOG_LVL_DEBUG,
1055 __FILE__, __LINE__, __func__,
1056 "New GDB Connection: %d, Target %s, state: %s",
1057 gdb_actual_connections,
1058 target_name(target),
1059 target_state_name(target));
1061 if (!target_was_examined(target)) {
1062 LOG_ERROR("Target %s not examined yet, refuse gdb connection %d!",
1063 target_name(target), gdb_actual_connections);
1064 gdb_actual_connections--;
1065 return ERROR_TARGET_NOT_EXAMINED;
1068 if (target->state != TARGET_HALTED)
1069 LOG_WARNING("GDB connection %d on target %s not halted",
1070 gdb_actual_connections, target_name(target));
1072 /* DANGER! If we fail subsequently, we must remove this handler,
1073 * otherwise we occasionally see crashes as the timer can invoke the
1076 * register callback to be informed about target events */
1077 target_register_event_callback(gdb_target_callback_event_handler, connection);
1082 static int gdb_connection_closed(struct connection *connection)
1084 struct target *target;
1085 struct gdb_connection *gdb_connection = connection->priv;
1087 target = get_target_from_connection(connection);
1089 /* we're done forwarding messages. Tear down callback before
1090 * cleaning up connection.
1092 log_remove_callback(gdb_log_callback, connection);
1094 gdb_actual_connections--;
1095 LOG_DEBUG("GDB Close, Target: %s, state: %s, gdb_actual_connections=%d",
1096 target_name(target),
1097 target_state_name(target),
1098 gdb_actual_connections);
1100 /* see if an image built with vFlash commands is left */
1101 if (gdb_connection->vflash_image) {
1102 image_close(gdb_connection->vflash_image);
1103 free(gdb_connection->vflash_image);
1104 gdb_connection->vflash_image = NULL;
1107 /* if this connection registered a debug-message receiver delete it */
1108 delete_debug_msg_receiver(connection->cmd_ctx, target);
1110 free(connection->priv);
1111 connection->priv = NULL;
1113 target_unregister_event_callback(gdb_target_callback_event_handler, connection);
1115 target_call_event_callbacks(target, TARGET_EVENT_GDB_END);
1117 target_call_event_callbacks(target, TARGET_EVENT_GDB_DETACH);
1122 static void gdb_send_error(struct connection *connection, uint8_t the_error)
1125 snprintf(err, 4, "E%2.2X", the_error);
1126 gdb_put_packet(connection, err, 3);
1129 static int gdb_last_signal_packet(struct connection *connection,
1130 char const *packet, int packet_size)
1132 struct target *target = get_target_from_connection(connection);
1133 struct gdb_connection *gdb_con = connection->priv;
1137 if (!gdb_con->attached) {
1138 /* if we are here we have received a kill packet
1139 * reply W stop reply otherwise gdb gets very unhappy */
1140 gdb_put_packet(connection, "W00", 3);
1144 signal_var = gdb_last_signal(target);
1146 snprintf(sig_reply, 4, "S%2.2x", signal_var);
1147 gdb_put_packet(connection, sig_reply, 3);
1152 static inline int gdb_reg_pos(struct target *target, int pos, int len)
1154 if (target->endianness == TARGET_LITTLE_ENDIAN)
1157 return len - 1 - pos;
1160 /* Convert register to string of bytes. NB! The # of bits in the
1161 * register might be non-divisible by 8(a byte), in which
1162 * case an entire byte is shown.
1164 * NB! the format on the wire is the target endianness
1166 * The format of reg->value is little endian
1169 static void gdb_str_to_target(struct target *target,
1170 char *tstr, struct reg *reg)
1177 buf_len = DIV_ROUND_UP(reg->size, 8);
1179 for (i = 0; i < buf_len; i++) {
1180 int j = gdb_reg_pos(target, i, buf_len);
1181 tstr += sprintf(tstr, "%02x", buf[j]);
1185 /* copy over in register buffer */
1186 static void gdb_target_to_reg(struct target *target,
1187 char const *tstr, int str_len, uint8_t *bin)
1190 LOG_ERROR("BUG: gdb value with uneven number of characters encountered");
1195 for (i = 0; i < str_len; i += 2) {
1197 if (sscanf(tstr + i, "%02x", &t) != 1) {
1198 LOG_ERROR("BUG: unable to convert register value");
1202 int j = gdb_reg_pos(target, i/2, str_len/2);
1207 static int gdb_get_registers_packet(struct connection *connection,
1208 char const *packet, int packet_size)
1210 struct target *target = get_target_from_connection(connection);
1211 struct reg **reg_list;
1214 int reg_packet_size = 0;
1219 #ifdef _DEBUG_GDB_IO_
1223 if ((target->rtos) && (rtos_get_gdb_reg_list(connection) == ERROR_OK))
1226 retval = target_get_gdb_reg_list(target, ®_list, ®_list_size,
1228 if (retval != ERROR_OK)
1229 return gdb_error(connection, retval);
1231 for (i = 0; i < reg_list_size; i++) {
1232 if (!reg_list[i] || reg_list[i]->exist == false || reg_list[i]->hidden)
1234 reg_packet_size += DIV_ROUND_UP(reg_list[i]->size, 8) * 2;
1237 assert(reg_packet_size > 0);
1239 reg_packet = malloc(reg_packet_size + 1); /* plus one for string termination null */
1243 reg_packet_p = reg_packet;
1245 for (i = 0; i < reg_list_size; i++) {
1246 if (!reg_list[i] || reg_list[i]->exist == false || reg_list[i]->hidden)
1248 if (!reg_list[i]->valid) {
1249 retval = reg_list[i]->type->get(reg_list[i]);
1250 if (retval != ERROR_OK && gdb_report_register_access_error) {
1251 LOG_DEBUG("Couldn't get register %s.", reg_list[i]->name);
1254 return gdb_error(connection, retval);
1257 gdb_str_to_target(target, reg_packet_p, reg_list[i]);
1258 reg_packet_p += DIV_ROUND_UP(reg_list[i]->size, 8) * 2;
1261 #ifdef _DEBUG_GDB_IO_
1263 char *reg_packet_p_debug;
1264 reg_packet_p_debug = strndup(reg_packet, reg_packet_size);
1265 LOG_DEBUG("reg_packet: %s", reg_packet_p_debug);
1266 free(reg_packet_p_debug);
1270 gdb_put_packet(connection, reg_packet, reg_packet_size);
1278 static int gdb_set_registers_packet(struct connection *connection,
1279 char const *packet, int packet_size)
1281 struct target *target = get_target_from_connection(connection);
1283 struct reg **reg_list;
1286 char const *packet_p;
1288 #ifdef _DEBUG_GDB_IO_
1292 /* skip command character */
1296 if (packet_size % 2) {
1297 LOG_WARNING("GDB set_registers packet with uneven characters received, dropping connection");
1298 return ERROR_SERVER_REMOTE_CLOSED;
1301 retval = target_get_gdb_reg_list(target, ®_list, ®_list_size,
1303 if (retval != ERROR_OK)
1304 return gdb_error(connection, retval);
1307 for (i = 0; i < reg_list_size; i++) {
1309 int chars = (DIV_ROUND_UP(reg_list[i]->size, 8) * 2);
1311 if (packet_p + chars > packet + packet_size)
1312 LOG_ERROR("BUG: register packet is too small for registers");
1314 bin_buf = malloc(DIV_ROUND_UP(reg_list[i]->size, 8));
1315 gdb_target_to_reg(target, packet_p, chars, bin_buf);
1317 retval = reg_list[i]->type->set(reg_list[i], bin_buf);
1318 if (retval != ERROR_OK && gdb_report_register_access_error) {
1319 LOG_DEBUG("Couldn't set register %s.", reg_list[i]->name);
1322 return gdb_error(connection, retval);
1325 /* advance packet pointer */
1331 /* free struct reg *reg_list[] array allocated by get_gdb_reg_list */
1334 gdb_put_packet(connection, "OK", 2);
1339 static int gdb_get_register_packet(struct connection *connection,
1340 char const *packet, int packet_size)
1342 struct target *target = get_target_from_connection(connection);
1344 int reg_num = strtoul(packet + 1, NULL, 16);
1345 struct reg **reg_list;
1349 #ifdef _DEBUG_GDB_IO_
1353 if ((target->rtos) && (rtos_get_gdb_reg(connection, reg_num) == ERROR_OK))
1356 retval = target_get_gdb_reg_list_noread(target, ®_list, ®_list_size,
1358 if (retval != ERROR_OK)
1359 return gdb_error(connection, retval);
1361 if (reg_list_size <= reg_num) {
1362 LOG_ERROR("gdb requested a non-existing register (reg_num=%d)", reg_num);
1363 return ERROR_SERVER_REMOTE_CLOSED;
1366 if (!reg_list[reg_num]->valid) {
1367 retval = reg_list[reg_num]->type->get(reg_list[reg_num]);
1368 if (retval != ERROR_OK && gdb_report_register_access_error) {
1369 LOG_DEBUG("Couldn't get register %s.", reg_list[reg_num]->name);
1371 return gdb_error(connection, retval);
1375 reg_packet = calloc(DIV_ROUND_UP(reg_list[reg_num]->size, 8) * 2 + 1, 1); /* plus one for string termination null */
1377 gdb_str_to_target(target, reg_packet, reg_list[reg_num]);
1379 gdb_put_packet(connection, reg_packet, DIV_ROUND_UP(reg_list[reg_num]->size, 8) * 2);
1387 static int gdb_set_register_packet(struct connection *connection,
1388 char const *packet, int packet_size)
1390 struct target *target = get_target_from_connection(connection);
1392 int reg_num = strtoul(packet + 1, &separator, 16);
1393 struct reg **reg_list;
1397 #ifdef _DEBUG_GDB_IO_
1401 if (*separator != '=') {
1402 LOG_ERROR("GDB 'set register packet', but no '=' following the register number");
1403 return ERROR_SERVER_REMOTE_CLOSED;
1405 size_t chars = strlen(separator + 1);
1406 uint8_t *bin_buf = malloc(chars / 2);
1407 gdb_target_to_reg(target, separator + 1, chars, bin_buf);
1409 if ((target->rtos) &&
1410 (rtos_set_reg(connection, reg_num, bin_buf) == ERROR_OK)) {
1412 gdb_put_packet(connection, "OK", 2);
1416 retval = target_get_gdb_reg_list_noread(target, ®_list, ®_list_size,
1418 if (retval != ERROR_OK) {
1420 return gdb_error(connection, retval);
1423 if (reg_list_size <= reg_num) {
1424 LOG_ERROR("gdb requested a non-existing register (reg_num=%d)", reg_num);
1427 return ERROR_SERVER_REMOTE_CLOSED;
1430 if (chars != (DIV_ROUND_UP(reg_list[reg_num]->size, 8) * 2)) {
1431 LOG_ERROR("gdb sent %zu bits for a %" PRIu32 "-bit register (%s)",
1432 chars * 4, reg_list[reg_num]->size, reg_list[reg_num]->name);
1435 return ERROR_SERVER_REMOTE_CLOSED;
1438 gdb_target_to_reg(target, separator + 1, chars, bin_buf);
1440 retval = reg_list[reg_num]->type->set(reg_list[reg_num], bin_buf);
1441 if (retval != ERROR_OK && gdb_report_register_access_error) {
1442 LOG_DEBUG("Couldn't set register %s.", reg_list[reg_num]->name);
1445 return gdb_error(connection, retval);
1448 gdb_put_packet(connection, "OK", 2);
1456 /* No attempt is made to translate the "retval" to
1457 * GDB speak. This has to be done at the calling
1458 * site as no mapping really exists.
1460 static int gdb_error(struct connection *connection, int retval)
1462 LOG_DEBUG("Reporting %i to GDB as generic error", retval);
1463 gdb_send_error(connection, EFAULT);
1467 /* We don't have to worry about the default 2 second timeout for GDB packets,
1468 * because GDB breaks up large memory reads into smaller reads.
1470 static int gdb_read_memory_packet(struct connection *connection,
1471 char const *packet, int packet_size)
1473 struct target *target = get_target_from_connection(connection);
1481 int retval = ERROR_OK;
1483 /* skip command character */
1486 addr = strtoull(packet, &separator, 16);
1488 if (*separator != ',') {
1489 LOG_ERROR("incomplete read memory packet received, dropping connection");
1490 return ERROR_SERVER_REMOTE_CLOSED;
1493 len = strtoul(separator + 1, NULL, 16);
1496 LOG_WARNING("invalid read memory packet received (len == 0)");
1497 gdb_put_packet(connection, "", 0);
1501 buffer = malloc(len);
1503 LOG_DEBUG("addr: 0x%16.16" PRIx64 ", len: 0x%8.8" PRIx32 "", addr, len);
1505 retval = ERROR_NOT_IMPLEMENTED;
1507 retval = rtos_read_buffer(target, addr, len, buffer);
1508 if (retval == ERROR_NOT_IMPLEMENTED)
1509 retval = target_read_buffer(target, addr, len, buffer);
1511 if ((retval != ERROR_OK) && !gdb_report_data_abort) {
1512 /* TODO : Here we have to lie and send back all zero's lest stack traces won't work.
1513 * At some point this might be fixed in GDB, in which case this code can be removed.
1515 * OpenOCD developers are acutely aware of this problem, but there is nothing
1516 * gained by involving the user in this problem that hopefully will get resolved
1519 * http://sourceware.org/cgi-bin/gnatsweb.pl? \
1520 * cmd = view%20audit-trail&database = gdb&pr = 2395
1522 * For now, the default is to fix up things to make current GDB versions work.
1523 * This can be overwritten using the gdb_report_data_abort <'enable'|'disable'> command.
1525 memset(buffer, 0, len);
1529 if (retval == ERROR_OK) {
1530 hex_buffer = malloc(len * 2 + 1);
1532 size_t pkt_len = hexify(hex_buffer, buffer, len, len * 2 + 1);
1534 gdb_put_packet(connection, hex_buffer, pkt_len);
1538 retval = gdb_error(connection, retval);
1545 static int gdb_write_memory_packet(struct connection *connection,
1546 char const *packet, int packet_size)
1548 struct target *target = get_target_from_connection(connection);
1556 /* skip command character */
1559 addr = strtoull(packet, &separator, 16);
1561 if (*separator != ',') {
1562 LOG_ERROR("incomplete write memory packet received, dropping connection");
1563 return ERROR_SERVER_REMOTE_CLOSED;
1566 len = strtoul(separator + 1, &separator, 16);
1568 if (*(separator++) != ':') {
1569 LOG_ERROR("incomplete write memory packet received, dropping connection");
1570 return ERROR_SERVER_REMOTE_CLOSED;
1573 buffer = malloc(len);
1575 LOG_DEBUG("addr: 0x%" PRIx64 ", len: 0x%8.8" PRIx32 "", addr, len);
1577 if (unhexify(buffer, separator, len) != len)
1578 LOG_ERROR("unable to decode memory packet");
1580 retval = ERROR_NOT_IMPLEMENTED;
1582 retval = rtos_write_buffer(target, addr, len, buffer);
1583 if (retval == ERROR_NOT_IMPLEMENTED)
1584 retval = target_write_buffer(target, addr, len, buffer);
1586 if (retval == ERROR_OK)
1587 gdb_put_packet(connection, "OK", 2);
1589 retval = gdb_error(connection, retval);
1596 static int gdb_write_memory_binary_packet(struct connection *connection,
1597 char const *packet, int packet_size)
1599 struct target *target = get_target_from_connection(connection);
1604 int retval = ERROR_OK;
1605 /* Packets larger than fast_limit bytes will be acknowledged instantly on
1606 * the assumption that we're in a download and it's important to go as fast
1608 uint32_t fast_limit = 8;
1610 /* skip command character */
1613 addr = strtoull(packet, &separator, 16);
1615 if (*separator != ',') {
1616 LOG_ERROR("incomplete write memory binary packet received, dropping connection");
1617 return ERROR_SERVER_REMOTE_CLOSED;
1620 len = strtoul(separator + 1, &separator, 16);
1622 if (*(separator++) != ':') {
1623 LOG_ERROR("incomplete write memory binary packet received, dropping connection");
1624 return ERROR_SERVER_REMOTE_CLOSED;
1627 struct gdb_connection *gdb_connection = connection->priv;
1629 if (gdb_connection->mem_write_error)
1630 retval = ERROR_FAIL;
1632 if (retval == ERROR_OK) {
1633 if (len >= fast_limit) {
1634 /* By replying the packet *immediately* GDB will send us a new packet
1635 * while we write the last one to the target.
1636 * We only do this for larger writes, so that users who do something like:
1637 * p *((int*)0xdeadbeef)=8675309
1638 * will get immediate feedback that that write failed.
1640 gdb_put_packet(connection, "OK", 2);
1643 retval = gdb_error(connection, retval);
1644 /* now that we have reported the memory write error, we can clear the condition */
1645 gdb_connection->mem_write_error = false;
1646 if (retval != ERROR_OK)
1651 LOG_DEBUG("addr: 0x%" PRIx64 ", len: 0x%8.8" PRIx32 "", addr, len);
1653 retval = ERROR_NOT_IMPLEMENTED;
1655 retval = rtos_write_buffer(target, addr, len, (uint8_t *)separator);
1656 if (retval == ERROR_NOT_IMPLEMENTED)
1657 retval = target_write_buffer(target, addr, len, (uint8_t *)separator);
1659 if (retval != ERROR_OK)
1660 gdb_connection->mem_write_error = true;
1663 if (len < fast_limit) {
1664 if (retval != ERROR_OK) {
1665 gdb_error(connection, retval);
1666 gdb_connection->mem_write_error = false;
1668 gdb_put_packet(connection, "OK", 2);
1675 static int gdb_step_continue_packet(struct connection *connection,
1676 char const *packet, int packet_size)
1678 struct target *target = get_target_from_connection(connection);
1680 uint64_t address = 0x0;
1681 int retval = ERROR_OK;
1685 if (packet_size > 1)
1686 address = strtoull(packet + 1, NULL, 16);
1690 gdb_running_type = packet[0];
1691 if (packet[0] == 'c') {
1692 LOG_DEBUG("continue");
1693 /* resume at current address, don't handle breakpoints, not debugging */
1694 retval = target_resume(target, current, address, 0, 0);
1695 } else if (packet[0] == 's') {
1697 /* step at current or address, don't handle breakpoints */
1698 retval = target_step(target, current, address, 0);
1703 static int gdb_breakpoint_watchpoint_packet(struct connection *connection,
1704 char const *packet, int packet_size)
1706 struct target *target = get_target_from_connection(connection);
1708 enum breakpoint_type bp_type = BKPT_SOFT /* dummy init to avoid warning */;
1709 enum watchpoint_rw wp_type = WPT_READ /* dummy init to avoid warning */;
1715 LOG_DEBUG("[%s]", target_name(target));
1717 type = strtoul(packet + 1, &separator, 16);
1719 if (type == 0) /* memory breakpoint */
1720 bp_type = BKPT_SOFT;
1721 else if (type == 1) /* hardware breakpoint */
1722 bp_type = BKPT_HARD;
1723 else if (type == 2) /* write watchpoint */
1724 wp_type = WPT_WRITE;
1725 else if (type == 3) /* read watchpoint */
1727 else if (type == 4) /* access watchpoint */
1728 wp_type = WPT_ACCESS;
1730 LOG_ERROR("invalid gdb watch/breakpoint type(%d), dropping connection", type);
1731 return ERROR_SERVER_REMOTE_CLOSED;
1734 if (gdb_breakpoint_override && ((bp_type == BKPT_SOFT) || (bp_type == BKPT_HARD)))
1735 bp_type = gdb_breakpoint_override_type;
1737 if (*separator != ',') {
1738 LOG_ERROR("incomplete breakpoint/watchpoint packet received, dropping connection");
1739 return ERROR_SERVER_REMOTE_CLOSED;
1742 address = strtoull(separator + 1, &separator, 16);
1744 if (*separator != ',') {
1745 LOG_ERROR("incomplete breakpoint/watchpoint packet received, dropping connection");
1746 return ERROR_SERVER_REMOTE_CLOSED;
1749 size = strtoul(separator + 1, &separator, 16);
1754 if (packet[0] == 'Z') {
1755 retval = breakpoint_add(target, address, size, bp_type);
1756 if (retval != ERROR_OK) {
1757 retval = gdb_error(connection, retval);
1758 if (retval != ERROR_OK)
1761 gdb_put_packet(connection, "OK", 2);
1763 breakpoint_remove(target, address);
1764 gdb_put_packet(connection, "OK", 2);
1771 if (packet[0] == 'Z') {
1772 retval = watchpoint_add(target, address, size, wp_type, 0, 0xffffffffu);
1773 if (retval != ERROR_OK) {
1774 retval = gdb_error(connection, retval);
1775 if (retval != ERROR_OK)
1778 gdb_put_packet(connection, "OK", 2);
1780 watchpoint_remove(target, address);
1781 gdb_put_packet(connection, "OK", 2);
1792 /* print out a string and allocate more space as needed,
1793 * mainly used for XML at this point
1795 static __attribute__ ((format (PRINTF_ATTRIBUTE_FORMAT, 5, 6))) void xml_printf(int *retval,
1796 char **xml, int *pos, int *size, const char *fmt, ...)
1798 if (*retval != ERROR_OK)
1803 if ((!*xml) || (!first)) {
1804 /* start by 0 to exercise all the code paths.
1805 * Need minimum 2 bytes to fit 1 char and 0 terminator. */
1807 *size = *size * 2 + 2;
1809 *xml = realloc(*xml, *size);
1812 *retval = ERROR_SERVER_REMOTE_CLOSED;
1820 ret = vsnprintf(*xml + *pos, *size - *pos, fmt, ap);
1822 if ((ret > 0) && ((ret + 1) < *size - *pos)) {
1826 /* there was just enough or not enough space, allocate more. */
1831 static int decode_xfer_read(char const *buf, char **annex, int *ofs, unsigned int *len)
1833 /* Locate the annex. */
1834 const char *annex_end = strchr(buf, ':');
1838 /* After the read marker and annex, qXfer looks like a
1839 * traditional 'm' packet. */
1841 *ofs = strtoul(annex_end + 1, &separator, 16);
1843 if (*separator != ',')
1846 *len = strtoul(separator + 1, NULL, 16);
1848 /* Extract the annex if needed */
1850 *annex = strndup(buf, annex_end - buf);
1858 static int compare_bank(const void *a, const void *b)
1860 struct flash_bank *b1, *b2;
1861 b1 = *((struct flash_bank **)a);
1862 b2 = *((struct flash_bank **)b);
1864 if (b1->base == b2->base)
1866 else if (b1->base > b2->base)
1872 static int gdb_memory_map(struct connection *connection,
1873 char const *packet, int packet_size)
1875 /* We get away with only specifying flash here. Regions that are not
1876 * specified are treated as if we provided no memory map(if not we
1877 * could detect the holes and mark them as RAM).
1878 * Normally we only execute this code once, but no big deal if we
1879 * have to regenerate it a couple of times.
1882 struct target *target = get_target_from_connection(connection);
1883 struct flash_bank *p;
1887 int retval = ERROR_OK;
1888 struct flash_bank **banks;
1892 target_addr_t ram_start = 0;
1893 unsigned int target_flash_banks = 0;
1895 /* skip command character */
1898 offset = strtoul(packet, &separator, 16);
1899 length = strtoul(separator + 1, &separator, 16);
1901 xml_printf(&retval, &xml, &pos, &size, "<memory-map>\n");
1903 /* Sort banks in ascending order. We need to report non-flash
1904 * memory as ram (or rather read/write) by default for GDB, since
1905 * it has no concept of non-cacheable read/write memory (i/o etc).
1907 banks = malloc(sizeof(struct flash_bank *)*flash_get_bank_count());
1909 for (unsigned int i = 0; i < flash_get_bank_count(); i++) {
1910 p = get_flash_bank_by_num_noprobe(i);
1911 if (p->target != target)
1913 retval = get_flash_bank_by_num(i, &p);
1914 if (retval != ERROR_OK) {
1916 gdb_error(connection, retval);
1919 banks[target_flash_banks++] = p;
1922 qsort(banks, target_flash_banks, sizeof(struct flash_bank *),
1925 for (unsigned int i = 0; i < target_flash_banks; i++) {
1926 unsigned sector_size = 0;
1927 unsigned group_len = 0;
1931 if (ram_start < p->base)
1932 xml_printf(&retval, &xml, &pos, &size,
1933 "<memory type=\"ram\" start=\"" TARGET_ADDR_FMT "\" "
1934 "length=\"" TARGET_ADDR_FMT "\"/>\n",
1935 ram_start, p->base - ram_start);
1937 /* Report adjacent groups of same-size sectors. So for
1938 * example top boot CFI flash will list an initial region
1939 * with several large sectors (maybe 128KB) and several
1940 * smaller ones at the end (maybe 32KB). STR7 will have
1941 * regions with 8KB, 32KB, and 64KB sectors; etc.
1943 for (unsigned int j = 0; j < p->num_sectors; j++) {
1945 /* Maybe start a new group of sectors. */
1946 if (sector_size == 0) {
1947 if (p->sectors[j].offset + p->sectors[j].size > p->size) {
1948 LOG_WARNING("The flash sector at offset 0x%08" PRIx32
1949 " overflows the end of %s bank.",
1950 p->sectors[j].offset, p->name);
1951 LOG_WARNING("The rest of bank will not show in gdb memory map.");
1954 target_addr_t start;
1955 start = p->base + p->sectors[j].offset;
1956 xml_printf(&retval, &xml, &pos, &size,
1957 "<memory type=\"flash\" "
1958 "start=\"" TARGET_ADDR_FMT "\" ",
1960 sector_size = p->sectors[j].size;
1961 group_len = sector_size;
1963 group_len += sector_size; /* equal to p->sectors[j].size */
1966 /* Does this finish a group of sectors?
1967 * If not, continue an already-started group.
1969 if (j < p->num_sectors - 1
1970 && p->sectors[j + 1].size == sector_size
1971 && p->sectors[j + 1].offset == p->sectors[j].offset + sector_size
1972 && p->sectors[j + 1].offset + p->sectors[j + 1].size <= p->size)
1975 xml_printf(&retval, &xml, &pos, &size,
1976 "length=\"0x%x\">\n"
1977 "<property name=\"blocksize\">"
1985 ram_start = p->base + p->size;
1989 xml_printf(&retval, &xml, &pos, &size,
1990 "<memory type=\"ram\" start=\"" TARGET_ADDR_FMT "\" "
1991 "length=\"" TARGET_ADDR_FMT "\"/>\n",
1992 ram_start, target_address_max(target) - ram_start + 1);
1993 /* ELSE a flash chip could be at the very end of the address space, in
1994 * which case ram_start will be precisely 0 */
1998 xml_printf(&retval, &xml, &pos, &size, "</memory-map>\n");
2000 if (retval != ERROR_OK) {
2002 gdb_error(connection, retval);
2006 if (offset + length > pos)
2007 length = pos - offset;
2009 char *t = malloc(length + 1);
2011 memcpy(t + 1, xml + offset, length);
2012 gdb_put_packet(connection, t, length + 1);
2019 static const char *gdb_get_reg_type_name(enum reg_type type)
2028 case REG_TYPE_INT16:
2030 case REG_TYPE_INT32:
2032 case REG_TYPE_INT64:
2034 case REG_TYPE_INT128:
2038 case REG_TYPE_UINT8:
2040 case REG_TYPE_UINT16:
2042 case REG_TYPE_UINT32:
2044 case REG_TYPE_UINT64:
2046 case REG_TYPE_UINT128:
2048 case REG_TYPE_CODE_PTR:
2050 case REG_TYPE_DATA_PTR:
2052 case REG_TYPE_FLOAT:
2054 case REG_TYPE_IEEE_SINGLE:
2055 return "ieee_single";
2056 case REG_TYPE_IEEE_DOUBLE:
2057 return "ieee_double";
2058 case REG_TYPE_ARCH_DEFINED:
2059 return "int"; /* return arbitrary string to avoid compile warning. */
2062 return "int"; /* "int" as default value */
2065 static int lookup_add_arch_defined_types(char const **arch_defined_types_list[], const char *type_id,
2066 int *num_arch_defined_types)
2068 int tbl_sz = *num_arch_defined_types;
2070 if (type_id && (strcmp(type_id, ""))) {
2071 for (int j = 0; j < (tbl_sz + 1); j++) {
2072 if (!((*arch_defined_types_list)[j])) {
2073 (*arch_defined_types_list)[tbl_sz++] = type_id;
2074 *arch_defined_types_list = realloc(*arch_defined_types_list,
2075 sizeof(char *) * (tbl_sz + 1));
2076 (*arch_defined_types_list)[tbl_sz] = NULL;
2077 *num_arch_defined_types = tbl_sz;
2080 if (!strcmp((*arch_defined_types_list)[j], type_id))
2089 static int gdb_generate_reg_type_description(struct target *target,
2090 char **tdesc, int *pos, int *size, struct reg_data_type *type,
2091 char const **arch_defined_types_list[], int *num_arch_defined_types)
2093 int retval = ERROR_OK;
2095 if (type->type_class == REG_TYPE_CLASS_VECTOR) {
2096 struct reg_data_type *data_type = type->reg_type_vector->type;
2097 if (data_type->type == REG_TYPE_ARCH_DEFINED) {
2098 if (lookup_add_arch_defined_types(arch_defined_types_list, data_type->id,
2099 num_arch_defined_types))
2100 gdb_generate_reg_type_description(target, tdesc, pos, size, data_type,
2101 arch_defined_types_list,
2102 num_arch_defined_types);
2104 /* <vector id="id" type="type" count="count"/> */
2105 xml_printf(&retval, tdesc, pos, size,
2106 "<vector id=\"%s\" type=\"%s\" count=\"%" PRIu32 "\"/>\n",
2107 type->id, type->reg_type_vector->type->id,
2108 type->reg_type_vector->count);
2110 } else if (type->type_class == REG_TYPE_CLASS_UNION) {
2111 struct reg_data_type_union_field *field;
2112 field = type->reg_type_union->fields;
2114 struct reg_data_type *data_type = field->type;
2115 if (data_type->type == REG_TYPE_ARCH_DEFINED) {
2116 if (lookup_add_arch_defined_types(arch_defined_types_list, data_type->id,
2117 num_arch_defined_types))
2118 gdb_generate_reg_type_description(target, tdesc, pos, size, data_type,
2119 arch_defined_types_list,
2120 num_arch_defined_types);
2123 field = field->next;
2126 * <field name="name" type="type"/> ...
2128 xml_printf(&retval, tdesc, pos, size,
2129 "<union id=\"%s\">\n",
2132 field = type->reg_type_union->fields;
2134 xml_printf(&retval, tdesc, pos, size,
2135 "<field name=\"%s\" type=\"%s\"/>\n",
2136 field->name, field->type->id);
2138 field = field->next;
2141 xml_printf(&retval, tdesc, pos, size,
2144 } else if (type->type_class == REG_TYPE_CLASS_STRUCT) {
2145 struct reg_data_type_struct_field *field;
2146 field = type->reg_type_struct->fields;
2148 if (field->use_bitfields) {
2149 /* <struct id="id" size="size">
2150 * <field name="name" start="start" end="end"/> ...
2152 xml_printf(&retval, tdesc, pos, size,
2153 "<struct id=\"%s\" size=\"%" PRIu32 "\">\n",
2154 type->id, type->reg_type_struct->size);
2156 xml_printf(&retval, tdesc, pos, size,
2157 "<field name=\"%s\" start=\"%" PRIu32 "\" end=\"%" PRIu32 "\" type=\"%s\" />\n",
2158 field->name, field->bitfield->start, field->bitfield->end,
2159 gdb_get_reg_type_name(field->bitfield->type));
2161 field = field->next;
2165 struct reg_data_type *data_type = field->type;
2166 if (data_type->type == REG_TYPE_ARCH_DEFINED) {
2167 if (lookup_add_arch_defined_types(arch_defined_types_list, data_type->id,
2168 num_arch_defined_types))
2169 gdb_generate_reg_type_description(target, tdesc, pos, size, data_type,
2170 arch_defined_types_list,
2171 num_arch_defined_types);
2176 * <field name="name" type="type"/> ...
2178 xml_printf(&retval, tdesc, pos, size,
2179 "<struct id=\"%s\">\n",
2182 xml_printf(&retval, tdesc, pos, size,
2183 "<field name=\"%s\" type=\"%s\"/>\n",
2184 field->name, field->type->id);
2186 field = field->next;
2190 xml_printf(&retval, tdesc, pos, size,
2193 } else if (type->type_class == REG_TYPE_CLASS_FLAGS) {
2194 /* <flags id="id" size="size">
2195 * <field name="name" start="start" end="end"/> ...
2197 xml_printf(&retval, tdesc, pos, size,
2198 "<flags id=\"%s\" size=\"%" PRIu32 "\">\n",
2199 type->id, type->reg_type_flags->size);
2201 struct reg_data_type_flags_field *field;
2202 field = type->reg_type_flags->fields;
2204 xml_printf(&retval, tdesc, pos, size,
2205 "<field name=\"%s\" start=\"%" PRIu32 "\" end=\"%" PRIu32 "\" type=\"%s\" />\n",
2206 field->name, field->bitfield->start, field->bitfield->end,
2207 gdb_get_reg_type_name(field->bitfield->type));
2209 field = field->next;
2212 xml_printf(&retval, tdesc, pos, size,
2220 /* Get a list of available target registers features. feature_list must
2221 * be freed by caller.
2223 static int get_reg_features_list(struct target *target, char const **feature_list[], int *feature_list_size,
2224 struct reg **reg_list, int reg_list_size)
2228 /* Start with only one element */
2229 *feature_list = calloc(1, sizeof(char *));
2231 for (int i = 0; i < reg_list_size; i++) {
2232 if (reg_list[i]->exist == false || reg_list[i]->hidden)
2235 if (reg_list[i]->feature
2236 && reg_list[i]->feature->name
2237 && (strcmp(reg_list[i]->feature->name, ""))) {
2238 /* We found a feature, check if the feature is already in the
2239 * table. If not, allocate a new entry for the table and
2240 * put the new feature in it.
2242 for (int j = 0; j < (tbl_sz + 1); j++) {
2243 if (!((*feature_list)[j])) {
2244 (*feature_list)[tbl_sz++] = reg_list[i]->feature->name;
2245 *feature_list = realloc(*feature_list, sizeof(char *) * (tbl_sz + 1));
2246 (*feature_list)[tbl_sz] = NULL;
2249 if (!strcmp((*feature_list)[j], reg_list[i]->feature->name))
2256 if (feature_list_size)
2257 *feature_list_size = tbl_sz;
2262 static int gdb_generate_target_description(struct target *target, char **tdesc_out)
2264 int retval = ERROR_OK;
2265 struct reg **reg_list = NULL;
2267 char const *architecture;
2268 char const **features = NULL;
2269 int feature_list_size = 0;
2275 retval = target_get_gdb_reg_list_noread(target, ®_list,
2276 ®_list_size, REG_CLASS_ALL);
2278 if (retval != ERROR_OK) {
2279 LOG_ERROR("get register list failed");
2280 retval = ERROR_FAIL;
2284 if (reg_list_size <= 0) {
2285 LOG_ERROR("get register list failed");
2286 retval = ERROR_FAIL;
2290 /* Get a list of available target registers features */
2291 retval = get_reg_features_list(target, &features, &feature_list_size, reg_list, reg_list_size);
2292 if (retval != ERROR_OK) {
2293 LOG_ERROR("Can't get the registers feature list");
2294 retval = ERROR_FAIL;
2298 /* If we found some features associated with registers, create sections */
2299 int current_feature = 0;
2301 xml_printf(&retval, &tdesc, &pos, &size,
2302 "<?xml version=\"1.0\"?>\n"
2303 "<!DOCTYPE target SYSTEM \"gdb-target.dtd\">\n"
2304 "<target version=\"1.0\">\n");
2306 /* generate architecture element if supported by target */
2307 architecture = target_get_gdb_arch(target);
2309 xml_printf(&retval, &tdesc, &pos, &size,
2310 "<architecture>%s</architecture>\n", architecture);
2312 /* generate target description according to register list */
2314 while (features[current_feature]) {
2315 char const **arch_defined_types = NULL;
2316 int num_arch_defined_types = 0;
2318 arch_defined_types = calloc(1, sizeof(char *));
2319 xml_printf(&retval, &tdesc, &pos, &size,
2320 "<feature name=\"%s\">\n",
2321 features[current_feature]);
2324 for (i = 0; i < reg_list_size; i++) {
2326 if (reg_list[i]->exist == false || reg_list[i]->hidden)
2329 if (strcmp(reg_list[i]->feature->name, features[current_feature]))
2332 const char *type_str;
2333 if (reg_list[i]->reg_data_type) {
2334 if (reg_list[i]->reg_data_type->type == REG_TYPE_ARCH_DEFINED) {
2335 /* generate <type... first, if there are architecture-defined types. */
2336 if (lookup_add_arch_defined_types(&arch_defined_types,
2337 reg_list[i]->reg_data_type->id,
2338 &num_arch_defined_types))
2339 gdb_generate_reg_type_description(target, &tdesc, &pos, &size,
2340 reg_list[i]->reg_data_type,
2341 &arch_defined_types,
2342 &num_arch_defined_types);
2344 type_str = reg_list[i]->reg_data_type->id;
2346 /* predefined type */
2347 type_str = gdb_get_reg_type_name(
2348 reg_list[i]->reg_data_type->type);
2351 /* Default type is "int" */
2355 xml_printf(&retval, &tdesc, &pos, &size,
2356 "<reg name=\"%s\"", reg_list[i]->name);
2357 xml_printf(&retval, &tdesc, &pos, &size,
2358 " bitsize=\"%" PRIu32 "\"", reg_list[i]->size);
2359 xml_printf(&retval, &tdesc, &pos, &size,
2360 " regnum=\"%" PRIu32 "\"", reg_list[i]->number);
2361 if (reg_list[i]->caller_save)
2362 xml_printf(&retval, &tdesc, &pos, &size,
2363 " save-restore=\"yes\"");
2365 xml_printf(&retval, &tdesc, &pos, &size,
2366 " save-restore=\"no\"");
2368 xml_printf(&retval, &tdesc, &pos, &size,
2369 " type=\"%s\"", type_str);
2371 if (reg_list[i]->group)
2372 xml_printf(&retval, &tdesc, &pos, &size,
2373 " group=\"%s\"", reg_list[i]->group);
2375 xml_printf(&retval, &tdesc, &pos, &size,
2379 xml_printf(&retval, &tdesc, &pos, &size,
2383 free(arch_defined_types);
2387 xml_printf(&retval, &tdesc, &pos, &size,
2394 if (retval == ERROR_OK)
2402 static int gdb_get_target_description_chunk(struct target *target, struct target_desc_format *target_desc,
2403 char **chunk, int32_t offset, uint32_t length)
2406 LOG_ERROR("Unable to Generate Target Description");
2410 char *tdesc = target_desc->tdesc;
2411 uint32_t tdesc_length = target_desc->tdesc_length;
2414 int retval = gdb_generate_target_description(target, &tdesc);
2415 if (retval != ERROR_OK) {
2416 LOG_ERROR("Unable to Generate Target Description");
2420 tdesc_length = strlen(tdesc);
2425 if (length < (tdesc_length - offset))
2426 transfer_type = 'm';
2428 transfer_type = 'l';
2430 *chunk = malloc(length + 2);
2432 LOG_ERROR("Unable to allocate memory");
2436 (*chunk)[0] = transfer_type;
2437 if (transfer_type == 'm') {
2438 strncpy((*chunk) + 1, tdesc + offset, length);
2439 (*chunk)[1 + length] = '\0';
2441 strncpy((*chunk) + 1, tdesc + offset, tdesc_length - offset);
2442 (*chunk)[1 + (tdesc_length - offset)] = '\0';
2444 /* After gdb-server sends out last chunk, invalidate tdesc. */
2450 target_desc->tdesc = tdesc;
2451 target_desc->tdesc_length = tdesc_length;
2456 static int gdb_target_description_supported(struct target *target, int *supported)
2458 int retval = ERROR_OK;
2459 struct reg **reg_list = NULL;
2460 int reg_list_size = 0;
2461 char const **features = NULL;
2462 int feature_list_size = 0;
2464 char const *architecture = target_get_gdb_arch(target);
2466 retval = target_get_gdb_reg_list_noread(target, ®_list,
2467 ®_list_size, REG_CLASS_ALL);
2468 if (retval != ERROR_OK) {
2469 LOG_ERROR("get register list failed");
2473 if (reg_list_size <= 0) {
2474 LOG_ERROR("get register list failed");
2475 retval = ERROR_FAIL;
2479 /* Get a list of available target registers features */
2480 retval = get_reg_features_list(target, &features, &feature_list_size, reg_list, reg_list_size);
2481 if (retval != ERROR_OK) {
2482 LOG_ERROR("Can't get the registers feature list");
2487 if (architecture || feature_list_size)
2501 static int gdb_generate_thread_list(struct target *target, char **thread_list_out)
2503 struct rtos *rtos = target->rtos;
2504 int retval = ERROR_OK;
2505 char *thread_list = NULL;
2509 xml_printf(&retval, &thread_list, &pos, &size,
2510 "<?xml version=\"1.0\"?>\n"
2514 for (int i = 0; i < rtos->thread_count; i++) {
2515 struct thread_detail *thread_detail = &rtos->thread_details[i];
2517 if (!thread_detail->exists)
2520 xml_printf(&retval, &thread_list, &pos, &size,
2521 "<thread id=\"%" PRIx64 "\">", thread_detail->threadid);
2523 if (thread_detail->thread_name_str)
2524 xml_printf(&retval, &thread_list, &pos, &size,
2525 "Name: %s", thread_detail->thread_name_str);
2527 if (thread_detail->extra_info_str) {
2528 if (thread_detail->thread_name_str)
2529 xml_printf(&retval, &thread_list, &pos, &size,
2531 xml_printf(&retval, &thread_list, &pos, &size,
2532 "%s", thread_detail->extra_info_str);
2535 xml_printf(&retval, &thread_list, &pos, &size,
2540 xml_printf(&retval, &thread_list, &pos, &size,
2543 if (retval == ERROR_OK)
2544 *thread_list_out = thread_list;
2551 static int gdb_get_thread_list_chunk(struct target *target, char **thread_list,
2552 char **chunk, int32_t offset, uint32_t length)
2554 if (!*thread_list) {
2555 int retval = gdb_generate_thread_list(target, thread_list);
2556 if (retval != ERROR_OK) {
2557 LOG_ERROR("Unable to Generate Thread List");
2562 size_t thread_list_length = strlen(*thread_list);
2565 length = MIN(length, thread_list_length - offset);
2566 if (length < (thread_list_length - offset))
2567 transfer_type = 'm';
2569 transfer_type = 'l';
2571 *chunk = malloc(length + 2 + 3);
2572 /* Allocating extra 3 bytes prevents false positive valgrind report
2573 * of strlen(chunk) word access:
2574 * Invalid read of size 4
2575 * Address 0x4479934 is 44 bytes inside a block of size 45 alloc'd */
2577 LOG_ERROR("Unable to allocate memory");
2581 (*chunk)[0] = transfer_type;
2582 strncpy((*chunk) + 1, (*thread_list) + offset, length);
2583 (*chunk)[1 + length] = '\0';
2585 /* After gdb-server sends out last chunk, invalidate thread list. */
2586 if (transfer_type == 'l') {
2588 *thread_list = NULL;
2594 static int gdb_query_packet(struct connection *connection,
2595 char const *packet, int packet_size)
2597 struct command_context *cmd_ctx = connection->cmd_ctx;
2598 struct gdb_connection *gdb_connection = connection->priv;
2599 struct target *target = get_target_from_connection(connection);
2601 if (strncmp(packet, "qRcmd,", 6) == 0) {
2602 if (packet_size > 6) {
2604 cmd = malloc((packet_size - 6) / 2 + 1);
2605 size_t len = unhexify((uint8_t *)cmd, packet + 6, (packet_size - 6) / 2);
2608 /* We want to print all debug output to GDB connection */
2609 log_add_callback(gdb_log_callback, connection);
2610 target_call_timer_callbacks_now();
2611 /* some commands need to know the GDB connection, make note of current
2612 * GDB connection. */
2613 current_gdb_connection = gdb_connection;
2614 command_run_line(cmd_ctx, cmd);
2615 current_gdb_connection = NULL;
2616 target_call_timer_callbacks_now();
2617 log_remove_callback(gdb_log_callback, connection);
2620 gdb_put_packet(connection, "OK", 2);
2622 } else if (strncmp(packet, "qCRC:", 5) == 0) {
2623 if (packet_size > 5) {
2628 target_addr_t addr = 0;
2631 /* skip command character */
2634 addr = strtoull(packet, &separator, 16);
2636 if (*separator != ',') {
2637 LOG_ERROR("incomplete read memory packet received, dropping connection");
2638 return ERROR_SERVER_REMOTE_CLOSED;
2641 len = strtoul(separator + 1, NULL, 16);
2643 retval = target_checksum_memory(target, addr, len, &checksum);
2645 if (retval == ERROR_OK) {
2646 snprintf(gdb_reply, 10, "C%8.8" PRIx32 "", checksum);
2647 gdb_put_packet(connection, gdb_reply, 9);
2649 retval = gdb_error(connection, retval);
2650 if (retval != ERROR_OK)
2656 } else if (strncmp(packet, "qSupported", 10) == 0) {
2657 /* we currently support packet size and qXfer:memory-map:read (if enabled)
2658 * qXfer:features:read is supported for some targets */
2659 int retval = ERROR_OK;
2660 char *buffer = NULL;
2663 int gdb_target_desc_supported = 0;
2665 /* we need to test that the target supports target descriptions */
2666 retval = gdb_target_description_supported(target, &gdb_target_desc_supported);
2667 if (retval != ERROR_OK) {
2668 LOG_INFO("Failed detecting Target Description Support, disabling");
2669 gdb_target_desc_supported = 0;
2672 /* support may be disabled globally */
2673 if (gdb_use_target_description == 0) {
2674 if (gdb_target_desc_supported)
2675 LOG_WARNING("Target Descriptions Supported, but disabled");
2676 gdb_target_desc_supported = 0;
2683 "PacketSize=%x;qXfer:memory-map:read%c;qXfer:features:read%c;qXfer:threads:read+;QStartNoAckMode+;vContSupported+",
2685 ((gdb_use_memory_map == 1) && (flash_get_bank_count() > 0)) ? '+' : '-',
2686 (gdb_target_desc_supported == 1) ? '+' : '-');
2688 if (retval != ERROR_OK) {
2689 gdb_send_error(connection, 01);
2693 gdb_put_packet(connection, buffer, strlen(buffer));
2697 } else if ((strncmp(packet, "qXfer:memory-map:read::", 23) == 0)
2698 && (flash_get_bank_count() > 0))
2699 return gdb_memory_map(connection, packet, packet_size);
2700 else if (strncmp(packet, "qXfer:features:read:", 20) == 0) {
2702 int retval = ERROR_OK;
2705 unsigned int length;
2707 /* skip command character */
2710 if (decode_xfer_read(packet, NULL, &offset, &length) < 0) {
2711 gdb_send_error(connection, 01);
2715 /* Target should prepare correct target description for annex.
2716 * The first character of returned xml is 'm' or 'l'. 'm' for
2717 * there are *more* chunks to transfer. 'l' for it is the *last*
2718 * chunk of target description.
2720 retval = gdb_get_target_description_chunk(target, &gdb_connection->target_desc,
2721 &xml, offset, length);
2722 if (retval != ERROR_OK) {
2723 gdb_error(connection, retval);
2727 gdb_put_packet(connection, xml, strlen(xml));
2731 } else if (strncmp(packet, "qXfer:threads:read:", 19) == 0) {
2733 int retval = ERROR_OK;
2736 unsigned int length;
2738 /* skip command character */
2741 if (decode_xfer_read(packet, NULL, &offset, &length) < 0) {
2742 gdb_send_error(connection, 01);
2746 /* Target should prepare correct thread list for annex.
2747 * The first character of returned xml is 'm' or 'l'. 'm' for
2748 * there are *more* chunks to transfer. 'l' for it is the *last*
2749 * chunk of target description.
2751 retval = gdb_get_thread_list_chunk(target, &gdb_connection->thread_list,
2752 &xml, offset, length);
2753 if (retval != ERROR_OK) {
2754 gdb_error(connection, retval);
2758 gdb_put_packet(connection, xml, strlen(xml));
2762 } else if (strncmp(packet, "QStartNoAckMode", 15) == 0) {
2763 gdb_connection->noack_mode = 1;
2764 gdb_put_packet(connection, "OK", 2);
2768 gdb_put_packet(connection, "", 0);
2772 static bool gdb_handle_vcont_packet(struct connection *connection, const char *packet, int packet_size)
2774 struct gdb_connection *gdb_connection = connection->priv;
2775 struct target *target = get_target_from_connection(connection);
2776 const char *parse = packet;
2779 /* query for vCont supported */
2780 if (parse[0] == '?') {
2781 if (target->type->step) {
2782 /* gdb doesn't accept c without C and s without S */
2783 gdb_put_packet(connection, "vCont;c;C;s;S", 13);
2789 if (parse[0] == ';') {
2794 /* simple case, a continue packet */
2795 if (parse[0] == 'c') {
2796 gdb_running_type = 'c';
2797 LOG_DEBUG("target %s continue", target_name(target));
2798 log_add_callback(gdb_log_callback, connection);
2799 retval = target_resume(target, 1, 0, 0, 0);
2800 if (retval == ERROR_TARGET_NOT_HALTED)
2801 LOG_INFO("target %s was not halted when resume was requested", target_name(target));
2803 /* poll target in an attempt to make its internal state consistent */
2804 if (retval != ERROR_OK) {
2805 retval = target_poll(target);
2806 if (retval != ERROR_OK)
2807 LOG_DEBUG("error polling target %s after failed resume", target_name(target));
2811 * We don't report errors to gdb here, move frontend_state to
2812 * TARGET_RUNNING to stay in sync with gdb's expectation of the
2815 gdb_connection->frontend_state = TARGET_RUNNING;
2816 target_call_event_callbacks(target, TARGET_EVENT_GDB_START);
2821 /* single-step or step-over-breakpoint */
2822 if (parse[0] == 's') {
2823 gdb_running_type = 's';
2824 bool fake_step = false;
2826 if (strncmp(parse, "s:", 2) == 0) {
2827 struct target *ct = target;
2835 thread_id = strtoll(parse, &endp, 16);
2837 packet_size -= endp - parse;
2842 /* FIXME: why is this necessary? rtos state should be up-to-date here already! */
2843 rtos_update_threads(target);
2845 target->rtos->gdb_target_for_threadid(connection, thread_id, &ct);
2848 * check if the thread to be stepped is the current rtos thread
2849 * if not, we must fake the step
2851 if (target->rtos->current_thread != thread_id)
2855 if (parse[0] == ';') {
2859 if (parse[0] == 'c') {
2862 /* check if thread-id follows */
2863 if (parse[0] == ':') {
2867 tid = strtoll(parse, &endp, 16);
2868 if (tid == thread_id) {
2870 * Special case: only step a single thread (core),
2871 * keep the other threads halted. Currently, only
2872 * aarch64 target understands it. Other target types don't
2873 * care (nobody checks the actual value of 'current')
2874 * and it doesn't really matter. This deserves
2875 * a symbolic constant and a formal interface documentation
2878 LOG_DEBUG("request to step current core only");
2879 /* uncomment after checking that indeed other targets are safe */
2886 LOG_DEBUG("target %s single-step thread %"PRIx64, target_name(ct), thread_id);
2887 log_add_callback(gdb_log_callback, connection);
2888 target_call_event_callbacks(ct, TARGET_EVENT_GDB_START);
2891 * work around an annoying gdb behaviour: when the current thread
2892 * is changed in gdb, it assumes that the target can follow and also
2893 * make the thread current. This is an assumption that cannot hold
2894 * for a real target running a multi-threading OS. We just fake
2895 * the step to not trigger an internal error in gdb. See
2896 * https://sourceware.org/bugzilla/show_bug.cgi?id=22925 for details
2900 char sig_reply[128];
2902 LOG_DEBUG("fake step thread %"PRIx64, thread_id);
2904 sig_reply_len = snprintf(sig_reply, sizeof(sig_reply),
2905 "T05thread:%016"PRIx64";", thread_id);
2907 gdb_put_packet(connection, sig_reply, sig_reply_len);
2908 log_remove_callback(gdb_log_callback, connection);
2913 /* support for gdb_sync command */
2914 if (gdb_connection->sync) {
2915 gdb_connection->sync = false;
2916 if (ct->state == TARGET_HALTED) {
2917 LOG_DEBUG("stepi ignored. GDB will now fetch the register state "
2918 "from the target.");
2919 gdb_sig_halted(connection);
2920 log_remove_callback(gdb_log_callback, connection);
2922 gdb_connection->frontend_state = TARGET_RUNNING;
2926 retval = target_step(ct, current_pc, 0, 0);
2927 if (retval == ERROR_TARGET_NOT_HALTED)
2928 LOG_INFO("target %s was not halted when step was requested", target_name(ct));
2930 /* if step was successful send a reply back to gdb */
2931 if (retval == ERROR_OK) {
2932 retval = target_poll(ct);
2933 if (retval != ERROR_OK)
2934 LOG_DEBUG("error polling target %s after successful step", target_name(ct));
2935 /* send back signal information */
2936 gdb_signal_reply(ct, connection);
2937 /* stop forwarding log packets! */
2938 log_remove_callback(gdb_log_callback, connection);
2940 gdb_connection->frontend_state = TARGET_RUNNING;
2942 LOG_ERROR("Unknown vCont packet");
2951 static char *next_hex_encoded_field(const char **str, char sep)
2954 const char *hex = *str;
2958 const char *end = strchr(hex, sep);
2960 hexlen = strlen(hex);
2963 *str = hex + hexlen + 1;
2965 if (hexlen % 2 != 0) {
2966 /* Malformed hex data */
2970 size_t count = hexlen / 2;
2971 char *decoded = malloc(count + 1);
2975 size_t converted = unhexify((void *)decoded, hex, count);
2976 if (converted != count) {
2981 decoded[count] = '\0';
2985 /* handle extended restart packet */
2986 static void gdb_restart_inferior(struct connection *connection, const char *packet, int packet_size)
2988 struct gdb_connection *gdb_con = connection->priv;
2989 struct target *target = get_target_from_connection(connection);
2991 breakpoint_clear_target(target);
2992 watchpoint_clear_target(target);
2993 command_run_linef(connection->cmd_ctx, "ocd_gdb_restart %s",
2994 target_name(target));
2995 /* set connection as attached after reset */
2996 gdb_con->attached = true;
2997 /* info rtos parts */
2998 gdb_thread_packet(connection, packet, packet_size);
3001 static bool gdb_handle_vrun_packet(struct connection *connection, const char *packet, int packet_size)
3003 struct target *target = get_target_from_connection(connection);
3004 const char *parse = packet;
3009 if (parse[0] != ';')
3013 /* Skip first field "filename"; don't know what to do with it. */
3014 free(next_hex_encoded_field(&parse, ';'));
3016 char *cmdline = next_hex_encoded_field(&parse, ';');
3018 char *arg = next_hex_encoded_field(&parse, ';');
3021 char *new_cmdline = alloc_printf("%s %s", cmdline, arg);
3024 cmdline = new_cmdline;
3028 if (target->semihosting) {
3029 LOG_INFO("GDB set inferior command line to '%s'", cmdline);
3030 free(target->semihosting->cmdline);
3031 target->semihosting->cmdline = cmdline;
3033 LOG_INFO("GDB set inferior command line to '%s' but semihosting is unavailable", cmdline);
3038 gdb_restart_inferior(connection, packet, packet_size);
3039 gdb_put_packet(connection, "S00", 3);
3043 static int gdb_v_packet(struct connection *connection,
3044 char const *packet, int packet_size)
3046 struct gdb_connection *gdb_connection = connection->priv;
3049 struct target *target = get_target_from_connection(connection);
3051 if (strncmp(packet, "vCont", 5) == 0) {
3057 handled = gdb_handle_vcont_packet(connection, packet, packet_size);
3059 gdb_put_packet(connection, "", 0);
3064 if (strncmp(packet, "vRun", 4) == 0) {
3067 handled = gdb_handle_vrun_packet(connection, packet, packet_size);
3069 gdb_put_packet(connection, "", 0);
3074 /* if flash programming disabled - send a empty reply */
3076 if (gdb_flash_program == 0) {
3077 gdb_put_packet(connection, "", 0);
3081 if (strncmp(packet, "vFlashErase:", 12) == 0) {
3083 unsigned long length;
3085 char const *parse = packet + 12;
3086 if (*parse == '\0') {
3087 LOG_ERROR("incomplete vFlashErase packet received, dropping connection");
3088 return ERROR_SERVER_REMOTE_CLOSED;
3091 addr = strtoul(parse, (char **)&parse, 16);
3093 if (*(parse++) != ',' || *parse == '\0') {
3094 LOG_ERROR("incomplete vFlashErase packet received, dropping connection");
3095 return ERROR_SERVER_REMOTE_CLOSED;
3098 length = strtoul(parse, (char **)&parse, 16);
3100 if (*parse != '\0') {
3101 LOG_ERROR("incomplete vFlashErase packet received, dropping connection");
3102 return ERROR_SERVER_REMOTE_CLOSED;
3105 /* assume all sectors need erasing - stops any problems
3106 * when flash_write is called multiple times */
3109 /* perform any target specific operations before the erase */
3110 target_call_event_callbacks(target,
3111 TARGET_EVENT_GDB_FLASH_ERASE_START);
3113 /* vFlashErase:addr,length messages require region start and
3114 * end to be "block" aligned ... if padding is ever needed,
3115 * GDB will have become dangerously confused.
3117 result = flash_erase_address_range(target, false, addr,
3120 /* perform any target specific operations after the erase */
3121 target_call_event_callbacks(target,
3122 TARGET_EVENT_GDB_FLASH_ERASE_END);
3125 if (result != ERROR_OK) {
3126 /* GDB doesn't evaluate the actual error number returned,
3127 * treat a failed erase as an I/O error
3129 gdb_send_error(connection, EIO);
3130 LOG_ERROR("flash_erase returned %i", result);
3132 gdb_put_packet(connection, "OK", 2);
3137 if (strncmp(packet, "vFlashWrite:", 12) == 0) {
3140 unsigned long length;
3141 char const *parse = packet + 12;
3143 if (*parse == '\0') {
3144 LOG_ERROR("incomplete vFlashErase packet received, dropping connection");
3145 return ERROR_SERVER_REMOTE_CLOSED;
3147 addr = strtoul(parse, (char **)&parse, 16);
3148 if (*(parse++) != ':') {
3149 LOG_ERROR("incomplete vFlashErase packet received, dropping connection");
3150 return ERROR_SERVER_REMOTE_CLOSED;
3152 length = packet_size - (parse - packet);
3154 /* create a new image if there isn't already one */
3155 if (!gdb_connection->vflash_image) {
3156 gdb_connection->vflash_image = malloc(sizeof(struct image));
3157 image_open(gdb_connection->vflash_image, "", "build");
3160 /* create new section with content from packet buffer */
3161 retval = image_add_section(gdb_connection->vflash_image,
3162 addr, length, 0x0, (uint8_t const *)parse);
3163 if (retval != ERROR_OK)
3166 gdb_put_packet(connection, "OK", 2);
3171 if (strncmp(packet, "vFlashDone", 10) == 0) {
3174 /* process the flashing buffer. No need to erase as GDB
3175 * always issues a vFlashErase first. */
3176 target_call_event_callbacks(target,
3177 TARGET_EVENT_GDB_FLASH_WRITE_START);
3178 result = flash_write(target, gdb_connection->vflash_image,
3180 target_call_event_callbacks(target,
3181 TARGET_EVENT_GDB_FLASH_WRITE_END);
3182 if (result != ERROR_OK) {
3183 if (result == ERROR_FLASH_DST_OUT_OF_BANK)
3184 gdb_put_packet(connection, "E.memtype", 9);
3186 gdb_send_error(connection, EIO);
3188 LOG_DEBUG("wrote %u bytes from vFlash image to flash", (unsigned)written);
3189 gdb_put_packet(connection, "OK", 2);
3192 image_close(gdb_connection->vflash_image);
3193 free(gdb_connection->vflash_image);
3194 gdb_connection->vflash_image = NULL;
3199 gdb_put_packet(connection, "", 0);
3203 static int gdb_detach(struct connection *connection)
3206 * Only reply "OK" to GDB
3207 * it will close the connection and this will trigger a call to
3208 * gdb_connection_closed() that will in turn trigger the event
3209 * TARGET_EVENT_GDB_DETACH
3211 return gdb_put_packet(connection, "OK", 2);
3214 /* The format of 'F' response packet is
3215 * Fretcode,errno,Ctrl-C flag;call-specific attachment
3217 static int gdb_fileio_response_packet(struct connection *connection,
3218 char const *packet, int packet_size)
3220 struct target *target = get_target_from_connection(connection);
3222 char *parsing_point;
3223 int fileio_retcode = strtoul(packet + 1, &separator, 16);
3224 int fileio_errno = 0;
3225 bool fileio_ctrl_c = false;
3230 if (*separator == ',') {
3231 parsing_point = separator + 1;
3232 fileio_errno = strtoul(parsing_point, &separator, 16);
3233 if (*separator == ',') {
3234 if (*(separator + 1) == 'C') {
3235 /* TODO: process ctrl-c */
3236 fileio_ctrl_c = true;
3241 LOG_DEBUG("File-I/O response, retcode: 0x%x, errno: 0x%x, ctrl-c: %s",
3242 fileio_retcode, fileio_errno, fileio_ctrl_c ? "true" : "false");
3244 retval = target_gdb_fileio_end(target, fileio_retcode, fileio_errno, fileio_ctrl_c);
3245 if (retval != ERROR_OK)
3248 /* After File-I/O ends, keep continue or step */
3249 if (gdb_running_type == 'c')
3250 retval = target_resume(target, 1, 0x0, 0, 0);
3251 else if (gdb_running_type == 's')
3252 retval = target_step(target, 1, 0x0, 0);
3254 retval = ERROR_FAIL;
3256 if (retval != ERROR_OK)
3262 static void gdb_log_callback(void *priv, const char *file, unsigned line,
3263 const char *function, const char *string)
3265 struct connection *connection = priv;
3266 struct gdb_connection *gdb_con = connection->priv;
3268 if (gdb_con->busy) {
3269 /* do not reply this using the O packet */
3273 gdb_output_con(connection, string);
3276 static void gdb_sig_halted(struct connection *connection)
3279 snprintf(sig_reply, 4, "T%2.2x", 2);
3280 gdb_put_packet(connection, sig_reply, 3);
3283 static int gdb_input_inner(struct connection *connection)
3285 /* Do not allocate this on the stack */
3286 static char gdb_packet_buffer[GDB_BUFFER_SIZE + 1]; /* Extra byte for null-termination */
3288 struct target *target;
3289 char const *packet = gdb_packet_buffer;
3292 struct gdb_connection *gdb_con = connection->priv;
3293 static bool warn_use_ext;
3295 target = get_target_from_connection(connection);
3297 /* drain input buffer. If one of the packets fail, then an error
3298 * packet is replied, if applicable.
3300 * This loop will terminate and the error code is returned.
3302 * The calling fn will check if this error is something that
3303 * can be recovered from, or if the connection must be closed.
3305 * If the error is recoverable, this fn is called again to
3306 * drain the rest of the buffer.
3309 packet_size = GDB_BUFFER_SIZE;
3310 retval = gdb_get_packet(connection, gdb_packet_buffer, &packet_size);
3311 if (retval != ERROR_OK)
3314 /* terminate with zero */
3315 gdb_packet_buffer[packet_size] = '\0';
3317 gdb_log_incoming_packet(gdb_packet_buffer);
3319 if (packet_size > 0) {
3321 switch (packet[0]) {
3322 case 'T': /* Is thread alive? */
3323 gdb_thread_packet(connection, packet, packet_size);
3325 case 'H': /* Set current thread ( 'c' for step and continue,
3326 * 'g' for all other operations ) */
3327 gdb_thread_packet(connection, packet, packet_size);
3331 retval = gdb_thread_packet(connection, packet, packet_size);
3332 if (retval == GDB_THREAD_PACKET_NOT_CONSUMED)
3333 retval = gdb_query_packet(connection, packet, packet_size);
3336 retval = gdb_get_registers_packet(connection, packet, packet_size);
3339 retval = gdb_set_registers_packet(connection, packet, packet_size);
3342 retval = gdb_get_register_packet(connection, packet, packet_size);
3345 retval = gdb_set_register_packet(connection, packet, packet_size);
3348 retval = gdb_read_memory_packet(connection, packet, packet_size);
3351 retval = gdb_write_memory_packet(connection, packet, packet_size);
3355 retval = gdb_breakpoint_watchpoint_packet(connection, packet, packet_size);
3358 gdb_last_signal_packet(connection, packet, packet_size);
3359 /* '?' is sent after the eventual '!' */
3360 if (!warn_use_ext && !gdb_con->extended_protocol) {
3361 warn_use_ext = true;
3362 LOG_WARNING("Prefer GDB command \"target extended-remote :%s\" instead of \"target remote :%s\"",
3363 connection->service->port, connection->service->port);
3369 gdb_thread_packet(connection, packet, packet_size);
3370 log_add_callback(gdb_log_callback, connection);
3372 if (gdb_con->mem_write_error) {
3373 LOG_ERROR("Memory write failure!");
3375 /* now that we have reported the memory write error,
3376 * we can clear the condition */
3377 gdb_con->mem_write_error = false;
3380 bool nostep = false;
3381 bool already_running = false;
3382 if (target->state == TARGET_RUNNING) {
3383 LOG_WARNING("WARNING! The target is already running. "
3384 "All changes GDB did to registers will be discarded! "
3385 "Waiting for target to halt.");
3386 already_running = true;
3387 } else if (target->state != TARGET_HALTED) {
3388 LOG_WARNING("The target is not in the halted nor running stated, "
3389 "stepi/continue ignored.");
3391 } else if ((packet[0] == 's') && gdb_con->sync) {
3392 /* Hmm..... when you issue a continue in GDB, then a "stepi" is
3393 * sent by GDB first to OpenOCD, thus defeating the check to
3394 * make only the single stepping have the sync feature...
3397 LOG_DEBUG("stepi ignored. GDB will now fetch the register state "
3398 "from the target.");
3400 gdb_con->sync = false;
3402 if (!already_running && nostep) {
3403 /* Either the target isn't in the halted state, then we can't
3404 * step/continue. This might be early setup, etc.
3406 * Or we want to allow GDB to pick up a fresh set of
3407 * register values without modifying the target state.
3410 gdb_sig_halted(connection);
3412 /* stop forwarding log packets! */
3413 log_remove_callback(gdb_log_callback, connection);
3415 /* We're running/stepping, in which case we can
3416 * forward log output until the target is halted
3418 gdb_con->frontend_state = TARGET_RUNNING;
3419 target_call_event_callbacks(target, TARGET_EVENT_GDB_START);
3421 if (!already_running) {
3422 /* Here we don't want packet processing to stop even if this fails,
3423 * so we use a local variable instead of retval. */
3424 retval = gdb_step_continue_packet(connection, packet, packet_size);
3425 if (retval != ERROR_OK) {
3426 /* we'll never receive a halted
3427 * condition... issue a false one..
3429 gdb_frontend_halted(target, connection);
3436 retval = gdb_v_packet(connection, packet, packet_size);
3439 retval = gdb_detach(connection);
3442 retval = gdb_write_memory_binary_packet(connection, packet, packet_size);
3443 if (retval != ERROR_OK)
3447 if (gdb_con->extended_protocol) {
3448 gdb_con->attached = false;
3451 gdb_put_packet(connection, "OK", 2);
3452 return ERROR_SERVER_REMOTE_CLOSED;
3454 /* handle extended remote protocol */
3455 gdb_con->extended_protocol = true;
3456 gdb_put_packet(connection, "OK", 2);
3459 /* handle extended restart packet */
3460 gdb_restart_inferior(connection, packet, packet_size);
3464 /* packet supported only by smp target i.e cortex_a.c*/
3465 /* handle smp packet replying coreid played to gbd */
3466 gdb_read_smp_packet(connection, packet, packet_size);
3470 /* packet supported only by smp target i.e cortex_a.c */
3471 /* handle smp packet setting coreid to be played at next
3473 gdb_write_smp_packet(connection, packet, packet_size);
3477 /* File-I/O extension */
3478 /* After gdb uses host-side syscall to complete target file
3479 * I/O, gdb sends host-side syscall return value to target
3481 * The format of 'F' response packet is
3482 * Fretcode,errno,Ctrl-C flag;call-specific attachment
3484 gdb_con->frontend_state = TARGET_RUNNING;
3485 log_add_callback(gdb_log_callback, connection);
3486 gdb_fileio_response_packet(connection, packet, packet_size);
3490 /* ignore unknown packets */
3491 LOG_DEBUG("ignoring 0x%2.2x packet", packet[0]);
3492 gdb_put_packet(connection, "", 0);
3496 /* if a packet handler returned an error, exit input loop */
3497 if (retval != ERROR_OK)
3501 if (gdb_con->ctrl_c) {
3502 if (target->state == TARGET_RUNNING) {
3503 struct target *t = target;
3505 target->rtos->gdb_target_for_threadid(connection, target->rtos->current_threadid, &t);
3506 retval = target_halt(t);
3507 if (retval == ERROR_OK)
3508 retval = target_poll(t);
3509 if (retval != ERROR_OK)
3510 target_call_event_callbacks(target, TARGET_EVENT_GDB_HALT);
3511 gdb_con->ctrl_c = false;
3513 LOG_INFO("The target is not running when halt was requested, stopping GDB.");
3514 target_call_event_callbacks(target, TARGET_EVENT_GDB_HALT);
3518 } while (gdb_con->buf_cnt > 0);
3523 static int gdb_input(struct connection *connection)
3525 int retval = gdb_input_inner(connection);
3526 struct gdb_connection *gdb_con = connection->priv;
3527 if (retval == ERROR_SERVER_REMOTE_CLOSED)
3530 /* logging does not propagate the error, yet can set the gdb_con->closed flag */
3531 if (gdb_con->closed)
3532 return ERROR_SERVER_REMOTE_CLOSED;
3534 /* we'll recover from any other errors(e.g. temporary timeouts, etc.) */
3538 static int gdb_target_start(struct target *target, const char *port)
3540 struct gdb_service *gdb_service;
3542 gdb_service = malloc(sizeof(struct gdb_service));
3547 LOG_INFO("starting gdb server for %s on %s", target_name(target), port);
3549 gdb_service->target = target;
3550 gdb_service->core[0] = -1;
3551 gdb_service->core[1] = -1;
3552 target->gdb_service = gdb_service;
3554 ret = add_service("gdb",
3555 port, target->gdb_max_connections, &gdb_new_connection, &gdb_input,
3556 &gdb_connection_closed, gdb_service);
3557 /* initialize all targets gdb service with the same pointer */
3559 struct target_list *head;
3560 struct target *curr;
3561 head = target->head;
3563 curr = head->target;
3565 curr->gdb_service = gdb_service;
3572 static int gdb_target_add_one(struct target *target)
3574 /* one gdb instance per smp list */
3575 if ((target->smp) && (target->gdb_service))
3578 /* skip targets that cannot handle a gdb connections (e.g. mem_ap) */
3579 if (!target_supports_gdb_connection(target)) {
3580 LOG_DEBUG("skip gdb server for target %s", target_name(target));
3584 if (target->gdb_port_override) {
3585 if (strcmp(target->gdb_port_override, "disabled") == 0) {
3586 LOG_INFO("gdb port disabled");
3589 return gdb_target_start(target, target->gdb_port_override);
3592 if (strcmp(gdb_port, "disabled") == 0) {
3593 LOG_INFO("gdb port disabled");
3597 int retval = gdb_target_start(target, gdb_port_next);
3598 if (retval == ERROR_OK) {
3599 /* save the port number so can be queried with
3600 * $target_name cget -gdb-port
3602 target->gdb_port_override = strdup(gdb_port_next);
3605 /* If we can parse the port number
3606 * then we increment the port number for the next target.
3609 portnumber = strtol(gdb_port_next, &end, 0);
3611 if (parse_long(gdb_port_next, &portnumber) == ERROR_OK) {
3612 free(gdb_port_next);
3614 gdb_port_next = alloc_printf("%ld", portnumber+1);
3616 /* Don't increment if gdb_port is 0, since we're just
3617 * trying to allocate an unused port. */
3618 gdb_port_next = strdup("0");
3626 int gdb_target_add_all(struct target *target)
3629 LOG_WARNING("gdb services need one or more targets defined");
3634 int retval = gdb_target_add_one(target);
3635 if (retval != ERROR_OK)
3638 target = target->next;
3644 COMMAND_HANDLER(handle_gdb_sync_command)
3647 return ERROR_COMMAND_SYNTAX_ERROR;
3649 if (!current_gdb_connection) {
3651 "gdb_sync command can only be run from within gdb using \"monitor gdb_sync\"");
3655 current_gdb_connection->sync = true;
3660 /* daemon configuration command gdb_port */
3661 COMMAND_HANDLER(handle_gdb_port_command)
3663 int retval = CALL_COMMAND_HANDLER(server_pipe_command, &gdb_port);
3664 if (retval == ERROR_OK) {
3665 free(gdb_port_next);
3666 gdb_port_next = strdup(gdb_port);
3671 COMMAND_HANDLER(handle_gdb_memory_map_command)
3674 return ERROR_COMMAND_SYNTAX_ERROR;
3676 COMMAND_PARSE_ENABLE(CMD_ARGV[0], gdb_use_memory_map);
3680 COMMAND_HANDLER(handle_gdb_flash_program_command)
3683 return ERROR_COMMAND_SYNTAX_ERROR;
3685 COMMAND_PARSE_ENABLE(CMD_ARGV[0], gdb_flash_program);
3689 COMMAND_HANDLER(handle_gdb_report_data_abort_command)
3692 return ERROR_COMMAND_SYNTAX_ERROR;
3694 COMMAND_PARSE_ENABLE(CMD_ARGV[0], gdb_report_data_abort);
3698 COMMAND_HANDLER(handle_gdb_report_register_access_error)
3701 return ERROR_COMMAND_SYNTAX_ERROR;
3703 COMMAND_PARSE_ENABLE(CMD_ARGV[0], gdb_report_register_access_error);
3707 /* gdb_breakpoint_override */
3708 COMMAND_HANDLER(handle_gdb_breakpoint_override_command)
3710 if (CMD_ARGC == 0) {
3712 } else if (CMD_ARGC == 1) {
3713 gdb_breakpoint_override = 1;
3714 if (strcmp(CMD_ARGV[0], "hard") == 0)
3715 gdb_breakpoint_override_type = BKPT_HARD;
3716 else if (strcmp(CMD_ARGV[0], "soft") == 0)
3717 gdb_breakpoint_override_type = BKPT_SOFT;
3718 else if (strcmp(CMD_ARGV[0], "disable") == 0)
3719 gdb_breakpoint_override = 0;
3721 return ERROR_COMMAND_SYNTAX_ERROR;
3722 if (gdb_breakpoint_override)
3723 LOG_USER("force %s breakpoints",
3724 (gdb_breakpoint_override_type == BKPT_HARD) ? "hard" : "soft");
3726 LOG_USER("breakpoint type is not overridden");
3731 COMMAND_HANDLER(handle_gdb_target_description_command)
3734 return ERROR_COMMAND_SYNTAX_ERROR;
3736 COMMAND_PARSE_ENABLE(CMD_ARGV[0], gdb_use_target_description);
3740 COMMAND_HANDLER(handle_gdb_save_tdesc_command)
3743 uint32_t tdesc_length;
3744 struct target *target = get_current_target(CMD_CTX);
3746 int retval = gdb_generate_target_description(target, &tdesc);
3747 if (retval != ERROR_OK) {
3748 LOG_ERROR("Unable to Generate Target Description");
3752 tdesc_length = strlen(tdesc);
3754 struct fileio *fileio;
3755 size_t size_written;
3757 char *tdesc_filename = alloc_printf("%s.xml", target_type_name(target));
3758 if (!tdesc_filename) {
3759 retval = ERROR_FAIL;
3763 retval = fileio_open(&fileio, tdesc_filename, FILEIO_WRITE, FILEIO_TEXT);
3765 if (retval != ERROR_OK) {
3766 LOG_ERROR("Can't open %s for writing", tdesc_filename);
3770 retval = fileio_write(fileio, tdesc_length, tdesc, &size_written);
3772 fileio_close(fileio);
3774 if (retval != ERROR_OK)
3775 LOG_ERROR("Error while writing the tdesc file");
3778 free(tdesc_filename);
3784 static const struct command_registration gdb_command_handlers[] = {
3787 .handler = handle_gdb_sync_command,
3788 .mode = COMMAND_ANY,
3789 .help = "next stepi will return immediately allowing "
3790 "GDB to fetch register state without affecting "
3796 .handler = handle_gdb_port_command,
3797 .mode = COMMAND_CONFIG,
3798 .help = "Normally gdb listens to a TCP/IP port. Each subsequent GDB "
3799 "server listens for the next port number after the "
3800 "base port number specified. "
3801 "No arguments reports GDB port. \"pipe\" means listen to stdin "
3802 "output to stdout, an integer is base port number, \"disabled\" disables "
3803 "port. Any other string is are interpreted as named pipe to listen to. "
3804 "Output pipe is the same name as input pipe, but with 'o' appended.",
3805 .usage = "[port_num]",
3808 .name = "gdb_memory_map",
3809 .handler = handle_gdb_memory_map_command,
3810 .mode = COMMAND_CONFIG,
3811 .help = "enable or disable memory map",
3812 .usage = "('enable'|'disable')"
3815 .name = "gdb_flash_program",
3816 .handler = handle_gdb_flash_program_command,
3817 .mode = COMMAND_CONFIG,
3818 .help = "enable or disable flash program",
3819 .usage = "('enable'|'disable')"
3822 .name = "gdb_report_data_abort",
3823 .handler = handle_gdb_report_data_abort_command,
3824 .mode = COMMAND_CONFIG,
3825 .help = "enable or disable reporting data aborts",
3826 .usage = "('enable'|'disable')"
3829 .name = "gdb_report_register_access_error",
3830 .handler = handle_gdb_report_register_access_error,
3831 .mode = COMMAND_CONFIG,
3832 .help = "enable or disable reporting register access errors",
3833 .usage = "('enable'|'disable')"
3836 .name = "gdb_breakpoint_override",
3837 .handler = handle_gdb_breakpoint_override_command,
3838 .mode = COMMAND_ANY,
3839 .help = "Display or specify type of breakpoint "
3840 "to be used by gdb 'break' commands.",
3841 .usage = "('hard'|'soft'|'disable')"
3844 .name = "gdb_target_description",
3845 .handler = handle_gdb_target_description_command,
3846 .mode = COMMAND_CONFIG,
3847 .help = "enable or disable target description",
3848 .usage = "('enable'|'disable')"
3851 .name = "gdb_save_tdesc",
3852 .handler = handle_gdb_save_tdesc_command,
3853 .mode = COMMAND_EXEC,
3854 .help = "Save the target description file",
3857 COMMAND_REGISTRATION_DONE
3860 int gdb_register_commands(struct command_context *cmd_ctx)
3862 gdb_port = strdup("3333");
3863 gdb_port_next = strdup("3333");
3864 return register_commands(cmd_ctx, NULL, gdb_command_handlers);
3867 void gdb_service_free(void)
3870 free(gdb_port_next);