1 /***************************************************************************
2 * Copyright (C) 2005 by Dominic Rath *
3 * Dominic.Rath@gmx.de *
5 * Copyright (C) 2007-2010 Øyvind Harboe *
6 * oyvind.harboe@zylin.com *
8 * Copyright (C) 2008 by Spencer Oliver *
9 * spen@spen-soft.co.uk *
11 * Copyright (C) 2011 by Broadcom Corporation *
12 * Evan Hunter - ehunter@broadcom.com *
14 * Copyright (C) ST-Ericsson SA 2011 *
15 * michel.jaouen@stericsson.com : smp minimum support *
17 * Copyright (C) 2013 Andes Technology *
18 * Hsiangkai Wang <hkwang@andestech.com> *
20 * Copyright (C) 2013 Franck Jullien *
21 * elec4fun@gmail.com *
23 * This program is free software; you can redistribute it and/or modify *
24 * it under the terms of the GNU General Public License as published by *
25 * the Free Software Foundation; either version 2 of the License, or *
26 * (at your option) any later version. *
28 * This program is distributed in the hope that it will be useful, *
29 * but WITHOUT ANY WARRANTY; without even the implied warranty of *
30 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
31 * GNU General Public License for more details. *
33 * You should have received a copy of the GNU General Public License *
34 * along with this program. If not, see <http://www.gnu.org/licenses/>. *
35 ***************************************************************************/
41 #include <target/breakpoints.h>
42 #include <target/target_request.h>
43 #include <target/register.h>
44 #include <target/target.h>
45 #include <target/target_type.h>
46 #include <target/semihosting_common.h>
48 #include <flash/nor/core.h>
49 #include "gdb_server.h"
50 #include <target/image.h>
51 #include <jtag/jtag.h>
52 #include "rtos/rtos.h"
53 #include "target/smp.h"
57 * GDB server implementation.
59 * This implements the GDB Remote Serial Protocol, over TCP connections,
60 * giving GDB access to the JTAG or other hardware debugging facilities
61 * found in most modern embedded processors.
64 struct target_desc_format {
66 uint32_t tdesc_length;
69 /* private connection data for GDB */
70 struct gdb_connection {
71 char buffer[GDB_BUFFER_SIZE + 1]; /* Extra byte for null-termination */
75 enum target_state frontend_state;
76 struct image *vflash_image;
80 /* set flag to true if you want the next stepi to return immediately.
81 * allowing GDB to pick up a fresh set of register values from the target
82 * without modifying the target state. */
84 /* We delay reporting memory write errors until next step/continue or memory
85 * write. This improves performance of gdb load significantly as the GDB packet
86 * can be replied immediately and a new GDB packet will be ready without delay
87 * (ca. 10% or so...). */
89 /* with extended-remote it seems we need to better emulate attach/detach.
90 * what this means is we reply with a W stop reply after a kill packet,
91 * normally we reply with a S reply via gdb_last_signal_packet.
92 * as a side note this behaviour only effects gdb > 6.8 */
94 /* set when extended protocol is used */
95 bool extended_protocol;
96 /* temporarily used for target description support */
97 struct target_desc_format target_desc;
98 /* temporarily used for thread list support */
103 #define _DEBUG_GDB_IO_
106 static struct gdb_connection *current_gdb_connection;
108 static int gdb_breakpoint_override;
109 static enum breakpoint_type gdb_breakpoint_override_type;
111 static int gdb_error(struct connection *connection, int retval);
112 static char *gdb_port;
113 static char *gdb_port_next;
115 static void gdb_log_callback(void *priv, const char *file, unsigned line,
116 const char *function, const char *string);
118 static void gdb_sig_halted(struct connection *connection);
120 /* number of gdb connections, mainly to suppress gdb related debugging spam
121 * in helper/log.c when no gdb connections are actually active */
122 int gdb_actual_connections;
124 /* set if we are sending a memory map to gdb
125 * via qXfer:memory-map:read packet */
126 /* enabled by default*/
127 static int gdb_use_memory_map = 1;
128 /* enabled by default*/
129 static int gdb_flash_program = 1;
131 /* if set, data aborts cause an error to be reported in memory read packets
132 * see the code in gdb_read_memory_packet() for further explanations.
133 * Disabled by default.
135 static int gdb_report_data_abort;
136 /* If set, errors when accessing registers are reported to gdb. Disabled by
138 static int gdb_report_register_access_error;
140 /* set if we are sending target descriptions to gdb
141 * via qXfer:features:read packet */
142 /* enabled by default */
143 static int gdb_use_target_description = 1;
145 /* current processing free-run type, used by file-I/O */
146 static char gdb_running_type;
148 static int gdb_last_signal(struct target *target)
150 switch (target->debug_reason) {
151 case DBG_REASON_DBGRQ:
152 return 0x2; /* SIGINT */
153 case DBG_REASON_BREAKPOINT:
154 case DBG_REASON_WATCHPOINT:
155 case DBG_REASON_WPTANDBKPT:
156 return 0x05; /* SIGTRAP */
157 case DBG_REASON_SINGLESTEP:
158 return 0x05; /* SIGTRAP */
159 case DBG_REASON_EXC_CATCH:
161 case DBG_REASON_NOTHALTED:
162 return 0x0; /* no signal... shouldn't happen */
164 LOG_USER("undefined debug reason %d - target needs reset",
165 target->debug_reason);
170 static int check_pending(struct connection *connection,
171 int timeout_s, int *got_data)
173 /* a non-blocking socket will block if there is 0 bytes available on the socket,
174 * but return with as many bytes as are available immediately
178 struct gdb_connection *gdb_con = connection->priv;
180 if (got_data == NULL)
184 if (gdb_con->buf_cnt > 0) {
190 FD_SET(connection->fd, &read_fds);
192 tv.tv_sec = timeout_s;
194 if (socket_select(connection->fd + 1, &read_fds, NULL, NULL, &tv) == 0) {
195 /* This can typically be because a "monitor" command took too long
196 * before printing any progress messages
199 return ERROR_GDB_TIMEOUT;
203 *got_data = FD_ISSET(connection->fd, &read_fds) != 0;
207 static int gdb_get_char_inner(struct connection *connection, int *next_char)
209 struct gdb_connection *gdb_con = connection->priv;
210 int retval = ERROR_OK;
212 #ifdef _DEBUG_GDB_IO_
216 if (connection->service->type != CONNECTION_TCP)
217 gdb_con->buf_cnt = read(connection->fd, gdb_con->buffer, GDB_BUFFER_SIZE);
219 retval = check_pending(connection, 1, NULL);
220 if (retval != ERROR_OK)
222 gdb_con->buf_cnt = read_socket(connection->fd,
227 if (gdb_con->buf_cnt > 0)
229 if (gdb_con->buf_cnt == 0) {
230 gdb_con->closed = true;
231 return ERROR_SERVER_REMOTE_CLOSED;
235 errno = WSAGetLastError();
241 case WSAECONNABORTED:
242 gdb_con->closed = true;
243 return ERROR_SERVER_REMOTE_CLOSED;
245 gdb_con->closed = true;
246 return ERROR_SERVER_REMOTE_CLOSED;
248 LOG_ERROR("read: %d", errno);
257 gdb_con->closed = true;
258 return ERROR_SERVER_REMOTE_CLOSED;
260 gdb_con->closed = true;
261 return ERROR_SERVER_REMOTE_CLOSED;
263 LOG_ERROR("read: %s", strerror(errno));
264 gdb_con->closed = true;
265 return ERROR_SERVER_REMOTE_CLOSED;
270 #ifdef _DEBUG_GDB_IO_
271 debug_buffer = strndup(gdb_con->buffer, gdb_con->buf_cnt);
272 LOG_DEBUG("received '%s'", debug_buffer);
276 gdb_con->buf_p = gdb_con->buffer;
278 *next_char = *(gdb_con->buf_p++);
279 if (gdb_con->buf_cnt > 0)
280 connection->input_pending = true;
282 connection->input_pending = false;
283 #ifdef _DEBUG_GDB_IO_
284 LOG_DEBUG("returned char '%c' (0x%2.2x)", *next_char, *next_char);
291 * The cool thing about this fn is that it allows buf_p and buf_cnt to be
292 * held in registers in the inner loop.
294 * For small caches and embedded systems this is important!
296 static inline int gdb_get_char_fast(struct connection *connection,
297 int *next_char, char **buf_p, int *buf_cnt)
299 int retval = ERROR_OK;
301 if ((*buf_cnt)-- > 0) {
302 *next_char = **buf_p;
305 connection->input_pending = true;
307 connection->input_pending = false;
309 #ifdef _DEBUG_GDB_IO_
310 LOG_DEBUG("returned char '%c' (0x%2.2x)", *next_char, *next_char);
316 struct gdb_connection *gdb_con = connection->priv;
317 gdb_con->buf_p = *buf_p;
318 gdb_con->buf_cnt = *buf_cnt;
319 retval = gdb_get_char_inner(connection, next_char);
320 *buf_p = gdb_con->buf_p;
321 *buf_cnt = gdb_con->buf_cnt;
326 static int gdb_get_char(struct connection *connection, int *next_char)
328 struct gdb_connection *gdb_con = connection->priv;
329 return gdb_get_char_fast(connection, next_char, &gdb_con->buf_p, &gdb_con->buf_cnt);
332 static int gdb_putback_char(struct connection *connection, int last_char)
334 struct gdb_connection *gdb_con = connection->priv;
336 if (gdb_con->buf_p > gdb_con->buffer) {
337 *(--gdb_con->buf_p) = last_char;
340 LOG_ERROR("BUG: couldn't put character back");
345 /* The only way we can detect that the socket is closed is the first time
346 * we write to it, we will fail. Subsequent write operations will
347 * succeed. Shudder! */
348 static int gdb_write(struct connection *connection, void *data, int len)
350 struct gdb_connection *gdb_con = connection->priv;
352 return ERROR_SERVER_REMOTE_CLOSED;
354 if (connection_write(connection, data, len) == len)
356 gdb_con->closed = true;
357 return ERROR_SERVER_REMOTE_CLOSED;
360 static void gdb_log_incoming_packet(char *packet)
362 if (!LOG_LEVEL_IS(LOG_LVL_DEBUG))
365 /* Avoid dumping non-printable characters to the terminal */
366 const unsigned packet_len = strlen(packet);
367 const char *nonprint = find_nonprint_char(packet, packet_len);
369 /* Does packet at least have a prefix that is printable?
370 * Look within the first 50 chars of the packet. */
371 const char *colon = memchr(packet, ':', MIN(50, packet_len));
372 const bool packet_has_prefix = (colon != NULL);
373 const bool packet_prefix_printable = (packet_has_prefix && nonprint > colon);
375 if (packet_prefix_printable) {
376 const unsigned int prefix_len = colon - packet + 1; /* + 1 to include the ':' */
377 const unsigned int payload_len = packet_len - prefix_len;
378 LOG_DEBUG("received packet: %.*s<binary-data-%u-bytes>", prefix_len, packet, payload_len);
380 LOG_DEBUG("received packet: <binary-data-%u-bytes>", packet_len);
383 /* All chars printable, dump the packet as is */
384 LOG_DEBUG("received packet: %s", packet);
388 static void gdb_log_outgoing_packet(char *packet_buf, unsigned int packet_len, unsigned char checksum)
390 if (!LOG_LEVEL_IS(LOG_LVL_DEBUG))
393 if (find_nonprint_char(packet_buf, packet_len))
394 LOG_DEBUG("sending packet: $<binary-data-%u-bytes>#%2.2x", packet_len, checksum);
396 LOG_DEBUG("sending packet: $%.*s#%2.2x'", packet_len, packet_buf, checksum);
399 static int gdb_put_packet_inner(struct connection *connection,
400 char *buffer, int len)
403 unsigned char my_checksum = 0;
406 struct gdb_connection *gdb_con = connection->priv;
408 for (i = 0; i < len; i++)
409 my_checksum += buffer[i];
411 #ifdef _DEBUG_GDB_IO_
413 * At this point we should have nothing in the input queue from GDB,
414 * however sometimes '-' is sent even though we've already received
415 * an ACK (+) for everything we've sent off.
419 retval = check_pending(connection, 0, &gotdata);
420 if (retval != ERROR_OK)
424 retval = gdb_get_char(connection, &reply);
425 if (retval != ERROR_OK)
428 /* fix a problem with some IAR tools */
429 gdb_putback_char(connection, reply);
430 LOG_DEBUG("Unexpected start of new packet");
434 LOG_WARNING("Discard unexpected char %c", reply);
439 gdb_log_outgoing_packet(buffer, len, my_checksum);
441 char local_buffer[1024];
442 local_buffer[0] = '$';
443 if ((size_t)len + 4 <= sizeof(local_buffer)) {
444 /* performance gain on smaller packets by only a single call to gdb_write() */
445 memcpy(local_buffer + 1, buffer, len++);
446 len += snprintf(local_buffer + len, sizeof(local_buffer) - len, "#%02x", my_checksum);
447 retval = gdb_write(connection, local_buffer, len);
448 if (retval != ERROR_OK)
451 /* larger packets are transmitted directly from caller supplied buffer
452 * by several calls to gdb_write() to avoid dynamic allocation */
453 snprintf(local_buffer + 1, sizeof(local_buffer) - 1, "#%02x", my_checksum);
454 retval = gdb_write(connection, local_buffer, 1);
455 if (retval != ERROR_OK)
457 retval = gdb_write(connection, buffer, len);
458 if (retval != ERROR_OK)
460 retval = gdb_write(connection, local_buffer + 1, 3);
461 if (retval != ERROR_OK)
465 if (gdb_con->noack_mode)
468 retval = gdb_get_char(connection, &reply);
469 if (retval != ERROR_OK)
474 else if (reply == '-') {
475 /* Stop sending output packets for now */
476 log_remove_callback(gdb_log_callback, connection);
477 LOG_WARNING("negative reply, retrying");
478 } else if (reply == 0x3) {
479 gdb_con->ctrl_c = true;
480 retval = gdb_get_char(connection, &reply);
481 if (retval != ERROR_OK)
485 else if (reply == '-') {
486 /* Stop sending output packets for now */
487 log_remove_callback(gdb_log_callback, connection);
488 LOG_WARNING("negative reply, retrying");
489 } else if (reply == '$') {
490 LOG_ERROR("GDB missing ack(1) - assumed good");
491 gdb_putback_char(connection, reply);
494 LOG_ERROR("unknown character(1) 0x%2.2x in reply, dropping connection", reply);
495 gdb_con->closed = true;
496 return ERROR_SERVER_REMOTE_CLOSED;
498 } else if (reply == '$') {
499 LOG_ERROR("GDB missing ack(2) - assumed good");
500 gdb_putback_char(connection, reply);
503 LOG_ERROR("unknown character(2) 0x%2.2x in reply, dropping connection",
505 gdb_con->closed = true;
506 return ERROR_SERVER_REMOTE_CLOSED;
510 return ERROR_SERVER_REMOTE_CLOSED;
515 int gdb_put_packet(struct connection *connection, char *buffer, int len)
517 struct gdb_connection *gdb_con = connection->priv;
518 gdb_con->busy = true;
519 int retval = gdb_put_packet_inner(connection, buffer, len);
520 gdb_con->busy = false;
522 /* we sent some data, reset timer for keep alive messages */
528 static inline int fetch_packet(struct connection *connection,
529 int *checksum_ok, int noack, int *len, char *buffer)
531 unsigned char my_checksum = 0;
534 int retval = ERROR_OK;
536 struct gdb_connection *gdb_con = connection->priv;
541 /* move this over into local variables to use registers and give the
542 * more freedom to optimize */
543 char *buf_p = gdb_con->buf_p;
544 int buf_cnt = gdb_con->buf_cnt;
547 /* The common case is that we have an entire packet with no escape chars.
548 * We need to leave at least 2 bytes in the buffer to have
549 * gdb_get_char() update various bits and bobs correctly.
551 if ((buf_cnt > 2) && ((buf_cnt + count) < *len)) {
552 /* The compiler will struggle a bit with constant propagation and
553 * aliasing, so we help it by showing that these values do not
554 * change inside the loop
558 int run = buf_cnt - 2;
564 if (character == '#') {
565 /* Danger! character can be '#' when esc is
566 * used so we need an explicit boolean for done here. */
571 if (character == '}') {
572 /* data transmitted in binary mode (X packet)
573 * uses 0x7d as escape character */
574 my_checksum += character & 0xff;
577 my_checksum += character & 0xff;
578 buffer[count++] = (character ^ 0x20) & 0xff;
580 my_checksum += character & 0xff;
581 buffer[count++] = character & 0xff;
590 LOG_ERROR("packet buffer too small");
591 retval = ERROR_GDB_BUFFER_TOO_SMALL;
595 retval = gdb_get_char_fast(connection, &character, &buf_p, &buf_cnt);
596 if (retval != ERROR_OK)
599 if (character == '#')
602 if (character == '}') {
603 /* data transmitted in binary mode (X packet)
604 * uses 0x7d as escape character */
605 my_checksum += character & 0xff;
607 retval = gdb_get_char_fast(connection, &character, &buf_p, &buf_cnt);
608 if (retval != ERROR_OK)
611 my_checksum += character & 0xff;
612 buffer[count++] = (character ^ 0x20) & 0xff;
614 my_checksum += character & 0xff;
615 buffer[count++] = character & 0xff;
619 gdb_con->buf_p = buf_p;
620 gdb_con->buf_cnt = buf_cnt;
622 if (retval != ERROR_OK)
627 retval = gdb_get_char(connection, &character);
628 if (retval != ERROR_OK)
630 checksum[0] = character;
631 retval = gdb_get_char(connection, &character);
632 if (retval != ERROR_OK)
634 checksum[1] = character;
638 *checksum_ok = (my_checksum == strtoul(checksum, NULL, 16));
643 static int gdb_get_packet_inner(struct connection *connection,
644 char *buffer, int *len)
648 struct gdb_connection *gdb_con = connection->priv;
652 retval = gdb_get_char(connection, &character);
653 if (retval != ERROR_OK)
656 #ifdef _DEBUG_GDB_IO_
657 LOG_DEBUG("character: '%c'", character);
664 /* According to the GDB documentation
665 * (https://sourceware.org/gdb/onlinedocs/gdb/Packet-Acknowledgment.html):
666 * "gdb sends a final `+` acknowledgment of the stub's `OK`
667 * response, which can be safely ignored by the stub."
668 * However OpenOCD server already is in noack mode at this
669 * point and instead of ignoring this it was emitting a
670 * warning. This code makes server ignore the first ACK
671 * that will be received after going into noack mode,
672 * warning only about subsequent ACK's. */
673 if (gdb_con->noack_mode > 1) {
674 LOG_WARNING("acknowledgment received, but no packet pending");
675 } else if (gdb_con->noack_mode) {
676 LOG_DEBUG("Received first acknowledgment after entering noack mode. Ignoring it.");
677 gdb_con->noack_mode = 2;
681 LOG_WARNING("negative acknowledgment, but no packet pending");
684 gdb_con->ctrl_c = true;
688 LOG_WARNING("ignoring character 0x%x", character);
691 } while (character != '$');
694 /* explicit code expansion here to get faster inlined code in -O3 by not
695 * calculating checksum */
696 if (gdb_con->noack_mode) {
697 retval = fetch_packet(connection, &checksum_ok, 1, len, buffer);
698 if (retval != ERROR_OK)
701 retval = fetch_packet(connection, &checksum_ok, 0, len, buffer);
702 if (retval != ERROR_OK)
706 if (gdb_con->noack_mode) {
707 /* checksum is not checked in noack mode */
711 retval = gdb_write(connection, "+", 1);
712 if (retval != ERROR_OK)
718 return ERROR_SERVER_REMOTE_CLOSED;
723 static int gdb_get_packet(struct connection *connection, char *buffer, int *len)
725 struct gdb_connection *gdb_con = connection->priv;
726 gdb_con->busy = true;
727 int retval = gdb_get_packet_inner(connection, buffer, len);
728 gdb_con->busy = false;
732 static int gdb_output_con(struct connection *connection, const char *line)
737 bin_size = strlen(line);
739 hex_buffer = malloc(bin_size * 2 + 2);
740 if (hex_buffer == NULL)
741 return ERROR_GDB_BUFFER_TOO_SMALL;
744 size_t pkt_len = hexify(hex_buffer + 1, (const uint8_t *)line, bin_size,
746 int retval = gdb_put_packet(connection, hex_buffer, pkt_len + 1);
752 static int gdb_output(struct command_context *context, const char *line)
754 /* this will be dumped to the log and also sent as an O packet if possible */
755 LOG_USER_N("%s", line);
759 static void gdb_signal_reply(struct target *target, struct connection *connection)
761 struct gdb_connection *gdb_connection = connection->priv;
763 char stop_reason[32];
764 char current_thread[25];
768 rtos_update_threads(target);
770 if (target->debug_reason == DBG_REASON_EXIT) {
771 sig_reply_len = snprintf(sig_reply, sizeof(sig_reply), "W00");
774 if (target->rtos != NULL) {
775 target->rtos->current_threadid = target->rtos->current_thread;
776 target->rtos->gdb_target_for_threadid(connection, target->rtos->current_threadid, &ct);
781 if (gdb_connection->ctrl_c) {
784 signal_var = gdb_last_signal(ct);
786 stop_reason[0] = '\0';
787 if (ct->debug_reason == DBG_REASON_WATCHPOINT) {
788 enum watchpoint_rw hit_wp_type;
789 target_addr_t hit_wp_address;
791 if (watchpoint_hit(ct, &hit_wp_type, &hit_wp_address) == ERROR_OK) {
793 switch (hit_wp_type) {
795 snprintf(stop_reason, sizeof(stop_reason),
796 "watch:%08" TARGET_PRIxADDR ";", hit_wp_address);
799 snprintf(stop_reason, sizeof(stop_reason),
800 "rwatch:%08" TARGET_PRIxADDR ";", hit_wp_address);
803 snprintf(stop_reason, sizeof(stop_reason),
804 "awatch:%08" TARGET_PRIxADDR ";", hit_wp_address);
812 current_thread[0] = '\0';
813 if (target->rtos != NULL)
814 snprintf(current_thread, sizeof(current_thread), "thread:%" PRIx64 ";",
815 target->rtos->current_thread);
817 sig_reply_len = snprintf(sig_reply, sizeof(sig_reply), "T%2.2x%s%s",
818 signal_var, stop_reason, current_thread);
820 gdb_connection->ctrl_c = false;
823 gdb_put_packet(connection, sig_reply, sig_reply_len);
824 gdb_connection->frontend_state = TARGET_HALTED;
827 static void gdb_fileio_reply(struct target *target, struct connection *connection)
829 struct gdb_connection *gdb_connection = connection->priv;
830 char fileio_command[256];
832 bool program_exited = false;
834 if (strcmp(target->fileio_info->identifier, "open") == 0)
835 sprintf(fileio_command, "F%s,%" PRIx64 "/%" PRIx64 ",%" PRIx64 ",%" PRIx64, target->fileio_info->identifier,
836 target->fileio_info->param_1,
837 target->fileio_info->param_2 + 1, /* len + trailing zero */
838 target->fileio_info->param_3,
839 target->fileio_info->param_4);
840 else if (strcmp(target->fileio_info->identifier, "close") == 0)
841 sprintf(fileio_command, "F%s,%" PRIx64, target->fileio_info->identifier,
842 target->fileio_info->param_1);
843 else if (strcmp(target->fileio_info->identifier, "read") == 0)
844 sprintf(fileio_command, "F%s,%" PRIx64 ",%" PRIx64 ",%" PRIx64, target->fileio_info->identifier,
845 target->fileio_info->param_1,
846 target->fileio_info->param_2,
847 target->fileio_info->param_3);
848 else if (strcmp(target->fileio_info->identifier, "write") == 0)
849 sprintf(fileio_command, "F%s,%" PRIx64 ",%" PRIx64 ",%" PRIx64, target->fileio_info->identifier,
850 target->fileio_info->param_1,
851 target->fileio_info->param_2,
852 target->fileio_info->param_3);
853 else if (strcmp(target->fileio_info->identifier, "lseek") == 0)
854 sprintf(fileio_command, "F%s,%" PRIx64 ",%" PRIx64 ",%" PRIx64, target->fileio_info->identifier,
855 target->fileio_info->param_1,
856 target->fileio_info->param_2,
857 target->fileio_info->param_3);
858 else if (strcmp(target->fileio_info->identifier, "rename") == 0)
859 sprintf(fileio_command, "F%s,%" PRIx64 "/%" PRIx64 ",%" PRIx64 "/%" PRIx64, target->fileio_info->identifier,
860 target->fileio_info->param_1,
861 target->fileio_info->param_2 + 1, /* len + trailing zero */
862 target->fileio_info->param_3,
863 target->fileio_info->param_4 + 1); /* len + trailing zero */
864 else if (strcmp(target->fileio_info->identifier, "unlink") == 0)
865 sprintf(fileio_command, "F%s,%" PRIx64 "/%" PRIx64, target->fileio_info->identifier,
866 target->fileio_info->param_1,
867 target->fileio_info->param_2 + 1); /* len + trailing zero */
868 else if (strcmp(target->fileio_info->identifier, "stat") == 0)
869 sprintf(fileio_command, "F%s,%" PRIx64 "/%" PRIx64 ",%" PRIx64, target->fileio_info->identifier,
870 target->fileio_info->param_1,
871 target->fileio_info->param_2,
872 target->fileio_info->param_3);
873 else if (strcmp(target->fileio_info->identifier, "fstat") == 0)
874 sprintf(fileio_command, "F%s,%" PRIx64 ",%" PRIx64, target->fileio_info->identifier,
875 target->fileio_info->param_1,
876 target->fileio_info->param_2);
877 else if (strcmp(target->fileio_info->identifier, "gettimeofday") == 0)
878 sprintf(fileio_command, "F%s,%" PRIx64 ",%" PRIx64, target->fileio_info->identifier,
879 target->fileio_info->param_1,
880 target->fileio_info->param_2);
881 else if (strcmp(target->fileio_info->identifier, "isatty") == 0)
882 sprintf(fileio_command, "F%s,%" PRIx64, target->fileio_info->identifier,
883 target->fileio_info->param_1);
884 else if (strcmp(target->fileio_info->identifier, "system") == 0)
885 sprintf(fileio_command, "F%s,%" PRIx64 "/%" PRIx64, target->fileio_info->identifier,
886 target->fileio_info->param_1,
887 target->fileio_info->param_2 + 1); /* len + trailing zero */
888 else if (strcmp(target->fileio_info->identifier, "exit") == 0) {
889 /* If target hits exit syscall, report to GDB the program is terminated.
890 * In addition, let target run its own exit syscall handler. */
891 program_exited = true;
892 sprintf(fileio_command, "W%02" PRIx64, target->fileio_info->param_1);
894 LOG_DEBUG("Unknown syscall: %s", target->fileio_info->identifier);
896 /* encounter unknown syscall, continue */
897 gdb_connection->frontend_state = TARGET_RUNNING;
898 target_resume(target, 1, 0x0, 0, 0);
902 command_len = strlen(fileio_command);
903 gdb_put_packet(connection, fileio_command, command_len);
905 if (program_exited) {
906 /* Use target_resume() to let target run its own exit syscall handler. */
907 gdb_connection->frontend_state = TARGET_RUNNING;
908 target_resume(target, 1, 0x0, 0, 0);
910 gdb_connection->frontend_state = TARGET_HALTED;
911 rtos_update_threads(target);
915 static void gdb_frontend_halted(struct target *target, struct connection *connection)
917 struct gdb_connection *gdb_connection = connection->priv;
919 /* In the GDB protocol when we are stepping or continuing execution,
920 * we have a lingering reply. Upon receiving a halted event
921 * when we have that lingering packet, we reply to the original
922 * step or continue packet.
924 * Executing monitor commands can bring the target in and
925 * out of the running state so we'll see lots of TARGET_EVENT_XXX
926 * that are to be ignored.
928 if (gdb_connection->frontend_state == TARGET_RUNNING) {
929 /* stop forwarding log packets! */
930 log_remove_callback(gdb_log_callback, connection);
932 /* check fileio first */
933 if (target_get_gdb_fileio_info(target, target->fileio_info) == ERROR_OK)
934 gdb_fileio_reply(target, connection);
936 gdb_signal_reply(target, connection);
940 static int gdb_target_callback_event_handler(struct target *target,
941 enum target_event event, void *priv)
943 struct connection *connection = priv;
944 struct gdb_service *gdb_service = connection->service->priv;
946 if (gdb_service->target != target)
950 case TARGET_EVENT_GDB_HALT:
951 gdb_frontend_halted(target, connection);
953 case TARGET_EVENT_HALTED:
954 target_call_event_callbacks(target, TARGET_EVENT_GDB_END);
963 static int gdb_new_connection(struct connection *connection)
965 struct gdb_connection *gdb_connection = malloc(sizeof(struct gdb_connection));
966 struct target *target;
970 target = get_target_from_connection(connection);
971 connection->priv = gdb_connection;
972 connection->cmd_ctx->current_target = target;
974 /* initialize gdb connection information */
975 gdb_connection->buf_p = gdb_connection->buffer;
976 gdb_connection->buf_cnt = 0;
977 gdb_connection->ctrl_c = false;
978 gdb_connection->frontend_state = TARGET_HALTED;
979 gdb_connection->vflash_image = NULL;
980 gdb_connection->closed = false;
981 gdb_connection->busy = false;
982 gdb_connection->noack_mode = 0;
983 gdb_connection->sync = false;
984 gdb_connection->mem_write_error = false;
985 gdb_connection->attached = true;
986 gdb_connection->extended_protocol = false;
987 gdb_connection->target_desc.tdesc = NULL;
988 gdb_connection->target_desc.tdesc_length = 0;
989 gdb_connection->thread_list = NULL;
991 /* send ACK to GDB for debug request */
992 gdb_write(connection, "+", 1);
994 /* output goes through gdb connection */
995 command_set_output_handler(connection->cmd_ctx, gdb_output, connection);
997 /* we must remove all breakpoints registered to the target as a previous
998 * GDB session could leave dangling breakpoints if e.g. communication
1001 breakpoint_clear_target(target);
1002 watchpoint_clear_target(target);
1004 /* remove the initial ACK from the incoming buffer */
1005 retval = gdb_get_char(connection, &initial_ack);
1006 if (retval != ERROR_OK)
1009 /* FIX!!!??? would we actually ever receive a + here???
1012 if (initial_ack != '+')
1013 gdb_putback_char(connection, initial_ack);
1014 target_call_event_callbacks(target, TARGET_EVENT_GDB_ATTACH);
1017 /* clean previous rtos session if supported*/
1018 if (target->rtos->type->clean)
1019 target->rtos->type->clean(target);
1021 /* update threads */
1022 rtos_update_threads(target);
1025 if (gdb_use_memory_map) {
1026 /* Connect must fail if the memory map can't be set up correctly.
1028 * This will cause an auto_probe to be invoked, which is either
1029 * a no-op or it will fail when the target isn't ready(e.g. not halted).
1031 for (unsigned int i = 0; i < flash_get_bank_count(); i++) {
1032 struct flash_bank *p;
1033 p = get_flash_bank_by_num_noprobe(i);
1034 if (p->target != target)
1036 retval = get_flash_bank_by_num(i, &p);
1037 if (retval != ERROR_OK) {
1038 LOG_ERROR("Connect failed. Consider setting up a gdb-attach event for the target "
1039 "to prepare target for GDB connect, or use 'gdb_memory_map disable'.");
1045 gdb_actual_connections++;
1046 log_printf_lf(all_targets->next != NULL ? LOG_LVL_INFO : LOG_LVL_DEBUG,
1047 __FILE__, __LINE__, __func__,
1048 "New GDB Connection: %d, Target %s, state: %s",
1049 gdb_actual_connections,
1050 target_name(target),
1051 target_state_name(target));
1053 if (!target_was_examined(target)) {
1054 LOG_ERROR("Target %s not examined yet, refuse gdb connection %d!",
1055 target_name(target), gdb_actual_connections);
1056 gdb_actual_connections--;
1057 return ERROR_TARGET_NOT_EXAMINED;
1060 if (target->state != TARGET_HALTED)
1061 LOG_WARNING("GDB connection %d on target %s not halted",
1062 gdb_actual_connections, target_name(target));
1064 /* DANGER! If we fail subsequently, we must remove this handler,
1065 * otherwise we occasionally see crashes as the timer can invoke the
1068 * register callback to be informed about target events */
1069 target_register_event_callback(gdb_target_callback_event_handler, connection);
1074 static int gdb_connection_closed(struct connection *connection)
1076 struct target *target;
1077 struct gdb_connection *gdb_connection = connection->priv;
1079 target = get_target_from_connection(connection);
1081 /* we're done forwarding messages. Tear down callback before
1082 * cleaning up connection.
1084 log_remove_callback(gdb_log_callback, connection);
1086 gdb_actual_connections--;
1087 LOG_DEBUG("GDB Close, Target: %s, state: %s, gdb_actual_connections=%d",
1088 target_name(target),
1089 target_state_name(target),
1090 gdb_actual_connections);
1092 /* see if an image built with vFlash commands is left */
1093 if (gdb_connection->vflash_image) {
1094 image_close(gdb_connection->vflash_image);
1095 free(gdb_connection->vflash_image);
1096 gdb_connection->vflash_image = NULL;
1099 /* if this connection registered a debug-message receiver delete it */
1100 delete_debug_msg_receiver(connection->cmd_ctx, target);
1102 free(connection->priv);
1103 connection->priv = NULL;
1105 target_unregister_event_callback(gdb_target_callback_event_handler, connection);
1107 target_call_event_callbacks(target, TARGET_EVENT_GDB_END);
1109 target_call_event_callbacks(target, TARGET_EVENT_GDB_DETACH);
1114 static void gdb_send_error(struct connection *connection, uint8_t the_error)
1117 snprintf(err, 4, "E%2.2X", the_error);
1118 gdb_put_packet(connection, err, 3);
1121 static int gdb_last_signal_packet(struct connection *connection,
1122 char const *packet, int packet_size)
1124 struct target *target = get_target_from_connection(connection);
1125 struct gdb_connection *gdb_con = connection->priv;
1129 if (!gdb_con->attached) {
1130 /* if we are here we have received a kill packet
1131 * reply W stop reply otherwise gdb gets very unhappy */
1132 gdb_put_packet(connection, "W00", 3);
1136 signal_var = gdb_last_signal(target);
1138 snprintf(sig_reply, 4, "S%2.2x", signal_var);
1139 gdb_put_packet(connection, sig_reply, 3);
1144 static inline int gdb_reg_pos(struct target *target, int pos, int len)
1146 if (target->endianness == TARGET_LITTLE_ENDIAN)
1149 return len - 1 - pos;
1152 /* Convert register to string of bytes. NB! The # of bits in the
1153 * register might be non-divisible by 8(a byte), in which
1154 * case an entire byte is shown.
1156 * NB! the format on the wire is the target endianness
1158 * The format of reg->value is little endian
1161 static void gdb_str_to_target(struct target *target,
1162 char *tstr, struct reg *reg)
1169 buf_len = DIV_ROUND_UP(reg->size, 8);
1171 for (i = 0; i < buf_len; i++) {
1172 int j = gdb_reg_pos(target, i, buf_len);
1173 tstr += sprintf(tstr, "%02x", buf[j]);
1177 /* copy over in register buffer */
1178 static void gdb_target_to_reg(struct target *target,
1179 char const *tstr, int str_len, uint8_t *bin)
1182 LOG_ERROR("BUG: gdb value with uneven number of characters encountered");
1187 for (i = 0; i < str_len; i += 2) {
1189 if (sscanf(tstr + i, "%02x", &t) != 1) {
1190 LOG_ERROR("BUG: unable to convert register value");
1194 int j = gdb_reg_pos(target, i/2, str_len/2);
1199 static int gdb_get_registers_packet(struct connection *connection,
1200 char const *packet, int packet_size)
1202 struct target *target = get_target_from_connection(connection);
1203 struct reg **reg_list;
1206 int reg_packet_size = 0;
1211 #ifdef _DEBUG_GDB_IO_
1215 if ((target->rtos != NULL) && (ERROR_OK == rtos_get_gdb_reg_list(connection)))
1218 retval = target_get_gdb_reg_list(target, ®_list, ®_list_size,
1220 if (retval != ERROR_OK)
1221 return gdb_error(connection, retval);
1223 for (i = 0; i < reg_list_size; i++) {
1224 if (reg_list[i] == NULL || reg_list[i]->exist == false || reg_list[i]->hidden)
1226 reg_packet_size += DIV_ROUND_UP(reg_list[i]->size, 8) * 2;
1229 assert(reg_packet_size > 0);
1231 reg_packet = malloc(reg_packet_size + 1); /* plus one for string termination null */
1232 if (reg_packet == NULL)
1235 reg_packet_p = reg_packet;
1237 for (i = 0; i < reg_list_size; i++) {
1238 if (reg_list[i] == NULL || reg_list[i]->exist == false || reg_list[i]->hidden)
1240 if (!reg_list[i]->valid) {
1241 retval = reg_list[i]->type->get(reg_list[i]);
1242 if (retval != ERROR_OK && gdb_report_register_access_error) {
1243 LOG_DEBUG("Couldn't get register %s.", reg_list[i]->name);
1246 return gdb_error(connection, retval);
1249 gdb_str_to_target(target, reg_packet_p, reg_list[i]);
1250 reg_packet_p += DIV_ROUND_UP(reg_list[i]->size, 8) * 2;
1253 #ifdef _DEBUG_GDB_IO_
1255 char *reg_packet_p_debug;
1256 reg_packet_p_debug = strndup(reg_packet, reg_packet_size);
1257 LOG_DEBUG("reg_packet: %s", reg_packet_p_debug);
1258 free(reg_packet_p_debug);
1262 gdb_put_packet(connection, reg_packet, reg_packet_size);
1270 static int gdb_set_registers_packet(struct connection *connection,
1271 char const *packet, int packet_size)
1273 struct target *target = get_target_from_connection(connection);
1275 struct reg **reg_list;
1278 char const *packet_p;
1280 #ifdef _DEBUG_GDB_IO_
1284 /* skip command character */
1288 if (packet_size % 2) {
1289 LOG_WARNING("GDB set_registers packet with uneven characters received, dropping connection");
1290 return ERROR_SERVER_REMOTE_CLOSED;
1293 retval = target_get_gdb_reg_list(target, ®_list, ®_list_size,
1295 if (retval != ERROR_OK)
1296 return gdb_error(connection, retval);
1299 for (i = 0; i < reg_list_size; i++) {
1301 int chars = (DIV_ROUND_UP(reg_list[i]->size, 8) * 2);
1303 if (packet_p + chars > packet + packet_size)
1304 LOG_ERROR("BUG: register packet is too small for registers");
1306 bin_buf = malloc(DIV_ROUND_UP(reg_list[i]->size, 8));
1307 gdb_target_to_reg(target, packet_p, chars, bin_buf);
1309 retval = reg_list[i]->type->set(reg_list[i], bin_buf);
1310 if (retval != ERROR_OK && gdb_report_register_access_error) {
1311 LOG_DEBUG("Couldn't set register %s.", reg_list[i]->name);
1314 return gdb_error(connection, retval);
1317 /* advance packet pointer */
1323 /* free struct reg *reg_list[] array allocated by get_gdb_reg_list */
1326 gdb_put_packet(connection, "OK", 2);
1331 static int gdb_get_register_packet(struct connection *connection,
1332 char const *packet, int packet_size)
1334 struct target *target = get_target_from_connection(connection);
1336 int reg_num = strtoul(packet + 1, NULL, 16);
1337 struct reg **reg_list;
1341 #ifdef _DEBUG_GDB_IO_
1345 if ((target->rtos != NULL) && (ERROR_OK == rtos_get_gdb_reg(connection, reg_num)))
1348 retval = target_get_gdb_reg_list_noread(target, ®_list, ®_list_size,
1350 if (retval != ERROR_OK)
1351 return gdb_error(connection, retval);
1353 if (reg_list_size <= reg_num) {
1354 LOG_ERROR("gdb requested a non-existing register");
1355 return ERROR_SERVER_REMOTE_CLOSED;
1358 if (!reg_list[reg_num]->valid) {
1359 retval = reg_list[reg_num]->type->get(reg_list[reg_num]);
1360 if (retval != ERROR_OK && gdb_report_register_access_error) {
1361 LOG_DEBUG("Couldn't get register %s.", reg_list[reg_num]->name);
1363 return gdb_error(connection, retval);
1367 reg_packet = calloc(DIV_ROUND_UP(reg_list[reg_num]->size, 8) * 2 + 1, 1); /* plus one for string termination null */
1369 gdb_str_to_target(target, reg_packet, reg_list[reg_num]);
1371 gdb_put_packet(connection, reg_packet, DIV_ROUND_UP(reg_list[reg_num]->size, 8) * 2);
1379 static int gdb_set_register_packet(struct connection *connection,
1380 char const *packet, int packet_size)
1382 struct target *target = get_target_from_connection(connection);
1384 int reg_num = strtoul(packet + 1, &separator, 16);
1385 struct reg **reg_list;
1389 #ifdef _DEBUG_GDB_IO_
1393 if (*separator != '=') {
1394 LOG_ERROR("GDB 'set register packet', but no '=' following the register number");
1395 return ERROR_SERVER_REMOTE_CLOSED;
1397 size_t chars = strlen(separator + 1);
1398 uint8_t *bin_buf = malloc(chars / 2);
1399 gdb_target_to_reg(target, separator + 1, chars, bin_buf);
1401 if ((target->rtos != NULL) &&
1402 (ERROR_OK == rtos_set_reg(connection, reg_num, bin_buf))) {
1404 gdb_put_packet(connection, "OK", 2);
1408 retval = target_get_gdb_reg_list_noread(target, ®_list, ®_list_size,
1410 if (retval != ERROR_OK) {
1412 return gdb_error(connection, retval);
1415 if (reg_list_size <= reg_num) {
1416 LOG_ERROR("gdb requested a non-existing register");
1419 return ERROR_SERVER_REMOTE_CLOSED;
1422 if (chars != (DIV_ROUND_UP(reg_list[reg_num]->size, 8) * 2)) {
1423 LOG_ERROR("gdb sent %zu bits for a %" PRIu32 "-bit register (%s)",
1424 chars * 4, reg_list[reg_num]->size, reg_list[reg_num]->name);
1427 return ERROR_SERVER_REMOTE_CLOSED;
1430 gdb_target_to_reg(target, separator + 1, chars, bin_buf);
1432 retval = reg_list[reg_num]->type->set(reg_list[reg_num], bin_buf);
1433 if (retval != ERROR_OK && gdb_report_register_access_error) {
1434 LOG_DEBUG("Couldn't set register %s.", reg_list[reg_num]->name);
1437 return gdb_error(connection, retval);
1440 gdb_put_packet(connection, "OK", 2);
1448 /* No attempt is made to translate the "retval" to
1449 * GDB speak. This has to be done at the calling
1450 * site as no mapping really exists.
1452 static int gdb_error(struct connection *connection, int retval)
1454 LOG_DEBUG("Reporting %i to GDB as generic error", retval);
1455 gdb_send_error(connection, EFAULT);
1459 /* We don't have to worry about the default 2 second timeout for GDB packets,
1460 * because GDB breaks up large memory reads into smaller reads.
1462 static int gdb_read_memory_packet(struct connection *connection,
1463 char const *packet, int packet_size)
1465 struct target *target = get_target_from_connection(connection);
1473 int retval = ERROR_OK;
1475 /* skip command character */
1478 addr = strtoull(packet, &separator, 16);
1480 if (*separator != ',') {
1481 LOG_ERROR("incomplete read memory packet received, dropping connection");
1482 return ERROR_SERVER_REMOTE_CLOSED;
1485 len = strtoul(separator + 1, NULL, 16);
1488 LOG_WARNING("invalid read memory packet received (len == 0)");
1489 gdb_put_packet(connection, "", 0);
1493 buffer = malloc(len);
1495 LOG_DEBUG("addr: 0x%16.16" PRIx64 ", len: 0x%8.8" PRIx32 "", addr, len);
1497 retval = target_read_buffer(target, addr, len, buffer);
1499 if ((retval != ERROR_OK) && !gdb_report_data_abort) {
1500 /* TODO : Here we have to lie and send back all zero's lest stack traces won't work.
1501 * At some point this might be fixed in GDB, in which case this code can be removed.
1503 * OpenOCD developers are acutely aware of this problem, but there is nothing
1504 * gained by involving the user in this problem that hopefully will get resolved
1507 * http://sourceware.org/cgi-bin/gnatsweb.pl? \
1508 * cmd = view%20audit-trail&database = gdb&pr = 2395
1510 * For now, the default is to fix up things to make current GDB versions work.
1511 * This can be overwritten using the gdb_report_data_abort <'enable'|'disable'> command.
1513 memset(buffer, 0, len);
1517 if (retval == ERROR_OK) {
1518 hex_buffer = malloc(len * 2 + 1);
1520 size_t pkt_len = hexify(hex_buffer, buffer, len, len * 2 + 1);
1522 gdb_put_packet(connection, hex_buffer, pkt_len);
1526 retval = gdb_error(connection, retval);
1533 static int gdb_write_memory_packet(struct connection *connection,
1534 char const *packet, int packet_size)
1536 struct target *target = get_target_from_connection(connection);
1544 /* skip command character */
1547 addr = strtoull(packet, &separator, 16);
1549 if (*separator != ',') {
1550 LOG_ERROR("incomplete write memory packet received, dropping connection");
1551 return ERROR_SERVER_REMOTE_CLOSED;
1554 len = strtoul(separator + 1, &separator, 16);
1556 if (*(separator++) != ':') {
1557 LOG_ERROR("incomplete write memory packet received, dropping connection");
1558 return ERROR_SERVER_REMOTE_CLOSED;
1561 buffer = malloc(len);
1563 LOG_DEBUG("addr: 0x%" PRIx64 ", len: 0x%8.8" PRIx32 "", addr, len);
1565 if (unhexify(buffer, separator, len) != len)
1566 LOG_ERROR("unable to decode memory packet");
1568 retval = target_write_buffer(target, addr, len, buffer);
1570 if (retval == ERROR_OK)
1571 gdb_put_packet(connection, "OK", 2);
1573 retval = gdb_error(connection, retval);
1580 static int gdb_write_memory_binary_packet(struct connection *connection,
1581 char const *packet, int packet_size)
1583 struct target *target = get_target_from_connection(connection);
1588 int retval = ERROR_OK;
1589 /* Packets larger than fast_limit bytes will be acknowledged instantly on
1590 * the assumption that we're in a download and it's important to go as fast
1592 uint32_t fast_limit = 8;
1594 /* skip command character */
1597 addr = strtoull(packet, &separator, 16);
1599 if (*separator != ',') {
1600 LOG_ERROR("incomplete write memory binary packet received, dropping connection");
1601 return ERROR_SERVER_REMOTE_CLOSED;
1604 len = strtoul(separator + 1, &separator, 16);
1606 if (*(separator++) != ':') {
1607 LOG_ERROR("incomplete write memory binary packet received, dropping connection");
1608 return ERROR_SERVER_REMOTE_CLOSED;
1611 struct gdb_connection *gdb_connection = connection->priv;
1613 if (gdb_connection->mem_write_error)
1614 retval = ERROR_FAIL;
1616 if (retval == ERROR_OK) {
1617 if (len >= fast_limit) {
1618 /* By replying the packet *immediately* GDB will send us a new packet
1619 * while we write the last one to the target.
1620 * We only do this for larger writes, so that users who do something like:
1621 * p *((int*)0xdeadbeef)=8675309
1622 * will get immediate feedback that that write failed.
1624 gdb_put_packet(connection, "OK", 2);
1627 retval = gdb_error(connection, retval);
1628 /* now that we have reported the memory write error, we can clear the condition */
1629 gdb_connection->mem_write_error = false;
1630 if (retval != ERROR_OK)
1635 LOG_DEBUG("addr: 0x%" PRIx64 ", len: 0x%8.8" PRIx32 "", addr, len);
1637 retval = target_write_buffer(target, addr, len, (uint8_t *)separator);
1638 if (retval != ERROR_OK)
1639 gdb_connection->mem_write_error = true;
1642 if (len < fast_limit) {
1643 if (retval != ERROR_OK) {
1644 gdb_error(connection, retval);
1645 gdb_connection->mem_write_error = false;
1647 gdb_put_packet(connection, "OK", 2);
1654 static int gdb_step_continue_packet(struct connection *connection,
1655 char const *packet, int packet_size)
1657 struct target *target = get_target_from_connection(connection);
1659 uint64_t address = 0x0;
1660 int retval = ERROR_OK;
1664 if (packet_size > 1)
1665 address = strtoull(packet + 1, NULL, 16);
1669 gdb_running_type = packet[0];
1670 if (packet[0] == 'c') {
1671 LOG_DEBUG("continue");
1672 /* resume at current address, don't handle breakpoints, not debugging */
1673 retval = target_resume(target, current, address, 0, 0);
1674 } else if (packet[0] == 's') {
1676 /* step at current or address, don't handle breakpoints */
1677 retval = target_step(target, current, address, 0);
1682 static int gdb_breakpoint_watchpoint_packet(struct connection *connection,
1683 char const *packet, int packet_size)
1685 struct target *target = get_target_from_connection(connection);
1687 enum breakpoint_type bp_type = BKPT_SOFT /* dummy init to avoid warning */;
1688 enum watchpoint_rw wp_type = WPT_READ /* dummy init to avoid warning */;
1694 LOG_DEBUG("[%s]", target_name(target));
1696 type = strtoul(packet + 1, &separator, 16);
1698 if (type == 0) /* memory breakpoint */
1699 bp_type = BKPT_SOFT;
1700 else if (type == 1) /* hardware breakpoint */
1701 bp_type = BKPT_HARD;
1702 else if (type == 2) /* write watchpoint */
1703 wp_type = WPT_WRITE;
1704 else if (type == 3) /* read watchpoint */
1706 else if (type == 4) /* access watchpoint */
1707 wp_type = WPT_ACCESS;
1709 LOG_ERROR("invalid gdb watch/breakpoint type(%d), dropping connection", type);
1710 return ERROR_SERVER_REMOTE_CLOSED;
1713 if (gdb_breakpoint_override && ((bp_type == BKPT_SOFT) || (bp_type == BKPT_HARD)))
1714 bp_type = gdb_breakpoint_override_type;
1716 if (*separator != ',') {
1717 LOG_ERROR("incomplete breakpoint/watchpoint packet received, dropping connection");
1718 return ERROR_SERVER_REMOTE_CLOSED;
1721 address = strtoull(separator + 1, &separator, 16);
1723 if (*separator != ',') {
1724 LOG_ERROR("incomplete breakpoint/watchpoint packet received, dropping connection");
1725 return ERROR_SERVER_REMOTE_CLOSED;
1728 size = strtoul(separator + 1, &separator, 16);
1733 if (packet[0] == 'Z') {
1734 retval = breakpoint_add(target, address, size, bp_type);
1735 if (retval != ERROR_OK) {
1736 retval = gdb_error(connection, retval);
1737 if (retval != ERROR_OK)
1740 gdb_put_packet(connection, "OK", 2);
1742 breakpoint_remove(target, address);
1743 gdb_put_packet(connection, "OK", 2);
1750 if (packet[0] == 'Z') {
1751 retval = watchpoint_add(target, address, size, wp_type, 0, 0xffffffffu);
1752 if (retval != ERROR_OK) {
1753 retval = gdb_error(connection, retval);
1754 if (retval != ERROR_OK)
1757 gdb_put_packet(connection, "OK", 2);
1759 watchpoint_remove(target, address);
1760 gdb_put_packet(connection, "OK", 2);
1771 /* print out a string and allocate more space as needed,
1772 * mainly used for XML at this point
1774 static __attribute__ ((format (PRINTF_ATTRIBUTE_FORMAT, 5, 6))) void xml_printf(int *retval,
1775 char **xml, int *pos, int *size, const char *fmt, ...)
1777 if (*retval != ERROR_OK)
1782 if ((*xml == NULL) || (!first)) {
1783 /* start by 0 to exercise all the code paths.
1784 * Need minimum 2 bytes to fit 1 char and 0 terminator. */
1786 *size = *size * 2 + 2;
1788 *xml = realloc(*xml, *size);
1791 *retval = ERROR_SERVER_REMOTE_CLOSED;
1799 ret = vsnprintf(*xml + *pos, *size - *pos, fmt, ap);
1801 if ((ret > 0) && ((ret + 1) < *size - *pos)) {
1805 /* there was just enough or not enough space, allocate more. */
1810 static int decode_xfer_read(char const *buf, char **annex, int *ofs, unsigned int *len)
1812 /* Locate the annex. */
1813 const char *annex_end = strchr(buf, ':');
1814 if (annex_end == NULL)
1817 /* After the read marker and annex, qXfer looks like a
1818 * traditional 'm' packet. */
1820 *ofs = strtoul(annex_end + 1, &separator, 16);
1822 if (*separator != ',')
1825 *len = strtoul(separator + 1, NULL, 16);
1827 /* Extract the annex if needed */
1828 if (annex != NULL) {
1829 *annex = strndup(buf, annex_end - buf);
1837 static int compare_bank(const void *a, const void *b)
1839 struct flash_bank *b1, *b2;
1840 b1 = *((struct flash_bank **)a);
1841 b2 = *((struct flash_bank **)b);
1843 if (b1->base == b2->base)
1845 else if (b1->base > b2->base)
1851 static int gdb_memory_map(struct connection *connection,
1852 char const *packet, int packet_size)
1854 /* We get away with only specifying flash here. Regions that are not
1855 * specified are treated as if we provided no memory map(if not we
1856 * could detect the holes and mark them as RAM).
1857 * Normally we only execute this code once, but no big deal if we
1858 * have to regenerate it a couple of times.
1861 struct target *target = get_target_from_connection(connection);
1862 struct flash_bank *p;
1866 int retval = ERROR_OK;
1867 struct flash_bank **banks;
1871 target_addr_t ram_start = 0;
1872 unsigned int target_flash_banks = 0;
1874 /* skip command character */
1877 offset = strtoul(packet, &separator, 16);
1878 length = strtoul(separator + 1, &separator, 16);
1880 xml_printf(&retval, &xml, &pos, &size, "<memory-map>\n");
1882 /* Sort banks in ascending order. We need to report non-flash
1883 * memory as ram (or rather read/write) by default for GDB, since
1884 * it has no concept of non-cacheable read/write memory (i/o etc).
1886 banks = malloc(sizeof(struct flash_bank *)*flash_get_bank_count());
1888 for (unsigned int i = 0; i < flash_get_bank_count(); i++) {
1889 p = get_flash_bank_by_num_noprobe(i);
1890 if (p->target != target)
1892 retval = get_flash_bank_by_num(i, &p);
1893 if (retval != ERROR_OK) {
1895 gdb_error(connection, retval);
1898 banks[target_flash_banks++] = p;
1901 qsort(banks, target_flash_banks, sizeof(struct flash_bank *),
1904 for (unsigned int i = 0; i < target_flash_banks; i++) {
1905 unsigned sector_size = 0;
1906 unsigned group_len = 0;
1910 if (ram_start < p->base)
1911 xml_printf(&retval, &xml, &pos, &size,
1912 "<memory type=\"ram\" start=\"" TARGET_ADDR_FMT "\" "
1913 "length=\"" TARGET_ADDR_FMT "\"/>\n",
1914 ram_start, p->base - ram_start);
1916 /* Report adjacent groups of same-size sectors. So for
1917 * example top boot CFI flash will list an initial region
1918 * with several large sectors (maybe 128KB) and several
1919 * smaller ones at the end (maybe 32KB). STR7 will have
1920 * regions with 8KB, 32KB, and 64KB sectors; etc.
1922 for (unsigned int j = 0; j < p->num_sectors; j++) {
1924 /* Maybe start a new group of sectors. */
1925 if (sector_size == 0) {
1926 if (p->sectors[j].offset + p->sectors[j].size > p->size) {
1927 LOG_WARNING("The flash sector at offset 0x%08" PRIx32
1928 " overflows the end of %s bank.",
1929 p->sectors[j].offset, p->name);
1930 LOG_WARNING("The rest of bank will not show in gdb memory map.");
1933 target_addr_t start;
1934 start = p->base + p->sectors[j].offset;
1935 xml_printf(&retval, &xml, &pos, &size,
1936 "<memory type=\"flash\" "
1937 "start=\"" TARGET_ADDR_FMT "\" ",
1939 sector_size = p->sectors[j].size;
1940 group_len = sector_size;
1942 group_len += sector_size; /* equal to p->sectors[j].size */
1945 /* Does this finish a group of sectors?
1946 * If not, continue an already-started group.
1948 if (j < p->num_sectors - 1
1949 && p->sectors[j + 1].size == sector_size
1950 && p->sectors[j + 1].offset == p->sectors[j].offset + sector_size
1951 && p->sectors[j + 1].offset + p->sectors[j + 1].size <= p->size)
1954 xml_printf(&retval, &xml, &pos, &size,
1955 "length=\"0x%x\">\n"
1956 "<property name=\"blocksize\">"
1964 ram_start = p->base + p->size;
1968 xml_printf(&retval, &xml, &pos, &size,
1969 "<memory type=\"ram\" start=\"" TARGET_ADDR_FMT "\" "
1970 "length=\"" TARGET_ADDR_FMT "\"/>\n",
1971 ram_start, target_address_max(target) - ram_start + 1);
1972 /* ELSE a flash chip could be at the very end of the address space, in
1973 * which case ram_start will be precisely 0 */
1977 xml_printf(&retval, &xml, &pos, &size, "</memory-map>\n");
1979 if (retval != ERROR_OK) {
1981 gdb_error(connection, retval);
1985 if (offset + length > pos)
1986 length = pos - offset;
1988 char *t = malloc(length + 1);
1990 memcpy(t + 1, xml + offset, length);
1991 gdb_put_packet(connection, t, length + 1);
1998 static const char *gdb_get_reg_type_name(enum reg_type type)
2007 case REG_TYPE_INT16:
2009 case REG_TYPE_INT32:
2011 case REG_TYPE_INT64:
2013 case REG_TYPE_INT128:
2017 case REG_TYPE_UINT8:
2019 case REG_TYPE_UINT16:
2021 case REG_TYPE_UINT32:
2023 case REG_TYPE_UINT64:
2025 case REG_TYPE_UINT128:
2027 case REG_TYPE_CODE_PTR:
2029 case REG_TYPE_DATA_PTR:
2031 case REG_TYPE_FLOAT:
2033 case REG_TYPE_IEEE_SINGLE:
2034 return "ieee_single";
2035 case REG_TYPE_IEEE_DOUBLE:
2036 return "ieee_double";
2037 case REG_TYPE_ARCH_DEFINED:
2038 return "int"; /* return arbitrary string to avoid compile warning. */
2041 return "int"; /* "int" as default value */
2044 static int lookup_add_arch_defined_types(char const **arch_defined_types_list[], const char *type_id,
2045 int *num_arch_defined_types)
2047 int tbl_sz = *num_arch_defined_types;
2049 if (type_id != NULL && (strcmp(type_id, ""))) {
2050 for (int j = 0; j < (tbl_sz + 1); j++) {
2051 if (!((*arch_defined_types_list)[j])) {
2052 (*arch_defined_types_list)[tbl_sz++] = type_id;
2053 *arch_defined_types_list = realloc(*arch_defined_types_list,
2054 sizeof(char *) * (tbl_sz + 1));
2055 (*arch_defined_types_list)[tbl_sz] = NULL;
2056 *num_arch_defined_types = tbl_sz;
2059 if (!strcmp((*arch_defined_types_list)[j], type_id))
2068 static int gdb_generate_reg_type_description(struct target *target,
2069 char **tdesc, int *pos, int *size, struct reg_data_type *type,
2070 char const **arch_defined_types_list[], int *num_arch_defined_types)
2072 int retval = ERROR_OK;
2074 if (type->type_class == REG_TYPE_CLASS_VECTOR) {
2075 struct reg_data_type *data_type = type->reg_type_vector->type;
2076 if (data_type->type == REG_TYPE_ARCH_DEFINED) {
2077 if (lookup_add_arch_defined_types(arch_defined_types_list, data_type->id,
2078 num_arch_defined_types))
2079 gdb_generate_reg_type_description(target, tdesc, pos, size, data_type,
2080 arch_defined_types_list,
2081 num_arch_defined_types);
2083 /* <vector id="id" type="type" count="count"/> */
2084 xml_printf(&retval, tdesc, pos, size,
2085 "<vector id=\"%s\" type=\"%s\" count=\"%" PRIu32 "\"/>\n",
2086 type->id, type->reg_type_vector->type->id,
2087 type->reg_type_vector->count);
2089 } else if (type->type_class == REG_TYPE_CLASS_UNION) {
2090 struct reg_data_type_union_field *field;
2091 field = type->reg_type_union->fields;
2092 while (field != NULL) {
2093 struct reg_data_type *data_type = field->type;
2094 if (data_type->type == REG_TYPE_ARCH_DEFINED) {
2095 if (lookup_add_arch_defined_types(arch_defined_types_list, data_type->id,
2096 num_arch_defined_types))
2097 gdb_generate_reg_type_description(target, tdesc, pos, size, data_type,
2098 arch_defined_types_list,
2099 num_arch_defined_types);
2102 field = field->next;
2105 * <field name="name" type="type"/> ...
2107 xml_printf(&retval, tdesc, pos, size,
2108 "<union id=\"%s\">\n",
2111 field = type->reg_type_union->fields;
2112 while (field != NULL) {
2113 xml_printf(&retval, tdesc, pos, size,
2114 "<field name=\"%s\" type=\"%s\"/>\n",
2115 field->name, field->type->id);
2117 field = field->next;
2120 xml_printf(&retval, tdesc, pos, size,
2123 } else if (type->type_class == REG_TYPE_CLASS_STRUCT) {
2124 struct reg_data_type_struct_field *field;
2125 field = type->reg_type_struct->fields;
2127 if (field->use_bitfields) {
2128 /* <struct id="id" size="size">
2129 * <field name="name" start="start" end="end"/> ...
2131 xml_printf(&retval, tdesc, pos, size,
2132 "<struct id=\"%s\" size=\"%" PRIu32 "\">\n",
2133 type->id, type->reg_type_struct->size);
2134 while (field != NULL) {
2135 xml_printf(&retval, tdesc, pos, size,
2136 "<field name=\"%s\" start=\"%" PRIu32 "\" end=\"%" PRIu32 "\" type=\"%s\" />\n",
2137 field->name, field->bitfield->start, field->bitfield->end,
2138 gdb_get_reg_type_name(field->bitfield->type));
2140 field = field->next;
2143 while (field != NULL) {
2144 struct reg_data_type *data_type = field->type;
2145 if (data_type->type == REG_TYPE_ARCH_DEFINED) {
2146 if (lookup_add_arch_defined_types(arch_defined_types_list, data_type->id,
2147 num_arch_defined_types))
2148 gdb_generate_reg_type_description(target, tdesc, pos, size, data_type,
2149 arch_defined_types_list,
2150 num_arch_defined_types);
2155 * <field name="name" type="type"/> ...
2157 xml_printf(&retval, tdesc, pos, size,
2158 "<struct id=\"%s\">\n",
2160 while (field != NULL) {
2161 xml_printf(&retval, tdesc, pos, size,
2162 "<field name=\"%s\" type=\"%s\"/>\n",
2163 field->name, field->type->id);
2165 field = field->next;
2169 xml_printf(&retval, tdesc, pos, size,
2172 } else if (type->type_class == REG_TYPE_CLASS_FLAGS) {
2173 /* <flags id="id" size="size">
2174 * <field name="name" start="start" end="end"/> ...
2176 xml_printf(&retval, tdesc, pos, size,
2177 "<flags id=\"%s\" size=\"%" PRIu32 "\">\n",
2178 type->id, type->reg_type_flags->size);
2180 struct reg_data_type_flags_field *field;
2181 field = type->reg_type_flags->fields;
2182 while (field != NULL) {
2183 xml_printf(&retval, tdesc, pos, size,
2184 "<field name=\"%s\" start=\"%" PRIu32 "\" end=\"%" PRIu32 "\" type=\"%s\" />\n",
2185 field->name, field->bitfield->start, field->bitfield->end,
2186 gdb_get_reg_type_name(field->bitfield->type));
2188 field = field->next;
2191 xml_printf(&retval, tdesc, pos, size,
2199 /* Get a list of available target registers features. feature_list must
2200 * be freed by caller.
2202 static int get_reg_features_list(struct target *target, char const **feature_list[], int *feature_list_size,
2203 struct reg **reg_list, int reg_list_size)
2207 /* Start with only one element */
2208 *feature_list = calloc(1, sizeof(char *));
2210 for (int i = 0; i < reg_list_size; i++) {
2211 if (reg_list[i]->exist == false || reg_list[i]->hidden)
2214 if (reg_list[i]->feature != NULL
2215 && reg_list[i]->feature->name != NULL
2216 && (strcmp(reg_list[i]->feature->name, ""))) {
2217 /* We found a feature, check if the feature is already in the
2218 * table. If not, allocate a new entry for the table and
2219 * put the new feature in it.
2221 for (int j = 0; j < (tbl_sz + 1); j++) {
2222 if (!((*feature_list)[j])) {
2223 (*feature_list)[tbl_sz++] = reg_list[i]->feature->name;
2224 *feature_list = realloc(*feature_list, sizeof(char *) * (tbl_sz + 1));
2225 (*feature_list)[tbl_sz] = NULL;
2228 if (!strcmp((*feature_list)[j], reg_list[i]->feature->name))
2235 if (feature_list_size)
2236 *feature_list_size = tbl_sz;
2241 static int gdb_generate_target_description(struct target *target, char **tdesc_out)
2243 int retval = ERROR_OK;
2244 struct reg **reg_list = NULL;
2246 char const *architecture;
2247 char const **features = NULL;
2248 int feature_list_size = 0;
2254 retval = target_get_gdb_reg_list_noread(target, ®_list,
2255 ®_list_size, REG_CLASS_ALL);
2257 if (retval != ERROR_OK) {
2258 LOG_ERROR("get register list failed");
2259 retval = ERROR_FAIL;
2263 if (reg_list_size <= 0) {
2264 LOG_ERROR("get register list failed");
2265 retval = ERROR_FAIL;
2269 /* Get a list of available target registers features */
2270 retval = get_reg_features_list(target, &features, &feature_list_size, reg_list, reg_list_size);
2271 if (retval != ERROR_OK) {
2272 LOG_ERROR("Can't get the registers feature list");
2273 retval = ERROR_FAIL;
2277 /* If we found some features associated with registers, create sections */
2278 int current_feature = 0;
2280 xml_printf(&retval, &tdesc, &pos, &size,
2281 "<?xml version=\"1.0\"?>\n"
2282 "<!DOCTYPE target SYSTEM \"gdb-target.dtd\">\n"
2283 "<target version=\"1.0\">\n");
2285 /* generate architecture element if supported by target */
2286 architecture = target_get_gdb_arch(target);
2287 if (architecture != NULL)
2288 xml_printf(&retval, &tdesc, &pos, &size,
2289 "<architecture>%s</architecture>\n", architecture);
2291 /* generate target description according to register list */
2292 if (features != NULL) {
2293 while (features[current_feature]) {
2294 char const **arch_defined_types = NULL;
2295 int num_arch_defined_types = 0;
2297 arch_defined_types = calloc(1, sizeof(char *));
2298 xml_printf(&retval, &tdesc, &pos, &size,
2299 "<feature name=\"%s\">\n",
2300 features[current_feature]);
2303 for (i = 0; i < reg_list_size; i++) {
2305 if (reg_list[i]->exist == false || reg_list[i]->hidden)
2308 if (strcmp(reg_list[i]->feature->name, features[current_feature]))
2311 const char *type_str;
2312 if (reg_list[i]->reg_data_type != NULL) {
2313 if (reg_list[i]->reg_data_type->type == REG_TYPE_ARCH_DEFINED) {
2314 /* generate <type... first, if there are architecture-defined types. */
2315 if (lookup_add_arch_defined_types(&arch_defined_types,
2316 reg_list[i]->reg_data_type->id,
2317 &num_arch_defined_types))
2318 gdb_generate_reg_type_description(target, &tdesc, &pos, &size,
2319 reg_list[i]->reg_data_type,
2320 &arch_defined_types,
2321 &num_arch_defined_types);
2323 type_str = reg_list[i]->reg_data_type->id;
2325 /* predefined type */
2326 type_str = gdb_get_reg_type_name(
2327 reg_list[i]->reg_data_type->type);
2330 /* Default type is "int" */
2334 xml_printf(&retval, &tdesc, &pos, &size,
2335 "<reg name=\"%s\"", reg_list[i]->name);
2336 xml_printf(&retval, &tdesc, &pos, &size,
2337 " bitsize=\"%" PRIu32 "\"", reg_list[i]->size);
2338 xml_printf(&retval, &tdesc, &pos, &size,
2339 " regnum=\"%" PRIu32 "\"", reg_list[i]->number);
2340 if (reg_list[i]->caller_save)
2341 xml_printf(&retval, &tdesc, &pos, &size,
2342 " save-restore=\"yes\"");
2344 xml_printf(&retval, &tdesc, &pos, &size,
2345 " save-restore=\"no\"");
2347 xml_printf(&retval, &tdesc, &pos, &size,
2348 " type=\"%s\"", type_str);
2350 if (reg_list[i]->group != NULL)
2351 xml_printf(&retval, &tdesc, &pos, &size,
2352 " group=\"%s\"", reg_list[i]->group);
2354 xml_printf(&retval, &tdesc, &pos, &size,
2358 xml_printf(&retval, &tdesc, &pos, &size,
2362 free(arch_defined_types);
2366 xml_printf(&retval, &tdesc, &pos, &size,
2373 if (retval == ERROR_OK)
2381 static int gdb_get_target_description_chunk(struct target *target, struct target_desc_format *target_desc,
2382 char **chunk, int32_t offset, uint32_t length)
2384 if (target_desc == NULL) {
2385 LOG_ERROR("Unable to Generate Target Description");
2389 char *tdesc = target_desc->tdesc;
2390 uint32_t tdesc_length = target_desc->tdesc_length;
2392 if (tdesc == NULL) {
2393 int retval = gdb_generate_target_description(target, &tdesc);
2394 if (retval != ERROR_OK) {
2395 LOG_ERROR("Unable to Generate Target Description");
2399 tdesc_length = strlen(tdesc);
2404 if (length < (tdesc_length - offset))
2405 transfer_type = 'm';
2407 transfer_type = 'l';
2409 *chunk = malloc(length + 2);
2410 if (*chunk == NULL) {
2411 LOG_ERROR("Unable to allocate memory");
2415 (*chunk)[0] = transfer_type;
2416 if (transfer_type == 'm') {
2417 strncpy((*chunk) + 1, tdesc + offset, length);
2418 (*chunk)[1 + length] = '\0';
2420 strncpy((*chunk) + 1, tdesc + offset, tdesc_length - offset);
2421 (*chunk)[1 + (tdesc_length - offset)] = '\0';
2423 /* After gdb-server sends out last chunk, invalidate tdesc. */
2429 target_desc->tdesc = tdesc;
2430 target_desc->tdesc_length = tdesc_length;
2435 static int gdb_target_description_supported(struct target *target, int *supported)
2437 int retval = ERROR_OK;
2438 struct reg **reg_list = NULL;
2439 int reg_list_size = 0;
2440 char const **features = NULL;
2441 int feature_list_size = 0;
2443 char const *architecture = target_get_gdb_arch(target);
2445 retval = target_get_gdb_reg_list_noread(target, ®_list,
2446 ®_list_size, REG_CLASS_ALL);
2447 if (retval != ERROR_OK) {
2448 LOG_ERROR("get register list failed");
2452 if (reg_list_size <= 0) {
2453 LOG_ERROR("get register list failed");
2454 retval = ERROR_FAIL;
2458 /* Get a list of available target registers features */
2459 retval = get_reg_features_list(target, &features, &feature_list_size, reg_list, reg_list_size);
2460 if (retval != ERROR_OK) {
2461 LOG_ERROR("Can't get the registers feature list");
2466 if (architecture || feature_list_size)
2480 static int gdb_generate_thread_list(struct target *target, char **thread_list_out)
2482 struct rtos *rtos = target->rtos;
2483 int retval = ERROR_OK;
2484 char *thread_list = NULL;
2488 xml_printf(&retval, &thread_list, &pos, &size,
2489 "<?xml version=\"1.0\"?>\n"
2493 for (int i = 0; i < rtos->thread_count; i++) {
2494 struct thread_detail *thread_detail = &rtos->thread_details[i];
2496 if (!thread_detail->exists)
2499 xml_printf(&retval, &thread_list, &pos, &size,
2500 "<thread id=\"%" PRIx64 "\">", thread_detail->threadid);
2502 if (thread_detail->thread_name_str != NULL)
2503 xml_printf(&retval, &thread_list, &pos, &size,
2504 "Name: %s", thread_detail->thread_name_str);
2506 if (thread_detail->extra_info_str != NULL) {
2507 if (thread_detail->thread_name_str != NULL)
2508 xml_printf(&retval, &thread_list, &pos, &size,
2510 xml_printf(&retval, &thread_list, &pos, &size,
2511 "%s", thread_detail->extra_info_str);
2514 xml_printf(&retval, &thread_list, &pos, &size,
2519 xml_printf(&retval, &thread_list, &pos, &size,
2522 if (retval == ERROR_OK)
2523 *thread_list_out = thread_list;
2530 static int gdb_get_thread_list_chunk(struct target *target, char **thread_list,
2531 char **chunk, int32_t offset, uint32_t length)
2533 if (*thread_list == NULL) {
2534 int retval = gdb_generate_thread_list(target, thread_list);
2535 if (retval != ERROR_OK) {
2536 LOG_ERROR("Unable to Generate Thread List");
2541 size_t thread_list_length = strlen(*thread_list);
2544 length = MIN(length, thread_list_length - offset);
2545 if (length < (thread_list_length - offset))
2546 transfer_type = 'm';
2548 transfer_type = 'l';
2550 *chunk = malloc(length + 2 + 3);
2551 /* Allocating extra 3 bytes prevents false positive valgrind report
2552 * of strlen(chunk) word access:
2553 * Invalid read of size 4
2554 * Address 0x4479934 is 44 bytes inside a block of size 45 alloc'd */
2555 if (*chunk == NULL) {
2556 LOG_ERROR("Unable to allocate memory");
2560 (*chunk)[0] = transfer_type;
2561 strncpy((*chunk) + 1, (*thread_list) + offset, length);
2562 (*chunk)[1 + length] = '\0';
2564 /* After gdb-server sends out last chunk, invalidate thread list. */
2565 if (transfer_type == 'l') {
2567 *thread_list = NULL;
2573 static int gdb_query_packet(struct connection *connection,
2574 char const *packet, int packet_size)
2576 struct command_context *cmd_ctx = connection->cmd_ctx;
2577 struct gdb_connection *gdb_connection = connection->priv;
2578 struct target *target = get_target_from_connection(connection);
2580 if (strncmp(packet, "qRcmd,", 6) == 0) {
2581 if (packet_size > 6) {
2583 cmd = malloc((packet_size - 6) / 2 + 1);
2584 size_t len = unhexify((uint8_t *)cmd, packet + 6, (packet_size - 6) / 2);
2587 /* We want to print all debug output to GDB connection */
2588 log_add_callback(gdb_log_callback, connection);
2589 target_call_timer_callbacks_now();
2590 /* some commands need to know the GDB connection, make note of current
2591 * GDB connection. */
2592 current_gdb_connection = gdb_connection;
2593 command_run_line(cmd_ctx, cmd);
2594 current_gdb_connection = NULL;
2595 target_call_timer_callbacks_now();
2596 log_remove_callback(gdb_log_callback, connection);
2599 gdb_put_packet(connection, "OK", 2);
2601 } else if (strncmp(packet, "qCRC:", 5) == 0) {
2602 if (packet_size > 5) {
2607 target_addr_t addr = 0;
2610 /* skip command character */
2613 addr = strtoull(packet, &separator, 16);
2615 if (*separator != ',') {
2616 LOG_ERROR("incomplete read memory packet received, dropping connection");
2617 return ERROR_SERVER_REMOTE_CLOSED;
2620 len = strtoul(separator + 1, NULL, 16);
2622 retval = target_checksum_memory(target, addr, len, &checksum);
2624 if (retval == ERROR_OK) {
2625 snprintf(gdb_reply, 10, "C%8.8" PRIx32 "", checksum);
2626 gdb_put_packet(connection, gdb_reply, 9);
2628 retval = gdb_error(connection, retval);
2629 if (retval != ERROR_OK)
2635 } else if (strncmp(packet, "qSupported", 10) == 0) {
2636 /* we currently support packet size and qXfer:memory-map:read (if enabled)
2637 * qXfer:features:read is supported for some targets */
2638 int retval = ERROR_OK;
2639 char *buffer = NULL;
2642 int gdb_target_desc_supported = 0;
2644 /* we need to test that the target supports target descriptions */
2645 retval = gdb_target_description_supported(target, &gdb_target_desc_supported);
2646 if (retval != ERROR_OK) {
2647 LOG_INFO("Failed detecting Target Description Support, disabling");
2648 gdb_target_desc_supported = 0;
2651 /* support may be disabled globally */
2652 if (gdb_use_target_description == 0) {
2653 if (gdb_target_desc_supported)
2654 LOG_WARNING("Target Descriptions Supported, but disabled");
2655 gdb_target_desc_supported = 0;
2662 "PacketSize=%x;qXfer:memory-map:read%c;qXfer:features:read%c;qXfer:threads:read+;QStartNoAckMode+;vContSupported+",
2664 ((gdb_use_memory_map == 1) && (flash_get_bank_count() > 0)) ? '+' : '-',
2665 (gdb_target_desc_supported == 1) ? '+' : '-');
2667 if (retval != ERROR_OK) {
2668 gdb_send_error(connection, 01);
2672 gdb_put_packet(connection, buffer, strlen(buffer));
2676 } else if ((strncmp(packet, "qXfer:memory-map:read::", 23) == 0)
2677 && (flash_get_bank_count() > 0))
2678 return gdb_memory_map(connection, packet, packet_size);
2679 else if (strncmp(packet, "qXfer:features:read:", 20) == 0) {
2681 int retval = ERROR_OK;
2684 unsigned int length;
2686 /* skip command character */
2689 if (decode_xfer_read(packet, NULL, &offset, &length) < 0) {
2690 gdb_send_error(connection, 01);
2694 /* Target should prepare correct target description for annex.
2695 * The first character of returned xml is 'm' or 'l'. 'm' for
2696 * there are *more* chunks to transfer. 'l' for it is the *last*
2697 * chunk of target description.
2699 retval = gdb_get_target_description_chunk(target, &gdb_connection->target_desc,
2700 &xml, offset, length);
2701 if (retval != ERROR_OK) {
2702 gdb_error(connection, retval);
2706 gdb_put_packet(connection, xml, strlen(xml));
2710 } else if (strncmp(packet, "qXfer:threads:read:", 19) == 0) {
2712 int retval = ERROR_OK;
2715 unsigned int length;
2717 /* skip command character */
2720 if (decode_xfer_read(packet, NULL, &offset, &length) < 0) {
2721 gdb_send_error(connection, 01);
2725 /* Target should prepare correct thread list for annex.
2726 * The first character of returned xml is 'm' or 'l'. 'm' for
2727 * there are *more* chunks to transfer. 'l' for it is the *last*
2728 * chunk of target description.
2730 retval = gdb_get_thread_list_chunk(target, &gdb_connection->thread_list,
2731 &xml, offset, length);
2732 if (retval != ERROR_OK) {
2733 gdb_error(connection, retval);
2737 gdb_put_packet(connection, xml, strlen(xml));
2741 } else if (strncmp(packet, "QStartNoAckMode", 15) == 0) {
2742 gdb_connection->noack_mode = 1;
2743 gdb_put_packet(connection, "OK", 2);
2747 gdb_put_packet(connection, "", 0);
2751 static bool gdb_handle_vcont_packet(struct connection *connection, const char *packet, int packet_size)
2753 struct gdb_connection *gdb_connection = connection->priv;
2754 struct target *target = get_target_from_connection(connection);
2755 const char *parse = packet;
2758 /* query for vCont supported */
2759 if (parse[0] == '?') {
2760 if (target->type->step != NULL) {
2761 /* gdb doesn't accept c without C and s without S */
2762 gdb_put_packet(connection, "vCont;c;C;s;S", 13);
2768 if (parse[0] == ';') {
2773 /* simple case, a continue packet */
2774 if (parse[0] == 'c') {
2775 gdb_running_type = 'c';
2776 LOG_DEBUG("target %s continue", target_name(target));
2777 log_add_callback(gdb_log_callback, connection);
2778 retval = target_resume(target, 1, 0, 0, 0);
2779 if (retval == ERROR_TARGET_NOT_HALTED)
2780 LOG_INFO("target %s was not halted when resume was requested", target_name(target));
2782 /* poll target in an attempt to make its internal state consistent */
2783 if (retval != ERROR_OK) {
2784 retval = target_poll(target);
2785 if (retval != ERROR_OK)
2786 LOG_DEBUG("error polling target %s after failed resume", target_name(target));
2790 * We don't report errors to gdb here, move frontend_state to
2791 * TARGET_RUNNING to stay in sync with gdb's expectation of the
2794 gdb_connection->frontend_state = TARGET_RUNNING;
2795 target_call_event_callbacks(target, TARGET_EVENT_GDB_START);
2800 /* single-step or step-over-breakpoint */
2801 if (parse[0] == 's') {
2802 gdb_running_type = 's';
2803 bool fake_step = false;
2805 if (strncmp(parse, "s:", 2) == 0) {
2806 struct target *ct = target;
2814 thread_id = strtoll(parse, &endp, 16);
2816 packet_size -= endp - parse;
2820 if (target->rtos != NULL) {
2821 /* FIXME: why is this necessary? rtos state should be up-to-date here already! */
2822 rtos_update_threads(target);
2824 target->rtos->gdb_target_for_threadid(connection, thread_id, &ct);
2827 * check if the thread to be stepped is the current rtos thread
2828 * if not, we must fake the step
2830 if (target->rtos->current_thread != thread_id)
2834 if (parse[0] == ';') {
2838 if (parse[0] == 'c') {
2841 /* check if thread-id follows */
2842 if (parse[0] == ':') {
2846 tid = strtoll(parse, &endp, 16);
2847 if (tid == thread_id) {
2849 * Special case: only step a single thread (core),
2850 * keep the other threads halted. Currently, only
2851 * aarch64 target understands it. Other target types don't
2852 * care (nobody checks the actual value of 'current')
2853 * and it doesn't really matter. This deserves
2854 * a symbolic constant and a formal interface documentation
2857 LOG_DEBUG("request to step current core only");
2858 /* uncomment after checking that indeed other targets are safe */
2865 LOG_DEBUG("target %s single-step thread %"PRIx64, target_name(ct), thread_id);
2866 log_add_callback(gdb_log_callback, connection);
2867 target_call_event_callbacks(ct, TARGET_EVENT_GDB_START);
2870 * work around an annoying gdb behaviour: when the current thread
2871 * is changed in gdb, it assumes that the target can follow and also
2872 * make the thread current. This is an assumption that cannot hold
2873 * for a real target running a multi-threading OS. We just fake
2874 * the step to not trigger an internal error in gdb. See
2875 * https://sourceware.org/bugzilla/show_bug.cgi?id=22925 for details
2879 char sig_reply[128];
2881 LOG_DEBUG("fake step thread %"PRIx64, thread_id);
2883 sig_reply_len = snprintf(sig_reply, sizeof(sig_reply),
2884 "T05thread:%016"PRIx64";", thread_id);
2886 gdb_put_packet(connection, sig_reply, sig_reply_len);
2887 log_remove_callback(gdb_log_callback, connection);
2892 /* support for gdb_sync command */
2893 if (gdb_connection->sync) {
2894 gdb_connection->sync = false;
2895 if (ct->state == TARGET_HALTED) {
2896 LOG_DEBUG("stepi ignored. GDB will now fetch the register state "
2897 "from the target.");
2898 gdb_sig_halted(connection);
2899 log_remove_callback(gdb_log_callback, connection);
2901 gdb_connection->frontend_state = TARGET_RUNNING;
2905 retval = target_step(ct, current_pc, 0, 0);
2906 if (retval == ERROR_TARGET_NOT_HALTED)
2907 LOG_INFO("target %s was not halted when step was requested", target_name(ct));
2909 /* if step was successful send a reply back to gdb */
2910 if (retval == ERROR_OK) {
2911 retval = target_poll(ct);
2912 if (retval != ERROR_OK)
2913 LOG_DEBUG("error polling target %s after successful step", target_name(ct));
2914 /* send back signal information */
2915 gdb_signal_reply(ct, connection);
2916 /* stop forwarding log packets! */
2917 log_remove_callback(gdb_log_callback, connection);
2919 gdb_connection->frontend_state = TARGET_RUNNING;
2921 LOG_ERROR("Unknown vCont packet");
2930 static char *next_hex_encoded_field(const char **str, char sep)
2933 const char *hex = *str;
2937 const char *end = strchr(hex, sep);
2939 hexlen = strlen(hex);
2942 *str = hex + hexlen + 1;
2944 if (hexlen % 2 != 0) {
2945 /* Malformed hex data */
2949 size_t count = hexlen / 2;
2950 char *decoded = malloc(count + 1);
2951 if (decoded == NULL)
2954 size_t converted = unhexify((void *)decoded, hex, count);
2955 if (converted != count) {
2960 decoded[count] = '\0';
2964 /* handle extended restart packet */
2965 static void gdb_restart_inferior(struct connection *connection, const char *packet, int packet_size)
2967 struct gdb_connection *gdb_con = connection->priv;
2968 struct target *target = get_target_from_connection(connection);
2970 breakpoint_clear_target(target);
2971 watchpoint_clear_target(target);
2972 command_run_linef(connection->cmd_ctx, "ocd_gdb_restart %s",
2973 target_name(target));
2974 /* set connection as attached after reset */
2975 gdb_con->attached = true;
2976 /* info rtos parts */
2977 gdb_thread_packet(connection, packet, packet_size);
2980 static bool gdb_handle_vrun_packet(struct connection *connection, const char *packet, int packet_size)
2982 struct target *target = get_target_from_connection(connection);
2983 const char *parse = packet;
2988 if (parse[0] != ';')
2992 /* Skip first field "filename"; don't know what to do with it. */
2993 free(next_hex_encoded_field(&parse, ';'));
2995 char *cmdline = next_hex_encoded_field(&parse, ';');
2997 while (cmdline != NULL && (arg = next_hex_encoded_field(&parse, ';')) != NULL) {
2998 char *new_cmdline = alloc_printf("%s %s", cmdline, arg);
3001 cmdline = new_cmdline;
3004 if (cmdline != NULL) {
3005 if (target->semihosting != NULL) {
3006 LOG_INFO("GDB set inferior command line to '%s'", cmdline);
3007 free(target->semihosting->cmdline);
3008 target->semihosting->cmdline = cmdline;
3010 LOG_INFO("GDB set inferior command line to '%s' but semihosting is unavailable", cmdline);
3015 gdb_restart_inferior(connection, packet, packet_size);
3016 gdb_put_packet(connection, "S00", 3);
3020 static int gdb_v_packet(struct connection *connection,
3021 char const *packet, int packet_size)
3023 struct gdb_connection *gdb_connection = connection->priv;
3026 struct target *target = get_target_from_connection(connection);
3028 if (strncmp(packet, "vCont", 5) == 0) {
3034 handled = gdb_handle_vcont_packet(connection, packet, packet_size);
3036 gdb_put_packet(connection, "", 0);
3041 if (strncmp(packet, "vRun", 4) == 0) {
3044 handled = gdb_handle_vrun_packet(connection, packet, packet_size);
3046 gdb_put_packet(connection, "", 0);
3051 /* if flash programming disabled - send a empty reply */
3053 if (gdb_flash_program == 0) {
3054 gdb_put_packet(connection, "", 0);
3058 if (strncmp(packet, "vFlashErase:", 12) == 0) {
3060 unsigned long length;
3062 char const *parse = packet + 12;
3063 if (*parse == '\0') {
3064 LOG_ERROR("incomplete vFlashErase packet received, dropping connection");
3065 return ERROR_SERVER_REMOTE_CLOSED;
3068 addr = strtoul(parse, (char **)&parse, 16);
3070 if (*(parse++) != ',' || *parse == '\0') {
3071 LOG_ERROR("incomplete vFlashErase packet received, dropping connection");
3072 return ERROR_SERVER_REMOTE_CLOSED;
3075 length = strtoul(parse, (char **)&parse, 16);
3077 if (*parse != '\0') {
3078 LOG_ERROR("incomplete vFlashErase packet received, dropping connection");
3079 return ERROR_SERVER_REMOTE_CLOSED;
3082 /* assume all sectors need erasing - stops any problems
3083 * when flash_write is called multiple times */
3086 /* perform any target specific operations before the erase */
3087 target_call_event_callbacks(target,
3088 TARGET_EVENT_GDB_FLASH_ERASE_START);
3090 /* vFlashErase:addr,length messages require region start and
3091 * end to be "block" aligned ... if padding is ever needed,
3092 * GDB will have become dangerously confused.
3094 result = flash_erase_address_range(target, false, addr,
3097 /* perform any target specific operations after the erase */
3098 target_call_event_callbacks(target,
3099 TARGET_EVENT_GDB_FLASH_ERASE_END);
3102 if (result != ERROR_OK) {
3103 /* GDB doesn't evaluate the actual error number returned,
3104 * treat a failed erase as an I/O error
3106 gdb_send_error(connection, EIO);
3107 LOG_ERROR("flash_erase returned %i", result);
3109 gdb_put_packet(connection, "OK", 2);
3114 if (strncmp(packet, "vFlashWrite:", 12) == 0) {
3117 unsigned long length;
3118 char const *parse = packet + 12;
3120 if (*parse == '\0') {
3121 LOG_ERROR("incomplete vFlashErase packet received, dropping connection");
3122 return ERROR_SERVER_REMOTE_CLOSED;
3124 addr = strtoul(parse, (char **)&parse, 16);
3125 if (*(parse++) != ':') {
3126 LOG_ERROR("incomplete vFlashErase packet received, dropping connection");
3127 return ERROR_SERVER_REMOTE_CLOSED;
3129 length = packet_size - (parse - packet);
3131 /* create a new image if there isn't already one */
3132 if (gdb_connection->vflash_image == NULL) {
3133 gdb_connection->vflash_image = malloc(sizeof(struct image));
3134 image_open(gdb_connection->vflash_image, "", "build");
3137 /* create new section with content from packet buffer */
3138 retval = image_add_section(gdb_connection->vflash_image,
3139 addr, length, 0x0, (uint8_t const *)parse);
3140 if (retval != ERROR_OK)
3143 gdb_put_packet(connection, "OK", 2);
3148 if (strncmp(packet, "vFlashDone", 10) == 0) {
3151 /* process the flashing buffer. No need to erase as GDB
3152 * always issues a vFlashErase first. */
3153 target_call_event_callbacks(target,
3154 TARGET_EVENT_GDB_FLASH_WRITE_START);
3155 result = flash_write(target, gdb_connection->vflash_image,
3157 target_call_event_callbacks(target,
3158 TARGET_EVENT_GDB_FLASH_WRITE_END);
3159 if (result != ERROR_OK) {
3160 if (result == ERROR_FLASH_DST_OUT_OF_BANK)
3161 gdb_put_packet(connection, "E.memtype", 9);
3163 gdb_send_error(connection, EIO);
3165 LOG_DEBUG("wrote %u bytes from vFlash image to flash", (unsigned)written);
3166 gdb_put_packet(connection, "OK", 2);
3169 image_close(gdb_connection->vflash_image);
3170 free(gdb_connection->vflash_image);
3171 gdb_connection->vflash_image = NULL;
3176 gdb_put_packet(connection, "", 0);
3180 static int gdb_detach(struct connection *connection)
3183 * Only reply "OK" to GDB
3184 * it will close the connection and this will trigger a call to
3185 * gdb_connection_closed() that will in turn trigger the event
3186 * TARGET_EVENT_GDB_DETACH
3188 return gdb_put_packet(connection, "OK", 2);
3191 /* The format of 'F' response packet is
3192 * Fretcode,errno,Ctrl-C flag;call-specific attachment
3194 static int gdb_fileio_response_packet(struct connection *connection,
3195 char const *packet, int packet_size)
3197 struct target *target = get_target_from_connection(connection);
3199 char *parsing_point;
3200 int fileio_retcode = strtoul(packet + 1, &separator, 16);
3201 int fileio_errno = 0;
3202 bool fileio_ctrl_c = false;
3207 if (*separator == ',') {
3208 parsing_point = separator + 1;
3209 fileio_errno = strtoul(parsing_point, &separator, 16);
3210 if (*separator == ',') {
3211 if (*(separator + 1) == 'C') {
3212 /* TODO: process ctrl-c */
3213 fileio_ctrl_c = true;
3218 LOG_DEBUG("File-I/O response, retcode: 0x%x, errno: 0x%x, ctrl-c: %s",
3219 fileio_retcode, fileio_errno, fileio_ctrl_c ? "true" : "false");
3221 retval = target_gdb_fileio_end(target, fileio_retcode, fileio_errno, fileio_ctrl_c);
3222 if (retval != ERROR_OK)
3225 /* After File-I/O ends, keep continue or step */
3226 if (gdb_running_type == 'c')
3227 retval = target_resume(target, 1, 0x0, 0, 0);
3228 else if (gdb_running_type == 's')
3229 retval = target_step(target, 1, 0x0, 0);
3231 retval = ERROR_FAIL;
3233 if (retval != ERROR_OK)
3239 static void gdb_log_callback(void *priv, const char *file, unsigned line,
3240 const char *function, const char *string)
3242 struct connection *connection = priv;
3243 struct gdb_connection *gdb_con = connection->priv;
3245 if (gdb_con->busy) {
3246 /* do not reply this using the O packet */
3250 gdb_output_con(connection, string);
3253 static void gdb_sig_halted(struct connection *connection)
3256 snprintf(sig_reply, 4, "T%2.2x", 2);
3257 gdb_put_packet(connection, sig_reply, 3);
3260 static int gdb_input_inner(struct connection *connection)
3262 /* Do not allocate this on the stack */
3263 static char gdb_packet_buffer[GDB_BUFFER_SIZE + 1]; /* Extra byte for null-termination */
3265 struct target *target;
3266 char const *packet = gdb_packet_buffer;
3269 struct gdb_connection *gdb_con = connection->priv;
3270 static bool warn_use_ext;
3272 target = get_target_from_connection(connection);
3274 /* drain input buffer. If one of the packets fail, then an error
3275 * packet is replied, if applicable.
3277 * This loop will terminate and the error code is returned.
3279 * The calling fn will check if this error is something that
3280 * can be recovered from, or if the connection must be closed.
3282 * If the error is recoverable, this fn is called again to
3283 * drain the rest of the buffer.
3286 packet_size = GDB_BUFFER_SIZE;
3287 retval = gdb_get_packet(connection, gdb_packet_buffer, &packet_size);
3288 if (retval != ERROR_OK)
3291 /* terminate with zero */
3292 gdb_packet_buffer[packet_size] = '\0';
3294 gdb_log_incoming_packet(gdb_packet_buffer);
3296 if (packet_size > 0) {
3298 switch (packet[0]) {
3299 case 'T': /* Is thread alive? */
3300 gdb_thread_packet(connection, packet, packet_size);
3302 case 'H': /* Set current thread ( 'c' for step and continue,
3303 * 'g' for all other operations ) */
3304 gdb_thread_packet(connection, packet, packet_size);
3308 retval = gdb_thread_packet(connection, packet, packet_size);
3309 if (retval == GDB_THREAD_PACKET_NOT_CONSUMED)
3310 retval = gdb_query_packet(connection, packet, packet_size);
3313 retval = gdb_get_registers_packet(connection, packet, packet_size);
3316 retval = gdb_set_registers_packet(connection, packet, packet_size);
3319 retval = gdb_get_register_packet(connection, packet, packet_size);
3322 retval = gdb_set_register_packet(connection, packet, packet_size);
3325 retval = gdb_read_memory_packet(connection, packet, packet_size);
3328 retval = gdb_write_memory_packet(connection, packet, packet_size);
3332 retval = gdb_breakpoint_watchpoint_packet(connection, packet, packet_size);
3335 gdb_last_signal_packet(connection, packet, packet_size);
3336 /* '?' is sent after the eventual '!' */
3337 if (!warn_use_ext && !gdb_con->extended_protocol) {
3338 warn_use_ext = true;
3339 LOG_WARNING("Prefer GDB command \"target extended-remote :%s\" instead of \"target remote :%s\"",
3340 connection->service->port, connection->service->port);
3346 gdb_thread_packet(connection, packet, packet_size);
3347 log_add_callback(gdb_log_callback, connection);
3349 if (gdb_con->mem_write_error) {
3350 LOG_ERROR("Memory write failure!");
3352 /* now that we have reported the memory write error,
3353 * we can clear the condition */
3354 gdb_con->mem_write_error = false;
3357 bool nostep = false;
3358 bool already_running = false;
3359 if (target->state == TARGET_RUNNING) {
3360 LOG_WARNING("WARNING! The target is already running. "
3361 "All changes GDB did to registers will be discarded! "
3362 "Waiting for target to halt.");
3363 already_running = true;
3364 } else if (target->state != TARGET_HALTED) {
3365 LOG_WARNING("The target is not in the halted nor running stated, "
3366 "stepi/continue ignored.");
3368 } else if ((packet[0] == 's') && gdb_con->sync) {
3369 /* Hmm..... when you issue a continue in GDB, then a "stepi" is
3370 * sent by GDB first to OpenOCD, thus defeating the check to
3371 * make only the single stepping have the sync feature...
3374 LOG_DEBUG("stepi ignored. GDB will now fetch the register state "
3375 "from the target.");
3377 gdb_con->sync = false;
3379 if (!already_running && nostep) {
3380 /* Either the target isn't in the halted state, then we can't
3381 * step/continue. This might be early setup, etc.
3383 * Or we want to allow GDB to pick up a fresh set of
3384 * register values without modifying the target state.
3387 gdb_sig_halted(connection);
3389 /* stop forwarding log packets! */
3390 log_remove_callback(gdb_log_callback, connection);
3392 /* We're running/stepping, in which case we can
3393 * forward log output until the target is halted
3395 gdb_con->frontend_state = TARGET_RUNNING;
3396 target_call_event_callbacks(target, TARGET_EVENT_GDB_START);
3398 if (!already_running) {
3399 /* Here we don't want packet processing to stop even if this fails,
3400 * so we use a local variable instead of retval. */
3401 retval = gdb_step_continue_packet(connection, packet, packet_size);
3402 if (retval != ERROR_OK) {
3403 /* we'll never receive a halted
3404 * condition... issue a false one..
3406 gdb_frontend_halted(target, connection);
3413 retval = gdb_v_packet(connection, packet, packet_size);
3416 retval = gdb_detach(connection);
3419 retval = gdb_write_memory_binary_packet(connection, packet, packet_size);
3420 if (retval != ERROR_OK)
3424 if (gdb_con->extended_protocol) {
3425 gdb_con->attached = false;
3428 gdb_put_packet(connection, "OK", 2);
3429 return ERROR_SERVER_REMOTE_CLOSED;
3431 /* handle extended remote protocol */
3432 gdb_con->extended_protocol = true;
3433 gdb_put_packet(connection, "OK", 2);
3436 /* handle extended restart packet */
3437 gdb_restart_inferior(connection, packet, packet_size);
3441 /* packet supported only by smp target i.e cortex_a.c*/
3442 /* handle smp packet replying coreid played to gbd */
3443 gdb_read_smp_packet(connection, packet, packet_size);
3447 /* packet supported only by smp target i.e cortex_a.c */
3448 /* handle smp packet setting coreid to be played at next
3450 gdb_write_smp_packet(connection, packet, packet_size);
3454 /* File-I/O extension */
3455 /* After gdb uses host-side syscall to complete target file
3456 * I/O, gdb sends host-side syscall return value to target
3458 * The format of 'F' response packet is
3459 * Fretcode,errno,Ctrl-C flag;call-specific attachment
3461 gdb_con->frontend_state = TARGET_RUNNING;
3462 log_add_callback(gdb_log_callback, connection);
3463 gdb_fileio_response_packet(connection, packet, packet_size);
3467 /* ignore unknown packets */
3468 LOG_DEBUG("ignoring 0x%2.2x packet", packet[0]);
3469 gdb_put_packet(connection, "", 0);
3473 /* if a packet handler returned an error, exit input loop */
3474 if (retval != ERROR_OK)
3478 if (gdb_con->ctrl_c) {
3479 if (target->state == TARGET_RUNNING) {
3480 struct target *t = target;
3482 target->rtos->gdb_target_for_threadid(connection, target->rtos->current_threadid, &t);
3483 retval = target_halt(t);
3484 if (retval == ERROR_OK)
3485 retval = target_poll(t);
3486 if (retval != ERROR_OK)
3487 target_call_event_callbacks(target, TARGET_EVENT_GDB_HALT);
3488 gdb_con->ctrl_c = false;
3490 LOG_INFO("The target is not running when halt was requested, stopping GDB.");
3491 target_call_event_callbacks(target, TARGET_EVENT_GDB_HALT);
3495 } while (gdb_con->buf_cnt > 0);
3500 static int gdb_input(struct connection *connection)
3502 int retval = gdb_input_inner(connection);
3503 struct gdb_connection *gdb_con = connection->priv;
3504 if (retval == ERROR_SERVER_REMOTE_CLOSED)
3507 /* logging does not propagate the error, yet can set the gdb_con->closed flag */
3508 if (gdb_con->closed)
3509 return ERROR_SERVER_REMOTE_CLOSED;
3511 /* we'll recover from any other errors(e.g. temporary timeouts, etc.) */
3515 static int gdb_target_start(struct target *target, const char *port)
3517 struct gdb_service *gdb_service;
3519 gdb_service = malloc(sizeof(struct gdb_service));
3521 if (NULL == gdb_service)
3524 LOG_INFO("starting gdb server for %s on %s", target_name(target), port);
3526 gdb_service->target = target;
3527 gdb_service->core[0] = -1;
3528 gdb_service->core[1] = -1;
3529 target->gdb_service = gdb_service;
3531 ret = add_service("gdb",
3532 port, target->gdb_max_connections, &gdb_new_connection, &gdb_input,
3533 &gdb_connection_closed, gdb_service);
3534 /* initialize all targets gdb service with the same pointer */
3536 struct target_list *head;
3537 struct target *curr;
3538 head = target->head;
3539 while (head != (struct target_list *)NULL) {
3540 curr = head->target;
3542 curr->gdb_service = gdb_service;
3549 static int gdb_target_add_one(struct target *target)
3551 /* one gdb instance per smp list */
3552 if ((target->smp) && (target->gdb_service))
3555 /* skip targets that cannot handle a gdb connections (e.g. mem_ap) */
3556 if (!target_supports_gdb_connection(target)) {
3557 LOG_DEBUG("skip gdb server for target %s", target_name(target));
3561 if (target->gdb_port_override) {
3562 if (strcmp(target->gdb_port_override, "disabled") == 0) {
3563 LOG_INFO("gdb port disabled");
3566 return gdb_target_start(target, target->gdb_port_override);
3569 if (strcmp(gdb_port, "disabled") == 0) {
3570 LOG_INFO("gdb port disabled");
3574 int retval = gdb_target_start(target, gdb_port_next);
3575 if (retval == ERROR_OK) {
3576 /* save the port number so can be queried with
3577 * $target_name cget -gdb-port
3579 target->gdb_port_override = strdup(gdb_port_next);
3582 /* If we can parse the port number
3583 * then we increment the port number for the next target.
3586 portnumber = strtol(gdb_port_next, &end, 0);
3588 if (parse_long(gdb_port_next, &portnumber) == ERROR_OK) {
3589 free(gdb_port_next);
3591 gdb_port_next = alloc_printf("%ld", portnumber+1);
3593 /* Don't increment if gdb_port is 0, since we're just
3594 * trying to allocate an unused port. */
3595 gdb_port_next = strdup("0");
3603 int gdb_target_add_all(struct target *target)
3605 if (NULL == target) {
3606 LOG_WARNING("gdb services need one or more targets defined");
3610 while (NULL != target) {
3611 int retval = gdb_target_add_one(target);
3612 if (ERROR_OK != retval)
3615 target = target->next;
3621 COMMAND_HANDLER(handle_gdb_sync_command)
3624 return ERROR_COMMAND_SYNTAX_ERROR;
3626 if (current_gdb_connection == NULL) {
3628 "gdb_sync command can only be run from within gdb using \"monitor gdb_sync\"");
3632 current_gdb_connection->sync = true;
3637 /* daemon configuration command gdb_port */
3638 COMMAND_HANDLER(handle_gdb_port_command)
3640 int retval = CALL_COMMAND_HANDLER(server_pipe_command, &gdb_port);
3641 if (ERROR_OK == retval) {
3642 free(gdb_port_next);
3643 gdb_port_next = strdup(gdb_port);
3648 COMMAND_HANDLER(handle_gdb_memory_map_command)
3651 return ERROR_COMMAND_SYNTAX_ERROR;
3653 COMMAND_PARSE_ENABLE(CMD_ARGV[0], gdb_use_memory_map);
3657 COMMAND_HANDLER(handle_gdb_flash_program_command)
3660 return ERROR_COMMAND_SYNTAX_ERROR;
3662 COMMAND_PARSE_ENABLE(CMD_ARGV[0], gdb_flash_program);
3666 COMMAND_HANDLER(handle_gdb_report_data_abort_command)
3669 return ERROR_COMMAND_SYNTAX_ERROR;
3671 COMMAND_PARSE_ENABLE(CMD_ARGV[0], gdb_report_data_abort);
3675 COMMAND_HANDLER(handle_gdb_report_register_access_error)
3678 return ERROR_COMMAND_SYNTAX_ERROR;
3680 COMMAND_PARSE_ENABLE(CMD_ARGV[0], gdb_report_register_access_error);
3684 /* gdb_breakpoint_override */
3685 COMMAND_HANDLER(handle_gdb_breakpoint_override_command)
3687 if (CMD_ARGC == 0) {
3689 } else if (CMD_ARGC == 1) {
3690 gdb_breakpoint_override = 1;
3691 if (strcmp(CMD_ARGV[0], "hard") == 0)
3692 gdb_breakpoint_override_type = BKPT_HARD;
3693 else if (strcmp(CMD_ARGV[0], "soft") == 0)
3694 gdb_breakpoint_override_type = BKPT_SOFT;
3695 else if (strcmp(CMD_ARGV[0], "disable") == 0)
3696 gdb_breakpoint_override = 0;
3698 return ERROR_COMMAND_SYNTAX_ERROR;
3699 if (gdb_breakpoint_override)
3700 LOG_USER("force %s breakpoints",
3701 (gdb_breakpoint_override_type == BKPT_HARD) ? "hard" : "soft");
3703 LOG_USER("breakpoint type is not overridden");
3708 COMMAND_HANDLER(handle_gdb_target_description_command)
3711 return ERROR_COMMAND_SYNTAX_ERROR;
3713 COMMAND_PARSE_ENABLE(CMD_ARGV[0], gdb_use_target_description);
3717 COMMAND_HANDLER(handle_gdb_save_tdesc_command)
3720 uint32_t tdesc_length;
3721 struct target *target = get_current_target(CMD_CTX);
3723 int retval = gdb_generate_target_description(target, &tdesc);
3724 if (retval != ERROR_OK) {
3725 LOG_ERROR("Unable to Generate Target Description");
3729 tdesc_length = strlen(tdesc);
3731 struct fileio *fileio;
3732 size_t size_written;
3734 char *tdesc_filename = alloc_printf("%s.xml", target_type_name(target));
3735 if (tdesc_filename == NULL) {
3736 retval = ERROR_FAIL;
3740 retval = fileio_open(&fileio, tdesc_filename, FILEIO_WRITE, FILEIO_TEXT);
3742 if (retval != ERROR_OK) {
3743 LOG_ERROR("Can't open %s for writing", tdesc_filename);
3747 retval = fileio_write(fileio, tdesc_length, tdesc, &size_written);
3749 fileio_close(fileio);
3751 if (retval != ERROR_OK)
3752 LOG_ERROR("Error while writing the tdesc file");
3755 free(tdesc_filename);
3761 static const struct command_registration gdb_command_handlers[] = {
3764 .handler = handle_gdb_sync_command,
3765 .mode = COMMAND_ANY,
3766 .help = "next stepi will return immediately allowing "
3767 "GDB to fetch register state without affecting "
3773 .handler = handle_gdb_port_command,
3774 .mode = COMMAND_CONFIG,
3775 .help = "Normally gdb listens to a TCP/IP port. Each subsequent GDB "
3776 "server listens for the next port number after the "
3777 "base port number specified. "
3778 "No arguments reports GDB port. \"pipe\" means listen to stdin "
3779 "output to stdout, an integer is base port number, \"disabled\" disables "
3780 "port. Any other string is are interpreted as named pipe to listen to. "
3781 "Output pipe is the same name as input pipe, but with 'o' appended.",
3782 .usage = "[port_num]",
3785 .name = "gdb_memory_map",
3786 .handler = handle_gdb_memory_map_command,
3787 .mode = COMMAND_CONFIG,
3788 .help = "enable or disable memory map",
3789 .usage = "('enable'|'disable')"
3792 .name = "gdb_flash_program",
3793 .handler = handle_gdb_flash_program_command,
3794 .mode = COMMAND_CONFIG,
3795 .help = "enable or disable flash program",
3796 .usage = "('enable'|'disable')"
3799 .name = "gdb_report_data_abort",
3800 .handler = handle_gdb_report_data_abort_command,
3801 .mode = COMMAND_CONFIG,
3802 .help = "enable or disable reporting data aborts",
3803 .usage = "('enable'|'disable')"
3806 .name = "gdb_report_register_access_error",
3807 .handler = handle_gdb_report_register_access_error,
3808 .mode = COMMAND_CONFIG,
3809 .help = "enable or disable reporting register access errors",
3810 .usage = "('enable'|'disable')"
3813 .name = "gdb_breakpoint_override",
3814 .handler = handle_gdb_breakpoint_override_command,
3815 .mode = COMMAND_ANY,
3816 .help = "Display or specify type of breakpoint "
3817 "to be used by gdb 'break' commands.",
3818 .usage = "('hard'|'soft'|'disable')"
3821 .name = "gdb_target_description",
3822 .handler = handle_gdb_target_description_command,
3823 .mode = COMMAND_CONFIG,
3824 .help = "enable or disable target description",
3825 .usage = "('enable'|'disable')"
3828 .name = "gdb_save_tdesc",
3829 .handler = handle_gdb_save_tdesc_command,
3830 .mode = COMMAND_EXEC,
3831 .help = "Save the target description file",
3834 COMMAND_REGISTRATION_DONE
3837 int gdb_register_commands(struct command_context *cmd_ctx)
3839 gdb_port = strdup("3333");
3840 gdb_port_next = strdup("3333");
3841 return register_commands(cmd_ctx, NULL, gdb_command_handlers);
3844 void gdb_service_free(void)
3847 free(gdb_port_next);