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 int gdb_put_packet_inner(struct connection *connection,
361 char *buffer, int len)
364 unsigned char my_checksum = 0;
365 #ifdef _DEBUG_GDB_IO_
370 struct gdb_connection *gdb_con = connection->priv;
372 for (i = 0; i < len; i++)
373 my_checksum += buffer[i];
375 #ifdef _DEBUG_GDB_IO_
377 * At this point we should have nothing in the input queue from GDB,
378 * however sometimes '-' is sent even though we've already received
379 * an ACK (+) for everything we've sent off.
383 retval = check_pending(connection, 0, &gotdata);
384 if (retval != ERROR_OK)
388 retval = gdb_get_char(connection, &reply);
389 if (retval != ERROR_OK)
392 /* fix a problem with some IAR tools */
393 gdb_putback_char(connection, reply);
394 LOG_DEBUG("Unexpected start of new packet");
398 LOG_WARNING("Discard unexpected char %c", reply);
403 #ifdef _DEBUG_GDB_IO_
404 debug_buffer = strndup(buffer, len);
405 LOG_DEBUG("sending packet '$%s#%2.2x'", debug_buffer, my_checksum);
409 char local_buffer[1024];
410 local_buffer[0] = '$';
411 if ((size_t)len + 4 <= sizeof(local_buffer)) {
412 /* performance gain on smaller packets by only a single call to gdb_write() */
413 memcpy(local_buffer + 1, buffer, len++);
414 len += snprintf(local_buffer + len, sizeof(local_buffer) - len, "#%02x", my_checksum);
415 retval = gdb_write(connection, local_buffer, len);
416 if (retval != ERROR_OK)
419 /* larger packets are transmitted directly from caller supplied buffer
420 * by several calls to gdb_write() to avoid dynamic allocation */
421 snprintf(local_buffer + 1, sizeof(local_buffer) - 1, "#%02x", my_checksum);
422 retval = gdb_write(connection, local_buffer, 1);
423 if (retval != ERROR_OK)
425 retval = gdb_write(connection, buffer, len);
426 if (retval != ERROR_OK)
428 retval = gdb_write(connection, local_buffer + 1, 3);
429 if (retval != ERROR_OK)
433 if (gdb_con->noack_mode)
436 retval = gdb_get_char(connection, &reply);
437 if (retval != ERROR_OK)
442 else if (reply == '-') {
443 /* Stop sending output packets for now */
444 log_remove_callback(gdb_log_callback, connection);
445 LOG_WARNING("negative reply, retrying");
446 } else if (reply == 0x3) {
447 gdb_con->ctrl_c = true;
448 retval = gdb_get_char(connection, &reply);
449 if (retval != ERROR_OK)
453 else if (reply == '-') {
454 /* Stop sending output packets for now */
455 log_remove_callback(gdb_log_callback, connection);
456 LOG_WARNING("negative reply, retrying");
457 } else if (reply == '$') {
458 LOG_ERROR("GDB missing ack(1) - assumed good");
459 gdb_putback_char(connection, reply);
462 LOG_ERROR("unknown character(1) 0x%2.2x in reply, dropping connection", reply);
463 gdb_con->closed = true;
464 return ERROR_SERVER_REMOTE_CLOSED;
466 } else if (reply == '$') {
467 LOG_ERROR("GDB missing ack(2) - assumed good");
468 gdb_putback_char(connection, reply);
471 LOG_ERROR("unknown character(2) 0x%2.2x in reply, dropping connection",
473 gdb_con->closed = true;
474 return ERROR_SERVER_REMOTE_CLOSED;
478 return ERROR_SERVER_REMOTE_CLOSED;
483 int gdb_put_packet(struct connection *connection, char *buffer, int len)
485 struct gdb_connection *gdb_con = connection->priv;
486 gdb_con->busy = true;
487 int retval = gdb_put_packet_inner(connection, buffer, len);
488 gdb_con->busy = false;
490 /* we sent some data, reset timer for keep alive messages */
496 static inline int fetch_packet(struct connection *connection,
497 int *checksum_ok, int noack, int *len, char *buffer)
499 unsigned char my_checksum = 0;
502 int retval = ERROR_OK;
504 struct gdb_connection *gdb_con = connection->priv;
509 /* move this over into local variables to use registers and give the
510 * more freedom to optimize */
511 char *buf_p = gdb_con->buf_p;
512 int buf_cnt = gdb_con->buf_cnt;
515 /* The common case is that we have an entire packet with no escape chars.
516 * We need to leave at least 2 bytes in the buffer to have
517 * gdb_get_char() update various bits and bobs correctly.
519 if ((buf_cnt > 2) && ((buf_cnt + count) < *len)) {
520 /* The compiler will struggle a bit with constant propagation and
521 * aliasing, so we help it by showing that these values do not
522 * change inside the loop
526 int run = buf_cnt - 2;
532 if (character == '#') {
533 /* Danger! character can be '#' when esc is
534 * used so we need an explicit boolean for done here. */
539 if (character == '}') {
540 /* data transmitted in binary mode (X packet)
541 * uses 0x7d as escape character */
542 my_checksum += character & 0xff;
545 my_checksum += character & 0xff;
546 buffer[count++] = (character ^ 0x20) & 0xff;
548 my_checksum += character & 0xff;
549 buffer[count++] = character & 0xff;
558 LOG_ERROR("packet buffer too small");
559 retval = ERROR_GDB_BUFFER_TOO_SMALL;
563 retval = gdb_get_char_fast(connection, &character, &buf_p, &buf_cnt);
564 if (retval != ERROR_OK)
567 if (character == '#')
570 if (character == '}') {
571 /* data transmitted in binary mode (X packet)
572 * uses 0x7d as escape character */
573 my_checksum += character & 0xff;
575 retval = gdb_get_char_fast(connection, &character, &buf_p, &buf_cnt);
576 if (retval != ERROR_OK)
579 my_checksum += character & 0xff;
580 buffer[count++] = (character ^ 0x20) & 0xff;
582 my_checksum += character & 0xff;
583 buffer[count++] = character & 0xff;
587 gdb_con->buf_p = buf_p;
588 gdb_con->buf_cnt = buf_cnt;
590 if (retval != ERROR_OK)
595 retval = gdb_get_char(connection, &character);
596 if (retval != ERROR_OK)
598 checksum[0] = character;
599 retval = gdb_get_char(connection, &character);
600 if (retval != ERROR_OK)
602 checksum[1] = character;
606 *checksum_ok = (my_checksum == strtoul(checksum, NULL, 16));
611 static int gdb_get_packet_inner(struct connection *connection,
612 char *buffer, int *len)
616 struct gdb_connection *gdb_con = connection->priv;
620 retval = gdb_get_char(connection, &character);
621 if (retval != ERROR_OK)
624 #ifdef _DEBUG_GDB_IO_
625 LOG_DEBUG("character: '%c'", character);
632 /* According to the GDB documentation
633 * (https://sourceware.org/gdb/onlinedocs/gdb/Packet-Acknowledgment.html):
634 * "gdb sends a final `+` acknowledgment of the stub's `OK`
635 * response, which can be safely ignored by the stub."
636 * However OpenOCD server already is in noack mode at this
637 * point and instead of ignoring this it was emitting a
638 * warning. This code makes server ignore the first ACK
639 * that will be received after going into noack mode,
640 * warning only about subsequent ACK's. */
641 if (gdb_con->noack_mode > 1) {
642 LOG_WARNING("acknowledgment received, but no packet pending");
643 } else if (gdb_con->noack_mode) {
644 LOG_DEBUG("Received first acknowledgment after entering noack mode. Ignoring it.");
645 gdb_con->noack_mode = 2;
649 LOG_WARNING("negative acknowledgment, but no packet pending");
652 gdb_con->ctrl_c = true;
656 LOG_WARNING("ignoring character 0x%x", character);
659 } while (character != '$');
662 /* explicit code expansion here to get faster inlined code in -O3 by not
663 * calculating checksum */
664 if (gdb_con->noack_mode) {
665 retval = fetch_packet(connection, &checksum_ok, 1, len, buffer);
666 if (retval != ERROR_OK)
669 retval = fetch_packet(connection, &checksum_ok, 0, len, buffer);
670 if (retval != ERROR_OK)
674 if (gdb_con->noack_mode) {
675 /* checksum is not checked in noack mode */
679 retval = gdb_write(connection, "+", 1);
680 if (retval != ERROR_OK)
686 return ERROR_SERVER_REMOTE_CLOSED;
691 static int gdb_get_packet(struct connection *connection, char *buffer, int *len)
693 struct gdb_connection *gdb_con = connection->priv;
694 gdb_con->busy = true;
695 int retval = gdb_get_packet_inner(connection, buffer, len);
696 gdb_con->busy = false;
700 static int gdb_output_con(struct connection *connection, const char *line)
705 bin_size = strlen(line);
707 hex_buffer = malloc(bin_size * 2 + 2);
708 if (hex_buffer == NULL)
709 return ERROR_GDB_BUFFER_TOO_SMALL;
712 size_t pkt_len = hexify(hex_buffer + 1, (const uint8_t *)line, bin_size,
714 int retval = gdb_put_packet(connection, hex_buffer, pkt_len + 1);
720 static int gdb_output(struct command_context *context, const char *line)
722 /* this will be dumped to the log and also sent as an O packet if possible */
723 LOG_USER_N("%s", line);
727 static void gdb_signal_reply(struct target *target, struct connection *connection)
729 struct gdb_connection *gdb_connection = connection->priv;
731 char stop_reason[20];
732 char current_thread[25];
736 rtos_update_threads(target);
738 if (target->debug_reason == DBG_REASON_EXIT) {
739 sig_reply_len = snprintf(sig_reply, sizeof(sig_reply), "W00");
742 if (target->rtos != NULL) {
743 target->rtos->current_threadid = target->rtos->current_thread;
744 target->rtos->gdb_target_for_threadid(connection, target->rtos->current_threadid, &ct);
749 if (gdb_connection->ctrl_c) {
752 signal_var = gdb_last_signal(ct);
754 stop_reason[0] = '\0';
755 if (ct->debug_reason == DBG_REASON_WATCHPOINT) {
756 enum watchpoint_rw hit_wp_type;
757 target_addr_t hit_wp_address;
759 if (watchpoint_hit(ct, &hit_wp_type, &hit_wp_address) == ERROR_OK) {
761 switch (hit_wp_type) {
763 snprintf(stop_reason, sizeof(stop_reason),
764 "watch:%08" TARGET_PRIxADDR ";", hit_wp_address);
767 snprintf(stop_reason, sizeof(stop_reason),
768 "rwatch:%08" TARGET_PRIxADDR ";", hit_wp_address);
771 snprintf(stop_reason, sizeof(stop_reason),
772 "awatch:%08" TARGET_PRIxADDR ";", hit_wp_address);
780 current_thread[0] = '\0';
781 if (target->rtos != NULL)
782 snprintf(current_thread, sizeof(current_thread), "thread:%" PRIx64 ";",
783 target->rtos->current_thread);
785 sig_reply_len = snprintf(sig_reply, sizeof(sig_reply), "T%2.2x%s%s",
786 signal_var, stop_reason, current_thread);
788 gdb_connection->ctrl_c = false;
791 gdb_put_packet(connection, sig_reply, sig_reply_len);
792 gdb_connection->frontend_state = TARGET_HALTED;
795 static void gdb_fileio_reply(struct target *target, struct connection *connection)
797 struct gdb_connection *gdb_connection = connection->priv;
798 char fileio_command[256];
800 bool program_exited = false;
802 if (strcmp(target->fileio_info->identifier, "open") == 0)
803 sprintf(fileio_command, "F%s,%" PRIx64 "/%" PRIx64 ",%" PRIx64 ",%" PRIx64, target->fileio_info->identifier,
804 target->fileio_info->param_1,
805 target->fileio_info->param_2 + 1, /* len + trailing zero */
806 target->fileio_info->param_3,
807 target->fileio_info->param_4);
808 else if (strcmp(target->fileio_info->identifier, "close") == 0)
809 sprintf(fileio_command, "F%s,%" PRIx64, target->fileio_info->identifier,
810 target->fileio_info->param_1);
811 else if (strcmp(target->fileio_info->identifier, "read") == 0)
812 sprintf(fileio_command, "F%s,%" PRIx64 ",%" PRIx64 ",%" PRIx64, target->fileio_info->identifier,
813 target->fileio_info->param_1,
814 target->fileio_info->param_2,
815 target->fileio_info->param_3);
816 else if (strcmp(target->fileio_info->identifier, "write") == 0)
817 sprintf(fileio_command, "F%s,%" PRIx64 ",%" PRIx64 ",%" PRIx64, target->fileio_info->identifier,
818 target->fileio_info->param_1,
819 target->fileio_info->param_2,
820 target->fileio_info->param_3);
821 else if (strcmp(target->fileio_info->identifier, "lseek") == 0)
822 sprintf(fileio_command, "F%s,%" PRIx64 ",%" PRIx64 ",%" PRIx64, target->fileio_info->identifier,
823 target->fileio_info->param_1,
824 target->fileio_info->param_2,
825 target->fileio_info->param_3);
826 else if (strcmp(target->fileio_info->identifier, "rename") == 0)
827 sprintf(fileio_command, "F%s,%" PRIx64 "/%" PRIx64 ",%" PRIx64 "/%" PRIx64, target->fileio_info->identifier,
828 target->fileio_info->param_1,
829 target->fileio_info->param_2 + 1, /* len + trailing zero */
830 target->fileio_info->param_3,
831 target->fileio_info->param_4 + 1); /* len + trailing zero */
832 else if (strcmp(target->fileio_info->identifier, "unlink") == 0)
833 sprintf(fileio_command, "F%s,%" PRIx64 "/%" PRIx64, target->fileio_info->identifier,
834 target->fileio_info->param_1,
835 target->fileio_info->param_2 + 1); /* len + trailing zero */
836 else if (strcmp(target->fileio_info->identifier, "stat") == 0)
837 sprintf(fileio_command, "F%s,%" PRIx64 "/%" PRIx64 ",%" PRIx64, target->fileio_info->identifier,
838 target->fileio_info->param_1,
839 target->fileio_info->param_2,
840 target->fileio_info->param_3);
841 else if (strcmp(target->fileio_info->identifier, "fstat") == 0)
842 sprintf(fileio_command, "F%s,%" PRIx64 ",%" PRIx64, target->fileio_info->identifier,
843 target->fileio_info->param_1,
844 target->fileio_info->param_2);
845 else if (strcmp(target->fileio_info->identifier, "gettimeofday") == 0)
846 sprintf(fileio_command, "F%s,%" PRIx64 ",%" PRIx64, target->fileio_info->identifier,
847 target->fileio_info->param_1,
848 target->fileio_info->param_2);
849 else if (strcmp(target->fileio_info->identifier, "isatty") == 0)
850 sprintf(fileio_command, "F%s,%" PRIx64, target->fileio_info->identifier,
851 target->fileio_info->param_1);
852 else if (strcmp(target->fileio_info->identifier, "system") == 0)
853 sprintf(fileio_command, "F%s,%" PRIx64 "/%" PRIx64, target->fileio_info->identifier,
854 target->fileio_info->param_1,
855 target->fileio_info->param_2 + 1); /* len + trailing zero */
856 else if (strcmp(target->fileio_info->identifier, "exit") == 0) {
857 /* If target hits exit syscall, report to GDB the program is terminated.
858 * In addition, let target run its own exit syscall handler. */
859 program_exited = true;
860 sprintf(fileio_command, "W%02" PRIx64, target->fileio_info->param_1);
862 LOG_DEBUG("Unknown syscall: %s", target->fileio_info->identifier);
864 /* encounter unknown syscall, continue */
865 gdb_connection->frontend_state = TARGET_RUNNING;
866 target_resume(target, 1, 0x0, 0, 0);
870 command_len = strlen(fileio_command);
871 gdb_put_packet(connection, fileio_command, command_len);
873 if (program_exited) {
874 /* Use target_resume() to let target run its own exit syscall handler. */
875 gdb_connection->frontend_state = TARGET_RUNNING;
876 target_resume(target, 1, 0x0, 0, 0);
878 gdb_connection->frontend_state = TARGET_HALTED;
879 rtos_update_threads(target);
883 static void gdb_frontend_halted(struct target *target, struct connection *connection)
885 struct gdb_connection *gdb_connection = connection->priv;
887 /* In the GDB protocol when we are stepping or continuing execution,
888 * we have a lingering reply. Upon receiving a halted event
889 * when we have that lingering packet, we reply to the original
890 * step or continue packet.
892 * Executing monitor commands can bring the target in and
893 * out of the running state so we'll see lots of TARGET_EVENT_XXX
894 * that are to be ignored.
896 if (gdb_connection->frontend_state == TARGET_RUNNING) {
897 /* stop forwarding log packets! */
898 log_remove_callback(gdb_log_callback, connection);
900 /* check fileio first */
901 if (target_get_gdb_fileio_info(target, target->fileio_info) == ERROR_OK)
902 gdb_fileio_reply(target, connection);
904 gdb_signal_reply(target, connection);
908 static int gdb_target_callback_event_handler(struct target *target,
909 enum target_event event, void *priv)
911 struct connection *connection = priv;
912 struct gdb_service *gdb_service = connection->service->priv;
914 if (gdb_service->target != target)
918 case TARGET_EVENT_GDB_HALT:
919 gdb_frontend_halted(target, connection);
921 case TARGET_EVENT_HALTED:
922 target_call_event_callbacks(target, TARGET_EVENT_GDB_END);
931 static int gdb_new_connection(struct connection *connection)
933 struct gdb_connection *gdb_connection = malloc(sizeof(struct gdb_connection));
934 struct target *target;
938 target = get_target_from_connection(connection);
939 connection->priv = gdb_connection;
940 connection->cmd_ctx->current_target = target;
942 /* initialize gdb connection information */
943 gdb_connection->buf_p = gdb_connection->buffer;
944 gdb_connection->buf_cnt = 0;
945 gdb_connection->ctrl_c = false;
946 gdb_connection->frontend_state = TARGET_HALTED;
947 gdb_connection->vflash_image = NULL;
948 gdb_connection->closed = false;
949 gdb_connection->busy = false;
950 gdb_connection->noack_mode = 0;
951 gdb_connection->sync = false;
952 gdb_connection->mem_write_error = false;
953 gdb_connection->attached = true;
954 gdb_connection->extended_protocol = false;
955 gdb_connection->target_desc.tdesc = NULL;
956 gdb_connection->target_desc.tdesc_length = 0;
957 gdb_connection->thread_list = NULL;
959 /* send ACK to GDB for debug request */
960 gdb_write(connection, "+", 1);
962 /* output goes through gdb connection */
963 command_set_output_handler(connection->cmd_ctx, gdb_output, connection);
965 /* we must remove all breakpoints registered to the target as a previous
966 * GDB session could leave dangling breakpoints if e.g. communication
969 breakpoint_clear_target(target);
970 watchpoint_clear_target(target);
973 /* clean previous rtos session if supported*/
974 if (target->rtos->type->clean)
975 target->rtos->type->clean(target);
978 rtos_update_threads(target);
981 /* remove the initial ACK from the incoming buffer */
982 retval = gdb_get_char(connection, &initial_ack);
983 if (retval != ERROR_OK)
986 /* FIX!!!??? would we actually ever receive a + here???
989 if (initial_ack != '+')
990 gdb_putback_char(connection, initial_ack);
991 target_call_event_callbacks(target, TARGET_EVENT_GDB_ATTACH);
993 if (gdb_use_memory_map) {
994 /* Connect must fail if the memory map can't be set up correctly.
996 * This will cause an auto_probe to be invoked, which is either
997 * a no-op or it will fail when the target isn't ready(e.g. not halted).
999 for (unsigned int i = 0; i < flash_get_bank_count(); i++) {
1000 struct flash_bank *p;
1001 p = get_flash_bank_by_num_noprobe(i);
1002 if (p->target != target)
1004 retval = get_flash_bank_by_num(i, &p);
1005 if (retval != ERROR_OK) {
1006 LOG_ERROR("Connect failed. Consider setting up a gdb-attach event for the target "
1007 "to prepare target for GDB connect, or use 'gdb_memory_map disable'.");
1013 gdb_actual_connections++;
1014 log_printf_lf(all_targets->next != NULL ? LOG_LVL_INFO : LOG_LVL_DEBUG,
1015 __FILE__, __LINE__, __func__,
1016 "New GDB Connection: %d, Target %s, state: %s",
1017 gdb_actual_connections,
1018 target_name(target),
1019 target_state_name(target));
1021 if (!target_was_examined(target)) {
1022 LOG_ERROR("Target %s not examined yet, refuse gdb connection %d!",
1023 target_name(target), gdb_actual_connections);
1024 gdb_actual_connections--;
1025 return ERROR_TARGET_NOT_EXAMINED;
1028 if (target->state == TARGET_HALTED)
1029 LOG_WARNING("GDB connection %d on target %s not halted",
1030 gdb_actual_connections, target_name(target));
1032 /* DANGER! If we fail subsequently, we must remove this handler,
1033 * otherwise we occasionally see crashes as the timer can invoke the
1036 * register callback to be informed about target events */
1037 target_register_event_callback(gdb_target_callback_event_handler, connection);
1042 static int gdb_connection_closed(struct connection *connection)
1044 struct target *target;
1045 struct gdb_connection *gdb_connection = connection->priv;
1047 target = get_target_from_connection(connection);
1049 /* we're done forwarding messages. Tear down callback before
1050 * cleaning up connection.
1052 log_remove_callback(gdb_log_callback, connection);
1054 gdb_actual_connections--;
1055 LOG_DEBUG("GDB Close, Target: %s, state: %s, gdb_actual_connections=%d",
1056 target_name(target),
1057 target_state_name(target),
1058 gdb_actual_connections);
1060 /* see if an image built with vFlash commands is left */
1061 if (gdb_connection->vflash_image) {
1062 image_close(gdb_connection->vflash_image);
1063 free(gdb_connection->vflash_image);
1064 gdb_connection->vflash_image = NULL;
1067 /* if this connection registered a debug-message receiver delete it */
1068 delete_debug_msg_receiver(connection->cmd_ctx, target);
1070 if (connection->priv) {
1071 free(connection->priv);
1072 connection->priv = NULL;
1074 LOG_ERROR("BUG: connection->priv == NULL");
1076 target_unregister_event_callback(gdb_target_callback_event_handler, connection);
1078 target_call_event_callbacks(target, TARGET_EVENT_GDB_END);
1080 target_call_event_callbacks(target, TARGET_EVENT_GDB_DETACH);
1085 static void gdb_send_error(struct connection *connection, uint8_t the_error)
1088 snprintf(err, 4, "E%2.2X", the_error);
1089 gdb_put_packet(connection, err, 3);
1092 static int gdb_last_signal_packet(struct connection *connection,
1093 char const *packet, int packet_size)
1095 struct target *target = get_target_from_connection(connection);
1096 struct gdb_connection *gdb_con = connection->priv;
1100 if (!gdb_con->attached) {
1101 /* if we are here we have received a kill packet
1102 * reply W stop reply otherwise gdb gets very unhappy */
1103 gdb_put_packet(connection, "W00", 3);
1107 signal_var = gdb_last_signal(target);
1109 snprintf(sig_reply, 4, "S%2.2x", signal_var);
1110 gdb_put_packet(connection, sig_reply, 3);
1115 static inline int gdb_reg_pos(struct target *target, int pos, int len)
1117 if (target->endianness == TARGET_LITTLE_ENDIAN)
1120 return len - 1 - pos;
1123 /* Convert register to string of bytes. NB! The # of bits in the
1124 * register might be non-divisible by 8(a byte), in which
1125 * case an entire byte is shown.
1127 * NB! the format on the wire is the target endianness
1129 * The format of reg->value is little endian
1132 static void gdb_str_to_target(struct target *target,
1133 char *tstr, struct reg *reg)
1140 buf_len = DIV_ROUND_UP(reg->size, 8);
1142 for (i = 0; i < buf_len; i++) {
1143 int j = gdb_reg_pos(target, i, buf_len);
1144 tstr += sprintf(tstr, "%02x", buf[j]);
1148 /* copy over in register buffer */
1149 static void gdb_target_to_reg(struct target *target,
1150 char const *tstr, int str_len, uint8_t *bin)
1153 LOG_ERROR("BUG: gdb value with uneven number of characters encountered");
1158 for (i = 0; i < str_len; i += 2) {
1160 if (sscanf(tstr + i, "%02x", &t) != 1) {
1161 LOG_ERROR("BUG: unable to convert register value");
1165 int j = gdb_reg_pos(target, i/2, str_len/2);
1170 static int gdb_get_registers_packet(struct connection *connection,
1171 char const *packet, int packet_size)
1173 struct target *target = get_target_from_connection(connection);
1174 struct reg **reg_list;
1177 int reg_packet_size = 0;
1182 #ifdef _DEBUG_GDB_IO_
1186 if ((target->rtos != NULL) && (ERROR_OK == rtos_get_gdb_reg_list(connection)))
1189 retval = target_get_gdb_reg_list(target, ®_list, ®_list_size,
1191 if (retval != ERROR_OK)
1192 return gdb_error(connection, retval);
1194 for (i = 0; i < reg_list_size; i++) {
1195 if (reg_list[i] == NULL || reg_list[i]->exist == false)
1197 reg_packet_size += DIV_ROUND_UP(reg_list[i]->size, 8) * 2;
1200 assert(reg_packet_size > 0);
1202 reg_packet = malloc(reg_packet_size + 1); /* plus one for string termination null */
1203 if (reg_packet == NULL)
1206 reg_packet_p = reg_packet;
1208 for (i = 0; i < reg_list_size; i++) {
1209 if (reg_list[i] == NULL || reg_list[i]->exist == false)
1211 if (!reg_list[i]->valid) {
1212 retval = reg_list[i]->type->get(reg_list[i]);
1213 if (retval != ERROR_OK && gdb_report_register_access_error) {
1214 LOG_DEBUG("Couldn't get register %s.", reg_list[i]->name);
1217 return gdb_error(connection, retval);
1220 gdb_str_to_target(target, reg_packet_p, reg_list[i]);
1221 reg_packet_p += DIV_ROUND_UP(reg_list[i]->size, 8) * 2;
1224 #ifdef _DEBUG_GDB_IO_
1226 char *reg_packet_p_debug;
1227 reg_packet_p_debug = strndup(reg_packet, reg_packet_size);
1228 LOG_DEBUG("reg_packet: %s", reg_packet_p_debug);
1229 free(reg_packet_p_debug);
1233 gdb_put_packet(connection, reg_packet, reg_packet_size);
1241 static int gdb_set_registers_packet(struct connection *connection,
1242 char const *packet, int packet_size)
1244 struct target *target = get_target_from_connection(connection);
1246 struct reg **reg_list;
1249 char const *packet_p;
1251 #ifdef _DEBUG_GDB_IO_
1255 /* skip command character */
1259 if (packet_size % 2) {
1260 LOG_WARNING("GDB set_registers packet with uneven characters received, dropping connection");
1261 return ERROR_SERVER_REMOTE_CLOSED;
1264 retval = target_get_gdb_reg_list(target, ®_list, ®_list_size,
1266 if (retval != ERROR_OK)
1267 return gdb_error(connection, retval);
1270 for (i = 0; i < reg_list_size; i++) {
1272 int chars = (DIV_ROUND_UP(reg_list[i]->size, 8) * 2);
1274 if (packet_p + chars > packet + packet_size)
1275 LOG_ERROR("BUG: register packet is too small for registers");
1277 bin_buf = malloc(DIV_ROUND_UP(reg_list[i]->size, 8));
1278 gdb_target_to_reg(target, packet_p, chars, bin_buf);
1280 retval = reg_list[i]->type->set(reg_list[i], bin_buf);
1281 if (retval != ERROR_OK && gdb_report_register_access_error) {
1282 LOG_DEBUG("Couldn't set register %s.", reg_list[i]->name);
1285 return gdb_error(connection, retval);
1288 /* advance packet pointer */
1294 /* free struct reg *reg_list[] array allocated by get_gdb_reg_list */
1297 gdb_put_packet(connection, "OK", 2);
1302 static int gdb_get_register_packet(struct connection *connection,
1303 char const *packet, int packet_size)
1305 struct target *target = get_target_from_connection(connection);
1307 int reg_num = strtoul(packet + 1, NULL, 16);
1308 struct reg **reg_list;
1312 #ifdef _DEBUG_GDB_IO_
1316 if ((target->rtos != NULL) && (ERROR_OK == rtos_get_gdb_reg(connection, reg_num)))
1319 retval = target_get_gdb_reg_list_noread(target, ®_list, ®_list_size,
1321 if (retval != ERROR_OK)
1322 return gdb_error(connection, retval);
1324 if (reg_list_size <= reg_num) {
1325 LOG_ERROR("gdb requested a non-existing register");
1326 return ERROR_SERVER_REMOTE_CLOSED;
1329 if (!reg_list[reg_num]->valid) {
1330 retval = reg_list[reg_num]->type->get(reg_list[reg_num]);
1331 if (retval != ERROR_OK && gdb_report_register_access_error) {
1332 LOG_DEBUG("Couldn't get register %s.", reg_list[reg_num]->name);
1334 return gdb_error(connection, retval);
1338 reg_packet = malloc(DIV_ROUND_UP(reg_list[reg_num]->size, 8) * 2 + 1); /* plus one for string termination null */
1340 gdb_str_to_target(target, reg_packet, reg_list[reg_num]);
1342 gdb_put_packet(connection, reg_packet, DIV_ROUND_UP(reg_list[reg_num]->size, 8) * 2);
1350 static int gdb_set_register_packet(struct connection *connection,
1351 char const *packet, int packet_size)
1353 struct target *target = get_target_from_connection(connection);
1355 int reg_num = strtoul(packet + 1, &separator, 16);
1356 struct reg **reg_list;
1360 #ifdef _DEBUG_GDB_IO_
1364 if (*separator != '=') {
1365 LOG_ERROR("GDB 'set register packet', but no '=' following the register number");
1366 return ERROR_SERVER_REMOTE_CLOSED;
1368 size_t chars = strlen(separator + 1);
1369 uint8_t *bin_buf = malloc(chars / 2);
1370 gdb_target_to_reg(target, separator + 1, chars, bin_buf);
1372 if ((target->rtos != NULL) &&
1373 (ERROR_OK == rtos_set_reg(connection, reg_num, bin_buf))) {
1375 gdb_put_packet(connection, "OK", 2);
1379 retval = target_get_gdb_reg_list_noread(target, ®_list, ®_list_size,
1381 if (retval != ERROR_OK) {
1383 return gdb_error(connection, retval);
1386 if (reg_list_size <= reg_num) {
1387 LOG_ERROR("gdb requested a non-existing register");
1390 return ERROR_SERVER_REMOTE_CLOSED;
1393 if (chars != (DIV_ROUND_UP(reg_list[reg_num]->size, 8) * 2)) {
1394 LOG_ERROR("gdb sent %d bits for a %d-bit register (%s)",
1395 (int) chars * 4, reg_list[reg_num]->size, reg_list[reg_num]->name);
1398 return ERROR_SERVER_REMOTE_CLOSED;
1401 gdb_target_to_reg(target, separator + 1, chars, bin_buf);
1403 retval = reg_list[reg_num]->type->set(reg_list[reg_num], bin_buf);
1404 if (retval != ERROR_OK && gdb_report_register_access_error) {
1405 LOG_DEBUG("Couldn't set register %s.", reg_list[reg_num]->name);
1408 return gdb_error(connection, retval);
1411 gdb_put_packet(connection, "OK", 2);
1419 /* No attempt is made to translate the "retval" to
1420 * GDB speak. This has to be done at the calling
1421 * site as no mapping really exists.
1423 static int gdb_error(struct connection *connection, int retval)
1425 LOG_DEBUG("Reporting %i to GDB as generic error", retval);
1426 gdb_send_error(connection, EFAULT);
1430 /* We don't have to worry about the default 2 second timeout for GDB packets,
1431 * because GDB breaks up large memory reads into smaller reads.
1433 static int gdb_read_memory_packet(struct connection *connection,
1434 char const *packet, int packet_size)
1436 struct target *target = get_target_from_connection(connection);
1444 int retval = ERROR_OK;
1446 /* skip command character */
1449 addr = strtoull(packet, &separator, 16);
1451 if (*separator != ',') {
1452 LOG_ERROR("incomplete read memory packet received, dropping connection");
1453 return ERROR_SERVER_REMOTE_CLOSED;
1456 len = strtoul(separator + 1, NULL, 16);
1459 LOG_WARNING("invalid read memory packet received (len == 0)");
1460 gdb_put_packet(connection, "", 0);
1464 buffer = malloc(len);
1466 LOG_DEBUG("addr: 0x%16.16" PRIx64 ", len: 0x%8.8" PRIx32 "", addr, len);
1468 retval = target_read_buffer(target, addr, len, buffer);
1470 if ((retval != ERROR_OK) && !gdb_report_data_abort) {
1471 /* TODO : Here we have to lie and send back all zero's lest stack traces won't work.
1472 * At some point this might be fixed in GDB, in which case this code can be removed.
1474 * OpenOCD developers are acutely aware of this problem, but there is nothing
1475 * gained by involving the user in this problem that hopefully will get resolved
1478 * http://sourceware.org/cgi-bin/gnatsweb.pl? \
1479 * cmd = view%20audit-trail&database = gdb&pr = 2395
1481 * For now, the default is to fix up things to make current GDB versions work.
1482 * This can be overwritten using the gdb_report_data_abort <'enable'|'disable'> command.
1484 memset(buffer, 0, len);
1488 if (retval == ERROR_OK) {
1489 hex_buffer = malloc(len * 2 + 1);
1491 size_t pkt_len = hexify(hex_buffer, buffer, len, len * 2 + 1);
1493 gdb_put_packet(connection, hex_buffer, pkt_len);
1497 retval = gdb_error(connection, retval);
1504 static int gdb_write_memory_packet(struct connection *connection,
1505 char const *packet, int packet_size)
1507 struct target *target = get_target_from_connection(connection);
1515 /* skip command character */
1518 addr = strtoull(packet, &separator, 16);
1520 if (*separator != ',') {
1521 LOG_ERROR("incomplete write memory packet received, dropping connection");
1522 return ERROR_SERVER_REMOTE_CLOSED;
1525 len = strtoul(separator + 1, &separator, 16);
1527 if (*(separator++) != ':') {
1528 LOG_ERROR("incomplete write memory packet received, dropping connection");
1529 return ERROR_SERVER_REMOTE_CLOSED;
1532 buffer = malloc(len);
1534 LOG_DEBUG("addr: 0x%" PRIx64 ", len: 0x%8.8" PRIx32 "", addr, len);
1536 if (unhexify(buffer, separator, len) != len)
1537 LOG_ERROR("unable to decode memory packet");
1539 retval = target_write_buffer(target, addr, len, buffer);
1541 if (retval == ERROR_OK)
1542 gdb_put_packet(connection, "OK", 2);
1544 retval = gdb_error(connection, retval);
1551 static int gdb_write_memory_binary_packet(struct connection *connection,
1552 char const *packet, int packet_size)
1554 struct target *target = get_target_from_connection(connection);
1559 int retval = ERROR_OK;
1560 /* Packets larger than fast_limit bytes will be acknowledged instantly on
1561 * the assumption that we're in a download and it's important to go as fast
1563 uint32_t fast_limit = 8;
1565 /* skip command character */
1568 addr = strtoull(packet, &separator, 16);
1570 if (*separator != ',') {
1571 LOG_ERROR("incomplete write memory binary packet received, dropping connection");
1572 return ERROR_SERVER_REMOTE_CLOSED;
1575 len = strtoul(separator + 1, &separator, 16);
1577 if (*(separator++) != ':') {
1578 LOG_ERROR("incomplete write memory binary packet received, dropping connection");
1579 return ERROR_SERVER_REMOTE_CLOSED;
1582 struct gdb_connection *gdb_connection = connection->priv;
1584 if (gdb_connection->mem_write_error)
1585 retval = ERROR_FAIL;
1587 if (retval == ERROR_OK) {
1588 if (len >= fast_limit) {
1589 /* By replying the packet *immediately* GDB will send us a new packet
1590 * while we write the last one to the target.
1591 * We only do this for larger writes, so that users who do something like:
1592 * p *((int*)0xdeadbeef)=8675309
1593 * will get immediate feedback that that write failed.
1595 gdb_put_packet(connection, "OK", 2);
1598 retval = gdb_error(connection, retval);
1599 /* now that we have reported the memory write error, we can clear the condition */
1600 gdb_connection->mem_write_error = false;
1601 if (retval != ERROR_OK)
1606 LOG_DEBUG("addr: 0x%" PRIx64 ", len: 0x%8.8" PRIx32 "", addr, len);
1608 retval = target_write_buffer(target, addr, len, (uint8_t *)separator);
1609 if (retval != ERROR_OK)
1610 gdb_connection->mem_write_error = true;
1613 if (len < fast_limit) {
1614 if (retval != ERROR_OK) {
1615 gdb_error(connection, retval);
1616 gdb_connection->mem_write_error = false;
1618 gdb_put_packet(connection, "OK", 2);
1625 static int gdb_step_continue_packet(struct connection *connection,
1626 char const *packet, int packet_size)
1628 struct target *target = get_target_from_connection(connection);
1630 uint64_t address = 0x0;
1631 int retval = ERROR_OK;
1635 if (packet_size > 1)
1636 address = strtoull(packet + 1, NULL, 16);
1640 gdb_running_type = packet[0];
1641 if (packet[0] == 'c') {
1642 LOG_DEBUG("continue");
1643 /* resume at current address, don't handle breakpoints, not debugging */
1644 retval = target_resume(target, current, address, 0, 0);
1645 } else if (packet[0] == 's') {
1647 /* step at current or address, don't handle breakpoints */
1648 retval = target_step(target, current, address, 0);
1653 static int gdb_breakpoint_watchpoint_packet(struct connection *connection,
1654 char const *packet, int packet_size)
1656 struct target *target = get_target_from_connection(connection);
1658 enum breakpoint_type bp_type = BKPT_SOFT /* dummy init to avoid warning */;
1659 enum watchpoint_rw wp_type = WPT_READ /* dummy init to avoid warning */;
1665 LOG_DEBUG("[%s]", target_name(target));
1667 type = strtoul(packet + 1, &separator, 16);
1669 if (type == 0) /* memory breakpoint */
1670 bp_type = BKPT_SOFT;
1671 else if (type == 1) /* hardware breakpoint */
1672 bp_type = BKPT_HARD;
1673 else if (type == 2) /* write watchpoint */
1674 wp_type = WPT_WRITE;
1675 else if (type == 3) /* read watchpoint */
1677 else if (type == 4) /* access watchpoint */
1678 wp_type = WPT_ACCESS;
1680 LOG_ERROR("invalid gdb watch/breakpoint type(%d), dropping connection", type);
1681 return ERROR_SERVER_REMOTE_CLOSED;
1684 if (gdb_breakpoint_override && ((bp_type == BKPT_SOFT) || (bp_type == BKPT_HARD)))
1685 bp_type = gdb_breakpoint_override_type;
1687 if (*separator != ',') {
1688 LOG_ERROR("incomplete breakpoint/watchpoint packet received, dropping connection");
1689 return ERROR_SERVER_REMOTE_CLOSED;
1692 address = strtoull(separator + 1, &separator, 16);
1694 if (*separator != ',') {
1695 LOG_ERROR("incomplete breakpoint/watchpoint packet received, dropping connection");
1696 return ERROR_SERVER_REMOTE_CLOSED;
1699 size = strtoul(separator + 1, &separator, 16);
1704 if (packet[0] == 'Z') {
1705 retval = breakpoint_add(target, address, size, bp_type);
1706 if (retval != ERROR_OK) {
1707 retval = gdb_error(connection, retval);
1708 if (retval != ERROR_OK)
1711 gdb_put_packet(connection, "OK", 2);
1713 breakpoint_remove(target, address);
1714 gdb_put_packet(connection, "OK", 2);
1721 if (packet[0] == 'Z') {
1722 retval = watchpoint_add(target, address, size, wp_type, 0, 0xffffffffu);
1723 if (retval != ERROR_OK) {
1724 retval = gdb_error(connection, retval);
1725 if (retval != ERROR_OK)
1728 gdb_put_packet(connection, "OK", 2);
1730 watchpoint_remove(target, address);
1731 gdb_put_packet(connection, "OK", 2);
1742 /* print out a string and allocate more space as needed,
1743 * mainly used for XML at this point
1745 static __attribute__ ((format (PRINTF_ATTRIBUTE_FORMAT, 5, 6))) void xml_printf(int *retval,
1746 char **xml, int *pos, int *size, const char *fmt, ...)
1748 if (*retval != ERROR_OK)
1753 if ((*xml == NULL) || (!first)) {
1754 /* start by 0 to exercise all the code paths.
1755 * Need minimum 2 bytes to fit 1 char and 0 terminator. */
1757 *size = *size * 2 + 2;
1759 *xml = realloc(*xml, *size);
1763 *retval = ERROR_SERVER_REMOTE_CLOSED;
1771 ret = vsnprintf(*xml + *pos, *size - *pos, fmt, ap);
1773 if ((ret > 0) && ((ret + 1) < *size - *pos)) {
1777 /* there was just enough or not enough space, allocate more. */
1782 static int decode_xfer_read(char const *buf, char **annex, int *ofs, unsigned int *len)
1784 /* Locate the annex. */
1785 const char *annex_end = strchr(buf, ':');
1786 if (annex_end == NULL)
1789 /* After the read marker and annex, qXfer looks like a
1790 * traditional 'm' packet. */
1792 *ofs = strtoul(annex_end + 1, &separator, 16);
1794 if (*separator != ',')
1797 *len = strtoul(separator + 1, NULL, 16);
1799 /* Extract the annex if needed */
1800 if (annex != NULL) {
1801 *annex = strndup(buf, annex_end - buf);
1809 static int compare_bank(const void *a, const void *b)
1811 struct flash_bank *b1, *b2;
1812 b1 = *((struct flash_bank **)a);
1813 b2 = *((struct flash_bank **)b);
1815 if (b1->base == b2->base)
1817 else if (b1->base > b2->base)
1823 static int gdb_memory_map(struct connection *connection,
1824 char const *packet, int packet_size)
1826 /* We get away with only specifying flash here. Regions that are not
1827 * specified are treated as if we provided no memory map(if not we
1828 * could detect the holes and mark them as RAM).
1829 * Normally we only execute this code once, but no big deal if we
1830 * have to regenerate it a couple of times.
1833 struct target *target = get_target_from_connection(connection);
1834 struct flash_bank *p;
1838 int retval = ERROR_OK;
1839 struct flash_bank **banks;
1843 target_addr_t ram_start = 0;
1844 unsigned int target_flash_banks = 0;
1846 /* skip command character */
1849 offset = strtoul(packet, &separator, 16);
1850 length = strtoul(separator + 1, &separator, 16);
1852 xml_printf(&retval, &xml, &pos, &size, "<memory-map>\n");
1854 /* Sort banks in ascending order. We need to report non-flash
1855 * memory as ram (or rather read/write) by default for GDB, since
1856 * it has no concept of non-cacheable read/write memory (i/o etc).
1858 banks = malloc(sizeof(struct flash_bank *)*flash_get_bank_count());
1860 for (unsigned int i = 0; i < flash_get_bank_count(); i++) {
1861 p = get_flash_bank_by_num_noprobe(i);
1862 if (p->target != target)
1864 retval = get_flash_bank_by_num(i, &p);
1865 if (retval != ERROR_OK) {
1867 gdb_error(connection, retval);
1870 banks[target_flash_banks++] = p;
1873 qsort(banks, target_flash_banks, sizeof(struct flash_bank *),
1876 for (unsigned int i = 0; i < target_flash_banks; i++) {
1877 unsigned sector_size = 0;
1878 unsigned group_len = 0;
1882 if (ram_start < p->base)
1883 xml_printf(&retval, &xml, &pos, &size,
1884 "<memory type=\"ram\" start=\"" TARGET_ADDR_FMT "\" "
1885 "length=\"" TARGET_ADDR_FMT "\"/>\n",
1886 ram_start, p->base - ram_start);
1888 /* Report adjacent groups of same-size sectors. So for
1889 * example top boot CFI flash will list an initial region
1890 * with several large sectors (maybe 128KB) and several
1891 * smaller ones at the end (maybe 32KB). STR7 will have
1892 * regions with 8KB, 32KB, and 64KB sectors; etc.
1894 for (unsigned int j = 0; j < p->num_sectors; j++) {
1896 /* Maybe start a new group of sectors. */
1897 if (sector_size == 0) {
1898 if (p->sectors[j].offset + p->sectors[j].size > p->size) {
1899 LOG_WARNING("The flash sector at offset 0x%08" PRIx32
1900 " overflows the end of %s bank.",
1901 p->sectors[j].offset, p->name);
1902 LOG_WARNING("The rest of bank will not show in gdb memory map.");
1905 target_addr_t start;
1906 start = p->base + p->sectors[j].offset;
1907 xml_printf(&retval, &xml, &pos, &size,
1908 "<memory type=\"flash\" "
1909 "start=\"" TARGET_ADDR_FMT "\" ",
1911 sector_size = p->sectors[j].size;
1912 group_len = sector_size;
1914 group_len += sector_size; /* equal to p->sectors[j].size */
1917 /* Does this finish a group of sectors?
1918 * If not, continue an already-started group.
1920 if (j < p->num_sectors - 1
1921 && p->sectors[j + 1].size == sector_size
1922 && p->sectors[j + 1].offset == p->sectors[j].offset + sector_size
1923 && p->sectors[j + 1].offset + p->sectors[j + 1].size <= p->size)
1926 xml_printf(&retval, &xml, &pos, &size,
1927 "length=\"0x%x\">\n"
1928 "<property name=\"blocksize\">"
1936 ram_start = p->base + p->size;
1940 xml_printf(&retval, &xml, &pos, &size,
1941 "<memory type=\"ram\" start=\"" TARGET_ADDR_FMT "\" "
1942 "length=\"" TARGET_ADDR_FMT "\"/>\n",
1943 ram_start, target_address_max(target) - ram_start + 1);
1944 /* ELSE a flash chip could be at the very end of the address space, in
1945 * which case ram_start will be precisely 0 */
1949 xml_printf(&retval, &xml, &pos, &size, "</memory-map>\n");
1951 if (retval != ERROR_OK) {
1953 gdb_error(connection, retval);
1957 if (offset + length > pos)
1958 length = pos - offset;
1960 char *t = malloc(length + 1);
1962 memcpy(t + 1, xml + offset, length);
1963 gdb_put_packet(connection, t, length + 1);
1970 static const char *gdb_get_reg_type_name(enum reg_type type)
1979 case REG_TYPE_INT16:
1981 case REG_TYPE_INT32:
1983 case REG_TYPE_INT64:
1985 case REG_TYPE_INT128:
1989 case REG_TYPE_UINT8:
1991 case REG_TYPE_UINT16:
1993 case REG_TYPE_UINT32:
1995 case REG_TYPE_UINT64:
1997 case REG_TYPE_UINT128:
1999 case REG_TYPE_CODE_PTR:
2001 case REG_TYPE_DATA_PTR:
2003 case REG_TYPE_FLOAT:
2005 case REG_TYPE_IEEE_SINGLE:
2006 return "ieee_single";
2007 case REG_TYPE_IEEE_DOUBLE:
2008 return "ieee_double";
2009 case REG_TYPE_ARCH_DEFINED:
2010 return "int"; /* return arbitrary string to avoid compile warning. */
2013 return "int"; /* "int" as default value */
2016 static int lookup_add_arch_defined_types(char const **arch_defined_types_list[], const char *type_id,
2017 int *num_arch_defined_types)
2019 int tbl_sz = *num_arch_defined_types;
2021 if (type_id != NULL && (strcmp(type_id, ""))) {
2022 for (int j = 0; j < (tbl_sz + 1); j++) {
2023 if (!((*arch_defined_types_list)[j])) {
2024 (*arch_defined_types_list)[tbl_sz++] = type_id;
2025 *arch_defined_types_list = realloc(*arch_defined_types_list,
2026 sizeof(char *) * (tbl_sz + 1));
2027 (*arch_defined_types_list)[tbl_sz] = NULL;
2028 *num_arch_defined_types = tbl_sz;
2031 if (!strcmp((*arch_defined_types_list)[j], type_id))
2040 static int gdb_generate_reg_type_description(struct target *target,
2041 char **tdesc, int *pos, int *size, struct reg_data_type *type,
2042 char const **arch_defined_types_list[], int *num_arch_defined_types)
2044 int retval = ERROR_OK;
2046 if (type->type_class == REG_TYPE_CLASS_VECTOR) {
2047 struct reg_data_type *data_type = type->reg_type_vector->type;
2048 if (data_type->type == REG_TYPE_ARCH_DEFINED) {
2049 if (lookup_add_arch_defined_types(arch_defined_types_list, data_type->id,
2050 num_arch_defined_types))
2051 gdb_generate_reg_type_description(target, tdesc, pos, size, data_type,
2052 arch_defined_types_list,
2053 num_arch_defined_types);
2055 /* <vector id="id" type="type" count="count"/> */
2056 xml_printf(&retval, tdesc, pos, size,
2057 "<vector id=\"%s\" type=\"%s\" count=\"%d\"/>\n",
2058 type->id, type->reg_type_vector->type->id,
2059 type->reg_type_vector->count);
2061 } else if (type->type_class == REG_TYPE_CLASS_UNION) {
2062 struct reg_data_type_union_field *field;
2063 field = type->reg_type_union->fields;
2064 while (field != NULL) {
2065 struct reg_data_type *data_type = field->type;
2066 if (data_type->type == REG_TYPE_ARCH_DEFINED) {
2067 if (lookup_add_arch_defined_types(arch_defined_types_list, data_type->id,
2068 num_arch_defined_types))
2069 gdb_generate_reg_type_description(target, tdesc, pos, size, data_type,
2070 arch_defined_types_list,
2071 num_arch_defined_types);
2074 field = field->next;
2077 * <field name="name" type="type"/> ...
2079 xml_printf(&retval, tdesc, pos, size,
2080 "<union id=\"%s\">\n",
2083 field = type->reg_type_union->fields;
2084 while (field != NULL) {
2085 xml_printf(&retval, tdesc, pos, size,
2086 "<field name=\"%s\" type=\"%s\"/>\n",
2087 field->name, field->type->id);
2089 field = field->next;
2092 xml_printf(&retval, tdesc, pos, size,
2095 } else if (type->type_class == REG_TYPE_CLASS_STRUCT) {
2096 struct reg_data_type_struct_field *field;
2097 field = type->reg_type_struct->fields;
2099 if (field->use_bitfields) {
2100 /* <struct id="id" size="size">
2101 * <field name="name" start="start" end="end"/> ...
2103 xml_printf(&retval, tdesc, pos, size,
2104 "<struct id=\"%s\" size=\"%d\">\n",
2105 type->id, type->reg_type_struct->size);
2106 while (field != NULL) {
2107 xml_printf(&retval, tdesc, pos, size,
2108 "<field name=\"%s\" start=\"%d\" end=\"%d\" type=\"%s\" />\n",
2109 field->name, field->bitfield->start, field->bitfield->end,
2110 gdb_get_reg_type_name(field->bitfield->type));
2112 field = field->next;
2115 while (field != NULL) {
2116 struct reg_data_type *data_type = field->type;
2117 if (data_type->type == REG_TYPE_ARCH_DEFINED) {
2118 if (lookup_add_arch_defined_types(arch_defined_types_list, data_type->id,
2119 num_arch_defined_types))
2120 gdb_generate_reg_type_description(target, tdesc, pos, size, data_type,
2121 arch_defined_types_list,
2122 num_arch_defined_types);
2127 * <field name="name" type="type"/> ...
2129 xml_printf(&retval, tdesc, pos, size,
2130 "<struct id=\"%s\">\n",
2132 while (field != NULL) {
2133 xml_printf(&retval, tdesc, pos, size,
2134 "<field name=\"%s\" type=\"%s\"/>\n",
2135 field->name, field->type->id);
2137 field = field->next;
2141 xml_printf(&retval, tdesc, pos, size,
2144 } else if (type->type_class == REG_TYPE_CLASS_FLAGS) {
2145 /* <flags id="id" size="size">
2146 * <field name="name" start="start" end="end"/> ...
2148 xml_printf(&retval, tdesc, pos, size,
2149 "<flags id=\"%s\" size=\"%d\">\n",
2150 type->id, type->reg_type_flags->size);
2152 struct reg_data_type_flags_field *field;
2153 field = type->reg_type_flags->fields;
2154 while (field != NULL) {
2155 xml_printf(&retval, tdesc, pos, size,
2156 "<field name=\"%s\" start=\"%d\" end=\"%d\" type=\"%s\" />\n",
2157 field->name, field->bitfield->start, field->bitfield->end,
2158 gdb_get_reg_type_name(field->bitfield->type));
2160 field = field->next;
2163 xml_printf(&retval, tdesc, pos, size,
2171 /* Get a list of available target registers features. feature_list must
2172 * be freed by caller.
2174 static int get_reg_features_list(struct target *target, char const **feature_list[], int *feature_list_size,
2175 struct reg **reg_list, int reg_list_size)
2179 /* Start with only one element */
2180 *feature_list = calloc(1, sizeof(char *));
2182 for (int i = 0; i < reg_list_size; i++) {
2183 if (reg_list[i]->exist == false)
2186 if (reg_list[i]->feature != NULL
2187 && reg_list[i]->feature->name != NULL
2188 && (strcmp(reg_list[i]->feature->name, ""))) {
2189 /* We found a feature, check if the feature is already in the
2190 * table. If not, allocate a new entry for the table and
2191 * put the new feature in it.
2193 for (int j = 0; j < (tbl_sz + 1); j++) {
2194 if (!((*feature_list)[j])) {
2195 (*feature_list)[tbl_sz++] = reg_list[i]->feature->name;
2196 *feature_list = realloc(*feature_list, sizeof(char *) * (tbl_sz + 1));
2197 (*feature_list)[tbl_sz] = NULL;
2200 if (!strcmp((*feature_list)[j], reg_list[i]->feature->name))
2207 if (feature_list_size)
2208 *feature_list_size = tbl_sz;
2213 static int gdb_generate_target_description(struct target *target, char **tdesc_out)
2215 int retval = ERROR_OK;
2216 struct reg **reg_list = NULL;
2218 char const *architecture;
2219 char const **features = NULL;
2220 int feature_list_size = 0;
2226 retval = target_get_gdb_reg_list_noread(target, ®_list,
2227 ®_list_size, REG_CLASS_ALL);
2229 if (retval != ERROR_OK) {
2230 LOG_ERROR("get register list failed");
2231 retval = ERROR_FAIL;
2235 if (reg_list_size <= 0) {
2236 LOG_ERROR("get register list failed");
2237 retval = ERROR_FAIL;
2241 /* Get a list of available target registers features */
2242 retval = get_reg_features_list(target, &features, &feature_list_size, reg_list, reg_list_size);
2243 if (retval != ERROR_OK) {
2244 LOG_ERROR("Can't get the registers feature list");
2245 retval = ERROR_FAIL;
2249 /* If we found some features associated with registers, create sections */
2250 int current_feature = 0;
2252 xml_printf(&retval, &tdesc, &pos, &size,
2253 "<?xml version=\"1.0\"?>\n"
2254 "<!DOCTYPE target SYSTEM \"gdb-target.dtd\">\n"
2255 "<target version=\"1.0\">\n");
2257 /* generate architecture element if supported by target */
2258 architecture = target_get_gdb_arch(target);
2259 if (architecture != NULL)
2260 xml_printf(&retval, &tdesc, &pos, &size,
2261 "<architecture>%s</architecture>\n", architecture);
2263 /* generate target description according to register list */
2264 if (features != NULL) {
2265 while (features[current_feature]) {
2266 char const **arch_defined_types = NULL;
2267 int num_arch_defined_types = 0;
2269 arch_defined_types = calloc(1, sizeof(char *));
2270 xml_printf(&retval, &tdesc, &pos, &size,
2271 "<feature name=\"%s\">\n",
2272 features[current_feature]);
2275 for (i = 0; i < reg_list_size; i++) {
2277 if (reg_list[i]->exist == false)
2280 if (strcmp(reg_list[i]->feature->name, features[current_feature]))
2283 const char *type_str;
2284 if (reg_list[i]->reg_data_type != NULL) {
2285 if (reg_list[i]->reg_data_type->type == REG_TYPE_ARCH_DEFINED) {
2286 /* generate <type... first, if there are architecture-defined types. */
2287 if (lookup_add_arch_defined_types(&arch_defined_types,
2288 reg_list[i]->reg_data_type->id,
2289 &num_arch_defined_types))
2290 gdb_generate_reg_type_description(target, &tdesc, &pos, &size,
2291 reg_list[i]->reg_data_type,
2292 &arch_defined_types,
2293 &num_arch_defined_types);
2295 type_str = reg_list[i]->reg_data_type->id;
2297 /* predefined type */
2298 type_str = gdb_get_reg_type_name(
2299 reg_list[i]->reg_data_type->type);
2302 /* Default type is "int" */
2306 xml_printf(&retval, &tdesc, &pos, &size,
2307 "<reg name=\"%s\"", reg_list[i]->name);
2308 xml_printf(&retval, &tdesc, &pos, &size,
2309 " bitsize=\"%d\"", reg_list[i]->size);
2310 xml_printf(&retval, &tdesc, &pos, &size,
2311 " regnum=\"%d\"", reg_list[i]->number);
2312 if (reg_list[i]->caller_save)
2313 xml_printf(&retval, &tdesc, &pos, &size,
2314 " save-restore=\"yes\"");
2316 xml_printf(&retval, &tdesc, &pos, &size,
2317 " save-restore=\"no\"");
2319 xml_printf(&retval, &tdesc, &pos, &size,
2320 " type=\"%s\"", type_str);
2322 if (reg_list[i]->group != NULL)
2323 xml_printf(&retval, &tdesc, &pos, &size,
2324 " group=\"%s\"", reg_list[i]->group);
2326 xml_printf(&retval, &tdesc, &pos, &size,
2330 xml_printf(&retval, &tdesc, &pos, &size,
2334 free(arch_defined_types);
2338 xml_printf(&retval, &tdesc, &pos, &size,
2345 if (retval == ERROR_OK)
2353 static int gdb_get_target_description_chunk(struct target *target, struct target_desc_format *target_desc,
2354 char **chunk, int32_t offset, uint32_t length)
2356 if (target_desc == NULL) {
2357 LOG_ERROR("Unable to Generate Target Description");
2361 char *tdesc = target_desc->tdesc;
2362 uint32_t tdesc_length = target_desc->tdesc_length;
2364 if (tdesc == NULL) {
2365 int retval = gdb_generate_target_description(target, &tdesc);
2366 if (retval != ERROR_OK) {
2367 LOG_ERROR("Unable to Generate Target Description");
2371 tdesc_length = strlen(tdesc);
2376 if (length < (tdesc_length - offset))
2377 transfer_type = 'm';
2379 transfer_type = 'l';
2381 *chunk = malloc(length + 2);
2382 if (*chunk == NULL) {
2383 LOG_ERROR("Unable to allocate memory");
2387 (*chunk)[0] = transfer_type;
2388 if (transfer_type == 'm') {
2389 strncpy((*chunk) + 1, tdesc + offset, length);
2390 (*chunk)[1 + length] = '\0';
2392 strncpy((*chunk) + 1, tdesc + offset, tdesc_length - offset);
2393 (*chunk)[1 + (tdesc_length - offset)] = '\0';
2395 /* After gdb-server sends out last chunk, invalidate tdesc. */
2401 target_desc->tdesc = tdesc;
2402 target_desc->tdesc_length = tdesc_length;
2407 static int gdb_target_description_supported(struct target *target, int *supported)
2409 int retval = ERROR_OK;
2410 struct reg **reg_list = NULL;
2411 int reg_list_size = 0;
2412 char const **features = NULL;
2413 int feature_list_size = 0;
2415 char const *architecture = target_get_gdb_arch(target);
2417 retval = target_get_gdb_reg_list_noread(target, ®_list,
2418 ®_list_size, REG_CLASS_ALL);
2419 if (retval != ERROR_OK) {
2420 LOG_ERROR("get register list failed");
2424 if (reg_list_size <= 0) {
2425 LOG_ERROR("get register list failed");
2426 retval = ERROR_FAIL;
2430 /* Get a list of available target registers features */
2431 retval = get_reg_features_list(target, &features, &feature_list_size, reg_list, reg_list_size);
2432 if (retval != ERROR_OK) {
2433 LOG_ERROR("Can't get the registers feature list");
2438 if (architecture || feature_list_size)
2452 static int gdb_generate_thread_list(struct target *target, char **thread_list_out)
2454 struct rtos *rtos = target->rtos;
2455 int retval = ERROR_OK;
2456 char *thread_list = NULL;
2460 xml_printf(&retval, &thread_list, &pos, &size,
2461 "<?xml version=\"1.0\"?>\n"
2465 for (int i = 0; i < rtos->thread_count; i++) {
2466 struct thread_detail *thread_detail = &rtos->thread_details[i];
2468 if (!thread_detail->exists)
2471 xml_printf(&retval, &thread_list, &pos, &size,
2472 "<thread id=\"%" PRIx64 "\">", thread_detail->threadid);
2474 if (thread_detail->thread_name_str != NULL)
2475 xml_printf(&retval, &thread_list, &pos, &size,
2476 "Name: %s", thread_detail->thread_name_str);
2478 if (thread_detail->extra_info_str != NULL) {
2479 if (thread_detail->thread_name_str != NULL)
2480 xml_printf(&retval, &thread_list, &pos, &size,
2482 xml_printf(&retval, &thread_list, &pos, &size,
2483 "%s", thread_detail->extra_info_str);
2486 xml_printf(&retval, &thread_list, &pos, &size,
2491 xml_printf(&retval, &thread_list, &pos, &size,
2494 if (retval == ERROR_OK)
2495 *thread_list_out = thread_list;
2502 static int gdb_get_thread_list_chunk(struct target *target, char **thread_list,
2503 char **chunk, int32_t offset, uint32_t length)
2505 if (*thread_list == NULL) {
2506 int retval = gdb_generate_thread_list(target, thread_list);
2507 if (retval != ERROR_OK) {
2508 LOG_ERROR("Unable to Generate Thread List");
2513 size_t thread_list_length = strlen(*thread_list);
2516 length = MIN(length, thread_list_length - offset);
2517 if (length < (thread_list_length - offset))
2518 transfer_type = 'm';
2520 transfer_type = 'l';
2522 *chunk = malloc(length + 2 + 3);
2523 /* Allocating extra 3 bytes prevents false positive valgrind report
2524 * of strlen(chunk) word access:
2525 * Invalid read of size 4
2526 * Address 0x4479934 is 44 bytes inside a block of size 45 alloc'd */
2527 if (*chunk == NULL) {
2528 LOG_ERROR("Unable to allocate memory");
2532 (*chunk)[0] = transfer_type;
2533 strncpy((*chunk) + 1, (*thread_list) + offset, length);
2534 (*chunk)[1 + length] = '\0';
2536 /* After gdb-server sends out last chunk, invalidate thread list. */
2537 if (transfer_type == 'l') {
2539 *thread_list = NULL;
2545 static int gdb_query_packet(struct connection *connection,
2546 char const *packet, int packet_size)
2548 struct command_context *cmd_ctx = connection->cmd_ctx;
2549 struct gdb_connection *gdb_connection = connection->priv;
2550 struct target *target = get_target_from_connection(connection);
2552 if (strncmp(packet, "qRcmd,", 6) == 0) {
2553 if (packet_size > 6) {
2555 cmd = malloc((packet_size - 6) / 2 + 1);
2556 size_t len = unhexify((uint8_t *)cmd, packet + 6, (packet_size - 6) / 2);
2559 /* We want to print all debug output to GDB connection */
2560 log_add_callback(gdb_log_callback, connection);
2561 target_call_timer_callbacks_now();
2562 /* some commands need to know the GDB connection, make note of current
2563 * GDB connection. */
2564 current_gdb_connection = gdb_connection;
2565 command_run_line(cmd_ctx, cmd);
2566 current_gdb_connection = NULL;
2567 target_call_timer_callbacks_now();
2568 log_remove_callback(gdb_log_callback, connection);
2571 gdb_put_packet(connection, "OK", 2);
2573 } else if (strncmp(packet, "qCRC:", 5) == 0) {
2574 if (packet_size > 5) {
2579 target_addr_t addr = 0;
2582 /* skip command character */
2585 addr = strtoull(packet, &separator, 16);
2587 if (*separator != ',') {
2588 LOG_ERROR("incomplete read memory packet received, dropping connection");
2589 return ERROR_SERVER_REMOTE_CLOSED;
2592 len = strtoul(separator + 1, NULL, 16);
2594 retval = target_checksum_memory(target, addr, len, &checksum);
2596 if (retval == ERROR_OK) {
2597 snprintf(gdb_reply, 10, "C%8.8" PRIx32 "", checksum);
2598 gdb_put_packet(connection, gdb_reply, 9);
2600 retval = gdb_error(connection, retval);
2601 if (retval != ERROR_OK)
2607 } else if (strncmp(packet, "qSupported", 10) == 0) {
2608 /* we currently support packet size and qXfer:memory-map:read (if enabled)
2609 * qXfer:features:read is supported for some targets */
2610 int retval = ERROR_OK;
2611 char *buffer = NULL;
2614 int gdb_target_desc_supported = 0;
2616 /* we need to test that the target supports target descriptions */
2617 retval = gdb_target_description_supported(target, &gdb_target_desc_supported);
2618 if (retval != ERROR_OK) {
2619 LOG_INFO("Failed detecting Target Description Support, disabling");
2620 gdb_target_desc_supported = 0;
2623 /* support may be disabled globally */
2624 if (gdb_use_target_description == 0) {
2625 if (gdb_target_desc_supported)
2626 LOG_WARNING("Target Descriptions Supported, but disabled");
2627 gdb_target_desc_supported = 0;
2634 "PacketSize=%x;qXfer:memory-map:read%c;qXfer:features:read%c;qXfer:threads:read+;QStartNoAckMode+;vContSupported+",
2636 ((gdb_use_memory_map == 1) && (flash_get_bank_count() > 0)) ? '+' : '-',
2637 (gdb_target_desc_supported == 1) ? '+' : '-');
2639 if (retval != ERROR_OK) {
2640 gdb_send_error(connection, 01);
2644 gdb_put_packet(connection, buffer, strlen(buffer));
2648 } else if ((strncmp(packet, "qXfer:memory-map:read::", 23) == 0)
2649 && (flash_get_bank_count() > 0))
2650 return gdb_memory_map(connection, packet, packet_size);
2651 else if (strncmp(packet, "qXfer:features:read:", 20) == 0) {
2653 int retval = ERROR_OK;
2656 unsigned int length;
2658 /* skip command character */
2661 if (decode_xfer_read(packet, NULL, &offset, &length) < 0) {
2662 gdb_send_error(connection, 01);
2666 /* Target should prepare correct target description for annex.
2667 * The first character of returned xml is 'm' or 'l'. 'm' for
2668 * there are *more* chunks to transfer. 'l' for it is the *last*
2669 * chunk of target description.
2671 retval = gdb_get_target_description_chunk(target, &gdb_connection->target_desc,
2672 &xml, offset, length);
2673 if (retval != ERROR_OK) {
2674 gdb_error(connection, retval);
2678 gdb_put_packet(connection, xml, strlen(xml));
2682 } else if (strncmp(packet, "qXfer:threads:read:", 19) == 0) {
2684 int retval = ERROR_OK;
2687 unsigned int length;
2689 /* skip command character */
2692 if (decode_xfer_read(packet, NULL, &offset, &length) < 0) {
2693 gdb_send_error(connection, 01);
2697 /* Target should prepare correct thread list for annex.
2698 * The first character of returned xml is 'm' or 'l'. 'm' for
2699 * there are *more* chunks to transfer. 'l' for it is the *last*
2700 * chunk of target description.
2702 retval = gdb_get_thread_list_chunk(target, &gdb_connection->thread_list,
2703 &xml, offset, length);
2704 if (retval != ERROR_OK) {
2705 gdb_error(connection, retval);
2709 gdb_put_packet(connection, xml, strlen(xml));
2713 } else if (strncmp(packet, "QStartNoAckMode", 15) == 0) {
2714 gdb_connection->noack_mode = 1;
2715 gdb_put_packet(connection, "OK", 2);
2719 gdb_put_packet(connection, "", 0);
2723 static bool gdb_handle_vcont_packet(struct connection *connection, const char *packet, int packet_size)
2725 struct gdb_connection *gdb_connection = connection->priv;
2726 struct target *target = get_target_from_connection(connection);
2727 const char *parse = packet;
2730 /* query for vCont supported */
2731 if (parse[0] == '?') {
2732 if (target->type->step != NULL) {
2733 /* gdb doesn't accept c without C and s without S */
2734 gdb_put_packet(connection, "vCont;c;C;s;S", 13);
2740 if (parse[0] == ';') {
2745 /* simple case, a continue packet */
2746 if (parse[0] == 'c') {
2747 gdb_running_type = 'c';
2748 LOG_DEBUG("target %s continue", target_name(target));
2749 log_add_callback(gdb_log_callback, connection);
2750 retval = target_resume(target, 1, 0, 0, 0);
2751 if (retval == ERROR_TARGET_NOT_HALTED)
2752 LOG_INFO("target %s was not halted when resume was requested", target_name(target));
2754 /* poll target in an attempt to make its internal state consistent */
2755 if (retval != ERROR_OK) {
2756 retval = target_poll(target);
2757 if (retval != ERROR_OK)
2758 LOG_DEBUG("error polling target %s after failed resume", target_name(target));
2762 * We don't report errors to gdb here, move frontend_state to
2763 * TARGET_RUNNING to stay in sync with gdb's expectation of the
2766 gdb_connection->frontend_state = TARGET_RUNNING;
2767 target_call_event_callbacks(target, TARGET_EVENT_GDB_START);
2772 /* single-step or step-over-breakpoint */
2773 if (parse[0] == 's') {
2774 gdb_running_type = 's';
2775 bool fake_step = false;
2777 if (strncmp(parse, "s:", 2) == 0) {
2778 struct target *ct = target;
2786 thread_id = strtoll(parse, &endp, 16);
2788 packet_size -= endp - parse;
2792 if (target->rtos != NULL) {
2793 /* FIXME: why is this necessary? rtos state should be up-to-date here already! */
2794 rtos_update_threads(target);
2796 target->rtos->gdb_target_for_threadid(connection, thread_id, &ct);
2799 * check if the thread to be stepped is the current rtos thread
2800 * if not, we must fake the step
2802 if (target->rtos->current_thread != thread_id)
2806 if (parse[0] == ';') {
2810 if (parse[0] == 'c') {
2813 /* check if thread-id follows */
2814 if (parse[0] == ':') {
2818 tid = strtoll(parse, &endp, 16);
2819 if (tid == thread_id) {
2821 * Special case: only step a single thread (core),
2822 * keep the other threads halted. Currently, only
2823 * aarch64 target understands it. Other target types don't
2824 * care (nobody checks the actual value of 'current')
2825 * and it doesn't really matter. This deserves
2826 * a symbolic constant and a formal interface documentation
2829 LOG_DEBUG("request to step current core only");
2830 /* uncomment after checking that indeed other targets are safe */
2837 LOG_DEBUG("target %s single-step thread %"PRIx64, target_name(ct), thread_id);
2838 log_add_callback(gdb_log_callback, connection);
2839 target_call_event_callbacks(ct, TARGET_EVENT_GDB_START);
2842 * work around an annoying gdb behaviour: when the current thread
2843 * is changed in gdb, it assumes that the target can follow and also
2844 * make the thread current. This is an assumption that cannot hold
2845 * for a real target running a multi-threading OS. We just fake
2846 * the step to not trigger an internal error in gdb. See
2847 * https://sourceware.org/bugzilla/show_bug.cgi?id=22925 for details
2851 char sig_reply[128];
2853 LOG_DEBUG("fake step thread %"PRIx64, thread_id);
2855 sig_reply_len = snprintf(sig_reply, sizeof(sig_reply),
2856 "T05thread:%016"PRIx64";", thread_id);
2858 gdb_put_packet(connection, sig_reply, sig_reply_len);
2859 log_remove_callback(gdb_log_callback, connection);
2864 /* support for gdb_sync command */
2865 if (gdb_connection->sync) {
2866 gdb_connection->sync = false;
2867 if (ct->state == TARGET_HALTED) {
2868 LOG_DEBUG("stepi ignored. GDB will now fetch the register state "
2869 "from the target.");
2870 gdb_sig_halted(connection);
2871 log_remove_callback(gdb_log_callback, connection);
2873 gdb_connection->frontend_state = TARGET_RUNNING;
2877 retval = target_step(ct, current_pc, 0, 0);
2878 if (retval == ERROR_TARGET_NOT_HALTED)
2879 LOG_INFO("target %s was not halted when step was requested", target_name(ct));
2881 /* if step was successful send a reply back to gdb */
2882 if (retval == ERROR_OK) {
2883 retval = target_poll(ct);
2884 if (retval != ERROR_OK)
2885 LOG_DEBUG("error polling target %s after successful step", target_name(ct));
2886 /* send back signal information */
2887 gdb_signal_reply(ct, connection);
2888 /* stop forwarding log packets! */
2889 log_remove_callback(gdb_log_callback, connection);
2891 gdb_connection->frontend_state = TARGET_RUNNING;
2893 LOG_ERROR("Unknown vCont packet");
2902 static char *next_hex_encoded_field(const char **str, char sep)
2905 const char *hex = *str;
2909 const char *end = strchr(hex, sep);
2911 hexlen = strlen(hex);
2914 *str = hex + hexlen + 1;
2916 if (hexlen % 2 != 0) {
2917 /* Malformed hex data */
2921 size_t count = hexlen / 2;
2922 char *decoded = malloc(count + 1);
2923 if (decoded == NULL)
2926 size_t converted = unhexify((void *)decoded, hex, count);
2927 if (converted != count) {
2932 decoded[count] = '\0';
2936 /* handle extended restart packet */
2937 static void gdb_restart_inferior(struct connection *connection, const char *packet, int packet_size)
2939 struct gdb_connection *gdb_con = connection->priv;
2940 struct target *target = get_target_from_connection(connection);
2942 breakpoint_clear_target(target);
2943 watchpoint_clear_target(target);
2944 command_run_linef(connection->cmd_ctx, "ocd_gdb_restart %s",
2945 target_name(target));
2946 /* set connection as attached after reset */
2947 gdb_con->attached = true;
2948 /* info rtos parts */
2949 gdb_thread_packet(connection, packet, packet_size);
2952 static bool gdb_handle_vrun_packet(struct connection *connection, const char *packet, int packet_size)
2954 struct target *target = get_target_from_connection(connection);
2955 const char *parse = packet;
2960 if (parse[0] != ';')
2964 /* Skip first field "filename"; don't know what to do with it. */
2965 free(next_hex_encoded_field(&parse, ';'));
2967 char *cmdline = next_hex_encoded_field(&parse, ';');
2969 while (cmdline != NULL && (arg = next_hex_encoded_field(&parse, ';')) != NULL) {
2970 char *new_cmdline = alloc_printf("%s %s", cmdline, arg);
2973 cmdline = new_cmdline;
2976 if (cmdline != NULL) {
2977 if (target->semihosting != NULL) {
2978 LOG_INFO("GDB set inferior command line to '%s'", cmdline);
2979 free(target->semihosting->cmdline);
2980 target->semihosting->cmdline = cmdline;
2982 LOG_INFO("GDB set inferior command line to '%s' but semihosting is unavailable", cmdline);
2987 gdb_restart_inferior(connection, packet, packet_size);
2988 gdb_put_packet(connection, "S00", 3);
2992 static int gdb_v_packet(struct connection *connection,
2993 char const *packet, int packet_size)
2995 struct gdb_connection *gdb_connection = connection->priv;
2998 struct target *target = get_target_from_connection(connection);
3000 if (strncmp(packet, "vCont", 5) == 0) {
3006 handled = gdb_handle_vcont_packet(connection, packet, packet_size);
3008 gdb_put_packet(connection, "", 0);
3013 if (strncmp(packet, "vRun", 4) == 0) {
3016 handled = gdb_handle_vrun_packet(connection, packet, packet_size);
3018 gdb_put_packet(connection, "", 0);
3023 /* if flash programming disabled - send a empty reply */
3025 if (gdb_flash_program == 0) {
3026 gdb_put_packet(connection, "", 0);
3030 if (strncmp(packet, "vFlashErase:", 12) == 0) {
3032 unsigned long length;
3034 char const *parse = packet + 12;
3035 if (*parse == '\0') {
3036 LOG_ERROR("incomplete vFlashErase packet received, dropping connection");
3037 return ERROR_SERVER_REMOTE_CLOSED;
3040 addr = strtoul(parse, (char **)&parse, 16);
3042 if (*(parse++) != ',' || *parse == '\0') {
3043 LOG_ERROR("incomplete vFlashErase packet received, dropping connection");
3044 return ERROR_SERVER_REMOTE_CLOSED;
3047 length = strtoul(parse, (char **)&parse, 16);
3049 if (*parse != '\0') {
3050 LOG_ERROR("incomplete vFlashErase packet received, dropping connection");
3051 return ERROR_SERVER_REMOTE_CLOSED;
3054 /* assume all sectors need erasing - stops any problems
3055 * when flash_write is called multiple times */
3058 /* perform any target specific operations before the erase */
3059 target_call_event_callbacks(target,
3060 TARGET_EVENT_GDB_FLASH_ERASE_START);
3062 /* vFlashErase:addr,length messages require region start and
3063 * end to be "block" aligned ... if padding is ever needed,
3064 * GDB will have become dangerously confused.
3066 result = flash_erase_address_range(target, false, addr,
3069 /* perform any target specific operations after the erase */
3070 target_call_event_callbacks(target,
3071 TARGET_EVENT_GDB_FLASH_ERASE_END);
3074 if (result != ERROR_OK) {
3075 /* GDB doesn't evaluate the actual error number returned,
3076 * treat a failed erase as an I/O error
3078 gdb_send_error(connection, EIO);
3079 LOG_ERROR("flash_erase returned %i", result);
3081 gdb_put_packet(connection, "OK", 2);
3086 if (strncmp(packet, "vFlashWrite:", 12) == 0) {
3089 unsigned long length;
3090 char const *parse = packet + 12;
3092 if (*parse == '\0') {
3093 LOG_ERROR("incomplete vFlashErase packet received, dropping connection");
3094 return ERROR_SERVER_REMOTE_CLOSED;
3096 addr = strtoul(parse, (char **)&parse, 16);
3097 if (*(parse++) != ':') {
3098 LOG_ERROR("incomplete vFlashErase packet received, dropping connection");
3099 return ERROR_SERVER_REMOTE_CLOSED;
3101 length = packet_size - (parse - packet);
3103 /* create a new image if there isn't already one */
3104 if (gdb_connection->vflash_image == NULL) {
3105 gdb_connection->vflash_image = malloc(sizeof(struct image));
3106 image_open(gdb_connection->vflash_image, "", "build");
3109 /* create new section with content from packet buffer */
3110 retval = image_add_section(gdb_connection->vflash_image,
3111 addr, length, 0x0, (uint8_t const *)parse);
3112 if (retval != ERROR_OK)
3115 gdb_put_packet(connection, "OK", 2);
3120 if (strncmp(packet, "vFlashDone", 10) == 0) {
3123 /* process the flashing buffer. No need to erase as GDB
3124 * always issues a vFlashErase first. */
3125 target_call_event_callbacks(target,
3126 TARGET_EVENT_GDB_FLASH_WRITE_START);
3127 result = flash_write(target, gdb_connection->vflash_image,
3129 target_call_event_callbacks(target,
3130 TARGET_EVENT_GDB_FLASH_WRITE_END);
3131 if (result != ERROR_OK) {
3132 if (result == ERROR_FLASH_DST_OUT_OF_BANK)
3133 gdb_put_packet(connection, "E.memtype", 9);
3135 gdb_send_error(connection, EIO);
3137 LOG_DEBUG("wrote %u bytes from vFlash image to flash", (unsigned)written);
3138 gdb_put_packet(connection, "OK", 2);
3141 image_close(gdb_connection->vflash_image);
3142 free(gdb_connection->vflash_image);
3143 gdb_connection->vflash_image = NULL;
3148 gdb_put_packet(connection, "", 0);
3152 static int gdb_detach(struct connection *connection)
3155 * Only reply "OK" to GDB
3156 * it will close the connection and this will trigger a call to
3157 * gdb_connection_closed() that will in turn trigger the event
3158 * TARGET_EVENT_GDB_DETACH
3160 return gdb_put_packet(connection, "OK", 2);
3163 /* The format of 'F' response packet is
3164 * Fretcode,errno,Ctrl-C flag;call-specific attachment
3166 static int gdb_fileio_response_packet(struct connection *connection,
3167 char const *packet, int packet_size)
3169 struct target *target = get_target_from_connection(connection);
3171 char *parsing_point;
3172 int fileio_retcode = strtoul(packet + 1, &separator, 16);
3173 int fileio_errno = 0;
3174 bool fileio_ctrl_c = false;
3179 if (*separator == ',') {
3180 parsing_point = separator + 1;
3181 fileio_errno = strtoul(parsing_point, &separator, 16);
3182 if (*separator == ',') {
3183 if (*(separator + 1) == 'C') {
3184 /* TODO: process ctrl-c */
3185 fileio_ctrl_c = true;
3190 LOG_DEBUG("File-I/O response, retcode: 0x%x, errno: 0x%x, ctrl-c: %s",
3191 fileio_retcode, fileio_errno, fileio_ctrl_c ? "true" : "false");
3193 retval = target_gdb_fileio_end(target, fileio_retcode, fileio_errno, fileio_ctrl_c);
3194 if (retval != ERROR_OK)
3197 /* After File-I/O ends, keep continue or step */
3198 if (gdb_running_type == 'c')
3199 retval = target_resume(target, 1, 0x0, 0, 0);
3200 else if (gdb_running_type == 's')
3201 retval = target_step(target, 1, 0x0, 0);
3203 retval = ERROR_FAIL;
3205 if (retval != ERROR_OK)
3211 static void gdb_log_callback(void *priv, const char *file, unsigned line,
3212 const char *function, const char *string)
3214 struct connection *connection = priv;
3215 struct gdb_connection *gdb_con = connection->priv;
3217 if (gdb_con->busy) {
3218 /* do not reply this using the O packet */
3222 gdb_output_con(connection, string);
3225 static void gdb_sig_halted(struct connection *connection)
3228 snprintf(sig_reply, 4, "T%2.2x", 2);
3229 gdb_put_packet(connection, sig_reply, 3);
3232 static int gdb_input_inner(struct connection *connection)
3234 /* Do not allocate this on the stack */
3235 static char gdb_packet_buffer[GDB_BUFFER_SIZE + 1]; /* Extra byte for null-termination */
3237 struct target *target;
3238 char const *packet = gdb_packet_buffer;
3241 struct gdb_connection *gdb_con = connection->priv;
3242 static bool warn_use_ext;
3244 target = get_target_from_connection(connection);
3246 /* drain input buffer. If one of the packets fail, then an error
3247 * packet is replied, if applicable.
3249 * This loop will terminate and the error code is returned.
3251 * The calling fn will check if this error is something that
3252 * can be recovered from, or if the connection must be closed.
3254 * If the error is recoverable, this fn is called again to
3255 * drain the rest of the buffer.
3258 packet_size = GDB_BUFFER_SIZE;
3259 retval = gdb_get_packet(connection, gdb_packet_buffer, &packet_size);
3260 if (retval != ERROR_OK)
3263 /* terminate with zero */
3264 gdb_packet_buffer[packet_size] = '\0';
3266 if (LOG_LEVEL_IS(LOG_LVL_DEBUG)) {
3267 if (packet[0] == 'X') {
3268 /* binary packets spew junk into the debug log stream */
3271 for (x = 0; (x < 49) && (packet[x] != ':'); x++)
3274 LOG_DEBUG("received packet: '%s:<binary-data>'", buf);
3276 LOG_DEBUG("received packet: '%s'", packet);
3279 if (packet_size > 0) {
3281 switch (packet[0]) {
3282 case 'T': /* Is thread alive? */
3283 gdb_thread_packet(connection, packet, packet_size);
3285 case 'H': /* Set current thread ( 'c' for step and continue,
3286 * 'g' for all other operations ) */
3287 gdb_thread_packet(connection, packet, packet_size);
3291 retval = gdb_thread_packet(connection, packet, packet_size);
3292 if (retval == GDB_THREAD_PACKET_NOT_CONSUMED)
3293 retval = gdb_query_packet(connection, packet, packet_size);
3296 retval = gdb_get_registers_packet(connection, packet, packet_size);
3299 retval = gdb_set_registers_packet(connection, packet, packet_size);
3302 retval = gdb_get_register_packet(connection, packet, packet_size);
3305 retval = gdb_set_register_packet(connection, packet, packet_size);
3308 retval = gdb_read_memory_packet(connection, packet, packet_size);
3311 retval = gdb_write_memory_packet(connection, packet, packet_size);
3315 retval = gdb_breakpoint_watchpoint_packet(connection, packet, packet_size);
3318 gdb_last_signal_packet(connection, packet, packet_size);
3319 /* '?' is sent after the eventual '!' */
3320 if (!warn_use_ext && !gdb_con->extended_protocol) {
3321 warn_use_ext = true;
3322 LOG_WARNING("Prefer GDB command \"target extended-remote %s\" instead of \"target remote %s\"",
3323 connection->service->port, connection->service->port);
3329 gdb_thread_packet(connection, packet, packet_size);
3330 log_add_callback(gdb_log_callback, connection);
3332 if (gdb_con->mem_write_error) {
3333 LOG_ERROR("Memory write failure!");
3335 /* now that we have reported the memory write error,
3336 * we can clear the condition */
3337 gdb_con->mem_write_error = false;
3340 bool nostep = false;
3341 bool already_running = false;
3342 if (target->state == TARGET_RUNNING) {
3343 LOG_WARNING("WARNING! The target is already running. "
3344 "All changes GDB did to registers will be discarded! "
3345 "Waiting for target to halt.");
3346 already_running = true;
3347 } else if (target->state != TARGET_HALTED) {
3348 LOG_WARNING("The target is not in the halted nor running stated, "
3349 "stepi/continue ignored.");
3351 } else if ((packet[0] == 's') && gdb_con->sync) {
3352 /* Hmm..... when you issue a continue in GDB, then a "stepi" is
3353 * sent by GDB first to OpenOCD, thus defeating the check to
3354 * make only the single stepping have the sync feature...
3357 LOG_DEBUG("stepi ignored. GDB will now fetch the register state "
3358 "from the target.");
3360 gdb_con->sync = false;
3362 if (!already_running && nostep) {
3363 /* Either the target isn't in the halted state, then we can't
3364 * step/continue. This might be early setup, etc.
3366 * Or we want to allow GDB to pick up a fresh set of
3367 * register values without modifying the target state.
3370 gdb_sig_halted(connection);
3372 /* stop forwarding log packets! */
3373 log_remove_callback(gdb_log_callback, connection);
3375 /* We're running/stepping, in which case we can
3376 * forward log output until the target is halted
3378 gdb_con->frontend_state = TARGET_RUNNING;
3379 target_call_event_callbacks(target, TARGET_EVENT_GDB_START);
3381 if (!already_running) {
3382 /* Here we don't want packet processing to stop even if this fails,
3383 * so we use a local variable instead of retval. */
3384 retval = gdb_step_continue_packet(connection, packet, packet_size);
3385 if (retval != ERROR_OK) {
3386 /* we'll never receive a halted
3387 * condition... issue a false one..
3389 gdb_frontend_halted(target, connection);
3396 retval = gdb_v_packet(connection, packet, packet_size);
3399 retval = gdb_detach(connection);
3402 retval = gdb_write_memory_binary_packet(connection, packet, packet_size);
3403 if (retval != ERROR_OK)
3407 if (gdb_con->extended_protocol) {
3408 gdb_con->attached = false;
3411 gdb_put_packet(connection, "OK", 2);
3412 return ERROR_SERVER_REMOTE_CLOSED;
3414 /* handle extended remote protocol */
3415 gdb_con->extended_protocol = true;
3416 gdb_put_packet(connection, "OK", 2);
3419 /* handle extended restart packet */
3420 gdb_restart_inferior(connection, packet, packet_size);
3424 /* packet supported only by smp target i.e cortex_a.c*/
3425 /* handle smp packet replying coreid played to gbd */
3426 gdb_read_smp_packet(connection, packet, packet_size);
3430 /* packet supported only by smp target i.e cortex_a.c */
3431 /* handle smp packet setting coreid to be played at next
3433 gdb_write_smp_packet(connection, packet, packet_size);
3437 /* File-I/O extension */
3438 /* After gdb uses host-side syscall to complete target file
3439 * I/O, gdb sends host-side syscall return value to target
3441 * The format of 'F' response packet is
3442 * Fretcode,errno,Ctrl-C flag;call-specific attachment
3444 gdb_con->frontend_state = TARGET_RUNNING;
3445 log_add_callback(gdb_log_callback, connection);
3446 gdb_fileio_response_packet(connection, packet, packet_size);
3450 /* ignore unknown packets */
3451 LOG_DEBUG("ignoring 0x%2.2x packet", packet[0]);
3452 gdb_put_packet(connection, "", 0);
3456 /* if a packet handler returned an error, exit input loop */
3457 if (retval != ERROR_OK)
3461 if (gdb_con->ctrl_c) {
3462 if (target->state == TARGET_RUNNING) {
3463 struct target *t = target;
3465 target->rtos->gdb_target_for_threadid(connection, target->rtos->current_threadid, &t);
3466 retval = target_halt(t);
3467 if (retval == ERROR_OK)
3468 retval = target_poll(t);
3469 if (retval != ERROR_OK)
3470 target_call_event_callbacks(target, TARGET_EVENT_GDB_HALT);
3471 gdb_con->ctrl_c = false;
3473 LOG_INFO("The target is not running when halt was requested, stopping GDB.");
3474 target_call_event_callbacks(target, TARGET_EVENT_GDB_HALT);
3478 } while (gdb_con->buf_cnt > 0);
3483 static int gdb_input(struct connection *connection)
3485 int retval = gdb_input_inner(connection);
3486 struct gdb_connection *gdb_con = connection->priv;
3487 if (retval == ERROR_SERVER_REMOTE_CLOSED)
3490 /* logging does not propagate the error, yet can set the gdb_con->closed flag */
3491 if (gdb_con->closed)
3492 return ERROR_SERVER_REMOTE_CLOSED;
3494 /* we'll recover from any other errors(e.g. temporary timeouts, etc.) */
3498 static int gdb_target_start(struct target *target, const char *port)
3500 struct gdb_service *gdb_service;
3502 gdb_service = malloc(sizeof(struct gdb_service));
3504 if (NULL == gdb_service)
3507 LOG_INFO("starting gdb server for %s on %s", target_name(target), port);
3509 gdb_service->target = target;
3510 gdb_service->core[0] = -1;
3511 gdb_service->core[1] = -1;
3512 target->gdb_service = gdb_service;
3514 ret = add_service("gdb",
3515 port, 1, &gdb_new_connection, &gdb_input,
3516 &gdb_connection_closed, gdb_service);
3517 /* initialize all targets gdb service with the same pointer */
3519 struct target_list *head;
3520 struct target *curr;
3521 head = target->head;
3522 while (head != (struct target_list *)NULL) {
3523 curr = head->target;
3525 curr->gdb_service = gdb_service;
3532 static int gdb_target_add_one(struct target *target)
3534 /* one gdb instance per smp list */
3535 if ((target->smp) && (target->gdb_service))
3538 /* skip targets that cannot handle a gdb connections (e.g. mem_ap) */
3539 if (!target_supports_gdb_connection(target)) {
3540 LOG_DEBUG("skip gdb server for target %s", target_name(target));
3544 if (target->gdb_port_override) {
3545 if (strcmp(target->gdb_port_override, "disabled") == 0) {
3546 LOG_INFO("gdb port disabled");
3549 return gdb_target_start(target, target->gdb_port_override);
3552 if (strcmp(gdb_port, "disabled") == 0) {
3553 LOG_INFO("gdb port disabled");
3557 int retval = gdb_target_start(target, gdb_port_next);
3558 if (retval == ERROR_OK) {
3559 /* save the port number so can be queried with
3560 * $target_name cget -gdb-port
3562 target->gdb_port_override = strdup(gdb_port_next);
3565 /* If we can parse the port number
3566 * then we increment the port number for the next target.
3569 portnumber = strtol(gdb_port_next, &end, 0);
3571 if (parse_long(gdb_port_next, &portnumber) == ERROR_OK) {
3572 free(gdb_port_next);
3574 gdb_port_next = alloc_printf("%ld", portnumber+1);
3576 /* Don't increment if gdb_port is 0, since we're just
3577 * trying to allocate an unused port. */
3578 gdb_port_next = strdup("0");
3586 int gdb_target_add_all(struct target *target)
3588 if (NULL == target) {
3589 LOG_WARNING("gdb services need one or more targets defined");
3593 while (NULL != target) {
3594 int retval = gdb_target_add_one(target);
3595 if (ERROR_OK != retval)
3598 target = target->next;
3604 COMMAND_HANDLER(handle_gdb_sync_command)
3607 return ERROR_COMMAND_SYNTAX_ERROR;
3609 if (current_gdb_connection == NULL) {
3611 "gdb_sync command can only be run from within gdb using \"monitor gdb_sync\"");
3615 current_gdb_connection->sync = true;
3620 /* daemon configuration command gdb_port */
3621 COMMAND_HANDLER(handle_gdb_port_command)
3623 int retval = CALL_COMMAND_HANDLER(server_pipe_command, &gdb_port);
3624 if (ERROR_OK == retval) {
3625 free(gdb_port_next);
3626 gdb_port_next = strdup(gdb_port);
3631 COMMAND_HANDLER(handle_gdb_memory_map_command)
3634 return ERROR_COMMAND_SYNTAX_ERROR;
3636 COMMAND_PARSE_ENABLE(CMD_ARGV[0], gdb_use_memory_map);
3640 COMMAND_HANDLER(handle_gdb_flash_program_command)
3643 return ERROR_COMMAND_SYNTAX_ERROR;
3645 COMMAND_PARSE_ENABLE(CMD_ARGV[0], gdb_flash_program);
3649 COMMAND_HANDLER(handle_gdb_report_data_abort_command)
3652 return ERROR_COMMAND_SYNTAX_ERROR;
3654 COMMAND_PARSE_ENABLE(CMD_ARGV[0], gdb_report_data_abort);
3658 COMMAND_HANDLER(handle_gdb_report_register_access_error)
3661 return ERROR_COMMAND_SYNTAX_ERROR;
3663 COMMAND_PARSE_ENABLE(CMD_ARGV[0], gdb_report_register_access_error);
3667 /* gdb_breakpoint_override */
3668 COMMAND_HANDLER(handle_gdb_breakpoint_override_command)
3670 if (CMD_ARGC == 0) {
3672 } else if (CMD_ARGC == 1) {
3673 gdb_breakpoint_override = 1;
3674 if (strcmp(CMD_ARGV[0], "hard") == 0)
3675 gdb_breakpoint_override_type = BKPT_HARD;
3676 else if (strcmp(CMD_ARGV[0], "soft") == 0)
3677 gdb_breakpoint_override_type = BKPT_SOFT;
3678 else if (strcmp(CMD_ARGV[0], "disable") == 0)
3679 gdb_breakpoint_override = 0;
3681 return ERROR_COMMAND_SYNTAX_ERROR;
3682 if (gdb_breakpoint_override)
3683 LOG_USER("force %s breakpoints",
3684 (gdb_breakpoint_override_type == BKPT_HARD) ? "hard" : "soft");
3686 LOG_USER("breakpoint type is not overridden");
3691 COMMAND_HANDLER(handle_gdb_target_description_command)
3694 return ERROR_COMMAND_SYNTAX_ERROR;
3696 COMMAND_PARSE_ENABLE(CMD_ARGV[0], gdb_use_target_description);
3700 COMMAND_HANDLER(handle_gdb_save_tdesc_command)
3703 uint32_t tdesc_length;
3704 struct target *target = get_current_target(CMD_CTX);
3706 int retval = gdb_generate_target_description(target, &tdesc);
3707 if (retval != ERROR_OK) {
3708 LOG_ERROR("Unable to Generate Target Description");
3712 tdesc_length = strlen(tdesc);
3714 struct fileio *fileio;
3715 size_t size_written;
3717 char *tdesc_filename = alloc_printf("%s.xml", target_type_name(target));
3718 if (tdesc_filename == NULL) {
3719 retval = ERROR_FAIL;
3723 retval = fileio_open(&fileio, tdesc_filename, FILEIO_WRITE, FILEIO_TEXT);
3725 if (retval != ERROR_OK) {
3726 LOG_ERROR("Can't open %s for writing", tdesc_filename);
3730 retval = fileio_write(fileio, tdesc_length, tdesc, &size_written);
3732 fileio_close(fileio);
3734 if (retval != ERROR_OK)
3735 LOG_ERROR("Error while writing the tdesc file");
3738 free(tdesc_filename);
3744 static const struct command_registration gdb_command_handlers[] = {
3747 .handler = handle_gdb_sync_command,
3748 .mode = COMMAND_ANY,
3749 .help = "next stepi will return immediately allowing "
3750 "GDB to fetch register state without affecting "
3756 .handler = handle_gdb_port_command,
3757 .mode = COMMAND_CONFIG,
3758 .help = "Normally gdb listens to a TCP/IP port. Each subsequent GDB "
3759 "server listens for the next port number after the "
3760 "base port number specified. "
3761 "No arguments reports GDB port. \"pipe\" means listen to stdin "
3762 "output to stdout, an integer is base port number, \"disabled\" disables "
3763 "port. Any other string is are interpreted as named pipe to listen to. "
3764 "Output pipe is the same name as input pipe, but with 'o' appended.",
3765 .usage = "[port_num]",
3768 .name = "gdb_memory_map",
3769 .handler = handle_gdb_memory_map_command,
3770 .mode = COMMAND_CONFIG,
3771 .help = "enable or disable memory map",
3772 .usage = "('enable'|'disable')"
3775 .name = "gdb_flash_program",
3776 .handler = handle_gdb_flash_program_command,
3777 .mode = COMMAND_CONFIG,
3778 .help = "enable or disable flash program",
3779 .usage = "('enable'|'disable')"
3782 .name = "gdb_report_data_abort",
3783 .handler = handle_gdb_report_data_abort_command,
3784 .mode = COMMAND_CONFIG,
3785 .help = "enable or disable reporting data aborts",
3786 .usage = "('enable'|'disable')"
3789 .name = "gdb_report_register_access_error",
3790 .handler = handle_gdb_report_register_access_error,
3791 .mode = COMMAND_CONFIG,
3792 .help = "enable or disable reporting register access errors",
3793 .usage = "('enable'|'disable')"
3796 .name = "gdb_breakpoint_override",
3797 .handler = handle_gdb_breakpoint_override_command,
3798 .mode = COMMAND_ANY,
3799 .help = "Display or specify type of breakpoint "
3800 "to be used by gdb 'break' commands.",
3801 .usage = "('hard'|'soft'|'disable')"
3804 .name = "gdb_target_description",
3805 .handler = handle_gdb_target_description_command,
3806 .mode = COMMAND_CONFIG,
3807 .help = "enable or disable target description",
3808 .usage = "('enable'|'disable')"
3811 .name = "gdb_save_tdesc",
3812 .handler = handle_gdb_save_tdesc_command,
3813 .mode = COMMAND_EXEC,
3814 .help = "Save the target description file",
3817 COMMAND_REGISTRATION_DONE
3820 int gdb_register_commands(struct command_context *cmd_ctx)
3822 gdb_port = strdup("3333");
3823 gdb_port_next = strdup("3333");
3824 return register_commands(cmd_ctx, NULL, gdb_command_handlers);
3827 void gdb_service_free(void)
3830 free(gdb_port_next);