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 enum gdb_output_flag {
65 /* GDB doesn't accept 'O' packets */
67 /* GDB accepts 'O' packets */
71 struct target_desc_format {
73 uint32_t tdesc_length;
76 /* private connection data for GDB */
77 struct gdb_connection {
78 char buffer[GDB_BUFFER_SIZE + 1]; /* Extra byte for null-termination */
82 enum target_state frontend_state;
83 struct image *vflash_image;
87 /* set flag to true if you want the next stepi to return immediately.
88 * allowing GDB to pick up a fresh set of register values from the target
89 * without modifying the target state. */
91 /* We delay reporting memory write errors until next step/continue or memory
92 * write. This improves performance of gdb load significantly as the GDB packet
93 * can be replied immediately and a new GDB packet will be ready without delay
94 * (ca. 10% or so...). */
96 /* with extended-remote it seems we need to better emulate attach/detach.
97 * what this means is we reply with a W stop reply after a kill packet,
98 * normally we reply with a S reply via gdb_last_signal_packet.
99 * as a side note this behaviour only effects gdb > 6.8 */
101 /* set when extended protocol is used */
102 bool extended_protocol;
103 /* temporarily used for target description support */
104 struct target_desc_format target_desc;
105 /* temporarily used for thread list support */
107 /* flag to mask the output from gdb_log_callback() */
108 enum gdb_output_flag output_flag;
112 #define _DEBUG_GDB_IO_
115 static struct gdb_connection *current_gdb_connection;
117 static int gdb_breakpoint_override;
118 static enum breakpoint_type gdb_breakpoint_override_type;
120 static int gdb_error(struct connection *connection, int retval);
121 static char *gdb_port;
122 static char *gdb_port_next;
124 static void gdb_log_callback(void *priv, const char *file, unsigned line,
125 const char *function, const char *string);
127 static void gdb_sig_halted(struct connection *connection);
129 /* number of gdb connections, mainly to suppress gdb related debugging spam
130 * in helper/log.c when no gdb connections are actually active */
131 int gdb_actual_connections;
133 /* set if we are sending a memory map to gdb
134 * via qXfer:memory-map:read packet */
135 /* enabled by default*/
136 static int gdb_use_memory_map = 1;
137 /* enabled by default*/
138 static int gdb_flash_program = 1;
140 /* if set, data aborts cause an error to be reported in memory read packets
141 * see the code in gdb_read_memory_packet() for further explanations.
142 * Disabled by default.
144 static int gdb_report_data_abort;
145 /* If set, errors when accessing registers are reported to gdb. Disabled by
147 static int gdb_report_register_access_error;
149 /* set if we are sending target descriptions to gdb
150 * via qXfer:features:read packet */
151 /* enabled by default */
152 static int gdb_use_target_description = 1;
154 /* current processing free-run type, used by file-I/O */
155 static char gdb_running_type;
157 static int gdb_last_signal(struct target *target)
159 switch (target->debug_reason) {
160 case DBG_REASON_DBGRQ:
161 return 0x2; /* SIGINT */
162 case DBG_REASON_BREAKPOINT:
163 case DBG_REASON_WATCHPOINT:
164 case DBG_REASON_WPTANDBKPT:
165 return 0x05; /* SIGTRAP */
166 case DBG_REASON_SINGLESTEP:
167 return 0x05; /* SIGTRAP */
168 case DBG_REASON_EXC_CATCH:
170 case DBG_REASON_NOTHALTED:
171 return 0x0; /* no signal... shouldn't happen */
173 LOG_USER("undefined debug reason %d - target needs reset",
174 target->debug_reason);
179 static int check_pending(struct connection *connection,
180 int timeout_s, int *got_data)
182 /* a non-blocking socket will block if there is 0 bytes available on the socket,
183 * but return with as many bytes as are available immediately
187 struct gdb_connection *gdb_con = connection->priv;
193 if (gdb_con->buf_cnt > 0) {
199 FD_SET(connection->fd, &read_fds);
201 tv.tv_sec = timeout_s;
203 if (socket_select(connection->fd + 1, &read_fds, NULL, NULL, &tv) == 0) {
204 /* This can typically be because a "monitor" command took too long
205 * before printing any progress messages
208 return ERROR_GDB_TIMEOUT;
212 *got_data = FD_ISSET(connection->fd, &read_fds) != 0;
216 static int gdb_get_char_inner(struct connection *connection, int *next_char)
218 struct gdb_connection *gdb_con = connection->priv;
219 int retval = ERROR_OK;
221 #ifdef _DEBUG_GDB_IO_
225 if (connection->service->type != CONNECTION_TCP)
226 gdb_con->buf_cnt = read(connection->fd, gdb_con->buffer, GDB_BUFFER_SIZE);
228 retval = check_pending(connection, 1, NULL);
229 if (retval != ERROR_OK)
231 gdb_con->buf_cnt = read_socket(connection->fd,
236 if (gdb_con->buf_cnt > 0)
238 if (gdb_con->buf_cnt == 0) {
239 LOG_DEBUG("GDB connection closed by the remote client");
240 gdb_con->closed = true;
241 return ERROR_SERVER_REMOTE_CLOSED;
245 errno = WSAGetLastError();
251 case WSAECONNABORTED:
252 gdb_con->closed = true;
253 return ERROR_SERVER_REMOTE_CLOSED;
255 gdb_con->closed = true;
256 return ERROR_SERVER_REMOTE_CLOSED;
258 LOG_ERROR("read: %d", errno);
267 gdb_con->closed = true;
268 return ERROR_SERVER_REMOTE_CLOSED;
270 gdb_con->closed = true;
271 return ERROR_SERVER_REMOTE_CLOSED;
273 LOG_ERROR("read: %s", strerror(errno));
274 gdb_con->closed = true;
275 return ERROR_SERVER_REMOTE_CLOSED;
280 #ifdef _DEBUG_GDB_IO_
281 debug_buffer = strndup(gdb_con->buffer, gdb_con->buf_cnt);
282 LOG_DEBUG("received '%s'", debug_buffer);
286 gdb_con->buf_p = gdb_con->buffer;
288 *next_char = *(gdb_con->buf_p++);
289 if (gdb_con->buf_cnt > 0)
290 connection->input_pending = true;
292 connection->input_pending = false;
293 #ifdef _DEBUG_GDB_IO_
294 LOG_DEBUG("returned char '%c' (0x%2.2x)", *next_char, *next_char);
301 * The cool thing about this fn is that it allows buf_p and buf_cnt to be
302 * held in registers in the inner loop.
304 * For small caches and embedded systems this is important!
306 static inline int gdb_get_char_fast(struct connection *connection,
307 int *next_char, char **buf_p, int *buf_cnt)
309 int retval = ERROR_OK;
311 if ((*buf_cnt)-- > 0) {
312 *next_char = **buf_p;
315 connection->input_pending = true;
317 connection->input_pending = false;
319 #ifdef _DEBUG_GDB_IO_
320 LOG_DEBUG("returned char '%c' (0x%2.2x)", *next_char, *next_char);
326 struct gdb_connection *gdb_con = connection->priv;
327 gdb_con->buf_p = *buf_p;
328 gdb_con->buf_cnt = *buf_cnt;
329 retval = gdb_get_char_inner(connection, next_char);
330 *buf_p = gdb_con->buf_p;
331 *buf_cnt = gdb_con->buf_cnt;
336 static int gdb_get_char(struct connection *connection, int *next_char)
338 struct gdb_connection *gdb_con = connection->priv;
339 return gdb_get_char_fast(connection, next_char, &gdb_con->buf_p, &gdb_con->buf_cnt);
342 static int gdb_putback_char(struct connection *connection, int last_char)
344 struct gdb_connection *gdb_con = connection->priv;
346 if (gdb_con->buf_p > gdb_con->buffer) {
347 *(--gdb_con->buf_p) = last_char;
350 LOG_ERROR("BUG: couldn't put character back");
355 /* The only way we can detect that the socket is closed is the first time
356 * we write to it, we will fail. Subsequent write operations will
357 * succeed. Shudder! */
358 static int gdb_write(struct connection *connection, void *data, int len)
360 struct gdb_connection *gdb_con = connection->priv;
361 if (gdb_con->closed) {
362 LOG_DEBUG("GDB socket marked as closed, cannot write to it.");
363 return ERROR_SERVER_REMOTE_CLOSED;
366 if (connection_write(connection, data, len) == len)
369 LOG_WARNING("Error writing to GDB socket. Dropping the connection.");
370 gdb_con->closed = true;
371 return ERROR_SERVER_REMOTE_CLOSED;
374 static void gdb_log_incoming_packet(char *packet)
376 if (!LOG_LEVEL_IS(LOG_LVL_DEBUG))
379 /* Avoid dumping non-printable characters to the terminal */
380 const unsigned packet_len = strlen(packet);
381 const char *nonprint = find_nonprint_char(packet, packet_len);
383 /* Does packet at least have a prefix that is printable?
384 * Look within the first 50 chars of the packet. */
385 const char *colon = memchr(packet, ':', MIN(50, packet_len));
386 const bool packet_has_prefix = (colon);
387 const bool packet_prefix_printable = (packet_has_prefix && nonprint > colon);
389 if (packet_prefix_printable) {
390 const unsigned int prefix_len = colon - packet + 1; /* + 1 to include the ':' */
391 const unsigned int payload_len = packet_len - prefix_len;
392 LOG_DEBUG("received packet: %.*s<binary-data-%u-bytes>", prefix_len, packet, payload_len);
394 LOG_DEBUG("received packet: <binary-data-%u-bytes>", packet_len);
397 /* All chars printable, dump the packet as is */
398 LOG_DEBUG("received packet: %s", packet);
402 static void gdb_log_outgoing_packet(char *packet_buf, unsigned int packet_len, unsigned char checksum)
404 if (!LOG_LEVEL_IS(LOG_LVL_DEBUG))
407 if (find_nonprint_char(packet_buf, packet_len))
408 LOG_DEBUG("sending packet: $<binary-data-%u-bytes>#%2.2x", packet_len, checksum);
410 LOG_DEBUG("sending packet: $%.*s#%2.2x'", packet_len, packet_buf, checksum);
413 static int gdb_put_packet_inner(struct connection *connection,
414 char *buffer, int len)
417 unsigned char my_checksum = 0;
420 struct gdb_connection *gdb_con = connection->priv;
422 for (i = 0; i < len; i++)
423 my_checksum += buffer[i];
425 #ifdef _DEBUG_GDB_IO_
427 * At this point we should have nothing in the input queue from GDB,
428 * however sometimes '-' is sent even though we've already received
429 * an ACK (+) for everything we've sent off.
433 retval = check_pending(connection, 0, &gotdata);
434 if (retval != ERROR_OK)
438 retval = gdb_get_char(connection, &reply);
439 if (retval != ERROR_OK)
442 /* fix a problem with some IAR tools */
443 gdb_putback_char(connection, reply);
444 LOG_DEBUG("Unexpected start of new packet");
448 LOG_WARNING("Discard unexpected char %c", reply);
453 gdb_log_outgoing_packet(buffer, len, my_checksum);
455 char local_buffer[1024];
456 local_buffer[0] = '$';
457 if ((size_t)len + 4 <= sizeof(local_buffer)) {
458 /* performance gain on smaller packets by only a single call to gdb_write() */
459 memcpy(local_buffer + 1, buffer, len++);
460 len += snprintf(local_buffer + len, sizeof(local_buffer) - len, "#%02x", my_checksum);
461 retval = gdb_write(connection, local_buffer, len);
462 if (retval != ERROR_OK)
465 /* larger packets are transmitted directly from caller supplied buffer
466 * by several calls to gdb_write() to avoid dynamic allocation */
467 snprintf(local_buffer + 1, sizeof(local_buffer) - 1, "#%02x", my_checksum);
468 retval = gdb_write(connection, local_buffer, 1);
469 if (retval != ERROR_OK)
471 retval = gdb_write(connection, buffer, len);
472 if (retval != ERROR_OK)
474 retval = gdb_write(connection, local_buffer + 1, 3);
475 if (retval != ERROR_OK)
479 if (gdb_con->noack_mode)
482 retval = gdb_get_char(connection, &reply);
483 if (retval != ERROR_OK)
488 else if (reply == '-') {
489 /* Stop sending output packets for now */
490 gdb_con->output_flag = GDB_OUTPUT_NO;
491 LOG_WARNING("negative reply, retrying");
492 } else if (reply == 0x3) {
493 gdb_con->ctrl_c = true;
494 retval = gdb_get_char(connection, &reply);
495 if (retval != ERROR_OK)
499 else if (reply == '-') {
500 /* Stop sending output packets for now */
501 gdb_con->output_flag = GDB_OUTPUT_NO;
502 LOG_WARNING("negative reply, retrying");
503 } else if (reply == '$') {
504 LOG_ERROR("GDB missing ack(1) - assumed good");
505 gdb_putback_char(connection, reply);
508 LOG_ERROR("unknown character(1) 0x%2.2x in reply, dropping connection", reply);
509 gdb_con->closed = true;
510 return ERROR_SERVER_REMOTE_CLOSED;
512 } else if (reply == '$') {
513 LOG_ERROR("GDB missing ack(2) - assumed good");
514 gdb_putback_char(connection, reply);
517 LOG_ERROR("unknown character(2) 0x%2.2x in reply, dropping connection",
519 gdb_con->closed = true;
520 return ERROR_SERVER_REMOTE_CLOSED;
524 return ERROR_SERVER_REMOTE_CLOSED;
529 int gdb_put_packet(struct connection *connection, char *buffer, int len)
531 struct gdb_connection *gdb_con = connection->priv;
532 gdb_con->busy = true;
533 int retval = gdb_put_packet_inner(connection, buffer, len);
534 gdb_con->busy = false;
536 /* we sent some data, reset timer for keep alive messages */
542 static inline int fetch_packet(struct connection *connection,
543 int *checksum_ok, int noack, int *len, char *buffer)
545 unsigned char my_checksum = 0;
548 int retval = ERROR_OK;
550 struct gdb_connection *gdb_con = connection->priv;
555 /* move this over into local variables to use registers and give the
556 * more freedom to optimize */
557 char *buf_p = gdb_con->buf_p;
558 int buf_cnt = gdb_con->buf_cnt;
561 /* The common case is that we have an entire packet with no escape chars.
562 * We need to leave at least 2 bytes in the buffer to have
563 * gdb_get_char() update various bits and bobs correctly.
565 if ((buf_cnt > 2) && ((buf_cnt + count) < *len)) {
566 /* The compiler will struggle a bit with constant propagation and
567 * aliasing, so we help it by showing that these values do not
568 * change inside the loop
572 int run = buf_cnt - 2;
578 if (character == '#') {
579 /* Danger! character can be '#' when esc is
580 * used so we need an explicit boolean for done here. */
585 if (character == '}') {
586 /* data transmitted in binary mode (X packet)
587 * uses 0x7d as escape character */
588 my_checksum += character & 0xff;
591 my_checksum += character & 0xff;
592 buffer[count++] = (character ^ 0x20) & 0xff;
594 my_checksum += character & 0xff;
595 buffer[count++] = character & 0xff;
604 LOG_ERROR("packet buffer too small");
605 retval = ERROR_GDB_BUFFER_TOO_SMALL;
609 retval = gdb_get_char_fast(connection, &character, &buf_p, &buf_cnt);
610 if (retval != ERROR_OK)
613 if (character == '#')
616 if (character == '}') {
617 /* data transmitted in binary mode (X packet)
618 * uses 0x7d as escape character */
619 my_checksum += character & 0xff;
621 retval = gdb_get_char_fast(connection, &character, &buf_p, &buf_cnt);
622 if (retval != ERROR_OK)
625 my_checksum += character & 0xff;
626 buffer[count++] = (character ^ 0x20) & 0xff;
628 my_checksum += character & 0xff;
629 buffer[count++] = character & 0xff;
633 gdb_con->buf_p = buf_p;
634 gdb_con->buf_cnt = buf_cnt;
636 if (retval != ERROR_OK)
641 retval = gdb_get_char(connection, &character);
642 if (retval != ERROR_OK)
644 checksum[0] = character;
645 retval = gdb_get_char(connection, &character);
646 if (retval != ERROR_OK)
648 checksum[1] = character;
652 *checksum_ok = (my_checksum == strtoul(checksum, NULL, 16));
657 static int gdb_get_packet_inner(struct connection *connection,
658 char *buffer, int *len)
662 struct gdb_connection *gdb_con = connection->priv;
666 retval = gdb_get_char(connection, &character);
667 if (retval != ERROR_OK)
670 #ifdef _DEBUG_GDB_IO_
671 LOG_DEBUG("character: '%c'", character);
678 /* According to the GDB documentation
679 * (https://sourceware.org/gdb/onlinedocs/gdb/Packet-Acknowledgment.html):
680 * "gdb sends a final `+` acknowledgment of the stub's `OK`
681 * response, which can be safely ignored by the stub."
682 * However OpenOCD server already is in noack mode at this
683 * point and instead of ignoring this it was emitting a
684 * warning. This code makes server ignore the first ACK
685 * that will be received after going into noack mode,
686 * warning only about subsequent ACK's. */
687 if (gdb_con->noack_mode > 1) {
688 LOG_WARNING("acknowledgment received, but no packet pending");
689 } else if (gdb_con->noack_mode) {
690 LOG_DEBUG("Received first acknowledgment after entering noack mode. Ignoring it.");
691 gdb_con->noack_mode = 2;
695 LOG_WARNING("negative acknowledgment, but no packet pending");
698 gdb_con->ctrl_c = true;
702 LOG_WARNING("ignoring character 0x%x", character);
705 } while (character != '$');
708 /* explicit code expansion here to get faster inlined code in -O3 by not
709 * calculating checksum */
710 if (gdb_con->noack_mode) {
711 retval = fetch_packet(connection, &checksum_ok, 1, len, buffer);
712 if (retval != ERROR_OK)
715 retval = fetch_packet(connection, &checksum_ok, 0, len, buffer);
716 if (retval != ERROR_OK)
720 if (gdb_con->noack_mode) {
721 /* checksum is not checked in noack mode */
725 retval = gdb_write(connection, "+", 1);
726 if (retval != ERROR_OK)
732 return ERROR_SERVER_REMOTE_CLOSED;
737 static int gdb_get_packet(struct connection *connection, char *buffer, int *len)
739 struct gdb_connection *gdb_con = connection->priv;
740 gdb_con->busy = true;
741 int retval = gdb_get_packet_inner(connection, buffer, len);
742 gdb_con->busy = false;
746 static int gdb_output_con(struct connection *connection, const char *line)
751 bin_size = strlen(line);
753 hex_buffer = malloc(bin_size * 2 + 2);
755 return ERROR_GDB_BUFFER_TOO_SMALL;
758 size_t pkt_len = hexify(hex_buffer + 1, (const uint8_t *)line, bin_size,
760 int retval = gdb_put_packet(connection, hex_buffer, pkt_len + 1);
766 static int gdb_output(struct command_context *context, const char *line)
768 /* this will be dumped to the log and also sent as an O packet if possible */
769 LOG_USER_N("%s", line);
773 static void gdb_signal_reply(struct target *target, struct connection *connection)
775 struct gdb_connection *gdb_connection = connection->priv;
777 char stop_reason[32];
778 char current_thread[25];
782 rtos_update_threads(target);
784 if (target->debug_reason == DBG_REASON_EXIT) {
785 sig_reply_len = snprintf(sig_reply, sizeof(sig_reply), "W00");
789 target->rtos->current_threadid = target->rtos->current_thread;
790 target->rtos->gdb_target_for_threadid(connection, target->rtos->current_threadid, &ct);
795 if (gdb_connection->ctrl_c) {
798 signal_var = gdb_last_signal(ct);
800 stop_reason[0] = '\0';
801 if (ct->debug_reason == DBG_REASON_WATCHPOINT) {
802 enum watchpoint_rw hit_wp_type;
803 target_addr_t hit_wp_address;
805 if (watchpoint_hit(ct, &hit_wp_type, &hit_wp_address) == ERROR_OK) {
807 switch (hit_wp_type) {
809 snprintf(stop_reason, sizeof(stop_reason),
810 "watch:%08" TARGET_PRIxADDR ";", hit_wp_address);
813 snprintf(stop_reason, sizeof(stop_reason),
814 "rwatch:%08" TARGET_PRIxADDR ";", hit_wp_address);
817 snprintf(stop_reason, sizeof(stop_reason),
818 "awatch:%08" TARGET_PRIxADDR ";", hit_wp_address);
826 current_thread[0] = '\0';
828 snprintf(current_thread, sizeof(current_thread), "thread:%" PRIx64 ";",
829 target->rtos->current_thread);
831 sig_reply_len = snprintf(sig_reply, sizeof(sig_reply), "T%2.2x%s%s",
832 signal_var, stop_reason, current_thread);
834 gdb_connection->ctrl_c = false;
837 gdb_put_packet(connection, sig_reply, sig_reply_len);
838 gdb_connection->frontend_state = TARGET_HALTED;
841 static void gdb_fileio_reply(struct target *target, struct connection *connection)
843 struct gdb_connection *gdb_connection = connection->priv;
844 char fileio_command[256];
846 bool program_exited = false;
848 if (strcmp(target->fileio_info->identifier, "open") == 0)
849 sprintf(fileio_command, "F%s,%" PRIx64 "/%" PRIx64 ",%" PRIx64 ",%" PRIx64, target->fileio_info->identifier,
850 target->fileio_info->param_1,
851 target->fileio_info->param_2 + 1, /* len + trailing zero */
852 target->fileio_info->param_3,
853 target->fileio_info->param_4);
854 else if (strcmp(target->fileio_info->identifier, "close") == 0)
855 sprintf(fileio_command, "F%s,%" PRIx64, target->fileio_info->identifier,
856 target->fileio_info->param_1);
857 else if (strcmp(target->fileio_info->identifier, "read") == 0)
858 sprintf(fileio_command, "F%s,%" PRIx64 ",%" PRIx64 ",%" PRIx64, target->fileio_info->identifier,
859 target->fileio_info->param_1,
860 target->fileio_info->param_2,
861 target->fileio_info->param_3);
862 else if (strcmp(target->fileio_info->identifier, "write") == 0)
863 sprintf(fileio_command, "F%s,%" PRIx64 ",%" PRIx64 ",%" PRIx64, target->fileio_info->identifier,
864 target->fileio_info->param_1,
865 target->fileio_info->param_2,
866 target->fileio_info->param_3);
867 else if (strcmp(target->fileio_info->identifier, "lseek") == 0)
868 sprintf(fileio_command, "F%s,%" PRIx64 ",%" PRIx64 ",%" PRIx64, target->fileio_info->identifier,
869 target->fileio_info->param_1,
870 target->fileio_info->param_2,
871 target->fileio_info->param_3);
872 else if (strcmp(target->fileio_info->identifier, "rename") == 0)
873 sprintf(fileio_command, "F%s,%" PRIx64 "/%" PRIx64 ",%" PRIx64 "/%" PRIx64, target->fileio_info->identifier,
874 target->fileio_info->param_1,
875 target->fileio_info->param_2 + 1, /* len + trailing zero */
876 target->fileio_info->param_3,
877 target->fileio_info->param_4 + 1); /* len + trailing zero */
878 else if (strcmp(target->fileio_info->identifier, "unlink") == 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 + 1); /* len + trailing zero */
882 else if (strcmp(target->fileio_info->identifier, "stat") == 0)
883 sprintf(fileio_command, "F%s,%" PRIx64 "/%" PRIx64 ",%" PRIx64, target->fileio_info->identifier,
884 target->fileio_info->param_1,
885 target->fileio_info->param_2,
886 target->fileio_info->param_3);
887 else if (strcmp(target->fileio_info->identifier, "fstat") == 0)
888 sprintf(fileio_command, "F%s,%" PRIx64 ",%" PRIx64, target->fileio_info->identifier,
889 target->fileio_info->param_1,
890 target->fileio_info->param_2);
891 else if (strcmp(target->fileio_info->identifier, "gettimeofday") == 0)
892 sprintf(fileio_command, "F%s,%" PRIx64 ",%" PRIx64, target->fileio_info->identifier,
893 target->fileio_info->param_1,
894 target->fileio_info->param_2);
895 else if (strcmp(target->fileio_info->identifier, "isatty") == 0)
896 sprintf(fileio_command, "F%s,%" PRIx64, target->fileio_info->identifier,
897 target->fileio_info->param_1);
898 else if (strcmp(target->fileio_info->identifier, "system") == 0)
899 sprintf(fileio_command, "F%s,%" PRIx64 "/%" PRIx64, target->fileio_info->identifier,
900 target->fileio_info->param_1,
901 target->fileio_info->param_2 + 1); /* len + trailing zero */
902 else if (strcmp(target->fileio_info->identifier, "exit") == 0) {
903 /* If target hits exit syscall, report to GDB the program is terminated.
904 * In addition, let target run its own exit syscall handler. */
905 program_exited = true;
906 sprintf(fileio_command, "W%02" PRIx64, target->fileio_info->param_1);
908 LOG_DEBUG("Unknown syscall: %s", target->fileio_info->identifier);
910 /* encounter unknown syscall, continue */
911 gdb_connection->frontend_state = TARGET_RUNNING;
912 target_resume(target, 1, 0x0, 0, 0);
916 command_len = strlen(fileio_command);
917 gdb_put_packet(connection, fileio_command, command_len);
919 if (program_exited) {
920 /* Use target_resume() to let target run its own exit syscall handler. */
921 gdb_connection->frontend_state = TARGET_RUNNING;
922 target_resume(target, 1, 0x0, 0, 0);
924 gdb_connection->frontend_state = TARGET_HALTED;
925 rtos_update_threads(target);
929 static void gdb_frontend_halted(struct target *target, struct connection *connection)
931 struct gdb_connection *gdb_connection = connection->priv;
933 /* In the GDB protocol when we are stepping or continuing execution,
934 * we have a lingering reply. Upon receiving a halted event
935 * when we have that lingering packet, we reply to the original
936 * step or continue packet.
938 * Executing monitor commands can bring the target in and
939 * out of the running state so we'll see lots of TARGET_EVENT_XXX
940 * that are to be ignored.
942 if (gdb_connection->frontend_state == TARGET_RUNNING) {
943 /* stop forwarding log packets! */
944 gdb_connection->output_flag = GDB_OUTPUT_NO;
946 /* check fileio first */
947 if (target_get_gdb_fileio_info(target, target->fileio_info) == ERROR_OK)
948 gdb_fileio_reply(target, connection);
950 gdb_signal_reply(target, connection);
954 static int gdb_target_callback_event_handler(struct target *target,
955 enum target_event event, void *priv)
957 struct connection *connection = priv;
958 struct gdb_service *gdb_service = connection->service->priv;
960 if (gdb_service->target != target)
964 case TARGET_EVENT_GDB_HALT:
965 gdb_frontend_halted(target, connection);
967 case TARGET_EVENT_HALTED:
968 target_call_event_callbacks(target, TARGET_EVENT_GDB_END);
977 static int gdb_new_connection(struct connection *connection)
979 struct gdb_connection *gdb_connection = malloc(sizeof(struct gdb_connection));
980 struct target *target;
984 target = get_target_from_connection(connection);
985 connection->priv = gdb_connection;
986 connection->cmd_ctx->current_target = target;
988 /* initialize gdb connection information */
989 gdb_connection->buf_p = gdb_connection->buffer;
990 gdb_connection->buf_cnt = 0;
991 gdb_connection->ctrl_c = false;
992 gdb_connection->frontend_state = TARGET_HALTED;
993 gdb_connection->vflash_image = NULL;
994 gdb_connection->closed = false;
995 gdb_connection->busy = false;
996 gdb_connection->noack_mode = 0;
997 gdb_connection->sync = false;
998 gdb_connection->mem_write_error = false;
999 gdb_connection->attached = true;
1000 gdb_connection->extended_protocol = false;
1001 gdb_connection->target_desc.tdesc = NULL;
1002 gdb_connection->target_desc.tdesc_length = 0;
1003 gdb_connection->thread_list = NULL;
1004 gdb_connection->output_flag = GDB_OUTPUT_NO;
1006 /* send ACK to GDB for debug request */
1007 gdb_write(connection, "+", 1);
1009 /* output goes through gdb connection */
1010 command_set_output_handler(connection->cmd_ctx, gdb_output, connection);
1012 /* we must remove all breakpoints registered to the target as a previous
1013 * GDB session could leave dangling breakpoints if e.g. communication
1016 breakpoint_clear_target(target);
1017 watchpoint_clear_target(target);
1019 /* Since version 3.95 (gdb-19990504), with the exclusion of 6.5~6.8, GDB
1020 * sends an ACK at connection with the following comment in its source code:
1021 * "Ack any packet which the remote side has already sent."
1022 * LLDB does the same since the first gdb-remote implementation.
1023 * Remove the initial ACK from the incoming buffer.
1025 retval = gdb_get_char(connection, &initial_ack);
1026 if (retval != ERROR_OK)
1029 if (initial_ack != '+')
1030 gdb_putback_char(connection, initial_ack);
1032 target_call_event_callbacks(target, TARGET_EVENT_GDB_ATTACH);
1035 /* clean previous rtos session if supported*/
1036 if (target->rtos->type->clean)
1037 target->rtos->type->clean(target);
1039 /* update threads */
1040 rtos_update_threads(target);
1043 if (gdb_use_memory_map) {
1044 /* Connect must fail if the memory map can't be set up correctly.
1046 * This will cause an auto_probe to be invoked, which is either
1047 * a no-op or it will fail when the target isn't ready(e.g. not halted).
1049 for (unsigned int i = 0; i < flash_get_bank_count(); i++) {
1050 struct flash_bank *p;
1051 p = get_flash_bank_by_num_noprobe(i);
1052 if (p->target != target)
1054 retval = get_flash_bank_by_num(i, &p);
1055 if (retval != ERROR_OK) {
1056 LOG_ERROR("Connect failed. Consider setting up a gdb-attach event for the target "
1057 "to prepare target for GDB connect, or use 'gdb_memory_map disable'.");
1063 gdb_actual_connections++;
1064 log_printf_lf(all_targets->next ? LOG_LVL_INFO : LOG_LVL_DEBUG,
1065 __FILE__, __LINE__, __func__,
1066 "New GDB Connection: %d, Target %s, state: %s",
1067 gdb_actual_connections,
1068 target_name(target),
1069 target_state_name(target));
1071 if (!target_was_examined(target)) {
1072 LOG_ERROR("Target %s not examined yet, refuse gdb connection %d!",
1073 target_name(target), gdb_actual_connections);
1074 gdb_actual_connections--;
1075 return ERROR_TARGET_NOT_EXAMINED;
1078 if (target->state != TARGET_HALTED)
1079 LOG_WARNING("GDB connection %d on target %s not halted",
1080 gdb_actual_connections, target_name(target));
1082 /* DANGER! If we fail subsequently, we must remove this handler,
1083 * otherwise we occasionally see crashes as the timer can invoke the
1086 * register callback to be informed about target events */
1087 target_register_event_callback(gdb_target_callback_event_handler, connection);
1089 log_add_callback(gdb_log_callback, connection);
1094 static int gdb_connection_closed(struct connection *connection)
1096 struct target *target;
1097 struct gdb_connection *gdb_connection = connection->priv;
1099 target = get_target_from_connection(connection);
1101 /* we're done forwarding messages. Tear down callback before
1102 * cleaning up connection.
1104 log_remove_callback(gdb_log_callback, connection);
1106 gdb_actual_connections--;
1107 LOG_DEBUG("GDB Close, Target: %s, state: %s, gdb_actual_connections=%d",
1108 target_name(target),
1109 target_state_name(target),
1110 gdb_actual_connections);
1112 /* see if an image built with vFlash commands is left */
1113 if (gdb_connection->vflash_image) {
1114 image_close(gdb_connection->vflash_image);
1115 free(gdb_connection->vflash_image);
1116 gdb_connection->vflash_image = NULL;
1119 /* if this connection registered a debug-message receiver delete it */
1120 delete_debug_msg_receiver(connection->cmd_ctx, target);
1122 free(connection->priv);
1123 connection->priv = NULL;
1125 target_unregister_event_callback(gdb_target_callback_event_handler, connection);
1127 target_call_event_callbacks(target, TARGET_EVENT_GDB_END);
1129 target_call_event_callbacks(target, TARGET_EVENT_GDB_DETACH);
1134 static void gdb_send_error(struct connection *connection, uint8_t the_error)
1137 snprintf(err, 4, "E%2.2X", the_error);
1138 gdb_put_packet(connection, err, 3);
1141 static int gdb_last_signal_packet(struct connection *connection,
1142 char const *packet, int packet_size)
1144 struct target *target = get_target_from_connection(connection);
1145 struct gdb_connection *gdb_con = connection->priv;
1149 if (!gdb_con->attached) {
1150 /* if we are here we have received a kill packet
1151 * reply W stop reply otherwise gdb gets very unhappy */
1152 gdb_put_packet(connection, "W00", 3);
1156 signal_var = gdb_last_signal(target);
1158 snprintf(sig_reply, 4, "S%2.2x", signal_var);
1159 gdb_put_packet(connection, sig_reply, 3);
1164 static inline int gdb_reg_pos(struct target *target, int pos, int len)
1166 if (target->endianness == TARGET_LITTLE_ENDIAN)
1169 return len - 1 - pos;
1172 /* Convert register to string of bytes. NB! The # of bits in the
1173 * register might be non-divisible by 8(a byte), in which
1174 * case an entire byte is shown.
1176 * NB! the format on the wire is the target endianness
1178 * The format of reg->value is little endian
1181 static void gdb_str_to_target(struct target *target,
1182 char *tstr, struct reg *reg)
1189 buf_len = DIV_ROUND_UP(reg->size, 8);
1191 for (i = 0; i < buf_len; i++) {
1192 int j = gdb_reg_pos(target, i, buf_len);
1193 tstr += sprintf(tstr, "%02x", buf[j]);
1197 /* copy over in register buffer */
1198 static void gdb_target_to_reg(struct target *target,
1199 char const *tstr, int str_len, uint8_t *bin)
1202 LOG_ERROR("BUG: gdb value with uneven number of characters encountered");
1207 for (i = 0; i < str_len; i += 2) {
1209 if (sscanf(tstr + i, "%02x", &t) != 1) {
1210 LOG_ERROR("BUG: unable to convert register value");
1214 int j = gdb_reg_pos(target, i/2, str_len/2);
1219 static int gdb_get_registers_packet(struct connection *connection,
1220 char const *packet, int packet_size)
1222 struct target *target = get_target_from_connection(connection);
1223 struct reg **reg_list;
1226 int reg_packet_size = 0;
1231 #ifdef _DEBUG_GDB_IO_
1235 if ((target->rtos) && (rtos_get_gdb_reg_list(connection) == ERROR_OK))
1238 retval = target_get_gdb_reg_list(target, ®_list, ®_list_size,
1240 if (retval != ERROR_OK)
1241 return gdb_error(connection, retval);
1243 for (i = 0; i < reg_list_size; i++) {
1244 if (!reg_list[i] || reg_list[i]->exist == false || reg_list[i]->hidden)
1246 reg_packet_size += DIV_ROUND_UP(reg_list[i]->size, 8) * 2;
1249 assert(reg_packet_size > 0);
1251 reg_packet = malloc(reg_packet_size + 1); /* plus one for string termination null */
1255 reg_packet_p = reg_packet;
1257 for (i = 0; i < reg_list_size; i++) {
1258 if (!reg_list[i] || reg_list[i]->exist == false || reg_list[i]->hidden)
1260 if (!reg_list[i]->valid) {
1261 retval = reg_list[i]->type->get(reg_list[i]);
1262 if (retval != ERROR_OK && gdb_report_register_access_error) {
1263 LOG_DEBUG("Couldn't get register %s.", reg_list[i]->name);
1266 return gdb_error(connection, retval);
1269 gdb_str_to_target(target, reg_packet_p, reg_list[i]);
1270 reg_packet_p += DIV_ROUND_UP(reg_list[i]->size, 8) * 2;
1273 #ifdef _DEBUG_GDB_IO_
1275 char *reg_packet_p_debug;
1276 reg_packet_p_debug = strndup(reg_packet, reg_packet_size);
1277 LOG_DEBUG("reg_packet: %s", reg_packet_p_debug);
1278 free(reg_packet_p_debug);
1282 gdb_put_packet(connection, reg_packet, reg_packet_size);
1290 static int gdb_set_registers_packet(struct connection *connection,
1291 char const *packet, int packet_size)
1293 struct target *target = get_target_from_connection(connection);
1295 struct reg **reg_list;
1298 char const *packet_p;
1300 #ifdef _DEBUG_GDB_IO_
1304 /* skip command character */
1308 if (packet_size % 2) {
1309 LOG_WARNING("GDB set_registers packet with uneven characters received, dropping connection");
1310 return ERROR_SERVER_REMOTE_CLOSED;
1313 retval = target_get_gdb_reg_list(target, ®_list, ®_list_size,
1315 if (retval != ERROR_OK)
1316 return gdb_error(connection, retval);
1319 for (i = 0; i < reg_list_size; i++) {
1321 int chars = (DIV_ROUND_UP(reg_list[i]->size, 8) * 2);
1323 if (packet_p + chars > packet + packet_size)
1324 LOG_ERROR("BUG: register packet is too small for registers");
1326 bin_buf = malloc(DIV_ROUND_UP(reg_list[i]->size, 8));
1327 gdb_target_to_reg(target, packet_p, chars, bin_buf);
1329 retval = reg_list[i]->type->set(reg_list[i], bin_buf);
1330 if (retval != ERROR_OK && gdb_report_register_access_error) {
1331 LOG_DEBUG("Couldn't set register %s.", reg_list[i]->name);
1334 return gdb_error(connection, retval);
1337 /* advance packet pointer */
1343 /* free struct reg *reg_list[] array allocated by get_gdb_reg_list */
1346 gdb_put_packet(connection, "OK", 2);
1351 static int gdb_get_register_packet(struct connection *connection,
1352 char const *packet, int packet_size)
1354 struct target *target = get_target_from_connection(connection);
1356 int reg_num = strtoul(packet + 1, NULL, 16);
1357 struct reg **reg_list;
1361 #ifdef _DEBUG_GDB_IO_
1365 if ((target->rtos) && (rtos_get_gdb_reg(connection, reg_num) == ERROR_OK))
1368 retval = target_get_gdb_reg_list_noread(target, ®_list, ®_list_size,
1370 if (retval != ERROR_OK)
1371 return gdb_error(connection, retval);
1373 if (reg_list_size <= reg_num) {
1374 LOG_ERROR("gdb requested a non-existing register (reg_num=%d)", reg_num);
1375 return ERROR_SERVER_REMOTE_CLOSED;
1378 if (!reg_list[reg_num]->valid) {
1379 retval = reg_list[reg_num]->type->get(reg_list[reg_num]);
1380 if (retval != ERROR_OK && gdb_report_register_access_error) {
1381 LOG_DEBUG("Couldn't get register %s.", reg_list[reg_num]->name);
1383 return gdb_error(connection, retval);
1387 reg_packet = calloc(DIV_ROUND_UP(reg_list[reg_num]->size, 8) * 2 + 1, 1); /* plus one for string termination null */
1389 gdb_str_to_target(target, reg_packet, reg_list[reg_num]);
1391 gdb_put_packet(connection, reg_packet, DIV_ROUND_UP(reg_list[reg_num]->size, 8) * 2);
1399 static int gdb_set_register_packet(struct connection *connection,
1400 char const *packet, int packet_size)
1402 struct target *target = get_target_from_connection(connection);
1404 int reg_num = strtoul(packet + 1, &separator, 16);
1405 struct reg **reg_list;
1409 #ifdef _DEBUG_GDB_IO_
1413 if (*separator != '=') {
1414 LOG_ERROR("GDB 'set register packet', but no '=' following the register number");
1415 return ERROR_SERVER_REMOTE_CLOSED;
1417 size_t chars = strlen(separator + 1);
1418 uint8_t *bin_buf = malloc(chars / 2);
1419 gdb_target_to_reg(target, separator + 1, chars, bin_buf);
1421 if ((target->rtos) &&
1422 (rtos_set_reg(connection, reg_num, bin_buf) == ERROR_OK)) {
1424 gdb_put_packet(connection, "OK", 2);
1428 retval = target_get_gdb_reg_list_noread(target, ®_list, ®_list_size,
1430 if (retval != ERROR_OK) {
1432 return gdb_error(connection, retval);
1435 if (reg_list_size <= reg_num) {
1436 LOG_ERROR("gdb requested a non-existing register (reg_num=%d)", reg_num);
1439 return ERROR_SERVER_REMOTE_CLOSED;
1442 if (chars != (DIV_ROUND_UP(reg_list[reg_num]->size, 8) * 2)) {
1443 LOG_ERROR("gdb sent %zu bits for a %" PRIu32 "-bit register (%s)",
1444 chars * 4, reg_list[reg_num]->size, reg_list[reg_num]->name);
1447 return ERROR_SERVER_REMOTE_CLOSED;
1450 gdb_target_to_reg(target, separator + 1, chars, bin_buf);
1452 retval = reg_list[reg_num]->type->set(reg_list[reg_num], bin_buf);
1453 if (retval != ERROR_OK && gdb_report_register_access_error) {
1454 LOG_DEBUG("Couldn't set register %s.", reg_list[reg_num]->name);
1457 return gdb_error(connection, retval);
1460 gdb_put_packet(connection, "OK", 2);
1468 /* No attempt is made to translate the "retval" to
1469 * GDB speak. This has to be done at the calling
1470 * site as no mapping really exists.
1472 static int gdb_error(struct connection *connection, int retval)
1474 LOG_DEBUG("Reporting %i to GDB as generic error", retval);
1475 gdb_send_error(connection, EFAULT);
1479 /* We don't have to worry about the default 2 second timeout for GDB packets,
1480 * because GDB breaks up large memory reads into smaller reads.
1482 static int gdb_read_memory_packet(struct connection *connection,
1483 char const *packet, int packet_size)
1485 struct target *target = get_target_from_connection(connection);
1493 int retval = ERROR_OK;
1495 /* skip command character */
1498 addr = strtoull(packet, &separator, 16);
1500 if (*separator != ',') {
1501 LOG_ERROR("incomplete read memory packet received, dropping connection");
1502 return ERROR_SERVER_REMOTE_CLOSED;
1505 len = strtoul(separator + 1, NULL, 16);
1508 LOG_WARNING("invalid read memory packet received (len == 0)");
1509 gdb_put_packet(connection, "", 0);
1513 buffer = malloc(len);
1515 LOG_DEBUG("addr: 0x%16.16" PRIx64 ", len: 0x%8.8" PRIx32 "", addr, len);
1517 retval = ERROR_NOT_IMPLEMENTED;
1519 retval = rtos_read_buffer(target, addr, len, buffer);
1520 if (retval == ERROR_NOT_IMPLEMENTED)
1521 retval = target_read_buffer(target, addr, len, buffer);
1523 if ((retval != ERROR_OK) && !gdb_report_data_abort) {
1524 /* TODO : Here we have to lie and send back all zero's lest stack traces won't work.
1525 * At some point this might be fixed in GDB, in which case this code can be removed.
1527 * OpenOCD developers are acutely aware of this problem, but there is nothing
1528 * gained by involving the user in this problem that hopefully will get resolved
1531 * http://sourceware.org/cgi-bin/gnatsweb.pl? \
1532 * cmd = view%20audit-trail&database = gdb&pr = 2395
1534 * For now, the default is to fix up things to make current GDB versions work.
1535 * This can be overwritten using the gdb_report_data_abort <'enable'|'disable'> command.
1537 memset(buffer, 0, len);
1541 if (retval == ERROR_OK) {
1542 hex_buffer = malloc(len * 2 + 1);
1544 size_t pkt_len = hexify(hex_buffer, buffer, len, len * 2 + 1);
1546 gdb_put_packet(connection, hex_buffer, pkt_len);
1550 retval = gdb_error(connection, retval);
1557 static int gdb_write_memory_packet(struct connection *connection,
1558 char const *packet, int packet_size)
1560 struct target *target = get_target_from_connection(connection);
1568 /* skip command character */
1571 addr = strtoull(packet, &separator, 16);
1573 if (*separator != ',') {
1574 LOG_ERROR("incomplete write memory packet received, dropping connection");
1575 return ERROR_SERVER_REMOTE_CLOSED;
1578 len = strtoul(separator + 1, &separator, 16);
1580 if (*(separator++) != ':') {
1581 LOG_ERROR("incomplete write memory packet received, dropping connection");
1582 return ERROR_SERVER_REMOTE_CLOSED;
1585 buffer = malloc(len);
1587 LOG_DEBUG("addr: 0x%" PRIx64 ", len: 0x%8.8" PRIx32 "", addr, len);
1589 if (unhexify(buffer, separator, len) != len)
1590 LOG_ERROR("unable to decode memory packet");
1592 retval = ERROR_NOT_IMPLEMENTED;
1594 retval = rtos_write_buffer(target, addr, len, buffer);
1595 if (retval == ERROR_NOT_IMPLEMENTED)
1596 retval = target_write_buffer(target, addr, len, buffer);
1598 if (retval == ERROR_OK)
1599 gdb_put_packet(connection, "OK", 2);
1601 retval = gdb_error(connection, retval);
1608 static int gdb_write_memory_binary_packet(struct connection *connection,
1609 char const *packet, int packet_size)
1611 struct target *target = get_target_from_connection(connection);
1616 int retval = ERROR_OK;
1617 /* Packets larger than fast_limit bytes will be acknowledged instantly on
1618 * the assumption that we're in a download and it's important to go as fast
1620 uint32_t fast_limit = 8;
1622 /* skip command character */
1625 addr = strtoull(packet, &separator, 16);
1627 if (*separator != ',') {
1628 LOG_ERROR("incomplete write memory binary packet received, dropping connection");
1629 return ERROR_SERVER_REMOTE_CLOSED;
1632 len = strtoul(separator + 1, &separator, 16);
1634 if (*(separator++) != ':') {
1635 LOG_ERROR("incomplete write memory binary packet received, dropping connection");
1636 return ERROR_SERVER_REMOTE_CLOSED;
1639 struct gdb_connection *gdb_connection = connection->priv;
1641 if (gdb_connection->mem_write_error)
1642 retval = ERROR_FAIL;
1644 if (retval == ERROR_OK) {
1645 if (len >= fast_limit) {
1646 /* By replying the packet *immediately* GDB will send us a new packet
1647 * while we write the last one to the target.
1648 * We only do this for larger writes, so that users who do something like:
1649 * p *((int*)0xdeadbeef)=8675309
1650 * will get immediate feedback that that write failed.
1652 gdb_put_packet(connection, "OK", 2);
1655 retval = gdb_error(connection, retval);
1656 /* now that we have reported the memory write error, we can clear the condition */
1657 gdb_connection->mem_write_error = false;
1658 if (retval != ERROR_OK)
1663 LOG_DEBUG("addr: 0x%" PRIx64 ", len: 0x%8.8" PRIx32 "", addr, len);
1665 retval = ERROR_NOT_IMPLEMENTED;
1667 retval = rtos_write_buffer(target, addr, len, (uint8_t *)separator);
1668 if (retval == ERROR_NOT_IMPLEMENTED)
1669 retval = target_write_buffer(target, addr, len, (uint8_t *)separator);
1671 if (retval != ERROR_OK)
1672 gdb_connection->mem_write_error = true;
1675 if (len < fast_limit) {
1676 if (retval != ERROR_OK) {
1677 gdb_error(connection, retval);
1678 gdb_connection->mem_write_error = false;
1680 gdb_put_packet(connection, "OK", 2);
1687 static int gdb_step_continue_packet(struct connection *connection,
1688 char const *packet, int packet_size)
1690 struct target *target = get_target_from_connection(connection);
1692 uint64_t address = 0x0;
1693 int retval = ERROR_OK;
1697 if (packet_size > 1)
1698 address = strtoull(packet + 1, NULL, 16);
1702 gdb_running_type = packet[0];
1703 if (packet[0] == 'c') {
1704 LOG_DEBUG("continue");
1705 /* resume at current address, don't handle breakpoints, not debugging */
1706 retval = target_resume(target, current, address, 0, 0);
1707 } else if (packet[0] == 's') {
1709 /* step at current or address, don't handle breakpoints */
1710 retval = target_step(target, current, address, 0);
1715 static int gdb_breakpoint_watchpoint_packet(struct connection *connection,
1716 char const *packet, int packet_size)
1718 struct target *target = get_target_from_connection(connection);
1720 enum breakpoint_type bp_type = BKPT_SOFT /* dummy init to avoid warning */;
1721 enum watchpoint_rw wp_type = WPT_READ /* dummy init to avoid warning */;
1727 LOG_DEBUG("[%s]", target_name(target));
1729 type = strtoul(packet + 1, &separator, 16);
1731 if (type == 0) /* memory breakpoint */
1732 bp_type = BKPT_SOFT;
1733 else if (type == 1) /* hardware breakpoint */
1734 bp_type = BKPT_HARD;
1735 else if (type == 2) /* write watchpoint */
1736 wp_type = WPT_WRITE;
1737 else if (type == 3) /* read watchpoint */
1739 else if (type == 4) /* access watchpoint */
1740 wp_type = WPT_ACCESS;
1742 LOG_ERROR("invalid gdb watch/breakpoint type(%d), dropping connection", type);
1743 return ERROR_SERVER_REMOTE_CLOSED;
1746 if (gdb_breakpoint_override && ((bp_type == BKPT_SOFT) || (bp_type == BKPT_HARD)))
1747 bp_type = gdb_breakpoint_override_type;
1749 if (*separator != ',') {
1750 LOG_ERROR("incomplete breakpoint/watchpoint packet received, dropping connection");
1751 return ERROR_SERVER_REMOTE_CLOSED;
1754 address = strtoull(separator + 1, &separator, 16);
1756 if (*separator != ',') {
1757 LOG_ERROR("incomplete breakpoint/watchpoint packet received, dropping connection");
1758 return ERROR_SERVER_REMOTE_CLOSED;
1761 size = strtoul(separator + 1, &separator, 16);
1766 if (packet[0] == 'Z') {
1767 retval = breakpoint_add(target, address, size, bp_type);
1768 if (retval != ERROR_OK) {
1769 retval = gdb_error(connection, retval);
1770 if (retval != ERROR_OK)
1773 gdb_put_packet(connection, "OK", 2);
1775 breakpoint_remove(target, address);
1776 gdb_put_packet(connection, "OK", 2);
1783 if (packet[0] == 'Z') {
1784 retval = watchpoint_add(target, address, size, wp_type, 0, 0xffffffffu);
1785 if (retval != ERROR_OK) {
1786 retval = gdb_error(connection, retval);
1787 if (retval != ERROR_OK)
1790 gdb_put_packet(connection, "OK", 2);
1792 watchpoint_remove(target, address);
1793 gdb_put_packet(connection, "OK", 2);
1804 /* print out a string and allocate more space as needed,
1805 * mainly used for XML at this point
1807 static __attribute__ ((format (PRINTF_ATTRIBUTE_FORMAT, 5, 6))) void xml_printf(int *retval,
1808 char **xml, int *pos, int *size, const char *fmt, ...)
1810 if (*retval != ERROR_OK)
1815 if ((!*xml) || (!first)) {
1816 /* start by 0 to exercise all the code paths.
1817 * Need minimum 2 bytes to fit 1 char and 0 terminator. */
1819 *size = *size * 2 + 2;
1821 *xml = realloc(*xml, *size);
1824 *retval = ERROR_SERVER_REMOTE_CLOSED;
1832 ret = vsnprintf(*xml + *pos, *size - *pos, fmt, ap);
1834 if ((ret > 0) && ((ret + 1) < *size - *pos)) {
1838 /* there was just enough or not enough space, allocate more. */
1843 static int decode_xfer_read(char const *buf, char **annex, int *ofs, unsigned int *len)
1845 /* Locate the annex. */
1846 const char *annex_end = strchr(buf, ':');
1850 /* After the read marker and annex, qXfer looks like a
1851 * traditional 'm' packet. */
1853 *ofs = strtoul(annex_end + 1, &separator, 16);
1855 if (*separator != ',')
1858 *len = strtoul(separator + 1, NULL, 16);
1860 /* Extract the annex if needed */
1862 *annex = strndup(buf, annex_end - buf);
1870 static int compare_bank(const void *a, const void *b)
1872 struct flash_bank *b1, *b2;
1873 b1 = *((struct flash_bank **)a);
1874 b2 = *((struct flash_bank **)b);
1876 if (b1->base == b2->base)
1878 else if (b1->base > b2->base)
1884 static int gdb_memory_map(struct connection *connection,
1885 char const *packet, int packet_size)
1887 /* We get away with only specifying flash here. Regions that are not
1888 * specified are treated as if we provided no memory map(if not we
1889 * could detect the holes and mark them as RAM).
1890 * Normally we only execute this code once, but no big deal if we
1891 * have to regenerate it a couple of times.
1894 struct target *target = get_target_from_connection(connection);
1895 struct flash_bank *p;
1899 int retval = ERROR_OK;
1900 struct flash_bank **banks;
1904 target_addr_t ram_start = 0;
1905 unsigned int target_flash_banks = 0;
1907 /* skip command character */
1910 offset = strtoul(packet, &separator, 16);
1911 length = strtoul(separator + 1, &separator, 16);
1913 xml_printf(&retval, &xml, &pos, &size, "<memory-map>\n");
1915 /* Sort banks in ascending order. We need to report non-flash
1916 * memory as ram (or rather read/write) by default for GDB, since
1917 * it has no concept of non-cacheable read/write memory (i/o etc).
1919 banks = malloc(sizeof(struct flash_bank *)*flash_get_bank_count());
1921 for (unsigned int i = 0; i < flash_get_bank_count(); i++) {
1922 p = get_flash_bank_by_num_noprobe(i);
1923 if (p->target != target)
1925 retval = get_flash_bank_by_num(i, &p);
1926 if (retval != ERROR_OK) {
1928 gdb_error(connection, retval);
1931 banks[target_flash_banks++] = p;
1934 qsort(banks, target_flash_banks, sizeof(struct flash_bank *),
1937 for (unsigned int i = 0; i < target_flash_banks; i++) {
1938 unsigned sector_size = 0;
1939 unsigned group_len = 0;
1943 if (ram_start < p->base)
1944 xml_printf(&retval, &xml, &pos, &size,
1945 "<memory type=\"ram\" start=\"" TARGET_ADDR_FMT "\" "
1946 "length=\"" TARGET_ADDR_FMT "\"/>\n",
1947 ram_start, p->base - ram_start);
1949 /* Report adjacent groups of same-size sectors. So for
1950 * example top boot CFI flash will list an initial region
1951 * with several large sectors (maybe 128KB) and several
1952 * smaller ones at the end (maybe 32KB). STR7 will have
1953 * regions with 8KB, 32KB, and 64KB sectors; etc.
1955 for (unsigned int j = 0; j < p->num_sectors; j++) {
1957 /* Maybe start a new group of sectors. */
1958 if (sector_size == 0) {
1959 if (p->sectors[j].offset + p->sectors[j].size > p->size) {
1960 LOG_WARNING("The flash sector at offset 0x%08" PRIx32
1961 " overflows the end of %s bank.",
1962 p->sectors[j].offset, p->name);
1963 LOG_WARNING("The rest of bank will not show in gdb memory map.");
1966 target_addr_t start;
1967 start = p->base + p->sectors[j].offset;
1968 xml_printf(&retval, &xml, &pos, &size,
1969 "<memory type=\"flash\" "
1970 "start=\"" TARGET_ADDR_FMT "\" ",
1972 sector_size = p->sectors[j].size;
1973 group_len = sector_size;
1975 group_len += sector_size; /* equal to p->sectors[j].size */
1978 /* Does this finish a group of sectors?
1979 * If not, continue an already-started group.
1981 if (j < p->num_sectors - 1
1982 && p->sectors[j + 1].size == sector_size
1983 && p->sectors[j + 1].offset == p->sectors[j].offset + sector_size
1984 && p->sectors[j + 1].offset + p->sectors[j + 1].size <= p->size)
1987 xml_printf(&retval, &xml, &pos, &size,
1988 "length=\"0x%x\">\n"
1989 "<property name=\"blocksize\">"
1997 ram_start = p->base + p->size;
2001 xml_printf(&retval, &xml, &pos, &size,
2002 "<memory type=\"ram\" start=\"" TARGET_ADDR_FMT "\" "
2003 "length=\"" TARGET_ADDR_FMT "\"/>\n",
2004 ram_start, target_address_max(target) - ram_start + 1);
2005 /* ELSE a flash chip could be at the very end of the address space, in
2006 * which case ram_start will be precisely 0 */
2010 xml_printf(&retval, &xml, &pos, &size, "</memory-map>\n");
2012 if (retval != ERROR_OK) {
2014 gdb_error(connection, retval);
2018 if (offset + length > pos)
2019 length = pos - offset;
2021 char *t = malloc(length + 1);
2023 memcpy(t + 1, xml + offset, length);
2024 gdb_put_packet(connection, t, length + 1);
2031 static const char *gdb_get_reg_type_name(enum reg_type type)
2040 case REG_TYPE_INT16:
2042 case REG_TYPE_INT32:
2044 case REG_TYPE_INT64:
2046 case REG_TYPE_INT128:
2050 case REG_TYPE_UINT8:
2052 case REG_TYPE_UINT16:
2054 case REG_TYPE_UINT32:
2056 case REG_TYPE_UINT64:
2058 case REG_TYPE_UINT128:
2060 case REG_TYPE_CODE_PTR:
2062 case REG_TYPE_DATA_PTR:
2064 case REG_TYPE_FLOAT:
2066 case REG_TYPE_IEEE_SINGLE:
2067 return "ieee_single";
2068 case REG_TYPE_IEEE_DOUBLE:
2069 return "ieee_double";
2070 case REG_TYPE_ARCH_DEFINED:
2071 return "int"; /* return arbitrary string to avoid compile warning. */
2074 return "int"; /* "int" as default value */
2077 static int lookup_add_arch_defined_types(char const **arch_defined_types_list[], const char *type_id,
2078 int *num_arch_defined_types)
2080 int tbl_sz = *num_arch_defined_types;
2082 if (type_id && (strcmp(type_id, ""))) {
2083 for (int j = 0; j < (tbl_sz + 1); j++) {
2084 if (!((*arch_defined_types_list)[j])) {
2085 (*arch_defined_types_list)[tbl_sz++] = type_id;
2086 *arch_defined_types_list = realloc(*arch_defined_types_list,
2087 sizeof(char *) * (tbl_sz + 1));
2088 (*arch_defined_types_list)[tbl_sz] = NULL;
2089 *num_arch_defined_types = tbl_sz;
2092 if (!strcmp((*arch_defined_types_list)[j], type_id))
2101 static int gdb_generate_reg_type_description(struct target *target,
2102 char **tdesc, int *pos, int *size, struct reg_data_type *type,
2103 char const **arch_defined_types_list[], int *num_arch_defined_types)
2105 int retval = ERROR_OK;
2107 if (type->type_class == REG_TYPE_CLASS_VECTOR) {
2108 struct reg_data_type *data_type = type->reg_type_vector->type;
2109 if (data_type->type == REG_TYPE_ARCH_DEFINED) {
2110 if (lookup_add_arch_defined_types(arch_defined_types_list, data_type->id,
2111 num_arch_defined_types))
2112 gdb_generate_reg_type_description(target, tdesc, pos, size, data_type,
2113 arch_defined_types_list,
2114 num_arch_defined_types);
2116 /* <vector id="id" type="type" count="count"/> */
2117 xml_printf(&retval, tdesc, pos, size,
2118 "<vector id=\"%s\" type=\"%s\" count=\"%" PRIu32 "\"/>\n",
2119 type->id, type->reg_type_vector->type->id,
2120 type->reg_type_vector->count);
2122 } else if (type->type_class == REG_TYPE_CLASS_UNION) {
2123 struct reg_data_type_union_field *field;
2124 field = type->reg_type_union->fields;
2126 struct reg_data_type *data_type = field->type;
2127 if (data_type->type == REG_TYPE_ARCH_DEFINED) {
2128 if (lookup_add_arch_defined_types(arch_defined_types_list, data_type->id,
2129 num_arch_defined_types))
2130 gdb_generate_reg_type_description(target, tdesc, pos, size, data_type,
2131 arch_defined_types_list,
2132 num_arch_defined_types);
2135 field = field->next;
2138 * <field name="name" type="type"/> ...
2140 xml_printf(&retval, tdesc, pos, size,
2141 "<union id=\"%s\">\n",
2144 field = type->reg_type_union->fields;
2146 xml_printf(&retval, tdesc, pos, size,
2147 "<field name=\"%s\" type=\"%s\"/>\n",
2148 field->name, field->type->id);
2150 field = field->next;
2153 xml_printf(&retval, tdesc, pos, size,
2156 } else if (type->type_class == REG_TYPE_CLASS_STRUCT) {
2157 struct reg_data_type_struct_field *field;
2158 field = type->reg_type_struct->fields;
2160 if (field->use_bitfields) {
2161 /* <struct id="id" size="size">
2162 * <field name="name" start="start" end="end"/> ...
2164 xml_printf(&retval, tdesc, pos, size,
2165 "<struct id=\"%s\" size=\"%" PRIu32 "\">\n",
2166 type->id, type->reg_type_struct->size);
2168 xml_printf(&retval, tdesc, pos, size,
2169 "<field name=\"%s\" start=\"%" PRIu32 "\" end=\"%" PRIu32 "\" type=\"%s\" />\n",
2170 field->name, field->bitfield->start, field->bitfield->end,
2171 gdb_get_reg_type_name(field->bitfield->type));
2173 field = field->next;
2177 struct reg_data_type *data_type = field->type;
2178 if (data_type->type == REG_TYPE_ARCH_DEFINED) {
2179 if (lookup_add_arch_defined_types(arch_defined_types_list, data_type->id,
2180 num_arch_defined_types))
2181 gdb_generate_reg_type_description(target, tdesc, pos, size, data_type,
2182 arch_defined_types_list,
2183 num_arch_defined_types);
2188 * <field name="name" type="type"/> ...
2190 xml_printf(&retval, tdesc, pos, size,
2191 "<struct id=\"%s\">\n",
2194 xml_printf(&retval, tdesc, pos, size,
2195 "<field name=\"%s\" type=\"%s\"/>\n",
2196 field->name, field->type->id);
2198 field = field->next;
2202 xml_printf(&retval, tdesc, pos, size,
2205 } else if (type->type_class == REG_TYPE_CLASS_FLAGS) {
2206 /* <flags id="id" size="size">
2207 * <field name="name" start="start" end="end"/> ...
2209 xml_printf(&retval, tdesc, pos, size,
2210 "<flags id=\"%s\" size=\"%" PRIu32 "\">\n",
2211 type->id, type->reg_type_flags->size);
2213 struct reg_data_type_flags_field *field;
2214 field = type->reg_type_flags->fields;
2216 xml_printf(&retval, tdesc, pos, size,
2217 "<field name=\"%s\" start=\"%" PRIu32 "\" end=\"%" PRIu32 "\" type=\"%s\" />\n",
2218 field->name, field->bitfield->start, field->bitfield->end,
2219 gdb_get_reg_type_name(field->bitfield->type));
2221 field = field->next;
2224 xml_printf(&retval, tdesc, pos, size,
2232 /* Get a list of available target registers features. feature_list must
2233 * be freed by caller.
2235 static int get_reg_features_list(struct target *target, char const **feature_list[], int *feature_list_size,
2236 struct reg **reg_list, int reg_list_size)
2240 /* Start with only one element */
2241 *feature_list = calloc(1, sizeof(char *));
2243 for (int i = 0; i < reg_list_size; i++) {
2244 if (reg_list[i]->exist == false || reg_list[i]->hidden)
2247 if (reg_list[i]->feature
2248 && reg_list[i]->feature->name
2249 && (strcmp(reg_list[i]->feature->name, ""))) {
2250 /* We found a feature, check if the feature is already in the
2251 * table. If not, allocate a new entry for the table and
2252 * put the new feature in it.
2254 for (int j = 0; j < (tbl_sz + 1); j++) {
2255 if (!((*feature_list)[j])) {
2256 (*feature_list)[tbl_sz++] = reg_list[i]->feature->name;
2257 *feature_list = realloc(*feature_list, sizeof(char *) * (tbl_sz + 1));
2258 (*feature_list)[tbl_sz] = NULL;
2261 if (!strcmp((*feature_list)[j], reg_list[i]->feature->name))
2268 if (feature_list_size)
2269 *feature_list_size = tbl_sz;
2274 /* Create a register list that's the union of all the registers of the SMP
2275 * group this target is in. If the target is not part of an SMP group, this
2276 * returns the same as target_get_gdb_reg_list_noread().
2278 static int smp_reg_list_noread(struct target *target,
2279 struct reg **combined_list[], int *combined_list_size,
2280 enum target_register_class reg_class)
2283 return target_get_gdb_reg_list_noread(target, combined_list,
2284 combined_list_size, REG_CLASS_ALL);
2286 unsigned int combined_allocated = 256;
2287 struct reg **local_list = malloc(combined_allocated * sizeof(struct reg *));
2289 LOG_ERROR("malloc(%zu) failed", combined_allocated * sizeof(struct reg *));
2292 unsigned int local_list_size = 0;
2294 struct target_list *head;
2295 foreach_smp_target(head, target->smp_targets) {
2296 if (!target_was_examined(head->target))
2299 struct reg **reg_list = NULL;
2301 int result = target_get_gdb_reg_list_noread(head->target, ®_list,
2302 ®_list_size, reg_class);
2303 if (result != ERROR_OK) {
2307 for (int i = 0; i < reg_list_size; i++) {
2309 struct reg *a = reg_list[i];
2311 /* Nested loop makes this O(n^2), but this entire function with
2312 * 5 RISC-V targets takes just 2ms on my computer. Fast enough
2314 for (unsigned int j = 0; j < local_list_size; j++) {
2315 struct reg *b = local_list[j];
2316 if (!strcmp(a->name, b->name)) {
2318 if (a->size != b->size) {
2319 LOG_ERROR("SMP register %s is %d bits on one "
2320 "target, but %d bits on another target.",
2321 a->name, a->size, b->size);
2330 LOG_DEBUG("[%s] %s not found in combined list", target_name(target), a->name);
2331 if (local_list_size >= combined_allocated) {
2332 combined_allocated *= 2;
2333 local_list = realloc(local_list, combined_allocated * sizeof(struct reg *));
2335 LOG_ERROR("realloc(%zu) failed", combined_allocated * sizeof(struct reg *));
2339 local_list[local_list_size] = a;
2347 if (local_list_size == 0) {
2348 LOG_ERROR("Unable to get register list");
2353 /* Now warn the user about any registers that weren't found in every target. */
2354 foreach_smp_target(head, target->smp_targets) {
2355 if (!target_was_examined(head->target))
2358 struct reg **reg_list = NULL;
2360 int result = target_get_gdb_reg_list_noread(head->target, ®_list,
2361 ®_list_size, reg_class);
2362 if (result != ERROR_OK) {
2366 for (unsigned int i = 0; i < local_list_size; i++) {
2368 struct reg *a = local_list[i];
2369 for (int j = 0; j < reg_list_size; j++) {
2370 struct reg *b = reg_list[j];
2371 if (b->exist && !strcmp(a->name, b->name)) {
2377 LOG_WARNING("Register %s does not exist in %s, which is part of an SMP group where "
2378 "this register does exist.",
2379 a->name, target_name(head->target));
2385 *combined_list = local_list;
2386 *combined_list_size = local_list_size;
2390 static int gdb_generate_target_description(struct target *target, char **tdesc_out)
2392 int retval = ERROR_OK;
2393 struct reg **reg_list = NULL;
2395 char const *architecture;
2396 char const **features = NULL;
2397 int feature_list_size = 0;
2403 retval = smp_reg_list_noread(target, ®_list, ®_list_size,
2406 if (retval != ERROR_OK) {
2407 LOG_ERROR("get register list failed");
2408 retval = ERROR_FAIL;
2412 if (reg_list_size <= 0) {
2413 LOG_ERROR("get register list failed");
2414 retval = ERROR_FAIL;
2418 /* Get a list of available target registers features */
2419 retval = get_reg_features_list(target, &features, &feature_list_size, reg_list, reg_list_size);
2420 if (retval != ERROR_OK) {
2421 LOG_ERROR("Can't get the registers feature list");
2422 retval = ERROR_FAIL;
2426 /* If we found some features associated with registers, create sections */
2427 int current_feature = 0;
2429 xml_printf(&retval, &tdesc, &pos, &size,
2430 "<?xml version=\"1.0\"?>\n"
2431 "<!DOCTYPE target SYSTEM \"gdb-target.dtd\">\n"
2432 "<target version=\"1.0\">\n");
2434 /* generate architecture element if supported by target */
2435 architecture = target_get_gdb_arch(target);
2437 xml_printf(&retval, &tdesc, &pos, &size,
2438 "<architecture>%s</architecture>\n", architecture);
2440 /* generate target description according to register list */
2442 while (features[current_feature]) {
2443 char const **arch_defined_types = NULL;
2444 int num_arch_defined_types = 0;
2446 arch_defined_types = calloc(1, sizeof(char *));
2447 xml_printf(&retval, &tdesc, &pos, &size,
2448 "<feature name=\"%s\">\n",
2449 features[current_feature]);
2452 for (i = 0; i < reg_list_size; i++) {
2454 if (reg_list[i]->exist == false || reg_list[i]->hidden)
2457 if (strcmp(reg_list[i]->feature->name, features[current_feature]))
2460 const char *type_str;
2461 if (reg_list[i]->reg_data_type) {
2462 if (reg_list[i]->reg_data_type->type == REG_TYPE_ARCH_DEFINED) {
2463 /* generate <type... first, if there are architecture-defined types. */
2464 if (lookup_add_arch_defined_types(&arch_defined_types,
2465 reg_list[i]->reg_data_type->id,
2466 &num_arch_defined_types))
2467 gdb_generate_reg_type_description(target, &tdesc, &pos, &size,
2468 reg_list[i]->reg_data_type,
2469 &arch_defined_types,
2470 &num_arch_defined_types);
2472 type_str = reg_list[i]->reg_data_type->id;
2474 /* predefined type */
2475 type_str = gdb_get_reg_type_name(
2476 reg_list[i]->reg_data_type->type);
2479 /* Default type is "int" */
2483 xml_printf(&retval, &tdesc, &pos, &size,
2484 "<reg name=\"%s\"", reg_list[i]->name);
2485 xml_printf(&retval, &tdesc, &pos, &size,
2486 " bitsize=\"%" PRIu32 "\"", reg_list[i]->size);
2487 xml_printf(&retval, &tdesc, &pos, &size,
2488 " regnum=\"%" PRIu32 "\"", reg_list[i]->number);
2489 if (reg_list[i]->caller_save)
2490 xml_printf(&retval, &tdesc, &pos, &size,
2491 " save-restore=\"yes\"");
2493 xml_printf(&retval, &tdesc, &pos, &size,
2494 " save-restore=\"no\"");
2496 xml_printf(&retval, &tdesc, &pos, &size,
2497 " type=\"%s\"", type_str);
2499 if (reg_list[i]->group)
2500 xml_printf(&retval, &tdesc, &pos, &size,
2501 " group=\"%s\"", reg_list[i]->group);
2503 xml_printf(&retval, &tdesc, &pos, &size,
2507 xml_printf(&retval, &tdesc, &pos, &size,
2511 free(arch_defined_types);
2515 xml_printf(&retval, &tdesc, &pos, &size,
2522 if (retval == ERROR_OK)
2530 static int gdb_get_target_description_chunk(struct target *target, struct target_desc_format *target_desc,
2531 char **chunk, int32_t offset, uint32_t length)
2534 LOG_ERROR("Unable to Generate Target Description");
2538 char *tdesc = target_desc->tdesc;
2539 uint32_t tdesc_length = target_desc->tdesc_length;
2542 int retval = gdb_generate_target_description(target, &tdesc);
2543 if (retval != ERROR_OK) {
2544 LOG_ERROR("Unable to Generate Target Description");
2548 tdesc_length = strlen(tdesc);
2553 if (length < (tdesc_length - offset))
2554 transfer_type = 'm';
2556 transfer_type = 'l';
2558 *chunk = malloc(length + 2);
2560 LOG_ERROR("Unable to allocate memory");
2564 (*chunk)[0] = transfer_type;
2565 if (transfer_type == 'm') {
2566 strncpy((*chunk) + 1, tdesc + offset, length);
2567 (*chunk)[1 + length] = '\0';
2569 strncpy((*chunk) + 1, tdesc + offset, tdesc_length - offset);
2570 (*chunk)[1 + (tdesc_length - offset)] = '\0';
2572 /* After gdb-server sends out last chunk, invalidate tdesc. */
2578 target_desc->tdesc = tdesc;
2579 target_desc->tdesc_length = tdesc_length;
2584 static int gdb_target_description_supported(struct target *target, int *supported)
2586 int retval = ERROR_OK;
2587 struct reg **reg_list = NULL;
2588 int reg_list_size = 0;
2589 char const **features = NULL;
2590 int feature_list_size = 0;
2592 char const *architecture = target_get_gdb_arch(target);
2594 retval = target_get_gdb_reg_list_noread(target, ®_list,
2595 ®_list_size, REG_CLASS_ALL);
2596 if (retval != ERROR_OK) {
2597 LOG_ERROR("get register list failed");
2601 if (reg_list_size <= 0) {
2602 LOG_ERROR("get register list failed");
2603 retval = ERROR_FAIL;
2607 /* Get a list of available target registers features */
2608 retval = get_reg_features_list(target, &features, &feature_list_size, reg_list, reg_list_size);
2609 if (retval != ERROR_OK) {
2610 LOG_ERROR("Can't get the registers feature list");
2615 if (architecture || feature_list_size)
2629 static int gdb_generate_thread_list(struct target *target, char **thread_list_out)
2631 struct rtos *rtos = target->rtos;
2632 int retval = ERROR_OK;
2633 char *thread_list = NULL;
2637 xml_printf(&retval, &thread_list, &pos, &size,
2638 "<?xml version=\"1.0\"?>\n"
2642 for (int i = 0; i < rtos->thread_count; i++) {
2643 struct thread_detail *thread_detail = &rtos->thread_details[i];
2645 if (!thread_detail->exists)
2648 if (thread_detail->thread_name_str)
2649 xml_printf(&retval, &thread_list, &pos, &size,
2650 "<thread id=\"%" PRIx64 "\" name=\"%s\">",
2651 thread_detail->threadid,
2652 thread_detail->thread_name_str);
2654 xml_printf(&retval, &thread_list, &pos, &size,
2655 "<thread id=\"%" PRIx64 "\">", thread_detail->threadid);
2657 if (thread_detail->thread_name_str)
2658 xml_printf(&retval, &thread_list, &pos, &size,
2659 "Name: %s", thread_detail->thread_name_str);
2661 if (thread_detail->extra_info_str) {
2662 if (thread_detail->thread_name_str)
2663 xml_printf(&retval, &thread_list, &pos, &size,
2665 xml_printf(&retval, &thread_list, &pos, &size,
2666 "%s", thread_detail->extra_info_str);
2669 xml_printf(&retval, &thread_list, &pos, &size,
2674 xml_printf(&retval, &thread_list, &pos, &size,
2677 if (retval == ERROR_OK)
2678 *thread_list_out = thread_list;
2685 static int gdb_get_thread_list_chunk(struct target *target, char **thread_list,
2686 char **chunk, int32_t offset, uint32_t length)
2688 if (!*thread_list) {
2689 int retval = gdb_generate_thread_list(target, thread_list);
2690 if (retval != ERROR_OK) {
2691 LOG_ERROR("Unable to Generate Thread List");
2696 size_t thread_list_length = strlen(*thread_list);
2699 length = MIN(length, thread_list_length - offset);
2700 if (length < (thread_list_length - offset))
2701 transfer_type = 'm';
2703 transfer_type = 'l';
2705 *chunk = malloc(length + 2 + 3);
2706 /* Allocating extra 3 bytes prevents false positive valgrind report
2707 * of strlen(chunk) word access:
2708 * Invalid read of size 4
2709 * Address 0x4479934 is 44 bytes inside a block of size 45 alloc'd */
2711 LOG_ERROR("Unable to allocate memory");
2715 (*chunk)[0] = transfer_type;
2716 strncpy((*chunk) + 1, (*thread_list) + offset, length);
2717 (*chunk)[1 + length] = '\0';
2719 /* After gdb-server sends out last chunk, invalidate thread list. */
2720 if (transfer_type == 'l') {
2722 *thread_list = NULL;
2728 static int gdb_query_packet(struct connection *connection,
2729 char const *packet, int packet_size)
2731 struct command_context *cmd_ctx = connection->cmd_ctx;
2732 struct gdb_connection *gdb_connection = connection->priv;
2733 struct target *target = get_target_from_connection(connection);
2735 if (strncmp(packet, "qRcmd,", 6) == 0) {
2736 if (packet_size > 6) {
2738 cmd = malloc((packet_size - 6) / 2 + 1);
2739 size_t len = unhexify((uint8_t *)cmd, packet + 6, (packet_size - 6) / 2);
2742 /* We want to print all debug output to GDB connection */
2743 gdb_connection->output_flag = GDB_OUTPUT_ALL;
2744 target_call_timer_callbacks_now();
2745 /* some commands need to know the GDB connection, make note of current
2746 * GDB connection. */
2747 current_gdb_connection = gdb_connection;
2748 command_run_line(cmd_ctx, cmd);
2749 current_gdb_connection = NULL;
2750 target_call_timer_callbacks_now();
2751 gdb_connection->output_flag = GDB_OUTPUT_NO;
2754 gdb_put_packet(connection, "OK", 2);
2756 } else if (strncmp(packet, "qCRC:", 5) == 0) {
2757 if (packet_size > 5) {
2762 target_addr_t addr = 0;
2765 /* skip command character */
2768 addr = strtoull(packet, &separator, 16);
2770 if (*separator != ',') {
2771 LOG_ERROR("incomplete read memory packet received, dropping connection");
2772 return ERROR_SERVER_REMOTE_CLOSED;
2775 len = strtoul(separator + 1, NULL, 16);
2777 retval = target_checksum_memory(target, addr, len, &checksum);
2779 if (retval == ERROR_OK) {
2780 snprintf(gdb_reply, 10, "C%8.8" PRIx32 "", checksum);
2781 gdb_put_packet(connection, gdb_reply, 9);
2783 retval = gdb_error(connection, retval);
2784 if (retval != ERROR_OK)
2790 } else if (strncmp(packet, "qSupported", 10) == 0) {
2791 /* we currently support packet size and qXfer:memory-map:read (if enabled)
2792 * qXfer:features:read is supported for some targets */
2793 int retval = ERROR_OK;
2794 char *buffer = NULL;
2797 int gdb_target_desc_supported = 0;
2799 /* we need to test that the target supports target descriptions */
2800 retval = gdb_target_description_supported(target, &gdb_target_desc_supported);
2801 if (retval != ERROR_OK) {
2802 LOG_INFO("Failed detecting Target Description Support, disabling");
2803 gdb_target_desc_supported = 0;
2806 /* support may be disabled globally */
2807 if (gdb_use_target_description == 0) {
2808 if (gdb_target_desc_supported)
2809 LOG_WARNING("Target Descriptions Supported, but disabled");
2810 gdb_target_desc_supported = 0;
2817 "PacketSize=%x;qXfer:memory-map:read%c;qXfer:features:read%c;qXfer:threads:read+;QStartNoAckMode+;vContSupported+",
2819 ((gdb_use_memory_map == 1) && (flash_get_bank_count() > 0)) ? '+' : '-',
2820 (gdb_target_desc_supported == 1) ? '+' : '-');
2822 if (retval != ERROR_OK) {
2823 gdb_send_error(connection, 01);
2827 gdb_put_packet(connection, buffer, strlen(buffer));
2831 } else if ((strncmp(packet, "qXfer:memory-map:read::", 23) == 0)
2832 && (flash_get_bank_count() > 0))
2833 return gdb_memory_map(connection, packet, packet_size);
2834 else if (strncmp(packet, "qXfer:features:read:", 20) == 0) {
2836 int retval = ERROR_OK;
2839 unsigned int length;
2841 /* skip command character */
2844 if (decode_xfer_read(packet, NULL, &offset, &length) < 0) {
2845 gdb_send_error(connection, 01);
2849 /* Target should prepare correct target description for annex.
2850 * The first character of returned xml is 'm' or 'l'. 'm' for
2851 * there are *more* chunks to transfer. 'l' for it is the *last*
2852 * chunk of target description.
2854 retval = gdb_get_target_description_chunk(target, &gdb_connection->target_desc,
2855 &xml, offset, length);
2856 if (retval != ERROR_OK) {
2857 gdb_error(connection, retval);
2861 gdb_put_packet(connection, xml, strlen(xml));
2865 } else if (strncmp(packet, "qXfer:threads:read:", 19) == 0) {
2867 int retval = ERROR_OK;
2870 unsigned int length;
2872 /* skip command character */
2875 if (decode_xfer_read(packet, NULL, &offset, &length) < 0) {
2876 gdb_send_error(connection, 01);
2880 /* Target should prepare correct thread list for annex.
2881 * The first character of returned xml is 'm' or 'l'. 'm' for
2882 * there are *more* chunks to transfer. 'l' for it is the *last*
2883 * chunk of target description.
2885 retval = gdb_get_thread_list_chunk(target, &gdb_connection->thread_list,
2886 &xml, offset, length);
2887 if (retval != ERROR_OK) {
2888 gdb_error(connection, retval);
2892 gdb_put_packet(connection, xml, strlen(xml));
2896 } else if (strncmp(packet, "QStartNoAckMode", 15) == 0) {
2897 gdb_connection->noack_mode = 1;
2898 gdb_put_packet(connection, "OK", 2);
2902 gdb_put_packet(connection, "", 0);
2906 static bool gdb_handle_vcont_packet(struct connection *connection, const char *packet, int packet_size)
2908 struct gdb_connection *gdb_connection = connection->priv;
2909 struct target *target = get_target_from_connection(connection);
2910 const char *parse = packet;
2913 /* query for vCont supported */
2914 if (parse[0] == '?') {
2915 if (target->type->step) {
2916 /* gdb doesn't accept c without C and s without S */
2917 gdb_put_packet(connection, "vCont;c;C;s;S", 13);
2923 if (parse[0] == ';') {
2928 /* simple case, a continue packet */
2929 if (parse[0] == 'c') {
2930 gdb_running_type = 'c';
2931 LOG_DEBUG("target %s continue", target_name(target));
2932 gdb_connection->output_flag = GDB_OUTPUT_ALL;
2933 retval = target_resume(target, 1, 0, 0, 0);
2934 if (retval == ERROR_TARGET_NOT_HALTED)
2935 LOG_INFO("target %s was not halted when resume was requested", target_name(target));
2937 /* poll target in an attempt to make its internal state consistent */
2938 if (retval != ERROR_OK) {
2939 retval = target_poll(target);
2940 if (retval != ERROR_OK)
2941 LOG_DEBUG("error polling target %s after failed resume", target_name(target));
2945 * We don't report errors to gdb here, move frontend_state to
2946 * TARGET_RUNNING to stay in sync with gdb's expectation of the
2949 gdb_connection->frontend_state = TARGET_RUNNING;
2950 target_call_event_callbacks(target, TARGET_EVENT_GDB_START);
2955 /* single-step or step-over-breakpoint */
2956 if (parse[0] == 's') {
2957 gdb_running_type = 's';
2958 bool fake_step = false;
2960 if (strncmp(parse, "s:", 2) == 0) {
2961 struct target *ct = target;
2969 thread_id = strtoll(parse, &endp, 16);
2971 packet_size -= endp - parse;
2976 /* FIXME: why is this necessary? rtos state should be up-to-date here already! */
2977 rtos_update_threads(target);
2979 target->rtos->gdb_target_for_threadid(connection, thread_id, &ct);
2982 * check if the thread to be stepped is the current rtos thread
2983 * if not, we must fake the step
2985 if (target->rtos->current_thread != thread_id)
2989 if (parse[0] == ';') {
2993 if (parse[0] == 'c') {
2996 /* check if thread-id follows */
2997 if (parse[0] == ':') {
3001 tid = strtoll(parse, &endp, 16);
3002 if (tid == thread_id) {
3004 * Special case: only step a single thread (core),
3005 * keep the other threads halted. Currently, only
3006 * aarch64 target understands it. Other target types don't
3007 * care (nobody checks the actual value of 'current')
3008 * and it doesn't really matter. This deserves
3009 * a symbolic constant and a formal interface documentation
3012 LOG_DEBUG("request to step current core only");
3013 /* uncomment after checking that indeed other targets are safe */
3020 LOG_DEBUG("target %s single-step thread %"PRIx64, target_name(ct), thread_id);
3021 gdb_connection->output_flag = GDB_OUTPUT_ALL;
3022 target_call_event_callbacks(ct, TARGET_EVENT_GDB_START);
3025 * work around an annoying gdb behaviour: when the current thread
3026 * is changed in gdb, it assumes that the target can follow and also
3027 * make the thread current. This is an assumption that cannot hold
3028 * for a real target running a multi-threading OS. We just fake
3029 * the step to not trigger an internal error in gdb. See
3030 * https://sourceware.org/bugzilla/show_bug.cgi?id=22925 for details
3034 char sig_reply[128];
3036 LOG_DEBUG("fake step thread %"PRIx64, thread_id);
3038 sig_reply_len = snprintf(sig_reply, sizeof(sig_reply),
3039 "T05thread:%016"PRIx64";", thread_id);
3041 gdb_put_packet(connection, sig_reply, sig_reply_len);
3042 gdb_connection->output_flag = GDB_OUTPUT_NO;
3047 /* support for gdb_sync command */
3048 if (gdb_connection->sync) {
3049 gdb_connection->sync = false;
3050 if (ct->state == TARGET_HALTED) {
3051 LOG_DEBUG("stepi ignored. GDB will now fetch the register state "
3052 "from the target.");
3053 gdb_sig_halted(connection);
3054 gdb_connection->output_flag = GDB_OUTPUT_NO;
3056 gdb_connection->frontend_state = TARGET_RUNNING;
3060 retval = target_step(ct, current_pc, 0, 0);
3061 if (retval == ERROR_TARGET_NOT_HALTED)
3062 LOG_INFO("target %s was not halted when step was requested", target_name(ct));
3064 /* if step was successful send a reply back to gdb */
3065 if (retval == ERROR_OK) {
3066 retval = target_poll(ct);
3067 if (retval != ERROR_OK)
3068 LOG_DEBUG("error polling target %s after successful step", target_name(ct));
3069 /* send back signal information */
3070 gdb_signal_reply(ct, connection);
3071 /* stop forwarding log packets! */
3072 gdb_connection->output_flag = GDB_OUTPUT_NO;
3074 gdb_connection->frontend_state = TARGET_RUNNING;
3076 LOG_ERROR("Unknown vCont packet");
3085 static char *next_hex_encoded_field(const char **str, char sep)
3088 const char *hex = *str;
3092 const char *end = strchr(hex, sep);
3094 hexlen = strlen(hex);
3097 *str = hex + hexlen + 1;
3099 if (hexlen % 2 != 0) {
3100 /* Malformed hex data */
3104 size_t count = hexlen / 2;
3105 char *decoded = malloc(count + 1);
3109 size_t converted = unhexify((void *)decoded, hex, count);
3110 if (converted != count) {
3115 decoded[count] = '\0';
3119 /* handle extended restart packet */
3120 static void gdb_restart_inferior(struct connection *connection, const char *packet, int packet_size)
3122 struct gdb_connection *gdb_con = connection->priv;
3123 struct target *target = get_target_from_connection(connection);
3125 breakpoint_clear_target(target);
3126 watchpoint_clear_target(target);
3127 command_run_linef(connection->cmd_ctx, "ocd_gdb_restart %s",
3128 target_name(target));
3129 /* set connection as attached after reset */
3130 gdb_con->attached = true;
3131 /* info rtos parts */
3132 gdb_thread_packet(connection, packet, packet_size);
3135 static bool gdb_handle_vrun_packet(struct connection *connection, const char *packet, int packet_size)
3137 struct target *target = get_target_from_connection(connection);
3138 const char *parse = packet;
3143 if (parse[0] != ';')
3147 /* Skip first field "filename"; don't know what to do with it. */
3148 free(next_hex_encoded_field(&parse, ';'));
3150 char *cmdline = next_hex_encoded_field(&parse, ';');
3152 char *arg = next_hex_encoded_field(&parse, ';');
3155 char *new_cmdline = alloc_printf("%s %s", cmdline, arg);
3158 cmdline = new_cmdline;
3162 if (target->semihosting) {
3163 LOG_INFO("GDB set inferior command line to '%s'", cmdline);
3164 free(target->semihosting->cmdline);
3165 target->semihosting->cmdline = cmdline;
3167 LOG_INFO("GDB set inferior command line to '%s' but semihosting is unavailable", cmdline);
3172 gdb_restart_inferior(connection, packet, packet_size);
3173 gdb_put_packet(connection, "S00", 3);
3177 static int gdb_v_packet(struct connection *connection,
3178 char const *packet, int packet_size)
3180 struct gdb_connection *gdb_connection = connection->priv;
3183 struct target *target = get_target_from_connection(connection);
3185 if (strncmp(packet, "vCont", 5) == 0) {
3191 handled = gdb_handle_vcont_packet(connection, packet, packet_size);
3193 gdb_put_packet(connection, "", 0);
3198 if (strncmp(packet, "vRun", 4) == 0) {
3201 handled = gdb_handle_vrun_packet(connection, packet, packet_size);
3203 gdb_put_packet(connection, "", 0);
3208 /* if flash programming disabled - send a empty reply */
3210 if (gdb_flash_program == 0) {
3211 gdb_put_packet(connection, "", 0);
3215 if (strncmp(packet, "vFlashErase:", 12) == 0) {
3217 unsigned long length;
3219 char const *parse = packet + 12;
3220 if (*parse == '\0') {
3221 LOG_ERROR("incomplete vFlashErase packet received, dropping connection");
3222 return ERROR_SERVER_REMOTE_CLOSED;
3225 addr = strtoul(parse, (char **)&parse, 16);
3227 if (*(parse++) != ',' || *parse == '\0') {
3228 LOG_ERROR("incomplete vFlashErase packet received, dropping connection");
3229 return ERROR_SERVER_REMOTE_CLOSED;
3232 length = strtoul(parse, (char **)&parse, 16);
3234 if (*parse != '\0') {
3235 LOG_ERROR("incomplete vFlashErase packet received, dropping connection");
3236 return ERROR_SERVER_REMOTE_CLOSED;
3239 /* assume all sectors need erasing - stops any problems
3240 * when flash_write is called multiple times */
3243 /* perform any target specific operations before the erase */
3244 target_call_event_callbacks(target,
3245 TARGET_EVENT_GDB_FLASH_ERASE_START);
3247 /* vFlashErase:addr,length messages require region start and
3248 * end to be "block" aligned ... if padding is ever needed,
3249 * GDB will have become dangerously confused.
3251 result = flash_erase_address_range(target, false, addr,
3254 /* perform any target specific operations after the erase */
3255 target_call_event_callbacks(target,
3256 TARGET_EVENT_GDB_FLASH_ERASE_END);
3259 if (result != ERROR_OK) {
3260 /* GDB doesn't evaluate the actual error number returned,
3261 * treat a failed erase as an I/O error
3263 gdb_send_error(connection, EIO);
3264 LOG_ERROR("flash_erase returned %i", result);
3266 gdb_put_packet(connection, "OK", 2);
3271 if (strncmp(packet, "vFlashWrite:", 12) == 0) {
3274 unsigned long length;
3275 char const *parse = packet + 12;
3277 if (*parse == '\0') {
3278 LOG_ERROR("incomplete vFlashErase packet received, dropping connection");
3279 return ERROR_SERVER_REMOTE_CLOSED;
3281 addr = strtoul(parse, (char **)&parse, 16);
3282 if (*(parse++) != ':') {
3283 LOG_ERROR("incomplete vFlashErase packet received, dropping connection");
3284 return ERROR_SERVER_REMOTE_CLOSED;
3286 length = packet_size - (parse - packet);
3288 /* create a new image if there isn't already one */
3289 if (!gdb_connection->vflash_image) {
3290 gdb_connection->vflash_image = malloc(sizeof(struct image));
3291 image_open(gdb_connection->vflash_image, "", "build");
3294 /* create new section with content from packet buffer */
3295 retval = image_add_section(gdb_connection->vflash_image,
3296 addr, length, 0x0, (uint8_t const *)parse);
3297 if (retval != ERROR_OK)
3300 gdb_put_packet(connection, "OK", 2);
3305 if (strncmp(packet, "vFlashDone", 10) == 0) {
3308 /* process the flashing buffer. No need to erase as GDB
3309 * always issues a vFlashErase first. */
3310 target_call_event_callbacks(target,
3311 TARGET_EVENT_GDB_FLASH_WRITE_START);
3312 result = flash_write(target, gdb_connection->vflash_image,
3314 target_call_event_callbacks(target,
3315 TARGET_EVENT_GDB_FLASH_WRITE_END);
3316 if (result != ERROR_OK) {
3317 if (result == ERROR_FLASH_DST_OUT_OF_BANK)
3318 gdb_put_packet(connection, "E.memtype", 9);
3320 gdb_send_error(connection, EIO);
3322 LOG_DEBUG("wrote %u bytes from vFlash image to flash", (unsigned)written);
3323 gdb_put_packet(connection, "OK", 2);
3326 image_close(gdb_connection->vflash_image);
3327 free(gdb_connection->vflash_image);
3328 gdb_connection->vflash_image = NULL;
3333 gdb_put_packet(connection, "", 0);
3337 static int gdb_detach(struct connection *connection)
3340 * Only reply "OK" to GDB
3341 * it will close the connection and this will trigger a call to
3342 * gdb_connection_closed() that will in turn trigger the event
3343 * TARGET_EVENT_GDB_DETACH
3345 return gdb_put_packet(connection, "OK", 2);
3348 /* The format of 'F' response packet is
3349 * Fretcode,errno,Ctrl-C flag;call-specific attachment
3351 static int gdb_fileio_response_packet(struct connection *connection,
3352 char const *packet, int packet_size)
3354 struct target *target = get_target_from_connection(connection);
3356 char *parsing_point;
3357 int fileio_retcode = strtoul(packet + 1, &separator, 16);
3358 int fileio_errno = 0;
3359 bool fileio_ctrl_c = false;
3364 if (*separator == ',') {
3365 parsing_point = separator + 1;
3366 fileio_errno = strtoul(parsing_point, &separator, 16);
3367 if (*separator == ',') {
3368 if (*(separator + 1) == 'C') {
3369 /* TODO: process ctrl-c */
3370 fileio_ctrl_c = true;
3375 LOG_DEBUG("File-I/O response, retcode: 0x%x, errno: 0x%x, ctrl-c: %s",
3376 fileio_retcode, fileio_errno, fileio_ctrl_c ? "true" : "false");
3378 retval = target_gdb_fileio_end(target, fileio_retcode, fileio_errno, fileio_ctrl_c);
3379 if (retval != ERROR_OK)
3382 /* After File-I/O ends, keep continue or step */
3383 if (gdb_running_type == 'c')
3384 retval = target_resume(target, 1, 0x0, 0, 0);
3385 else if (gdb_running_type == 's')
3386 retval = target_step(target, 1, 0x0, 0);
3388 retval = ERROR_FAIL;
3390 if (retval != ERROR_OK)
3396 static void gdb_log_callback(void *priv, const char *file, unsigned line,
3397 const char *function, const char *string)
3399 struct connection *connection = priv;
3400 struct gdb_connection *gdb_con = connection->priv;
3402 if (gdb_con->output_flag == GDB_OUTPUT_NO)
3403 /* No out allowed */
3406 if (gdb_con->busy) {
3407 /* do not reply this using the O packet */
3411 gdb_output_con(connection, string);
3414 static void gdb_sig_halted(struct connection *connection)
3417 snprintf(sig_reply, 4, "T%2.2x", 2);
3418 gdb_put_packet(connection, sig_reply, 3);
3421 static int gdb_input_inner(struct connection *connection)
3423 /* Do not allocate this on the stack */
3424 static char gdb_packet_buffer[GDB_BUFFER_SIZE + 1]; /* Extra byte for null-termination */
3426 struct target *target;
3427 char const *packet = gdb_packet_buffer;
3430 struct gdb_connection *gdb_con = connection->priv;
3431 static bool warn_use_ext;
3433 target = get_target_from_connection(connection);
3435 /* drain input buffer. If one of the packets fail, then an error
3436 * packet is replied, if applicable.
3438 * This loop will terminate and the error code is returned.
3440 * The calling fn will check if this error is something that
3441 * can be recovered from, or if the connection must be closed.
3443 * If the error is recoverable, this fn is called again to
3444 * drain the rest of the buffer.
3447 packet_size = GDB_BUFFER_SIZE;
3448 retval = gdb_get_packet(connection, gdb_packet_buffer, &packet_size);
3449 if (retval != ERROR_OK)
3452 /* terminate with zero */
3453 gdb_packet_buffer[packet_size] = '\0';
3455 gdb_log_incoming_packet(gdb_packet_buffer);
3457 if (packet_size > 0) {
3459 switch (packet[0]) {
3460 case 'T': /* Is thread alive? */
3461 gdb_thread_packet(connection, packet, packet_size);
3463 case 'H': /* Set current thread ( 'c' for step and continue,
3464 * 'g' for all other operations ) */
3465 gdb_thread_packet(connection, packet, packet_size);
3469 retval = gdb_thread_packet(connection, packet, packet_size);
3470 if (retval == GDB_THREAD_PACKET_NOT_CONSUMED)
3471 retval = gdb_query_packet(connection, packet, packet_size);
3474 retval = gdb_get_registers_packet(connection, packet, packet_size);
3477 retval = gdb_set_registers_packet(connection, packet, packet_size);
3480 retval = gdb_get_register_packet(connection, packet, packet_size);
3483 retval = gdb_set_register_packet(connection, packet, packet_size);
3486 retval = gdb_read_memory_packet(connection, packet, packet_size);
3489 retval = gdb_write_memory_packet(connection, packet, packet_size);
3493 retval = gdb_breakpoint_watchpoint_packet(connection, packet, packet_size);
3496 gdb_last_signal_packet(connection, packet, packet_size);
3497 /* '?' is sent after the eventual '!' */
3498 if (!warn_use_ext && !gdb_con->extended_protocol) {
3499 warn_use_ext = true;
3500 LOG_WARNING("Prefer GDB command \"target extended-remote :%s\" instead of \"target remote :%s\"",
3501 connection->service->port, connection->service->port);
3507 gdb_thread_packet(connection, packet, packet_size);
3508 gdb_con->output_flag = GDB_OUTPUT_ALL;
3510 if (gdb_con->mem_write_error) {
3511 LOG_ERROR("Memory write failure!");
3513 /* now that we have reported the memory write error,
3514 * we can clear the condition */
3515 gdb_con->mem_write_error = false;
3518 bool nostep = false;
3519 bool already_running = false;
3520 if (target->state == TARGET_RUNNING) {
3521 LOG_WARNING("WARNING! The target is already running. "
3522 "All changes GDB did to registers will be discarded! "
3523 "Waiting for target to halt.");
3524 already_running = true;
3525 } else if (target->state != TARGET_HALTED) {
3526 LOG_WARNING("The target is not in the halted nor running stated, "
3527 "stepi/continue ignored.");
3529 } else if ((packet[0] == 's') && gdb_con->sync) {
3530 /* Hmm..... when you issue a continue in GDB, then a "stepi" is
3531 * sent by GDB first to OpenOCD, thus defeating the check to
3532 * make only the single stepping have the sync feature...
3535 LOG_DEBUG("stepi ignored. GDB will now fetch the register state "
3536 "from the target.");
3538 gdb_con->sync = false;
3540 if (!already_running && nostep) {
3541 /* Either the target isn't in the halted state, then we can't
3542 * step/continue. This might be early setup, etc.
3544 * Or we want to allow GDB to pick up a fresh set of
3545 * register values without modifying the target state.
3548 gdb_sig_halted(connection);
3550 /* stop forwarding log packets! */
3551 gdb_con->output_flag = GDB_OUTPUT_NO;
3553 /* We're running/stepping, in which case we can
3554 * forward log output until the target is halted
3556 gdb_con->frontend_state = TARGET_RUNNING;
3557 target_call_event_callbacks(target, TARGET_EVENT_GDB_START);
3559 if (!already_running) {
3560 /* Here we don't want packet processing to stop even if this fails,
3561 * so we use a local variable instead of retval. */
3562 retval = gdb_step_continue_packet(connection, packet, packet_size);
3563 if (retval != ERROR_OK) {
3564 /* we'll never receive a halted
3565 * condition... issue a false one..
3567 gdb_frontend_halted(target, connection);
3574 retval = gdb_v_packet(connection, packet, packet_size);
3577 retval = gdb_detach(connection);
3580 retval = gdb_write_memory_binary_packet(connection, packet, packet_size);
3581 if (retval != ERROR_OK)
3585 if (gdb_con->extended_protocol) {
3586 gdb_con->attached = false;
3589 gdb_put_packet(connection, "OK", 2);
3590 return ERROR_SERVER_REMOTE_CLOSED;
3592 /* handle extended remote protocol */
3593 gdb_con->extended_protocol = true;
3594 gdb_put_packet(connection, "OK", 2);
3597 /* handle extended restart packet */
3598 gdb_restart_inferior(connection, packet, packet_size);
3602 /* packet supported only by smp target i.e cortex_a.c*/
3603 /* handle smp packet replying coreid played to gbd */
3604 gdb_read_smp_packet(connection, packet, packet_size);
3608 /* packet supported only by smp target i.e cortex_a.c */
3609 /* handle smp packet setting coreid to be played at next
3611 gdb_write_smp_packet(connection, packet, packet_size);
3615 /* File-I/O extension */
3616 /* After gdb uses host-side syscall to complete target file
3617 * I/O, gdb sends host-side syscall return value to target
3619 * The format of 'F' response packet is
3620 * Fretcode,errno,Ctrl-C flag;call-specific attachment
3622 gdb_con->frontend_state = TARGET_RUNNING;
3623 gdb_con->output_flag = GDB_OUTPUT_ALL;
3624 gdb_fileio_response_packet(connection, packet, packet_size);
3628 /* ignore unknown packets */
3629 LOG_DEBUG("ignoring 0x%2.2x packet", packet[0]);
3630 gdb_put_packet(connection, "", 0);
3634 /* if a packet handler returned an error, exit input loop */
3635 if (retval != ERROR_OK)
3639 if (gdb_con->ctrl_c) {
3640 if (target->state == TARGET_RUNNING) {
3641 struct target *t = target;
3643 target->rtos->gdb_target_for_threadid(connection, target->rtos->current_threadid, &t);
3644 retval = target_halt(t);
3645 if (retval == ERROR_OK)
3646 retval = target_poll(t);
3647 if (retval != ERROR_OK)
3648 target_call_event_callbacks(target, TARGET_EVENT_GDB_HALT);
3649 gdb_con->ctrl_c = false;
3651 LOG_INFO("The target is not running when halt was requested, stopping GDB.");
3652 target_call_event_callbacks(target, TARGET_EVENT_GDB_HALT);
3656 } while (gdb_con->buf_cnt > 0);
3661 static int gdb_input(struct connection *connection)
3663 int retval = gdb_input_inner(connection);
3664 struct gdb_connection *gdb_con = connection->priv;
3665 if (retval == ERROR_SERVER_REMOTE_CLOSED)
3668 /* logging does not propagate the error, yet can set the gdb_con->closed flag */
3669 if (gdb_con->closed)
3670 return ERROR_SERVER_REMOTE_CLOSED;
3672 /* we'll recover from any other errors(e.g. temporary timeouts, etc.) */
3676 static void gdb_keep_client_alive(struct connection *connection)
3678 struct gdb_connection *gdb_con = connection->priv;
3680 if (gdb_con->busy) {
3681 /* do not send packets, retry asap */
3685 switch (gdb_con->output_flag) {
3687 /* no need for keep-alive */
3689 case GDB_OUTPUT_ALL:
3690 /* send an empty O packet */
3691 gdb_output_con(connection, "");
3698 static const struct service_driver gdb_service_driver = {
3700 .new_connection_during_keep_alive_handler = NULL,
3701 .new_connection_handler = gdb_new_connection,
3702 .input_handler = gdb_input,
3703 .connection_closed_handler = gdb_connection_closed,
3704 .keep_client_alive_handler = gdb_keep_client_alive,
3707 static int gdb_target_start(struct target *target, const char *port)
3709 struct gdb_service *gdb_service;
3711 gdb_service = malloc(sizeof(struct gdb_service));
3716 LOG_INFO("starting gdb server for %s on %s", target_name(target), port);
3718 gdb_service->target = target;
3719 gdb_service->core[0] = -1;
3720 gdb_service->core[1] = -1;
3721 target->gdb_service = gdb_service;
3723 ret = add_service(&gdb_service_driver, port, target->gdb_max_connections, gdb_service);
3724 /* initialize all targets gdb service with the same pointer */
3726 struct target_list *head;
3727 foreach_smp_target(head, target->smp_targets) {
3728 struct target *curr = head->target;
3730 curr->gdb_service = gdb_service;
3736 static int gdb_target_add_one(struct target *target)
3738 /* one gdb instance per smp list */
3739 if ((target->smp) && (target->gdb_service))
3742 /* skip targets that cannot handle a gdb connections (e.g. mem_ap) */
3743 if (!target_supports_gdb_connection(target)) {
3744 LOG_DEBUG("skip gdb server for target %s", target_name(target));
3748 if (target->gdb_port_override) {
3749 if (strcmp(target->gdb_port_override, "disabled") == 0) {
3750 LOG_INFO("gdb port disabled");
3753 return gdb_target_start(target, target->gdb_port_override);
3756 if (strcmp(gdb_port, "disabled") == 0) {
3757 LOG_INFO("gdb port disabled");
3761 int retval = gdb_target_start(target, gdb_port_next);
3762 if (retval == ERROR_OK) {
3763 /* save the port number so can be queried with
3764 * $target_name cget -gdb-port
3766 target->gdb_port_override = strdup(gdb_port_next);
3769 /* If we can parse the port number
3770 * then we increment the port number for the next target.
3773 portnumber = strtol(gdb_port_next, &end, 0);
3775 if (parse_long(gdb_port_next, &portnumber) == ERROR_OK) {
3776 free(gdb_port_next);
3778 gdb_port_next = alloc_printf("%ld", portnumber+1);
3780 /* Don't increment if gdb_port is 0, since we're just
3781 * trying to allocate an unused port. */
3782 gdb_port_next = strdup("0");
3790 int gdb_target_add_all(struct target *target)
3793 LOG_WARNING("gdb services need one or more targets defined");
3798 int retval = gdb_target_add_one(target);
3799 if (retval != ERROR_OK)
3802 target = target->next;
3808 COMMAND_HANDLER(handle_gdb_sync_command)
3811 return ERROR_COMMAND_SYNTAX_ERROR;
3813 if (!current_gdb_connection) {
3815 "gdb_sync command can only be run from within gdb using \"monitor gdb_sync\"");
3819 current_gdb_connection->sync = true;
3824 /* daemon configuration command gdb_port */
3825 COMMAND_HANDLER(handle_gdb_port_command)
3827 int retval = CALL_COMMAND_HANDLER(server_pipe_command, &gdb_port);
3828 if (retval == ERROR_OK) {
3829 free(gdb_port_next);
3830 gdb_port_next = strdup(gdb_port);
3835 COMMAND_HANDLER(handle_gdb_memory_map_command)
3838 return ERROR_COMMAND_SYNTAX_ERROR;
3840 COMMAND_PARSE_ENABLE(CMD_ARGV[0], gdb_use_memory_map);
3844 COMMAND_HANDLER(handle_gdb_flash_program_command)
3847 return ERROR_COMMAND_SYNTAX_ERROR;
3849 COMMAND_PARSE_ENABLE(CMD_ARGV[0], gdb_flash_program);
3853 COMMAND_HANDLER(handle_gdb_report_data_abort_command)
3856 return ERROR_COMMAND_SYNTAX_ERROR;
3858 COMMAND_PARSE_ENABLE(CMD_ARGV[0], gdb_report_data_abort);
3862 COMMAND_HANDLER(handle_gdb_report_register_access_error)
3865 return ERROR_COMMAND_SYNTAX_ERROR;
3867 COMMAND_PARSE_ENABLE(CMD_ARGV[0], gdb_report_register_access_error);
3871 /* gdb_breakpoint_override */
3872 COMMAND_HANDLER(handle_gdb_breakpoint_override_command)
3874 if (CMD_ARGC == 0) {
3876 } else if (CMD_ARGC == 1) {
3877 gdb_breakpoint_override = 1;
3878 if (strcmp(CMD_ARGV[0], "hard") == 0)
3879 gdb_breakpoint_override_type = BKPT_HARD;
3880 else if (strcmp(CMD_ARGV[0], "soft") == 0)
3881 gdb_breakpoint_override_type = BKPT_SOFT;
3882 else if (strcmp(CMD_ARGV[0], "disable") == 0)
3883 gdb_breakpoint_override = 0;
3885 return ERROR_COMMAND_SYNTAX_ERROR;
3886 if (gdb_breakpoint_override)
3887 LOG_USER("force %s breakpoints",
3888 (gdb_breakpoint_override_type == BKPT_HARD) ? "hard" : "soft");
3890 LOG_USER("breakpoint type is not overridden");
3895 COMMAND_HANDLER(handle_gdb_target_description_command)
3898 return ERROR_COMMAND_SYNTAX_ERROR;
3900 COMMAND_PARSE_ENABLE(CMD_ARGV[0], gdb_use_target_description);
3904 COMMAND_HANDLER(handle_gdb_save_tdesc_command)
3907 uint32_t tdesc_length;
3908 struct target *target = get_current_target(CMD_CTX);
3910 int retval = gdb_generate_target_description(target, &tdesc);
3911 if (retval != ERROR_OK) {
3912 LOG_ERROR("Unable to Generate Target Description");
3916 tdesc_length = strlen(tdesc);
3918 struct fileio *fileio;
3919 size_t size_written;
3921 char *tdesc_filename = alloc_printf("%s.xml", target_type_name(target));
3922 if (!tdesc_filename) {
3923 retval = ERROR_FAIL;
3927 retval = fileio_open(&fileio, tdesc_filename, FILEIO_WRITE, FILEIO_TEXT);
3929 if (retval != ERROR_OK) {
3930 LOG_ERROR("Can't open %s for writing", tdesc_filename);
3934 retval = fileio_write(fileio, tdesc_length, tdesc, &size_written);
3936 fileio_close(fileio);
3938 if (retval != ERROR_OK)
3939 LOG_ERROR("Error while writing the tdesc file");
3942 free(tdesc_filename);
3948 static const struct command_registration gdb_command_handlers[] = {
3951 .handler = handle_gdb_sync_command,
3952 .mode = COMMAND_ANY,
3953 .help = "next stepi will return immediately allowing "
3954 "GDB to fetch register state without affecting "
3960 .handler = handle_gdb_port_command,
3961 .mode = COMMAND_CONFIG,
3962 .help = "Normally gdb listens to a TCP/IP port. Each subsequent GDB "
3963 "server listens for the next port number after the "
3964 "base port number specified. "
3965 "No arguments reports GDB port. \"pipe\" means listen to stdin "
3966 "output to stdout, an integer is base port number, \"disabled\" disables "
3967 "port. Any other string is are interpreted as named pipe to listen to. "
3968 "Output pipe is the same name as input pipe, but with 'o' appended.",
3969 .usage = "[port_num]",
3972 .name = "gdb_memory_map",
3973 .handler = handle_gdb_memory_map_command,
3974 .mode = COMMAND_CONFIG,
3975 .help = "enable or disable memory map",
3976 .usage = "('enable'|'disable')"
3979 .name = "gdb_flash_program",
3980 .handler = handle_gdb_flash_program_command,
3981 .mode = COMMAND_CONFIG,
3982 .help = "enable or disable flash program",
3983 .usage = "('enable'|'disable')"
3986 .name = "gdb_report_data_abort",
3987 .handler = handle_gdb_report_data_abort_command,
3988 .mode = COMMAND_CONFIG,
3989 .help = "enable or disable reporting data aborts",
3990 .usage = "('enable'|'disable')"
3993 .name = "gdb_report_register_access_error",
3994 .handler = handle_gdb_report_register_access_error,
3995 .mode = COMMAND_CONFIG,
3996 .help = "enable or disable reporting register access errors",
3997 .usage = "('enable'|'disable')"
4000 .name = "gdb_breakpoint_override",
4001 .handler = handle_gdb_breakpoint_override_command,
4002 .mode = COMMAND_ANY,
4003 .help = "Display or specify type of breakpoint "
4004 "to be used by gdb 'break' commands.",
4005 .usage = "('hard'|'soft'|'disable')"
4008 .name = "gdb_target_description",
4009 .handler = handle_gdb_target_description_command,
4010 .mode = COMMAND_CONFIG,
4011 .help = "enable or disable target description",
4012 .usage = "('enable'|'disable')"
4015 .name = "gdb_save_tdesc",
4016 .handler = handle_gdb_save_tdesc_command,
4017 .mode = COMMAND_EXEC,
4018 .help = "Save the target description file",
4021 COMMAND_REGISTRATION_DONE
4024 int gdb_register_commands(struct command_context *cmd_ctx)
4026 gdb_port = strdup("3333");
4027 gdb_port_next = strdup("3333");
4028 return register_commands(cmd_ctx, NULL, gdb_command_handlers);
4031 void gdb_service_free(void)
4034 free(gdb_port_next);