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>
47 #include <flash/nor/core.h>
48 #include "gdb_server.h"
49 #include <target/image.h>
50 #include <jtag/jtag.h>
51 #include "rtos/rtos.h"
52 #include "target/smp.h"
56 * GDB server implementation.
58 * This implements the GDB Remote Serial Protocol, over TCP connections,
59 * giving GDB access to the JTAG or other hardware debugging facilities
60 * found in most modern embedded processors.
63 struct target_desc_format {
65 uint32_t tdesc_length;
68 /* private connection data for GDB */
69 struct gdb_connection {
70 char buffer[GDB_BUFFER_SIZE + 1]; /* Extra byte for nul-termination */
74 enum target_state frontend_state;
75 struct image *vflash_image;
79 /* set flag to true if you want the next stepi to return immediately.
80 * allowing GDB to pick up a fresh set of register values from the target
81 * without modifying the target state. */
83 /* We delay reporting memory write errors until next step/continue or memory
84 * write. This improves performance of gdb load significantly as the GDB packet
85 * can be replied immediately and a new GDB packet will be ready without delay
86 * (ca. 10% or so...). */
88 /* with extended-remote it seems we need to better emulate attach/detach.
89 * what this means is we reply with a W stop reply after a kill packet,
90 * normally we reply with a S reply via gdb_last_signal_packet.
91 * as a side note this behaviour only effects gdb > 6.8 */
93 /* temporarily used for target description support */
94 struct target_desc_format target_desc;
95 /* temporarily used for thread list support */
100 #define _DEBUG_GDB_IO_
103 static struct gdb_connection *current_gdb_connection;
105 static int gdb_breakpoint_override;
106 static enum breakpoint_type gdb_breakpoint_override_type;
108 static int gdb_error(struct connection *connection, int retval);
109 static char *gdb_port;
110 static char *gdb_port_next;
112 static void gdb_log_callback(void *priv, const char *file, unsigned line,
113 const char *function, const char *string);
115 static void gdb_sig_halted(struct connection *connection);
117 /* number of gdb connections, mainly to suppress gdb related debugging spam
118 * in helper/log.c when no gdb connections are actually active */
119 int gdb_actual_connections;
121 /* set if we are sending a memory map to gdb
122 * via qXfer:memory-map:read packet */
123 /* enabled by default*/
124 static int gdb_use_memory_map = 1;
125 /* enabled by default*/
126 static int gdb_flash_program = 1;
128 /* if set, data aborts cause an error to be reported in memory read packets
129 * see the code in gdb_read_memory_packet() for further explanations.
130 * Disabled by default.
132 static int gdb_report_data_abort;
133 /* If set, errors when accessing registers are reported to gdb. Disabled by
135 static int gdb_report_register_access_error;
137 /* set if we are sending target descriptions to gdb
138 * via qXfer:features:read packet */
139 /* enabled by default */
140 static int gdb_use_target_description = 1;
142 /* current processing free-run type, used by file-I/O */
143 static char gdb_running_type;
145 static int gdb_last_signal(struct target *target)
147 switch (target->debug_reason) {
148 case DBG_REASON_DBGRQ:
149 return 0x2; /* SIGINT */
150 case DBG_REASON_BREAKPOINT:
151 case DBG_REASON_WATCHPOINT:
152 case DBG_REASON_WPTANDBKPT:
153 return 0x05; /* SIGTRAP */
154 case DBG_REASON_SINGLESTEP:
155 return 0x05; /* SIGTRAP */
156 case DBG_REASON_EXC_CATCH:
158 case DBG_REASON_NOTHALTED:
159 return 0x0; /* no signal... shouldn't happen */
161 LOG_USER("undefined debug reason %d - target needs reset",
162 target->debug_reason);
167 static int check_pending(struct connection *connection,
168 int timeout_s, int *got_data)
170 /* a non-blocking socket will block if there is 0 bytes available on the socket,
171 * but return with as many bytes as are available immediately
175 struct gdb_connection *gdb_con = connection->priv;
177 if (got_data == NULL)
181 if (gdb_con->buf_cnt > 0) {
187 FD_SET(connection->fd, &read_fds);
189 tv.tv_sec = timeout_s;
191 if (socket_select(connection->fd + 1, &read_fds, NULL, NULL, &tv) == 0) {
192 /* This can typically be because a "monitor" command took too long
193 * before printing any progress messages
196 return ERROR_GDB_TIMEOUT;
200 *got_data = FD_ISSET(connection->fd, &read_fds) != 0;
204 static int gdb_get_char_inner(struct connection *connection, int *next_char)
206 struct gdb_connection *gdb_con = connection->priv;
207 int retval = ERROR_OK;
209 #ifdef _DEBUG_GDB_IO_
213 if (connection->service->type != CONNECTION_TCP)
214 gdb_con->buf_cnt = read(connection->fd, gdb_con->buffer, GDB_BUFFER_SIZE);
216 retval = check_pending(connection, 1, NULL);
217 if (retval != ERROR_OK)
219 gdb_con->buf_cnt = read_socket(connection->fd,
224 if (gdb_con->buf_cnt > 0)
226 if (gdb_con->buf_cnt == 0) {
227 gdb_con->closed = true;
228 return ERROR_SERVER_REMOTE_CLOSED;
232 errno = WSAGetLastError();
238 case WSAECONNABORTED:
239 gdb_con->closed = true;
240 return ERROR_SERVER_REMOTE_CLOSED;
242 gdb_con->closed = true;
243 return ERROR_SERVER_REMOTE_CLOSED;
245 LOG_ERROR("read: %d", errno);
254 gdb_con->closed = true;
255 return ERROR_SERVER_REMOTE_CLOSED;
257 gdb_con->closed = true;
258 return ERROR_SERVER_REMOTE_CLOSED;
260 LOG_ERROR("read: %s", strerror(errno));
261 gdb_con->closed = true;
262 return ERROR_SERVER_REMOTE_CLOSED;
267 #ifdef _DEBUG_GDB_IO_
268 debug_buffer = strndup(gdb_con->buffer, gdb_con->buf_cnt);
269 LOG_DEBUG("received '%s'", debug_buffer);
273 gdb_con->buf_p = gdb_con->buffer;
275 *next_char = *(gdb_con->buf_p++);
276 if (gdb_con->buf_cnt > 0)
277 connection->input_pending = 1;
279 connection->input_pending = 0;
280 #ifdef _DEBUG_GDB_IO_
281 LOG_DEBUG("returned char '%c' (0x%2.2x)", *next_char, *next_char);
288 * The cool thing about this fn is that it allows buf_p and buf_cnt to be
289 * held in registers in the inner loop.
291 * For small caches and embedded systems this is important!
293 static inline int gdb_get_char_fast(struct connection *connection,
294 int *next_char, char **buf_p, int *buf_cnt)
296 int retval = ERROR_OK;
298 if ((*buf_cnt)-- > 0) {
299 *next_char = **buf_p;
302 connection->input_pending = 1;
304 connection->input_pending = 0;
306 #ifdef _DEBUG_GDB_IO_
307 LOG_DEBUG("returned char '%c' (0x%2.2x)", *next_char, *next_char);
313 struct gdb_connection *gdb_con = connection->priv;
314 gdb_con->buf_p = *buf_p;
315 gdb_con->buf_cnt = *buf_cnt;
316 retval = gdb_get_char_inner(connection, next_char);
317 *buf_p = gdb_con->buf_p;
318 *buf_cnt = gdb_con->buf_cnt;
323 static int gdb_get_char(struct connection *connection, int *next_char)
325 struct gdb_connection *gdb_con = connection->priv;
326 return gdb_get_char_fast(connection, next_char, &gdb_con->buf_p, &gdb_con->buf_cnt);
329 static int gdb_putback_char(struct connection *connection, int last_char)
331 struct gdb_connection *gdb_con = connection->priv;
333 if (gdb_con->buf_p > gdb_con->buffer) {
334 *(--gdb_con->buf_p) = last_char;
337 LOG_ERROR("BUG: couldn't put character back");
342 /* The only way we can detect that the socket is closed is the first time
343 * we write to it, we will fail. Subsequent write operations will
344 * succeed. Shudder! */
345 static int gdb_write(struct connection *connection, void *data, int len)
347 struct gdb_connection *gdb_con = connection->priv;
349 return ERROR_SERVER_REMOTE_CLOSED;
351 if (connection_write(connection, data, len) == len)
353 gdb_con->closed = true;
354 return ERROR_SERVER_REMOTE_CLOSED;
357 static int gdb_put_packet_inner(struct connection *connection,
358 char *buffer, int len)
361 unsigned char my_checksum = 0;
362 #ifdef _DEBUG_GDB_IO_
367 struct gdb_connection *gdb_con = connection->priv;
369 for (i = 0; i < len; i++)
370 my_checksum += buffer[i];
372 #ifdef _DEBUG_GDB_IO_
374 * At this point we should have nothing in the input queue from GDB,
375 * however sometimes '-' is sent even though we've already received
376 * an ACK (+) for everything we've sent off.
380 retval = check_pending(connection, 0, &gotdata);
381 if (retval != ERROR_OK)
385 retval = gdb_get_char(connection, &reply);
386 if (retval != ERROR_OK)
389 /* fix a problem with some IAR tools */
390 gdb_putback_char(connection, reply);
391 LOG_DEBUG("Unexpected start of new packet");
395 LOG_WARNING("Discard unexpected char %c", reply);
400 #ifdef _DEBUG_GDB_IO_
401 debug_buffer = strndup(buffer, len);
402 LOG_DEBUG("sending packet '$%s#%2.2x'", debug_buffer, my_checksum);
406 char local_buffer[1024];
407 local_buffer[0] = '$';
408 if ((size_t)len + 4 <= sizeof(local_buffer)) {
409 /* performance gain on smaller packets by only a single call to gdb_write() */
410 memcpy(local_buffer + 1, buffer, len++);
411 len += snprintf(local_buffer + len, sizeof(local_buffer) - len, "#%02x", my_checksum);
412 retval = gdb_write(connection, local_buffer, len);
413 if (retval != ERROR_OK)
416 /* larger packets are transmitted directly from caller supplied buffer
417 * by several calls to gdb_write() to avoid dynamic allocation */
418 snprintf(local_buffer + 1, sizeof(local_buffer) - 1, "#%02x", my_checksum);
419 retval = gdb_write(connection, local_buffer, 1);
420 if (retval != ERROR_OK)
422 retval = gdb_write(connection, buffer, len);
423 if (retval != ERROR_OK)
425 retval = gdb_write(connection, local_buffer + 1, 3);
426 if (retval != ERROR_OK)
430 if (gdb_con->noack_mode)
433 retval = gdb_get_char(connection, &reply);
434 if (retval != ERROR_OK)
439 else if (reply == '-') {
440 /* Stop sending output packets for now */
441 log_remove_callback(gdb_log_callback, connection);
442 LOG_WARNING("negative reply, retrying");
443 } else if (reply == 0x3) {
445 retval = gdb_get_char(connection, &reply);
446 if (retval != ERROR_OK)
450 else if (reply == '-') {
451 /* Stop sending output packets for now */
452 log_remove_callback(gdb_log_callback, connection);
453 LOG_WARNING("negative reply, retrying");
454 } else if (reply == '$') {
455 LOG_ERROR("GDB missing ack(1) - assumed good");
456 gdb_putback_char(connection, reply);
459 LOG_ERROR("unknown character(1) 0x%2.2x in reply, dropping connection", reply);
460 gdb_con->closed = true;
461 return ERROR_SERVER_REMOTE_CLOSED;
463 } else if (reply == '$') {
464 LOG_ERROR("GDB missing ack(2) - assumed good");
465 gdb_putback_char(connection, reply);
468 LOG_ERROR("unknown character(2) 0x%2.2x in reply, dropping connection",
470 gdb_con->closed = true;
471 return ERROR_SERVER_REMOTE_CLOSED;
475 return ERROR_SERVER_REMOTE_CLOSED;
480 int gdb_put_packet(struct connection *connection, char *buffer, int len)
482 struct gdb_connection *gdb_con = connection->priv;
483 gdb_con->busy = true;
484 int retval = gdb_put_packet_inner(connection, buffer, len);
485 gdb_con->busy = false;
487 /* we sent some data, reset timer for keep alive messages */
493 static inline int fetch_packet(struct connection *connection,
494 int *checksum_ok, int noack, int *len, char *buffer)
496 unsigned char my_checksum = 0;
499 int retval = ERROR_OK;
501 struct gdb_connection *gdb_con = connection->priv;
506 /* move this over into local variables to use registers and give the
507 * more freedom to optimize */
508 char *buf_p = gdb_con->buf_p;
509 int buf_cnt = gdb_con->buf_cnt;
512 /* The common case is that we have an entire packet with no escape chars.
513 * We need to leave at least 2 bytes in the buffer to have
514 * gdb_get_char() update various bits and bobs correctly.
516 if ((buf_cnt > 2) && ((buf_cnt + count) < *len)) {
517 /* The compiler will struggle a bit with constant propagation and
518 * aliasing, so we help it by showing that these values do not
519 * change inside the loop
523 int run = buf_cnt - 2;
529 if (character == '#') {
530 /* Danger! character can be '#' when esc is
531 * used so we need an explicit boolean for done here. */
536 if (character == '}') {
537 /* data transmitted in binary mode (X packet)
538 * uses 0x7d as escape character */
539 my_checksum += character & 0xff;
542 my_checksum += character & 0xff;
543 buffer[count++] = (character ^ 0x20) & 0xff;
545 my_checksum += character & 0xff;
546 buffer[count++] = character & 0xff;
555 LOG_ERROR("packet buffer too small");
556 retval = ERROR_GDB_BUFFER_TOO_SMALL;
560 retval = gdb_get_char_fast(connection, &character, &buf_p, &buf_cnt);
561 if (retval != ERROR_OK)
564 if (character == '#')
567 if (character == '}') {
568 /* data transmitted in binary mode (X packet)
569 * uses 0x7d as escape character */
570 my_checksum += character & 0xff;
572 retval = gdb_get_char_fast(connection, &character, &buf_p, &buf_cnt);
573 if (retval != ERROR_OK)
576 my_checksum += character & 0xff;
577 buffer[count++] = (character ^ 0x20) & 0xff;
579 my_checksum += character & 0xff;
580 buffer[count++] = character & 0xff;
584 gdb_con->buf_p = buf_p;
585 gdb_con->buf_cnt = buf_cnt;
587 if (retval != ERROR_OK)
592 retval = gdb_get_char(connection, &character);
593 if (retval != ERROR_OK)
595 checksum[0] = character;
596 retval = gdb_get_char(connection, &character);
597 if (retval != ERROR_OK)
599 checksum[1] = character;
603 *checksum_ok = (my_checksum == strtoul(checksum, NULL, 16));
608 static int gdb_get_packet_inner(struct connection *connection,
609 char *buffer, int *len)
613 struct gdb_connection *gdb_con = connection->priv;
617 retval = gdb_get_char(connection, &character);
618 if (retval != ERROR_OK)
621 #ifdef _DEBUG_GDB_IO_
622 LOG_DEBUG("character: '%c'", character);
629 /* According to the GDB documentation
630 * (https://sourceware.org/gdb/onlinedocs/gdb/Packet-Acknowledgment.html):
631 * "gdb sends a final `+` acknowledgment of the stub's `OK`
632 * response, which can be safely ignored by the stub."
633 * However OpenOCD server already is in noack mode at this
634 * point and instead of ignoring this it was emitting a
635 * warning. This code makes server ignore the first ACK
636 * that will be received after going into noack mode,
637 * warning only about subsequent ACK's. */
638 if (gdb_con->noack_mode > 1) {
639 LOG_WARNING("acknowledgment received, but no packet pending");
640 } else if (gdb_con->noack_mode) {
641 LOG_DEBUG("Received first acknowledgment after entering noack mode. Ignoring it.");
642 gdb_con->noack_mode = 2;
646 LOG_WARNING("negative acknowledgment, but no packet pending");
653 LOG_WARNING("ignoring character 0x%x", character);
656 } while (character != '$');
659 /* explicit code expansion here to get faster inlined code in -O3 by not
660 * calculating checksum */
661 if (gdb_con->noack_mode) {
662 retval = fetch_packet(connection, &checksum_ok, 1, len, buffer);
663 if (retval != ERROR_OK)
666 retval = fetch_packet(connection, &checksum_ok, 0, len, buffer);
667 if (retval != ERROR_OK)
671 if (gdb_con->noack_mode) {
672 /* checksum is not checked in noack mode */
676 retval = gdb_write(connection, "+", 1);
677 if (retval != ERROR_OK)
683 return ERROR_SERVER_REMOTE_CLOSED;
688 static int gdb_get_packet(struct connection *connection, char *buffer, int *len)
690 struct gdb_connection *gdb_con = connection->priv;
691 gdb_con->busy = true;
692 int retval = gdb_get_packet_inner(connection, buffer, len);
693 gdb_con->busy = false;
697 static int gdb_output_con(struct connection *connection, const char *line)
702 bin_size = strlen(line);
704 hex_buffer = malloc(bin_size * 2 + 2);
705 if (hex_buffer == NULL)
706 return ERROR_GDB_BUFFER_TOO_SMALL;
709 size_t pkt_len = hexify(hex_buffer + 1, (const uint8_t *)line, bin_size,
711 int retval = gdb_put_packet(connection, hex_buffer, pkt_len + 1);
717 static int gdb_output(struct command_context *context, const char *line)
719 /* this will be dumped to the log and also sent as an O packet if possible */
720 LOG_USER_N("%s", line);
724 static void gdb_signal_reply(struct target *target, struct connection *connection)
726 struct gdb_connection *gdb_connection = connection->priv;
728 char stop_reason[20];
729 char current_thread[25];
733 rtos_update_threads(target);
735 if (target->debug_reason == DBG_REASON_EXIT) {
736 sig_reply_len = snprintf(sig_reply, sizeof(sig_reply), "W00");
739 if (target->rtos != NULL) {
740 target->rtos->current_threadid = target->rtos->current_thread;
741 target->rtos->gdb_target_for_threadid(connection, target->rtos->current_threadid, &ct);
746 if (gdb_connection->ctrl_c) {
749 signal_var = gdb_last_signal(ct);
751 stop_reason[0] = '\0';
752 if (ct->debug_reason == DBG_REASON_WATCHPOINT) {
753 enum watchpoint_rw hit_wp_type;
754 target_addr_t hit_wp_address;
756 if (watchpoint_hit(ct, &hit_wp_type, &hit_wp_address) == ERROR_OK) {
758 switch (hit_wp_type) {
760 snprintf(stop_reason, sizeof(stop_reason),
761 "watch:%08" TARGET_PRIxADDR ";", hit_wp_address);
764 snprintf(stop_reason, sizeof(stop_reason),
765 "rwatch:%08" TARGET_PRIxADDR ";", hit_wp_address);
768 snprintf(stop_reason, sizeof(stop_reason),
769 "awatch:%08" TARGET_PRIxADDR ";", hit_wp_address);
777 current_thread[0] = '\0';
778 if (target->rtos != NULL)
779 snprintf(current_thread, sizeof(current_thread), "thread:%" PRIx64 ";",
780 target->rtos->current_thread);
782 sig_reply_len = snprintf(sig_reply, sizeof(sig_reply), "T%2.2x%s%s",
783 signal_var, stop_reason, current_thread);
785 gdb_connection->ctrl_c = 0;
788 gdb_put_packet(connection, sig_reply, sig_reply_len);
789 gdb_connection->frontend_state = TARGET_HALTED;
792 static void gdb_fileio_reply(struct target *target, struct connection *connection)
794 struct gdb_connection *gdb_connection = connection->priv;
795 char fileio_command[256];
797 bool program_exited = false;
799 if (strcmp(target->fileio_info->identifier, "open") == 0)
800 sprintf(fileio_command, "F%s,%" PRIx64 "/%" PRIx64 ",%" PRIx64 ",%" PRIx64, target->fileio_info->identifier,
801 target->fileio_info->param_1,
802 target->fileio_info->param_2,
803 target->fileio_info->param_3,
804 target->fileio_info->param_4);
805 else if (strcmp(target->fileio_info->identifier, "close") == 0)
806 sprintf(fileio_command, "F%s,%" PRIx64, target->fileio_info->identifier,
807 target->fileio_info->param_1);
808 else if (strcmp(target->fileio_info->identifier, "read") == 0)
809 sprintf(fileio_command, "F%s,%" PRIx64 ",%" PRIx64 ",%" PRIx64, target->fileio_info->identifier,
810 target->fileio_info->param_1,
811 target->fileio_info->param_2,
812 target->fileio_info->param_3);
813 else if (strcmp(target->fileio_info->identifier, "write") == 0)
814 sprintf(fileio_command, "F%s,%" PRIx64 ",%" PRIx64 ",%" PRIx64, target->fileio_info->identifier,
815 target->fileio_info->param_1,
816 target->fileio_info->param_2,
817 target->fileio_info->param_3);
818 else if (strcmp(target->fileio_info->identifier, "lseek") == 0)
819 sprintf(fileio_command, "F%s,%" PRIx64 ",%" PRIx64 ",%" PRIx64, target->fileio_info->identifier,
820 target->fileio_info->param_1,
821 target->fileio_info->param_2,
822 target->fileio_info->param_3);
823 else if (strcmp(target->fileio_info->identifier, "rename") == 0)
824 sprintf(fileio_command, "F%s,%" PRIx64 "/%" PRIx64 ",%" PRIx64 "/%" PRIx64, target->fileio_info->identifier,
825 target->fileio_info->param_1,
826 target->fileio_info->param_2,
827 target->fileio_info->param_3,
828 target->fileio_info->param_4);
829 else if (strcmp(target->fileio_info->identifier, "unlink") == 0)
830 sprintf(fileio_command, "F%s,%" PRIx64 "/%" PRIx64, target->fileio_info->identifier,
831 target->fileio_info->param_1,
832 target->fileio_info->param_2);
833 else if (strcmp(target->fileio_info->identifier, "stat") == 0)
834 sprintf(fileio_command, "F%s,%" PRIx64 "/%" PRIx64 ",%" PRIx64, target->fileio_info->identifier,
835 target->fileio_info->param_1,
836 target->fileio_info->param_2,
837 target->fileio_info->param_3);
838 else if (strcmp(target->fileio_info->identifier, "fstat") == 0)
839 sprintf(fileio_command, "F%s,%" PRIx64 ",%" PRIx64, target->fileio_info->identifier,
840 target->fileio_info->param_1,
841 target->fileio_info->param_2);
842 else if (strcmp(target->fileio_info->identifier, "gettimeofday") == 0)
843 sprintf(fileio_command, "F%s,%" PRIx64 ",%" PRIx64, target->fileio_info->identifier,
844 target->fileio_info->param_1,
845 target->fileio_info->param_2);
846 else if (strcmp(target->fileio_info->identifier, "isatty") == 0)
847 sprintf(fileio_command, "F%s,%" PRIx64, target->fileio_info->identifier,
848 target->fileio_info->param_1);
849 else if (strcmp(target->fileio_info->identifier, "system") == 0)
850 sprintf(fileio_command, "F%s,%" PRIx64 "/%" PRIx64, target->fileio_info->identifier,
851 target->fileio_info->param_1,
852 target->fileio_info->param_2);
853 else if (strcmp(target->fileio_info->identifier, "exit") == 0) {
854 /* If target hits exit syscall, report to GDB the program is terminated.
855 * In addition, let target run its own exit syscall handler. */
856 program_exited = true;
857 sprintf(fileio_command, "W%02" PRIx64, target->fileio_info->param_1);
859 LOG_DEBUG("Unknown syscall: %s", target->fileio_info->identifier);
861 /* encounter unknown syscall, continue */
862 gdb_connection->frontend_state = TARGET_RUNNING;
863 target_resume(target, 1, 0x0, 0, 0);
867 command_len = strlen(fileio_command);
868 gdb_put_packet(connection, fileio_command, command_len);
870 if (program_exited) {
871 /* Use target_resume() to let target run its own exit syscall handler. */
872 gdb_connection->frontend_state = TARGET_RUNNING;
873 target_resume(target, 1, 0x0, 0, 0);
875 gdb_connection->frontend_state = TARGET_HALTED;
876 rtos_update_threads(target);
880 static void gdb_frontend_halted(struct target *target, struct connection *connection)
882 struct gdb_connection *gdb_connection = connection->priv;
884 /* In the GDB protocol when we are stepping or continuing execution,
885 * we have a lingering reply. Upon receiving a halted event
886 * when we have that lingering packet, we reply to the original
887 * step or continue packet.
889 * Executing monitor commands can bring the target in and
890 * out of the running state so we'll see lots of TARGET_EVENT_XXX
891 * that are to be ignored.
893 if (gdb_connection->frontend_state == TARGET_RUNNING) {
894 /* stop forwarding log packets! */
895 log_remove_callback(gdb_log_callback, connection);
897 /* check fileio first */
898 if (target_get_gdb_fileio_info(target, target->fileio_info) == ERROR_OK)
899 gdb_fileio_reply(target, connection);
901 gdb_signal_reply(target, connection);
905 static int gdb_target_callback_event_handler(struct target *target,
906 enum target_event event, void *priv)
908 struct connection *connection = priv;
909 struct gdb_service *gdb_service = connection->service->priv;
911 if (gdb_service->target != target)
915 case TARGET_EVENT_GDB_HALT:
916 gdb_frontend_halted(target, connection);
918 case TARGET_EVENT_HALTED:
919 target_call_event_callbacks(target, TARGET_EVENT_GDB_END);
928 static int gdb_new_connection(struct connection *connection)
930 struct gdb_connection *gdb_connection = malloc(sizeof(struct gdb_connection));
931 struct target *target;
935 target = get_target_from_connection(connection);
936 connection->priv = gdb_connection;
937 connection->cmd_ctx->current_target = target;
939 /* initialize gdb connection information */
940 gdb_connection->buf_p = gdb_connection->buffer;
941 gdb_connection->buf_cnt = 0;
942 gdb_connection->ctrl_c = 0;
943 gdb_connection->frontend_state = TARGET_HALTED;
944 gdb_connection->vflash_image = NULL;
945 gdb_connection->closed = false;
946 gdb_connection->busy = false;
947 gdb_connection->noack_mode = 0;
948 gdb_connection->sync = false;
949 gdb_connection->mem_write_error = false;
950 gdb_connection->attached = true;
951 gdb_connection->target_desc.tdesc = NULL;
952 gdb_connection->target_desc.tdesc_length = 0;
953 gdb_connection->thread_list = NULL;
955 /* send ACK to GDB for debug request */
956 gdb_write(connection, "+", 1);
958 /* output goes through gdb connection */
959 command_set_output_handler(connection->cmd_ctx, gdb_output, connection);
961 /* we must remove all breakpoints registered to the target as a previous
962 * GDB session could leave dangling breakpoints if e.g. communication
965 breakpoint_clear_target(target);
966 watchpoint_clear_target(target);
969 /* clean previous rtos session if supported*/
970 if (target->rtos->type->clean)
971 target->rtos->type->clean(target);
974 rtos_update_threads(target);
977 /* remove the initial ACK from the incoming buffer */
978 retval = gdb_get_char(connection, &initial_ack);
979 if (retval != ERROR_OK)
982 /* FIX!!!??? would we actually ever receive a + here???
985 if (initial_ack != '+')
986 gdb_putback_char(connection, initial_ack);
987 target_call_event_callbacks(target, TARGET_EVENT_GDB_ATTACH);
989 if (gdb_use_memory_map) {
990 /* Connect must fail if the memory map can't be set up correctly.
992 * This will cause an auto_probe to be invoked, which is either
993 * a no-op or it will fail when the target isn't ready(e.g. not halted).
996 for (i = 0; i < flash_get_bank_count(); i++) {
997 struct flash_bank *p;
998 p = get_flash_bank_by_num_noprobe(i);
999 if (p->target != target)
1001 retval = get_flash_bank_by_num(i, &p);
1002 if (retval != ERROR_OK) {
1003 LOG_ERROR("Connect failed. Consider setting up a gdb-attach event for the target " \
1004 "to prepare target for GDB connect, or use 'gdb_memory_map disable'.");
1010 gdb_actual_connections++;
1011 log_printf_lf(all_targets->next != NULL ? LOG_LVL_INFO : LOG_LVL_DEBUG,
1012 __FILE__, __LINE__, __func__,
1013 "New GDB Connection: %d, Target %s, state: %s",
1014 gdb_actual_connections,
1015 target_name(target),
1016 target_state_name(target));
1018 /* DANGER! If we fail subsequently, we must remove this handler,
1019 * otherwise we occasionally see crashes as the timer can invoke the
1022 * register callback to be informed about target events */
1023 target_register_event_callback(gdb_target_callback_event_handler, connection);
1028 static int gdb_connection_closed(struct connection *connection)
1030 struct target *target;
1031 struct gdb_connection *gdb_connection = connection->priv;
1033 target = get_target_from_connection(connection);
1035 /* we're done forwarding messages. Tear down callback before
1036 * cleaning up connection.
1038 log_remove_callback(gdb_log_callback, connection);
1040 gdb_actual_connections--;
1041 LOG_DEBUG("GDB Close, Target: %s, state: %s, gdb_actual_connections=%d",
1042 target_name(target),
1043 target_state_name(target),
1044 gdb_actual_connections);
1046 /* see if an image built with vFlash commands is left */
1047 if (gdb_connection->vflash_image) {
1048 image_close(gdb_connection->vflash_image);
1049 free(gdb_connection->vflash_image);
1050 gdb_connection->vflash_image = NULL;
1053 /* if this connection registered a debug-message receiver delete it */
1054 delete_debug_msg_receiver(connection->cmd_ctx, target);
1056 if (connection->priv) {
1057 free(connection->priv);
1058 connection->priv = NULL;
1060 LOG_ERROR("BUG: connection->priv == NULL");
1062 target_unregister_event_callback(gdb_target_callback_event_handler, connection);
1064 target_call_event_callbacks(target, TARGET_EVENT_GDB_END);
1066 target_call_event_callbacks(target, TARGET_EVENT_GDB_DETACH);
1071 static void gdb_send_error(struct connection *connection, uint8_t the_error)
1074 snprintf(err, 4, "E%2.2X", the_error);
1075 gdb_put_packet(connection, err, 3);
1078 static int gdb_last_signal_packet(struct connection *connection,
1079 char const *packet, int packet_size)
1081 struct target *target = get_target_from_connection(connection);
1082 struct gdb_connection *gdb_con = connection->priv;
1086 if (!gdb_con->attached) {
1087 /* if we are here we have received a kill packet
1088 * reply W stop reply otherwise gdb gets very unhappy */
1089 gdb_put_packet(connection, "W00", 3);
1093 signal_var = gdb_last_signal(target);
1095 snprintf(sig_reply, 4, "S%2.2x", signal_var);
1096 gdb_put_packet(connection, sig_reply, 3);
1101 static inline int gdb_reg_pos(struct target *target, int pos, int len)
1103 if (target->endianness == TARGET_LITTLE_ENDIAN)
1106 return len - 1 - pos;
1109 /* Convert register to string of bytes. NB! The # of bits in the
1110 * register might be non-divisible by 8(a byte), in which
1111 * case an entire byte is shown.
1113 * NB! the format on the wire is the target endianness
1115 * The format of reg->value is little endian
1118 static void gdb_str_to_target(struct target *target,
1119 char *tstr, struct reg *reg)
1126 buf_len = DIV_ROUND_UP(reg->size, 8);
1128 for (i = 0; i < buf_len; i++) {
1129 int j = gdb_reg_pos(target, i, buf_len);
1130 tstr += sprintf(tstr, "%02x", buf[j]);
1134 /* copy over in register buffer */
1135 static void gdb_target_to_reg(struct target *target,
1136 char const *tstr, int str_len, uint8_t *bin)
1139 LOG_ERROR("BUG: gdb value with uneven number of characters encountered");
1144 for (i = 0; i < str_len; i += 2) {
1146 if (sscanf(tstr + i, "%02x", &t) != 1) {
1147 LOG_ERROR("BUG: unable to convert register value");
1151 int j = gdb_reg_pos(target, i/2, str_len/2);
1156 static int gdb_get_registers_packet(struct connection *connection,
1157 char const *packet, int packet_size)
1159 struct target *target = get_target_from_connection(connection);
1160 struct reg **reg_list;
1163 int reg_packet_size = 0;
1168 #ifdef _DEBUG_GDB_IO_
1172 if ((target->rtos != NULL) && (ERROR_OK == rtos_get_gdb_reg_list(connection)))
1175 retval = target_get_gdb_reg_list(target, ®_list, ®_list_size,
1177 if (retval != ERROR_OK)
1178 return gdb_error(connection, retval);
1180 for (i = 0; i < reg_list_size; i++) {
1181 if (reg_list[i] == NULL || reg_list[i]->exist == false)
1183 reg_packet_size += DIV_ROUND_UP(reg_list[i]->size, 8) * 2;
1186 assert(reg_packet_size > 0);
1188 reg_packet = malloc(reg_packet_size + 1); /* plus one for string termination null */
1189 if (reg_packet == NULL)
1192 reg_packet_p = reg_packet;
1194 for (i = 0; i < reg_list_size; i++) {
1195 if (reg_list[i] == NULL || reg_list[i]->exist == false)
1197 if (!reg_list[i]->valid) {
1198 retval = reg_list[i]->type->get(reg_list[i]);
1199 if (retval != ERROR_OK && gdb_report_register_access_error) {
1200 LOG_DEBUG("Couldn't get register %s.", reg_list[i]->name);
1203 return gdb_error(connection, retval);
1206 gdb_str_to_target(target, reg_packet_p, reg_list[i]);
1207 reg_packet_p += DIV_ROUND_UP(reg_list[i]->size, 8) * 2;
1210 #ifdef _DEBUG_GDB_IO_
1212 char *reg_packet_p_debug;
1213 reg_packet_p_debug = strndup(reg_packet, reg_packet_size);
1214 LOG_DEBUG("reg_packet: %s", reg_packet_p_debug);
1215 free(reg_packet_p_debug);
1219 gdb_put_packet(connection, reg_packet, reg_packet_size);
1227 static int gdb_set_registers_packet(struct connection *connection,
1228 char const *packet, int packet_size)
1230 struct target *target = get_target_from_connection(connection);
1232 struct reg **reg_list;
1235 char const *packet_p;
1237 #ifdef _DEBUG_GDB_IO_
1241 /* skip command character */
1245 if (packet_size % 2) {
1246 LOG_WARNING("GDB set_registers packet with uneven characters received, dropping connection");
1247 return ERROR_SERVER_REMOTE_CLOSED;
1250 retval = target_get_gdb_reg_list(target, ®_list, ®_list_size,
1252 if (retval != ERROR_OK)
1253 return gdb_error(connection, retval);
1256 for (i = 0; i < reg_list_size; i++) {
1258 int chars = (DIV_ROUND_UP(reg_list[i]->size, 8) * 2);
1260 if (packet_p + chars > packet + packet_size)
1261 LOG_ERROR("BUG: register packet is too small for registers");
1263 bin_buf = malloc(DIV_ROUND_UP(reg_list[i]->size, 8));
1264 gdb_target_to_reg(target, packet_p, chars, bin_buf);
1266 retval = reg_list[i]->type->set(reg_list[i], bin_buf);
1267 if (retval != ERROR_OK && gdb_report_register_access_error) {
1268 LOG_DEBUG("Couldn't set register %s.", reg_list[i]->name);
1271 return gdb_error(connection, retval);
1274 /* advance packet pointer */
1280 /* free struct reg *reg_list[] array allocated by get_gdb_reg_list */
1283 gdb_put_packet(connection, "OK", 2);
1288 static int gdb_get_register_packet(struct connection *connection,
1289 char const *packet, int packet_size)
1291 struct target *target = get_target_from_connection(connection);
1293 int reg_num = strtoul(packet + 1, NULL, 16);
1294 struct reg **reg_list;
1298 #ifdef _DEBUG_GDB_IO_
1302 if ((target->rtos != NULL) && (ERROR_OK == rtos_get_gdb_reg(connection, reg_num)))
1305 retval = target_get_gdb_reg_list_noread(target, ®_list, ®_list_size,
1307 if (retval != ERROR_OK)
1308 return gdb_error(connection, retval);
1310 if (reg_list_size <= reg_num) {
1311 LOG_ERROR("gdb requested a non-existing register");
1312 return ERROR_SERVER_REMOTE_CLOSED;
1315 if (!reg_list[reg_num]->valid) {
1316 retval = reg_list[reg_num]->type->get(reg_list[reg_num]);
1317 if (retval != ERROR_OK && gdb_report_register_access_error) {
1318 LOG_DEBUG("Couldn't get register %s.", reg_list[reg_num]->name);
1320 return gdb_error(connection, retval);
1324 reg_packet = malloc(DIV_ROUND_UP(reg_list[reg_num]->size, 8) * 2 + 1); /* plus one for string termination null */
1326 gdb_str_to_target(target, reg_packet, reg_list[reg_num]);
1328 gdb_put_packet(connection, reg_packet, DIV_ROUND_UP(reg_list[reg_num]->size, 8) * 2);
1336 static int gdb_set_register_packet(struct connection *connection,
1337 char const *packet, int packet_size)
1339 struct target *target = get_target_from_connection(connection);
1341 int reg_num = strtoul(packet + 1, &separator, 16);
1342 struct reg **reg_list;
1346 #ifdef _DEBUG_GDB_IO_
1350 if (*separator != '=') {
1351 LOG_ERROR("GDB 'set register packet', but no '=' following the register number");
1352 return ERROR_SERVER_REMOTE_CLOSED;
1354 size_t chars = strlen(separator + 1);
1355 uint8_t *bin_buf = malloc(chars / 2);
1356 gdb_target_to_reg(target, separator + 1, chars, bin_buf);
1358 if ((target->rtos != NULL) &&
1359 (ERROR_OK == rtos_set_reg(connection, reg_num, bin_buf))) {
1361 gdb_put_packet(connection, "OK", 2);
1365 retval = target_get_gdb_reg_list_noread(target, ®_list, ®_list_size,
1367 if (retval != ERROR_OK) {
1369 return gdb_error(connection, retval);
1372 if (reg_list_size <= reg_num) {
1373 LOG_ERROR("gdb requested a non-existing register");
1376 return ERROR_SERVER_REMOTE_CLOSED;
1379 if (chars != (DIV_ROUND_UP(reg_list[reg_num]->size, 8) * 2)) {
1380 LOG_ERROR("gdb sent %d bits for a %d-bit register (%s)",
1381 (int) chars * 4, reg_list[reg_num]->size, reg_list[reg_num]->name);
1384 return ERROR_SERVER_REMOTE_CLOSED;
1387 gdb_target_to_reg(target, separator + 1, chars, bin_buf);
1389 retval = reg_list[reg_num]->type->set(reg_list[reg_num], bin_buf);
1390 if (retval != ERROR_OK && gdb_report_register_access_error) {
1391 LOG_DEBUG("Couldn't set register %s.", reg_list[reg_num]->name);
1394 return gdb_error(connection, retval);
1397 gdb_put_packet(connection, "OK", 2);
1405 /* No attempt is made to translate the "retval" to
1406 * GDB speak. This has to be done at the calling
1407 * site as no mapping really exists.
1409 static int gdb_error(struct connection *connection, int retval)
1411 LOG_DEBUG("Reporting %i to GDB as generic error", retval);
1412 gdb_send_error(connection, EFAULT);
1416 /* We don't have to worry about the default 2 second timeout for GDB packets,
1417 * because GDB breaks up large memory reads into smaller reads.
1419 static int gdb_read_memory_packet(struct connection *connection,
1420 char const *packet, int packet_size)
1422 struct target *target = get_target_from_connection(connection);
1430 int retval = ERROR_OK;
1432 /* skip command character */
1435 addr = strtoull(packet, &separator, 16);
1437 if (*separator != ',') {
1438 LOG_ERROR("incomplete read memory packet received, dropping connection");
1439 return ERROR_SERVER_REMOTE_CLOSED;
1442 len = strtoul(separator + 1, NULL, 16);
1445 LOG_WARNING("invalid read memory packet received (len == 0)");
1446 gdb_put_packet(connection, "", 0);
1450 buffer = malloc(len);
1452 LOG_DEBUG("addr: 0x%16.16" PRIx64 ", len: 0x%8.8" PRIx32 "", addr, len);
1454 retval = target_read_buffer(target, addr, len, buffer);
1456 if ((retval != ERROR_OK) && !gdb_report_data_abort) {
1457 /* TODO : Here we have to lie and send back all zero's lest stack traces won't work.
1458 * At some point this might be fixed in GDB, in which case this code can be removed.
1460 * OpenOCD developers are acutely aware of this problem, but there is nothing
1461 * gained by involving the user in this problem that hopefully will get resolved
1464 * http://sourceware.org/cgi-bin/gnatsweb.pl? \
1465 * cmd = view%20audit-trail&database = gdb&pr = 2395
1467 * For now, the default is to fix up things to make current GDB versions work.
1468 * This can be overwritten using the gdb_report_data_abort <'enable'|'disable'> command.
1470 memset(buffer, 0, len);
1474 if (retval == ERROR_OK) {
1475 hex_buffer = malloc(len * 2 + 1);
1477 size_t pkt_len = hexify(hex_buffer, buffer, len, len * 2 + 1);
1479 gdb_put_packet(connection, hex_buffer, pkt_len);
1483 retval = gdb_error(connection, retval);
1490 static int gdb_write_memory_packet(struct connection *connection,
1491 char const *packet, int packet_size)
1493 struct target *target = get_target_from_connection(connection);
1501 /* skip command character */
1504 addr = strtoull(packet, &separator, 16);
1506 if (*separator != ',') {
1507 LOG_ERROR("incomplete write memory packet received, dropping connection");
1508 return ERROR_SERVER_REMOTE_CLOSED;
1511 len = strtoul(separator + 1, &separator, 16);
1513 if (*(separator++) != ':') {
1514 LOG_ERROR("incomplete write memory packet received, dropping connection");
1515 return ERROR_SERVER_REMOTE_CLOSED;
1518 buffer = malloc(len);
1520 LOG_DEBUG("addr: 0x%" PRIx64 ", len: 0x%8.8" PRIx32 "", addr, len);
1522 if (unhexify(buffer, separator, len) != len)
1523 LOG_ERROR("unable to decode memory packet");
1525 retval = target_write_buffer(target, addr, len, buffer);
1527 if (retval == ERROR_OK)
1528 gdb_put_packet(connection, "OK", 2);
1530 retval = gdb_error(connection, retval);
1537 static int gdb_write_memory_binary_packet(struct connection *connection,
1538 char const *packet, int packet_size)
1540 struct target *target = get_target_from_connection(connection);
1545 int retval = ERROR_OK;
1546 /* Packets larger than fast_limit bytes will be acknowledged instantly on
1547 * the assumption that we're in a download and it's important to go as fast
1549 uint32_t fast_limit = 8;
1551 /* skip command character */
1554 addr = strtoull(packet, &separator, 16);
1556 if (*separator != ',') {
1557 LOG_ERROR("incomplete write memory binary packet received, dropping connection");
1558 return ERROR_SERVER_REMOTE_CLOSED;
1561 len = strtoul(separator + 1, &separator, 16);
1563 if (*(separator++) != ':') {
1564 LOG_ERROR("incomplete write memory binary packet received, dropping connection");
1565 return ERROR_SERVER_REMOTE_CLOSED;
1568 struct gdb_connection *gdb_connection = connection->priv;
1570 if (gdb_connection->mem_write_error)
1571 retval = ERROR_FAIL;
1573 if (retval == ERROR_OK) {
1574 if (len >= fast_limit) {
1575 /* By replying the packet *immediately* GDB will send us a new packet
1576 * while we write the last one to the target.
1577 * We only do this for larger writes, so that users who do something like:
1578 * p *((int*)0xdeadbeef)=8675309
1579 * will get immediate feedback that that write failed.
1581 gdb_put_packet(connection, "OK", 2);
1584 retval = gdb_error(connection, retval);
1585 /* now that we have reported the memory write error, we can clear the condition */
1586 gdb_connection->mem_write_error = false;
1587 if (retval != ERROR_OK)
1592 LOG_DEBUG("addr: 0x%" PRIx64 ", len: 0x%8.8" PRIx32 "", addr, len);
1594 retval = target_write_buffer(target, addr, len, (uint8_t *)separator);
1595 if (retval != ERROR_OK)
1596 gdb_connection->mem_write_error = true;
1599 if (len < fast_limit) {
1600 if (retval != ERROR_OK) {
1601 gdb_error(connection, retval);
1602 gdb_connection->mem_write_error = false;
1604 gdb_put_packet(connection, "OK", 2);
1611 static int gdb_step_continue_packet(struct connection *connection,
1612 char const *packet, int packet_size)
1614 struct target *target = get_target_from_connection(connection);
1616 uint64_t address = 0x0;
1617 int retval = ERROR_OK;
1621 if (packet_size > 1)
1622 address = strtoull(packet + 1, NULL, 16);
1626 gdb_running_type = packet[0];
1627 if (packet[0] == 'c') {
1628 LOG_DEBUG("continue");
1629 /* resume at current address, don't handle breakpoints, not debugging */
1630 retval = target_resume(target, current, address, 0, 0);
1631 } else if (packet[0] == 's') {
1633 /* step at current or address, don't handle breakpoints */
1634 retval = target_step(target, current, address, 0);
1639 static int gdb_breakpoint_watchpoint_packet(struct connection *connection,
1640 char const *packet, int packet_size)
1642 struct target *target = get_target_from_connection(connection);
1644 enum breakpoint_type bp_type = BKPT_SOFT /* dummy init to avoid warning */;
1645 enum watchpoint_rw wp_type = WPT_READ /* dummy init to avoid warning */;
1651 LOG_DEBUG("[%s]", target_name(target));
1653 type = strtoul(packet + 1, &separator, 16);
1655 if (type == 0) /* memory breakpoint */
1656 bp_type = BKPT_SOFT;
1657 else if (type == 1) /* hardware breakpoint */
1658 bp_type = BKPT_HARD;
1659 else if (type == 2) /* write watchpoint */
1660 wp_type = WPT_WRITE;
1661 else if (type == 3) /* read watchpoint */
1663 else if (type == 4) /* access watchpoint */
1664 wp_type = WPT_ACCESS;
1666 LOG_ERROR("invalid gdb watch/breakpoint type(%d), dropping connection", type);
1667 return ERROR_SERVER_REMOTE_CLOSED;
1670 if (gdb_breakpoint_override && ((bp_type == BKPT_SOFT) || (bp_type == BKPT_HARD)))
1671 bp_type = gdb_breakpoint_override_type;
1673 if (*separator != ',') {
1674 LOG_ERROR("incomplete breakpoint/watchpoint packet received, dropping connection");
1675 return ERROR_SERVER_REMOTE_CLOSED;
1678 address = strtoull(separator + 1, &separator, 16);
1680 if (*separator != ',') {
1681 LOG_ERROR("incomplete breakpoint/watchpoint packet received, dropping connection");
1682 return ERROR_SERVER_REMOTE_CLOSED;
1685 size = strtoul(separator + 1, &separator, 16);
1690 if (packet[0] == 'Z') {
1691 retval = breakpoint_add(target, address, size, bp_type);
1692 if (retval != ERROR_OK) {
1693 retval = gdb_error(connection, retval);
1694 if (retval != ERROR_OK)
1697 gdb_put_packet(connection, "OK", 2);
1699 breakpoint_remove(target, address);
1700 gdb_put_packet(connection, "OK", 2);
1707 if (packet[0] == 'Z') {
1708 retval = watchpoint_add(target, address, size, wp_type, 0, 0xffffffffu);
1709 if (retval != ERROR_OK) {
1710 retval = gdb_error(connection, retval);
1711 if (retval != ERROR_OK)
1714 gdb_put_packet(connection, "OK", 2);
1716 watchpoint_remove(target, address);
1717 gdb_put_packet(connection, "OK", 2);
1728 /* print out a string and allocate more space as needed,
1729 * mainly used for XML at this point
1731 static void xml_printf(int *retval, char **xml, int *pos, int *size,
1732 const char *fmt, ...)
1734 if (*retval != ERROR_OK)
1739 if ((*xml == NULL) || (!first)) {
1740 /* start by 0 to exercise all the code paths.
1741 * Need minimum 2 bytes to fit 1 char and 0 terminator. */
1743 *size = *size * 2 + 2;
1745 *xml = realloc(*xml, *size);
1749 *retval = ERROR_SERVER_REMOTE_CLOSED;
1757 ret = vsnprintf(*xml + *pos, *size - *pos, fmt, ap);
1759 if ((ret > 0) && ((ret + 1) < *size - *pos)) {
1763 /* there was just enough or not enough space, allocate more. */
1768 static int decode_xfer_read(char const *buf, char **annex, int *ofs, unsigned int *len)
1770 /* Locate the annex. */
1771 const char *annex_end = strchr(buf, ':');
1772 if (annex_end == NULL)
1775 /* After the read marker and annex, qXfer looks like a
1776 * traditional 'm' packet. */
1778 *ofs = strtoul(annex_end + 1, &separator, 16);
1780 if (*separator != ',')
1783 *len = strtoul(separator + 1, NULL, 16);
1785 /* Extract the annex if needed */
1786 if (annex != NULL) {
1787 *annex = strndup(buf, annex_end - buf);
1795 static int compare_bank(const void *a, const void *b)
1797 struct flash_bank *b1, *b2;
1798 b1 = *((struct flash_bank **)a);
1799 b2 = *((struct flash_bank **)b);
1801 if (b1->base == b2->base)
1803 else if (b1->base > b2->base)
1809 static int gdb_memory_map(struct connection *connection,
1810 char const *packet, int packet_size)
1812 /* We get away with only specifying flash here. Regions that are not
1813 * specified are treated as if we provided no memory map(if not we
1814 * could detect the holes and mark them as RAM).
1815 * Normally we only execute this code once, but no big deal if we
1816 * have to regenerate it a couple of times.
1819 struct target *target = get_target_from_connection(connection);
1820 struct flash_bank *p;
1824 int retval = ERROR_OK;
1825 struct flash_bank **banks;
1829 target_addr_t ram_start = 0;
1831 int target_flash_banks = 0;
1833 /* skip command character */
1836 offset = strtoul(packet, &separator, 16);
1837 length = strtoul(separator + 1, &separator, 16);
1839 xml_printf(&retval, &xml, &pos, &size, "<memory-map>\n");
1841 /* Sort banks in ascending order. We need to report non-flash
1842 * memory as ram (or rather read/write) by default for GDB, since
1843 * it has no concept of non-cacheable read/write memory (i/o etc).
1845 banks = malloc(sizeof(struct flash_bank *)*flash_get_bank_count());
1847 for (i = 0; i < flash_get_bank_count(); i++) {
1848 p = get_flash_bank_by_num_noprobe(i);
1849 if (p->target != target)
1851 retval = get_flash_bank_by_num(i, &p);
1852 if (retval != ERROR_OK) {
1854 gdb_error(connection, retval);
1857 banks[target_flash_banks++] = p;
1860 qsort(banks, target_flash_banks, sizeof(struct flash_bank *),
1863 for (i = 0; i < target_flash_banks; i++) {
1865 unsigned sector_size = 0;
1866 unsigned group_len = 0;
1870 if (ram_start < p->base)
1871 xml_printf(&retval, &xml, &pos, &size,
1872 "<memory type=\"ram\" start=\"" TARGET_ADDR_FMT "\" "
1873 "length=\"0x%x\"/>\n",
1874 ram_start, p->base - ram_start);
1876 /* Report adjacent groups of same-size sectors. So for
1877 * example top boot CFI flash will list an initial region
1878 * with several large sectors (maybe 128KB) and several
1879 * smaller ones at the end (maybe 32KB). STR7 will have
1880 * regions with 8KB, 32KB, and 64KB sectors; etc.
1882 for (j = 0; j < p->num_sectors; j++) {
1884 /* Maybe start a new group of sectors. */
1885 if (sector_size == 0) {
1886 if (p->sectors[j].offset + p->sectors[j].size > p->size) {
1887 LOG_WARNING("The flash sector at offset 0x%08" PRIx32
1888 " overflows the end of %s bank.",
1889 p->sectors[j].offset, p->name);
1890 LOG_WARNING("The rest of bank will not show in gdb memory map.");
1893 target_addr_t start;
1894 start = p->base + p->sectors[j].offset;
1895 xml_printf(&retval, &xml, &pos, &size,
1896 "<memory type=\"flash\" "
1897 "start=\"" TARGET_ADDR_FMT "\" ",
1899 sector_size = p->sectors[j].size;
1900 group_len = sector_size;
1902 group_len += sector_size; /* equal to p->sectors[j].size */
1905 /* Does this finish a group of sectors?
1906 * If not, continue an already-started group.
1908 if (j < p->num_sectors - 1
1909 && p->sectors[j + 1].size == sector_size
1910 && p->sectors[j + 1].offset == p->sectors[j].offset + sector_size
1911 && p->sectors[j + 1].offset + p->sectors[j + 1].size <= p->size)
1914 xml_printf(&retval, &xml, &pos, &size,
1915 "length=\"0x%x\">\n"
1916 "<property name=\"blocksize\">"
1924 ram_start = p->base + p->size;
1928 xml_printf(&retval, &xml, &pos, &size,
1929 "<memory type=\"ram\" start=\"" TARGET_ADDR_FMT "\" "
1930 "length=\"" TARGET_ADDR_FMT "\"/>\n",
1931 ram_start, target_address_max(target) - ram_start + 1);
1932 /* ELSE a flash chip could be at the very end of the address space, in
1933 * which case ram_start will be precisely 0 */
1937 xml_printf(&retval, &xml, &pos, &size, "</memory-map>\n");
1939 if (retval != ERROR_OK) {
1941 gdb_error(connection, retval);
1945 if (offset + length > pos)
1946 length = pos - offset;
1948 char *t = malloc(length + 1);
1950 memcpy(t + 1, xml + offset, length);
1951 gdb_put_packet(connection, t, length + 1);
1958 static const char *gdb_get_reg_type_name(enum reg_type type)
1967 case REG_TYPE_INT16:
1969 case REG_TYPE_INT32:
1971 case REG_TYPE_INT64:
1973 case REG_TYPE_INT128:
1977 case REG_TYPE_UINT8:
1979 case REG_TYPE_UINT16:
1981 case REG_TYPE_UINT32:
1983 case REG_TYPE_UINT64:
1985 case REG_TYPE_UINT128:
1987 case REG_TYPE_CODE_PTR:
1989 case REG_TYPE_DATA_PTR:
1991 case REG_TYPE_FLOAT:
1993 case REG_TYPE_IEEE_SINGLE:
1994 return "ieee_single";
1995 case REG_TYPE_IEEE_DOUBLE:
1996 return "ieee_double";
1997 case REG_TYPE_ARCH_DEFINED:
1998 return "int"; /* return arbitrary string to avoid compile warning. */
2001 return "int"; /* "int" as default value */
2004 static int lookup_add_arch_defined_types(char const **arch_defined_types_list[], const char *type_id,
2005 int *num_arch_defined_types)
2007 int tbl_sz = *num_arch_defined_types;
2009 if (type_id != NULL && (strcmp(type_id, ""))) {
2010 for (int j = 0; j < (tbl_sz + 1); j++) {
2011 if (!((*arch_defined_types_list)[j])) {
2012 (*arch_defined_types_list)[tbl_sz++] = type_id;
2013 *arch_defined_types_list = realloc(*arch_defined_types_list,
2014 sizeof(char *) * (tbl_sz + 1));
2015 (*arch_defined_types_list)[tbl_sz] = NULL;
2016 *num_arch_defined_types = tbl_sz;
2019 if (!strcmp((*arch_defined_types_list)[j], type_id))
2028 static int gdb_generate_reg_type_description(struct target *target,
2029 char **tdesc, int *pos, int *size, struct reg_data_type *type,
2030 char const **arch_defined_types_list[], int * num_arch_defined_types)
2032 int retval = ERROR_OK;
2034 if (type->type_class == REG_TYPE_CLASS_VECTOR) {
2035 struct reg_data_type *data_type = type->reg_type_vector->type;
2036 if (data_type->type == REG_TYPE_ARCH_DEFINED) {
2037 if (lookup_add_arch_defined_types(arch_defined_types_list, data_type->id,
2038 num_arch_defined_types))
2039 gdb_generate_reg_type_description(target, tdesc, pos, size, data_type,
2040 arch_defined_types_list,
2041 num_arch_defined_types);
2043 /* <vector id="id" type="type" count="count"/> */
2044 xml_printf(&retval, tdesc, pos, size,
2045 "<vector id=\"%s\" type=\"%s\" count=\"%d\"/>\n",
2046 type->id, type->reg_type_vector->type->id,
2047 type->reg_type_vector->count);
2049 } else if (type->type_class == REG_TYPE_CLASS_UNION) {
2050 struct reg_data_type_union_field *field;
2051 field = type->reg_type_union->fields;
2052 while (field != NULL) {
2053 struct reg_data_type *data_type = field->type;
2054 if (data_type->type == REG_TYPE_ARCH_DEFINED) {
2055 if (lookup_add_arch_defined_types(arch_defined_types_list, data_type->id,
2056 num_arch_defined_types))
2057 gdb_generate_reg_type_description(target, tdesc, pos, size, data_type,
2058 arch_defined_types_list,
2059 num_arch_defined_types);
2062 field = field->next;
2065 * <field name="name" type="type"/> ...
2067 xml_printf(&retval, tdesc, pos, size,
2068 "<union id=\"%s\">\n",
2071 field = type->reg_type_union->fields;
2072 while (field != NULL) {
2073 xml_printf(&retval, tdesc, pos, size,
2074 "<field name=\"%s\" type=\"%s\"/>\n",
2075 field->name, field->type->id);
2077 field = field->next;
2080 xml_printf(&retval, tdesc, pos, size,
2083 } else if (type->type_class == REG_TYPE_CLASS_STRUCT) {
2084 struct reg_data_type_struct_field *field;
2085 field = type->reg_type_struct->fields;
2087 if (field->use_bitfields) {
2088 /* <struct id="id" size="size">
2089 * <field name="name" start="start" end="end"/> ...
2091 xml_printf(&retval, tdesc, pos, size,
2092 "<struct id=\"%s\" size=\"%d\">\n",
2093 type->id, type->reg_type_struct->size);
2094 while (field != NULL) {
2095 xml_printf(&retval, tdesc, pos, size,
2096 "<field name=\"%s\" start=\"%d\" end=\"%d\" type=\"%s\" />\n",
2097 field->name, field->bitfield->start, field->bitfield->end,
2098 gdb_get_reg_type_name(field->bitfield->type));
2100 field = field->next;
2103 while (field != NULL) {
2104 struct reg_data_type *data_type = field->type;
2105 if (data_type->type == REG_TYPE_ARCH_DEFINED) {
2106 if (lookup_add_arch_defined_types(arch_defined_types_list, data_type->id,
2107 num_arch_defined_types))
2108 gdb_generate_reg_type_description(target, tdesc, pos, size, data_type,
2109 arch_defined_types_list,
2110 num_arch_defined_types);
2115 * <field name="name" type="type"/> ...
2117 xml_printf(&retval, tdesc, pos, size,
2118 "<struct id=\"%s\">\n",
2120 while (field != NULL) {
2121 xml_printf(&retval, tdesc, pos, size,
2122 "<field name=\"%s\" type=\"%s\"/>\n",
2123 field->name, field->type->id);
2125 field = field->next;
2129 xml_printf(&retval, tdesc, pos, size,
2132 } else if (type->type_class == REG_TYPE_CLASS_FLAGS) {
2133 /* <flags id="id" size="size">
2134 * <field name="name" start="start" end="end"/> ...
2136 xml_printf(&retval, tdesc, pos, size,
2137 "<flags id=\"%s\" size=\"%d\">\n",
2138 type->id, type->reg_type_flags->size);
2140 struct reg_data_type_flags_field *field;
2141 field = type->reg_type_flags->fields;
2142 while (field != NULL) {
2143 xml_printf(&retval, tdesc, pos, size,
2144 "<field name=\"%s\" start=\"%d\" end=\"%d\" type=\"%s\" />\n",
2145 field->name, field->bitfield->start, field->bitfield->end,
2146 gdb_get_reg_type_name(field->bitfield->type));
2148 field = field->next;
2151 xml_printf(&retval, tdesc, pos, size,
2159 /* Get a list of available target registers features. feature_list must
2160 * be freed by caller.
2162 static int get_reg_features_list(struct target *target, char const **feature_list[], int *feature_list_size,
2163 struct reg **reg_list, int reg_list_size)
2167 /* Start with only one element */
2168 *feature_list = calloc(1, sizeof(char *));
2170 for (int i = 0; i < reg_list_size; i++) {
2171 if (reg_list[i]->exist == false)
2174 if (reg_list[i]->feature != NULL
2175 && reg_list[i]->feature->name != NULL
2176 && (strcmp(reg_list[i]->feature->name, ""))) {
2177 /* We found a feature, check if the feature is already in the
2178 * table. If not, allocate a new entry for the table and
2179 * put the new feature in it.
2181 for (int j = 0; j < (tbl_sz + 1); j++) {
2182 if (!((*feature_list)[j])) {
2183 (*feature_list)[tbl_sz++] = reg_list[i]->feature->name;
2184 *feature_list = realloc(*feature_list, sizeof(char *) * (tbl_sz + 1));
2185 (*feature_list)[tbl_sz] = NULL;
2188 if (!strcmp((*feature_list)[j], reg_list[i]->feature->name))
2195 if (feature_list_size)
2196 *feature_list_size = tbl_sz;
2201 static int gdb_generate_target_description(struct target *target, char **tdesc_out)
2203 int retval = ERROR_OK;
2204 struct reg **reg_list = NULL;
2206 char const *architecture;
2207 char const **features = NULL;
2208 char const **arch_defined_types = NULL;
2209 int feature_list_size = 0;
2210 int num_arch_defined_types = 0;
2215 arch_defined_types = calloc(1, sizeof(char *));
2217 retval = target_get_gdb_reg_list_noread(target, ®_list,
2218 ®_list_size, REG_CLASS_ALL);
2220 if (retval != ERROR_OK) {
2221 LOG_ERROR("get register list failed");
2222 retval = ERROR_FAIL;
2226 if (reg_list_size <= 0) {
2227 LOG_ERROR("get register list failed");
2228 retval = ERROR_FAIL;
2232 /* Get a list of available target registers features */
2233 retval = get_reg_features_list(target, &features, &feature_list_size, reg_list, reg_list_size);
2234 if (retval != ERROR_OK) {
2235 LOG_ERROR("Can't get the registers feature list");
2236 retval = ERROR_FAIL;
2240 /* If we found some features associated with registers, create sections */
2241 int current_feature = 0;
2243 xml_printf(&retval, &tdesc, &pos, &size,
2244 "<?xml version=\"1.0\"?>\n"
2245 "<!DOCTYPE target SYSTEM \"gdb-target.dtd\">\n"
2246 "<target version=\"1.0\">\n");
2248 /* generate architecture element if supported by target */
2249 architecture = target_get_gdb_arch(target);
2250 if (architecture != NULL)
2251 xml_printf(&retval, &tdesc, &pos, &size,
2252 "<architecture>%s</architecture>\n", architecture);
2254 /* generate target description according to register list */
2255 if (features != NULL) {
2256 while (features[current_feature]) {
2258 xml_printf(&retval, &tdesc, &pos, &size,
2259 "<feature name=\"%s\">\n",
2260 features[current_feature]);
2263 for (i = 0; i < reg_list_size; i++) {
2265 if (reg_list[i]->exist == false)
2268 if (strcmp(reg_list[i]->feature->name, features[current_feature]))
2271 const char *type_str;
2272 if (reg_list[i]->reg_data_type != NULL) {
2273 if (reg_list[i]->reg_data_type->type == REG_TYPE_ARCH_DEFINED) {
2274 /* generate <type... first, if there are architecture-defined types. */
2275 if (lookup_add_arch_defined_types(&arch_defined_types,
2276 reg_list[i]->reg_data_type->id,
2277 &num_arch_defined_types))
2278 gdb_generate_reg_type_description(target, &tdesc, &pos, &size,
2279 reg_list[i]->reg_data_type,
2280 &arch_defined_types,
2281 &num_arch_defined_types);
2283 type_str = reg_list[i]->reg_data_type->id;
2285 /* predefined type */
2286 type_str = gdb_get_reg_type_name(
2287 reg_list[i]->reg_data_type->type);
2290 /* Default type is "int" */
2294 xml_printf(&retval, &tdesc, &pos, &size,
2295 "<reg name=\"%s\"", reg_list[i]->name);
2296 xml_printf(&retval, &tdesc, &pos, &size,
2297 " bitsize=\"%d\"", reg_list[i]->size);
2298 xml_printf(&retval, &tdesc, &pos, &size,
2299 " regnum=\"%d\"", reg_list[i]->number);
2300 if (reg_list[i]->caller_save)
2301 xml_printf(&retval, &tdesc, &pos, &size,
2302 " save-restore=\"yes\"");
2304 xml_printf(&retval, &tdesc, &pos, &size,
2305 " save-restore=\"no\"");
2307 xml_printf(&retval, &tdesc, &pos, &size,
2308 " type=\"%s\"", type_str);
2310 if (reg_list[i]->group != NULL)
2311 xml_printf(&retval, &tdesc, &pos, &size,
2312 " group=\"%s\"", reg_list[i]->group);
2314 xml_printf(&retval, &tdesc, &pos, &size,
2318 xml_printf(&retval, &tdesc, &pos, &size,
2325 xml_printf(&retval, &tdesc, &pos, &size,
2331 free(arch_defined_types);
2333 if (retval == ERROR_OK)
2341 static int gdb_get_target_description_chunk(struct target *target, struct target_desc_format *target_desc,
2342 char **chunk, int32_t offset, uint32_t length)
2344 if (target_desc == NULL) {
2345 LOG_ERROR("Unable to Generate Target Description");
2349 char *tdesc = target_desc->tdesc;
2350 uint32_t tdesc_length = target_desc->tdesc_length;
2352 if (tdesc == NULL) {
2353 int retval = gdb_generate_target_description(target, &tdesc);
2354 if (retval != ERROR_OK) {
2355 LOG_ERROR("Unable to Generate Target Description");
2359 tdesc_length = strlen(tdesc);
2364 if (length < (tdesc_length - offset))
2365 transfer_type = 'm';
2367 transfer_type = 'l';
2369 *chunk = malloc(length + 2);
2370 if (*chunk == NULL) {
2371 LOG_ERROR("Unable to allocate memory");
2375 (*chunk)[0] = transfer_type;
2376 if (transfer_type == 'm') {
2377 strncpy((*chunk) + 1, tdesc + offset, length);
2378 (*chunk)[1 + length] = '\0';
2380 strncpy((*chunk) + 1, tdesc + offset, tdesc_length - offset);
2381 (*chunk)[1 + (tdesc_length - offset)] = '\0';
2383 /* After gdb-server sends out last chunk, invalidate tdesc. */
2389 target_desc->tdesc = tdesc;
2390 target_desc->tdesc_length = tdesc_length;
2395 static int gdb_target_description_supported(struct target *target, int *supported)
2397 int retval = ERROR_OK;
2398 struct reg **reg_list = NULL;
2399 int reg_list_size = 0;
2400 char const **features = NULL;
2401 int feature_list_size = 0;
2403 char const *architecture = target_get_gdb_arch(target);
2405 retval = target_get_gdb_reg_list_noread(target, ®_list,
2406 ®_list_size, REG_CLASS_ALL);
2407 if (retval != ERROR_OK) {
2408 LOG_ERROR("get register list failed");
2412 if (reg_list_size <= 0) {
2413 LOG_ERROR("get register list failed");
2414 retval = ERROR_FAIL;
2418 /* Get a list of available target registers features */
2419 retval = get_reg_features_list(target, &features, &feature_list_size, reg_list, reg_list_size);
2420 if (retval != ERROR_OK) {
2421 LOG_ERROR("Can't get the registers feature list");
2426 if (architecture || feature_list_size)
2440 static int gdb_generate_thread_list(struct target *target, char **thread_list_out)
2442 struct rtos *rtos = target->rtos;
2443 int retval = ERROR_OK;
2444 char *thread_list = NULL;
2448 xml_printf(&retval, &thread_list, &pos, &size,
2449 "<?xml version=\"1.0\"?>\n"
2453 for (int i = 0; i < rtos->thread_count; i++) {
2454 struct thread_detail *thread_detail = &rtos->thread_details[i];
2456 if (!thread_detail->exists)
2459 xml_printf(&retval, &thread_list, &pos, &size,
2460 "<thread id=\"%" PRIx64 "\">", thread_detail->threadid);
2462 if (thread_detail->thread_name_str != NULL)
2463 xml_printf(&retval, &thread_list, &pos, &size,
2464 "Name: %s", thread_detail->thread_name_str);
2466 if (thread_detail->extra_info_str != NULL) {
2467 if (thread_detail->thread_name_str != NULL)
2468 xml_printf(&retval, &thread_list, &pos, &size,
2470 xml_printf(&retval, &thread_list, &pos, &size,
2471 thread_detail->extra_info_str);
2474 xml_printf(&retval, &thread_list, &pos, &size,
2479 xml_printf(&retval, &thread_list, &pos, &size,
2482 if (retval == ERROR_OK)
2483 *thread_list_out = thread_list;
2490 static int gdb_get_thread_list_chunk(struct target *target, char **thread_list,
2491 char **chunk, int32_t offset, uint32_t length)
2493 if (*thread_list == NULL) {
2494 int retval = gdb_generate_thread_list(target, thread_list);
2495 if (retval != ERROR_OK) {
2496 LOG_ERROR("Unable to Generate Thread List");
2501 size_t thread_list_length = strlen(*thread_list);
2504 length = MIN(length, thread_list_length - offset);
2505 if (length < (thread_list_length - offset))
2506 transfer_type = 'm';
2508 transfer_type = 'l';
2510 *chunk = malloc(length + 2 + 3);
2511 /* Allocating extra 3 bytes prevents false positive valgrind report
2512 * of strlen(chunk) word access:
2513 * Invalid read of size 4
2514 * Address 0x4479934 is 44 bytes inside a block of size 45 alloc'd */
2515 if (*chunk == NULL) {
2516 LOG_ERROR("Unable to allocate memory");
2520 (*chunk)[0] = transfer_type;
2521 strncpy((*chunk) + 1, (*thread_list) + offset, length);
2522 (*chunk)[1 + length] = '\0';
2524 /* After gdb-server sends out last chunk, invalidate thread list. */
2525 if (transfer_type == 'l') {
2527 *thread_list = NULL;
2533 static int gdb_query_packet(struct connection *connection,
2534 char const *packet, int packet_size)
2536 struct command_context *cmd_ctx = connection->cmd_ctx;
2537 struct gdb_connection *gdb_connection = connection->priv;
2538 struct target *target = get_target_from_connection(connection);
2540 if (strncmp(packet, "qRcmd,", 6) == 0) {
2541 if (packet_size > 6) {
2543 cmd = malloc((packet_size - 6) / 2 + 1);
2544 size_t len = unhexify((uint8_t *)cmd, packet + 6, (packet_size - 6) / 2);
2547 /* We want to print all debug output to GDB connection */
2548 log_add_callback(gdb_log_callback, connection);
2549 target_call_timer_callbacks_now();
2550 /* some commands need to know the GDB connection, make note of current
2551 * GDB connection. */
2552 current_gdb_connection = gdb_connection;
2553 command_run_line(cmd_ctx, cmd);
2554 current_gdb_connection = NULL;
2555 target_call_timer_callbacks_now();
2556 log_remove_callback(gdb_log_callback, connection);
2559 gdb_put_packet(connection, "OK", 2);
2561 } else if (strncmp(packet, "qCRC:", 5) == 0) {
2562 if (packet_size > 5) {
2567 target_addr_t addr = 0;
2570 /* skip command character */
2573 addr = strtoull(packet, &separator, 16);
2575 if (*separator != ',') {
2576 LOG_ERROR("incomplete read memory packet received, dropping connection");
2577 return ERROR_SERVER_REMOTE_CLOSED;
2580 len = strtoul(separator + 1, NULL, 16);
2582 retval = target_checksum_memory(target, addr, len, &checksum);
2584 if (retval == ERROR_OK) {
2585 snprintf(gdb_reply, 10, "C%8.8" PRIx32 "", checksum);
2586 gdb_put_packet(connection, gdb_reply, 9);
2588 retval = gdb_error(connection, retval);
2589 if (retval != ERROR_OK)
2595 } else if (strncmp(packet, "qSupported", 10) == 0) {
2596 /* we currently support packet size and qXfer:memory-map:read (if enabled)
2597 * qXfer:features:read is supported for some targets */
2598 int retval = ERROR_OK;
2599 char *buffer = NULL;
2602 int gdb_target_desc_supported = 0;
2604 /* we need to test that the target supports target descriptions */
2605 retval = gdb_target_description_supported(target, &gdb_target_desc_supported);
2606 if (retval != ERROR_OK) {
2607 LOG_INFO("Failed detecting Target Description Support, disabling");
2608 gdb_target_desc_supported = 0;
2611 /* support may be disabled globally */
2612 if (gdb_use_target_description == 0) {
2613 if (gdb_target_desc_supported)
2614 LOG_WARNING("Target Descriptions Supported, but disabled");
2615 gdb_target_desc_supported = 0;
2622 "PacketSize=%x;qXfer:memory-map:read%c;qXfer:features:read%c;qXfer:threads:read+;QStartNoAckMode+;vContSupported+",
2624 ((gdb_use_memory_map == 1) && (flash_get_bank_count() > 0)) ? '+' : '-',
2625 (gdb_target_desc_supported == 1) ? '+' : '-');
2627 if (retval != ERROR_OK) {
2628 gdb_send_error(connection, 01);
2632 gdb_put_packet(connection, buffer, strlen(buffer));
2636 } else if ((strncmp(packet, "qXfer:memory-map:read::", 23) == 0)
2637 && (flash_get_bank_count() > 0))
2638 return gdb_memory_map(connection, packet, packet_size);
2639 else if (strncmp(packet, "qXfer:features:read:", 20) == 0) {
2641 int retval = ERROR_OK;
2644 unsigned int length;
2646 /* skip command character */
2649 if (decode_xfer_read(packet, NULL, &offset, &length) < 0) {
2650 gdb_send_error(connection, 01);
2654 /* Target should prepare correct target description for annex.
2655 * The first character of returned xml is 'm' or 'l'. 'm' for
2656 * there are *more* chunks to transfer. 'l' for it is the *last*
2657 * chunk of target description.
2659 retval = gdb_get_target_description_chunk(target, &gdb_connection->target_desc,
2660 &xml, offset, length);
2661 if (retval != ERROR_OK) {
2662 gdb_error(connection, retval);
2666 gdb_put_packet(connection, xml, strlen(xml));
2670 } else if (strncmp(packet, "qXfer:threads:read:", 19) == 0) {
2672 int retval = ERROR_OK;
2675 unsigned int length;
2677 /* skip command character */
2680 if (decode_xfer_read(packet, NULL, &offset, &length) < 0) {
2681 gdb_send_error(connection, 01);
2685 /* Target should prepare correct thread list for annex.
2686 * The first character of returned xml is 'm' or 'l'. 'm' for
2687 * there are *more* chunks to transfer. 'l' for it is the *last*
2688 * chunk of target description.
2690 retval = gdb_get_thread_list_chunk(target, &gdb_connection->thread_list,
2691 &xml, offset, length);
2692 if (retval != ERROR_OK) {
2693 gdb_error(connection, retval);
2697 gdb_put_packet(connection, xml, strlen(xml));
2701 } else if (strncmp(packet, "QStartNoAckMode", 15) == 0) {
2702 gdb_connection->noack_mode = 1;
2703 gdb_put_packet(connection, "OK", 2);
2707 gdb_put_packet(connection, "", 0);
2711 static bool gdb_handle_vcont_packet(struct connection *connection, const char *packet, int packet_size)
2713 struct gdb_connection *gdb_connection = connection->priv;
2714 struct target *target = get_target_from_connection(connection);
2715 const char *parse = packet;
2718 /* query for vCont supported */
2719 if (parse[0] == '?') {
2720 if (target->type->step != NULL) {
2721 /* gdb doesn't accept c without C and s without S */
2722 gdb_put_packet(connection, "vCont;c;C;s;S", 13);
2728 if (parse[0] == ';') {
2733 /* simple case, a continue packet */
2734 if (parse[0] == 'c') {
2735 gdb_running_type = 'c';
2736 LOG_DEBUG("target %s continue", target_name(target));
2737 log_add_callback(gdb_log_callback, connection);
2738 retval = target_resume(target, 1, 0, 0, 0);
2739 if (retval == ERROR_TARGET_NOT_HALTED)
2740 LOG_INFO("target %s was not halted when resume was requested", target_name(target));
2742 /* poll target in an attempt to make its internal state consistent */
2743 if (retval != ERROR_OK) {
2744 retval = target_poll(target);
2745 if (retval != ERROR_OK)
2746 LOG_DEBUG("error polling target %s after failed resume", target_name(target));
2750 * We don't report errors to gdb here, move frontend_state to
2751 * TARGET_RUNNING to stay in sync with gdb's expectation of the
2754 gdb_connection->frontend_state = TARGET_RUNNING;
2755 target_call_event_callbacks(target, TARGET_EVENT_GDB_START);
2760 /* single-step or step-over-breakpoint */
2761 if (parse[0] == 's') {
2762 gdb_running_type = 's';
2763 bool fake_step = false;
2765 if (strncmp(parse, "s:", 2) == 0) {
2766 struct target *ct = target;
2774 thread_id = strtoll(parse, &endp, 16);
2776 packet_size -= endp - parse;
2780 if (target->rtos != NULL) {
2781 /* FIXME: why is this necessary? rtos state should be up-to-date here already! */
2782 rtos_update_threads(target);
2784 target->rtos->gdb_target_for_threadid(connection, thread_id, &ct);
2787 * check if the thread to be stepped is the current rtos thread
2788 * if not, we must fake the step
2790 if (target->rtos->current_thread != thread_id)
2794 if (parse[0] == ';') {
2798 if (parse[0] == 'c') {
2801 /* check if thread-id follows */
2802 if (parse[0] == ':') {
2806 tid = strtoll(parse, &endp, 16);
2807 if (tid == thread_id) {
2809 * Special case: only step a single thread (core),
2810 * keep the other threads halted. Currently, only
2811 * aarch64 target understands it. Other target types don't
2812 * care (nobody checks the actual value of 'current')
2813 * and it doesn't really matter. This deserves
2814 * a symbolic constant and a formal interface documentation
2817 LOG_DEBUG("request to step current core only");
2818 /* uncomment after checking that indeed other targets are safe */
2825 LOG_DEBUG("target %s single-step thread %"PRIx64, target_name(ct), thread_id);
2826 log_add_callback(gdb_log_callback, connection);
2827 target_call_event_callbacks(ct, TARGET_EVENT_GDB_START);
2830 * work around an annoying gdb behaviour: when the current thread
2831 * is changed in gdb, it assumes that the target can follow and also
2832 * make the thread current. This is an assumption that cannot hold
2833 * for a real target running a multi-threading OS. We just fake
2834 * the step to not trigger an internal error in gdb. See
2835 * https://sourceware.org/bugzilla/show_bug.cgi?id=22925 for details
2839 char sig_reply[128];
2841 LOG_DEBUG("fake step thread %"PRIx64, thread_id);
2843 sig_reply_len = snprintf(sig_reply, sizeof(sig_reply),
2844 "T05thread:%016"PRIx64";", thread_id);
2846 gdb_put_packet(connection, sig_reply, sig_reply_len);
2847 log_remove_callback(gdb_log_callback, connection);
2852 /* support for gdb_sync command */
2853 if (gdb_connection->sync) {
2854 gdb_connection->sync = false;
2855 if (ct->state == TARGET_HALTED) {
2856 LOG_DEBUG("stepi ignored. GDB will now fetch the register state " \
2857 "from the target.");
2858 gdb_sig_halted(connection);
2859 log_remove_callback(gdb_log_callback, connection);
2861 gdb_connection->frontend_state = TARGET_RUNNING;
2865 retval = target_step(ct, current_pc, 0, 0);
2866 if (retval == ERROR_TARGET_NOT_HALTED)
2867 LOG_INFO("target %s was not halted when step was requested", target_name(ct));
2869 /* if step was successful send a reply back to gdb */
2870 if (retval == ERROR_OK) {
2871 retval = target_poll(ct);
2872 if (retval != ERROR_OK)
2873 LOG_DEBUG("error polling target %s after successful step", target_name(ct));
2874 /* send back signal information */
2875 gdb_signal_reply(ct, connection);
2876 /* stop forwarding log packets! */
2877 log_remove_callback(gdb_log_callback, connection);
2879 gdb_connection->frontend_state = TARGET_RUNNING;
2881 LOG_ERROR("Unknown vCont packet");
2890 static int gdb_v_packet(struct connection *connection,
2891 char const *packet, int packet_size)
2893 struct gdb_connection *gdb_connection = connection->priv;
2896 struct target *target = get_target_from_connection(connection);
2898 if (strncmp(packet, "vCont", 5) == 0) {
2904 handled = gdb_handle_vcont_packet(connection, packet, packet_size);
2906 gdb_put_packet(connection, "", 0);
2911 /* if flash programming disabled - send a empty reply */
2913 if (gdb_flash_program == 0) {
2914 gdb_put_packet(connection, "", 0);
2918 if (strncmp(packet, "vFlashErase:", 12) == 0) {
2920 unsigned long length;
2922 char const *parse = packet + 12;
2923 if (*parse == '\0') {
2924 LOG_ERROR("incomplete vFlashErase packet received, dropping connection");
2925 return ERROR_SERVER_REMOTE_CLOSED;
2928 addr = strtoul(parse, (char **)&parse, 16);
2930 if (*(parse++) != ',' || *parse == '\0') {
2931 LOG_ERROR("incomplete vFlashErase packet received, dropping connection");
2932 return ERROR_SERVER_REMOTE_CLOSED;
2935 length = strtoul(parse, (char **)&parse, 16);
2937 if (*parse != '\0') {
2938 LOG_ERROR("incomplete vFlashErase packet received, dropping connection");
2939 return ERROR_SERVER_REMOTE_CLOSED;
2942 /* assume all sectors need erasing - stops any problems
2943 * when flash_write is called multiple times */
2946 /* perform any target specific operations before the erase */
2947 target_call_event_callbacks(target,
2948 TARGET_EVENT_GDB_FLASH_ERASE_START);
2950 /* vFlashErase:addr,length messages require region start and
2951 * end to be "block" aligned ... if padding is ever needed,
2952 * GDB will have become dangerously confused.
2954 result = flash_erase_address_range(target, false, addr,
2957 /* perform any target specific operations after the erase */
2958 target_call_event_callbacks(target,
2959 TARGET_EVENT_GDB_FLASH_ERASE_END);
2962 if (result != ERROR_OK) {
2963 /* GDB doesn't evaluate the actual error number returned,
2964 * treat a failed erase as an I/O error
2966 gdb_send_error(connection, EIO);
2967 LOG_ERROR("flash_erase returned %i", result);
2969 gdb_put_packet(connection, "OK", 2);
2974 if (strncmp(packet, "vFlashWrite:", 12) == 0) {
2977 unsigned long length;
2978 char const *parse = packet + 12;
2980 if (*parse == '\0') {
2981 LOG_ERROR("incomplete vFlashErase packet received, dropping connection");
2982 return ERROR_SERVER_REMOTE_CLOSED;
2984 addr = strtoul(parse, (char **)&parse, 16);
2985 if (*(parse++) != ':') {
2986 LOG_ERROR("incomplete vFlashErase packet received, dropping connection");
2987 return ERROR_SERVER_REMOTE_CLOSED;
2989 length = packet_size - (parse - packet);
2991 /* create a new image if there isn't already one */
2992 if (gdb_connection->vflash_image == NULL) {
2993 gdb_connection->vflash_image = malloc(sizeof(struct image));
2994 image_open(gdb_connection->vflash_image, "", "build");
2997 /* create new section with content from packet buffer */
2998 retval = image_add_section(gdb_connection->vflash_image,
2999 addr, length, 0x0, (uint8_t const *)parse);
3000 if (retval != ERROR_OK)
3003 gdb_put_packet(connection, "OK", 2);
3008 if (strncmp(packet, "vFlashDone", 10) == 0) {
3011 /* process the flashing buffer. No need to erase as GDB
3012 * always issues a vFlashErase first. */
3013 target_call_event_callbacks(target,
3014 TARGET_EVENT_GDB_FLASH_WRITE_START);
3015 result = flash_write(target, gdb_connection->vflash_image,
3017 target_call_event_callbacks(target,
3018 TARGET_EVENT_GDB_FLASH_WRITE_END);
3019 if (result != ERROR_OK) {
3020 if (result == ERROR_FLASH_DST_OUT_OF_BANK)
3021 gdb_put_packet(connection, "E.memtype", 9);
3023 gdb_send_error(connection, EIO);
3025 LOG_DEBUG("wrote %u bytes from vFlash image to flash", (unsigned)written);
3026 gdb_put_packet(connection, "OK", 2);
3029 image_close(gdb_connection->vflash_image);
3030 free(gdb_connection->vflash_image);
3031 gdb_connection->vflash_image = NULL;
3036 gdb_put_packet(connection, "", 0);
3040 static int gdb_detach(struct connection *connection)
3043 * Only reply "OK" to GDB
3044 * it will close the connection and this will trigger a call to
3045 * gdb_connection_closed() that will in turn trigger the event
3046 * TARGET_EVENT_GDB_DETACH
3048 return gdb_put_packet(connection, "OK", 2);
3051 /* The format of 'F' response packet is
3052 * Fretcode,errno,Ctrl-C flag;call-specific attachment
3054 static int gdb_fileio_response_packet(struct connection *connection,
3055 char const *packet, int packet_size)
3057 struct target *target = get_target_from_connection(connection);
3059 char *parsing_point;
3060 int fileio_retcode = strtoul(packet + 1, &separator, 16);
3061 int fileio_errno = 0;
3062 bool fileio_ctrl_c = false;
3067 if (*separator == ',') {
3068 parsing_point = separator + 1;
3069 fileio_errno = strtoul(parsing_point, &separator, 16);
3070 if (*separator == ',') {
3071 if (*(separator + 1) == 'C') {
3072 /* TODO: process ctrl-c */
3073 fileio_ctrl_c = true;
3078 LOG_DEBUG("File-I/O response, retcode: 0x%x, errno: 0x%x, ctrl-c: %s",
3079 fileio_retcode, fileio_errno, fileio_ctrl_c ? "true" : "false");
3081 retval = target_gdb_fileio_end(target, fileio_retcode, fileio_errno, fileio_ctrl_c);
3082 if (retval != ERROR_OK)
3085 /* After File-I/O ends, keep continue or step */
3086 if (gdb_running_type == 'c')
3087 retval = target_resume(target, 1, 0x0, 0, 0);
3088 else if (gdb_running_type == 's')
3089 retval = target_step(target, 1, 0x0, 0);
3091 retval = ERROR_FAIL;
3093 if (retval != ERROR_OK)
3099 static void gdb_log_callback(void *priv, const char *file, unsigned line,
3100 const char *function, const char *string)
3102 struct connection *connection = priv;
3103 struct gdb_connection *gdb_con = connection->priv;
3105 if (gdb_con->busy) {
3106 /* do not reply this using the O packet */
3110 gdb_output_con(connection, string);
3113 static void gdb_sig_halted(struct connection *connection)
3116 snprintf(sig_reply, 4, "T%2.2x", 2);
3117 gdb_put_packet(connection, sig_reply, 3);
3120 static int gdb_input_inner(struct connection *connection)
3122 /* Do not allocate this on the stack */
3123 static char gdb_packet_buffer[GDB_BUFFER_SIZE + 1]; /* Extra byte for nul-termination */
3125 struct target *target;
3126 char const *packet = gdb_packet_buffer;
3129 struct gdb_connection *gdb_con = connection->priv;
3130 static int extended_protocol;
3132 target = get_target_from_connection(connection);
3134 /* drain input buffer. If one of the packets fail, then an error
3135 * packet is replied, if applicable.
3137 * This loop will terminate and the error code is returned.
3139 * The calling fn will check if this error is something that
3140 * can be recovered from, or if the connection must be closed.
3142 * If the error is recoverable, this fn is called again to
3143 * drain the rest of the buffer.
3146 packet_size = GDB_BUFFER_SIZE;
3147 retval = gdb_get_packet(connection, gdb_packet_buffer, &packet_size);
3148 if (retval != ERROR_OK)
3151 /* terminate with zero */
3152 gdb_packet_buffer[packet_size] = '\0';
3154 if (LOG_LEVEL_IS(LOG_LVL_DEBUG)) {
3155 if (packet[0] == 'X') {
3156 /* binary packets spew junk into the debug log stream */
3159 for (x = 0; (x < 49) && (packet[x] != ':'); x++)
3162 LOG_DEBUG("received packet: '%s:<binary-data>'", buf);
3164 LOG_DEBUG("received packet: '%s'", packet);
3167 if (packet_size > 0) {
3169 switch (packet[0]) {
3170 case 'T': /* Is thread alive? */
3171 gdb_thread_packet(connection, packet, packet_size);
3173 case 'H': /* Set current thread ( 'c' for step and continue,
3174 * 'g' for all other operations ) */
3175 gdb_thread_packet(connection, packet, packet_size);
3179 retval = gdb_thread_packet(connection, packet, packet_size);
3180 if (retval == GDB_THREAD_PACKET_NOT_CONSUMED)
3181 retval = gdb_query_packet(connection, packet, packet_size);
3184 retval = gdb_get_registers_packet(connection, packet, packet_size);
3187 retval = gdb_set_registers_packet(connection, packet, packet_size);
3190 retval = gdb_get_register_packet(connection, packet, packet_size);
3193 retval = gdb_set_register_packet(connection, packet, packet_size);
3196 retval = gdb_read_memory_packet(connection, packet, packet_size);
3199 retval = gdb_write_memory_packet(connection, packet, packet_size);
3203 retval = gdb_breakpoint_watchpoint_packet(connection, packet, packet_size);
3206 gdb_last_signal_packet(connection, packet, packet_size);
3211 gdb_thread_packet(connection, packet, packet_size);
3212 log_add_callback(gdb_log_callback, connection);
3214 if (gdb_con->mem_write_error) {
3215 LOG_ERROR("Memory write failure!");
3217 /* now that we have reported the memory write error,
3218 * we can clear the condition */
3219 gdb_con->mem_write_error = false;
3222 bool nostep = false;
3223 bool already_running = false;
3224 if (target->state == TARGET_RUNNING) {
3225 LOG_WARNING("WARNING! The target is already running. "
3226 "All changes GDB did to registers will be discarded! "
3227 "Waiting for target to halt.");
3228 already_running = true;
3229 } else if (target->state != TARGET_HALTED) {
3230 LOG_WARNING("The target is not in the halted nor running stated, " \
3231 "stepi/continue ignored.");
3233 } else if ((packet[0] == 's') && gdb_con->sync) {
3234 /* Hmm..... when you issue a continue in GDB, then a "stepi" is
3235 * sent by GDB first to OpenOCD, thus defeating the check to
3236 * make only the single stepping have the sync feature...
3239 LOG_DEBUG("stepi ignored. GDB will now fetch the register state " \
3240 "from the target.");
3242 gdb_con->sync = false;
3244 if (!already_running && nostep) {
3245 /* Either the target isn't in the halted state, then we can't
3246 * step/continue. This might be early setup, etc.
3248 * Or we want to allow GDB to pick up a fresh set of
3249 * register values without modifying the target state.
3252 gdb_sig_halted(connection);
3254 /* stop forwarding log packets! */
3255 log_remove_callback(gdb_log_callback, connection);
3257 /* We're running/stepping, in which case we can
3258 * forward log output until the target is halted
3260 gdb_con->frontend_state = TARGET_RUNNING;
3261 target_call_event_callbacks(target, TARGET_EVENT_GDB_START);
3263 if (!already_running) {
3264 /* Here we don't want packet processing to stop even if this fails,
3265 * so we use a local variable instead of retval. */
3266 retval = gdb_step_continue_packet(connection, packet, packet_size);
3267 if (retval != ERROR_OK) {
3268 /* we'll never receive a halted
3269 * condition... issue a false one..
3271 gdb_frontend_halted(target, connection);
3278 retval = gdb_v_packet(connection, packet, packet_size);
3281 retval = gdb_detach(connection);
3282 extended_protocol = 0;
3285 retval = gdb_write_memory_binary_packet(connection, packet, packet_size);
3286 if (retval != ERROR_OK)
3290 if (extended_protocol != 0) {
3291 gdb_con->attached = false;
3294 gdb_put_packet(connection, "OK", 2);
3295 return ERROR_SERVER_REMOTE_CLOSED;
3297 /* handle extended remote protocol */
3298 extended_protocol = 1;
3299 gdb_put_packet(connection, "OK", 2);
3302 /* handle extended restart packet */
3303 breakpoint_clear_target(target);
3304 watchpoint_clear_target(target);
3305 command_run_linef(connection->cmd_ctx, "ocd_gdb_restart %s",
3306 target_name(target));
3307 /* set connection as attached after reset */
3308 gdb_con->attached = true;
3309 /* info rtos parts */
3310 gdb_thread_packet(connection, packet, packet_size);
3314 /* packet supported only by smp target i.e cortex_a.c*/
3315 /* handle smp packet replying coreid played to gbd */
3316 gdb_read_smp_packet(connection, packet, packet_size);
3320 /* packet supported only by smp target i.e cortex_a.c */
3321 /* handle smp packet setting coreid to be played at next
3323 gdb_write_smp_packet(connection, packet, packet_size);
3327 /* File-I/O extension */
3328 /* After gdb uses host-side syscall to complete target file
3329 * I/O, gdb sends host-side syscall return value to target
3331 * The format of 'F' response packet is
3332 * Fretcode,errno,Ctrl-C flag;call-specific attachment
3334 gdb_con->frontend_state = TARGET_RUNNING;
3335 log_add_callback(gdb_log_callback, connection);
3336 gdb_fileio_response_packet(connection, packet, packet_size);
3340 /* ignore unknown packets */
3341 LOG_DEBUG("ignoring 0x%2.2x packet", packet[0]);
3342 gdb_put_packet(connection, "", 0);
3346 /* if a packet handler returned an error, exit input loop */
3347 if (retval != ERROR_OK)
3351 if (gdb_con->ctrl_c) {
3352 if (target->state == TARGET_RUNNING) {
3353 struct target *t = target;
3355 target->rtos->gdb_target_for_threadid(connection, target->rtos->current_threadid, &t);
3356 retval = target_halt(t);
3357 if (retval == ERROR_OK)
3358 retval = target_poll(t);
3359 if (retval != ERROR_OK)
3360 target_call_event_callbacks(target, TARGET_EVENT_GDB_HALT);
3361 gdb_con->ctrl_c = 0;
3363 LOG_INFO("The target is not running when halt was requested, stopping GDB.");
3364 target_call_event_callbacks(target, TARGET_EVENT_GDB_HALT);
3368 } while (gdb_con->buf_cnt > 0);
3373 static int gdb_input(struct connection *connection)
3375 int retval = gdb_input_inner(connection);
3376 struct gdb_connection *gdb_con = connection->priv;
3377 if (retval == ERROR_SERVER_REMOTE_CLOSED)
3380 /* logging does not propagate the error, yet can set the gdb_con->closed flag */
3381 if (gdb_con->closed)
3382 return ERROR_SERVER_REMOTE_CLOSED;
3384 /* we'll recover from any other errors(e.g. temporary timeouts, etc.) */
3388 static int gdb_target_start(struct target *target, const char *port)
3390 struct gdb_service *gdb_service;
3392 gdb_service = malloc(sizeof(struct gdb_service));
3394 if (NULL == gdb_service)
3397 LOG_DEBUG("starting gdb server for %s on %s", target_name(target), port);
3399 gdb_service->target = target;
3400 gdb_service->core[0] = -1;
3401 gdb_service->core[1] = -1;
3402 target->gdb_service = gdb_service;
3404 ret = add_service("gdb",
3405 port, 1, &gdb_new_connection, &gdb_input,
3406 &gdb_connection_closed, gdb_service);
3407 /* initialialize all targets gdb service with the same pointer */
3409 struct target_list *head;
3410 struct target *curr;
3411 head = target->head;
3412 while (head != (struct target_list *)NULL) {
3413 curr = head->target;
3415 curr->gdb_service = gdb_service;
3422 static int gdb_target_add_one(struct target *target)
3424 /* one gdb instance per smp list */
3425 if ((target->smp) && (target->gdb_service))
3428 /* skip targets that cannot handle a gdb connections (e.g. mem_ap) */
3429 if (!target_supports_gdb_connection(target)) {
3430 LOG_DEBUG("skip gdb server for target %s", target_name(target));
3434 if (target->gdb_port_override) {
3435 if (strcmp(target->gdb_port_override, "disabled") == 0) {
3436 LOG_INFO("gdb port disabled");
3439 return gdb_target_start(target, target->gdb_port_override);
3442 if (strcmp(gdb_port, "disabled") == 0) {
3443 LOG_INFO("gdb port disabled");
3447 int retval = gdb_target_start(target, gdb_port_next);
3448 if (retval == ERROR_OK) {
3449 /* save the port number so can be queried with
3450 * $target_name cget -gdb-port
3452 target->gdb_port_override = strdup(gdb_port_next);
3455 /* If we can parse the port number
3456 * then we increment the port number for the next target.
3459 portnumber = strtol(gdb_port_next, &end, 0);
3461 if (parse_long(gdb_port_next, &portnumber) == ERROR_OK) {
3462 free(gdb_port_next);
3464 gdb_port_next = alloc_printf("%d", portnumber+1);
3466 /* Don't increment if gdb_port is 0, since we're just
3467 * trying to allocate an unused port. */
3468 gdb_port_next = strdup("0");
3476 int gdb_target_add_all(struct target *target)
3478 if (NULL == target) {
3479 LOG_WARNING("gdb services need one or more targets defined");
3483 while (NULL != target) {
3484 int retval = gdb_target_add_one(target);
3485 if (ERROR_OK != retval)
3488 target = target->next;
3494 COMMAND_HANDLER(handle_gdb_sync_command)
3497 return ERROR_COMMAND_SYNTAX_ERROR;
3499 if (current_gdb_connection == NULL) {
3501 "gdb_sync command can only be run from within gdb using \"monitor gdb_sync\"");
3505 current_gdb_connection->sync = true;
3510 /* daemon configuration command gdb_port */
3511 COMMAND_HANDLER(handle_gdb_port_command)
3513 int retval = CALL_COMMAND_HANDLER(server_pipe_command, &gdb_port);
3514 if (ERROR_OK == retval) {
3515 free(gdb_port_next);
3516 gdb_port_next = strdup(gdb_port);
3521 COMMAND_HANDLER(handle_gdb_memory_map_command)
3524 return ERROR_COMMAND_SYNTAX_ERROR;
3526 COMMAND_PARSE_ENABLE(CMD_ARGV[0], gdb_use_memory_map);
3530 COMMAND_HANDLER(handle_gdb_flash_program_command)
3533 return ERROR_COMMAND_SYNTAX_ERROR;
3535 COMMAND_PARSE_ENABLE(CMD_ARGV[0], gdb_flash_program);
3539 COMMAND_HANDLER(handle_gdb_report_data_abort_command)
3542 return ERROR_COMMAND_SYNTAX_ERROR;
3544 COMMAND_PARSE_ENABLE(CMD_ARGV[0], gdb_report_data_abort);
3548 COMMAND_HANDLER(handle_gdb_report_register_access_error)
3551 return ERROR_COMMAND_SYNTAX_ERROR;
3553 COMMAND_PARSE_ENABLE(CMD_ARGV[0], gdb_report_register_access_error);
3557 /* gdb_breakpoint_override */
3558 COMMAND_HANDLER(handle_gdb_breakpoint_override_command)
3560 if (CMD_ARGC == 0) {
3562 } else if (CMD_ARGC == 1) {
3563 gdb_breakpoint_override = 1;
3564 if (strcmp(CMD_ARGV[0], "hard") == 0)
3565 gdb_breakpoint_override_type = BKPT_HARD;
3566 else if (strcmp(CMD_ARGV[0], "soft") == 0)
3567 gdb_breakpoint_override_type = BKPT_SOFT;
3568 else if (strcmp(CMD_ARGV[0], "disable") == 0)
3569 gdb_breakpoint_override = 0;
3571 return ERROR_COMMAND_SYNTAX_ERROR;
3572 if (gdb_breakpoint_override)
3573 LOG_USER("force %s breakpoints",
3574 (gdb_breakpoint_override_type == BKPT_HARD) ? "hard" : "soft");
3576 LOG_USER("breakpoint type is not overridden");
3581 COMMAND_HANDLER(handle_gdb_target_description_command)
3584 return ERROR_COMMAND_SYNTAX_ERROR;
3586 COMMAND_PARSE_ENABLE(CMD_ARGV[0], gdb_use_target_description);
3590 COMMAND_HANDLER(handle_gdb_save_tdesc_command)
3593 uint32_t tdesc_length;
3594 struct target *target = get_current_target(CMD_CTX);
3596 int retval = gdb_generate_target_description(target, &tdesc);
3597 if (retval != ERROR_OK) {
3598 LOG_ERROR("Unable to Generate Target Description");
3602 tdesc_length = strlen(tdesc);
3604 struct fileio *fileio;
3605 size_t size_written;
3607 char *tdesc_filename = alloc_printf("%s.xml", target_type_name(target));
3608 if (tdesc_filename == NULL) {
3609 retval = ERROR_FAIL;
3613 retval = fileio_open(&fileio, tdesc_filename, FILEIO_WRITE, FILEIO_TEXT);
3615 if (retval != ERROR_OK) {
3616 LOG_ERROR("Can't open %s for writing", tdesc_filename);
3620 retval = fileio_write(fileio, tdesc_length, tdesc, &size_written);
3622 fileio_close(fileio);
3624 if (retval != ERROR_OK)
3625 LOG_ERROR("Error while writing the tdesc file");
3628 free(tdesc_filename);
3634 static const struct command_registration gdb_command_handlers[] = {
3637 .handler = handle_gdb_sync_command,
3638 .mode = COMMAND_ANY,
3639 .help = "next stepi will return immediately allowing "
3640 "GDB to fetch register state without affecting "
3646 .handler = handle_gdb_port_command,
3647 .mode = COMMAND_ANY,
3648 .help = "Normally gdb listens to a TCP/IP port. Each subsequent GDB "
3649 "server listens for the next port number after the "
3650 "base port number specified. "
3651 "No arguments reports GDB port. \"pipe\" means listen to stdin "
3652 "output to stdout, an integer is base port number, \"disabled\" disables "
3653 "port. Any other string is are interpreted as named pipe to listen to. "
3654 "Output pipe is the same name as input pipe, but with 'o' appended.",
3655 .usage = "[port_num]",
3658 .name = "gdb_memory_map",
3659 .handler = handle_gdb_memory_map_command,
3660 .mode = COMMAND_CONFIG,
3661 .help = "enable or disable memory map",
3662 .usage = "('enable'|'disable')"
3665 .name = "gdb_flash_program",
3666 .handler = handle_gdb_flash_program_command,
3667 .mode = COMMAND_CONFIG,
3668 .help = "enable or disable flash program",
3669 .usage = "('enable'|'disable')"
3672 .name = "gdb_report_data_abort",
3673 .handler = handle_gdb_report_data_abort_command,
3674 .mode = COMMAND_CONFIG,
3675 .help = "enable or disable reporting data aborts",
3676 .usage = "('enable'|'disable')"
3679 .name = "gdb_report_register_access_error",
3680 .handler = handle_gdb_report_register_access_error,
3681 .mode = COMMAND_CONFIG,
3682 .help = "enable or disable reporting register access errors",
3683 .usage = "('enable'|'disable')"
3686 .name = "gdb_breakpoint_override",
3687 .handler = handle_gdb_breakpoint_override_command,
3688 .mode = COMMAND_ANY,
3689 .help = "Display or specify type of breakpoint "
3690 "to be used by gdb 'break' commands.",
3691 .usage = "('hard'|'soft'|'disable')"
3694 .name = "gdb_target_description",
3695 .handler = handle_gdb_target_description_command,
3696 .mode = COMMAND_CONFIG,
3697 .help = "enable or disable target description",
3698 .usage = "('enable'|'disable')"
3701 .name = "gdb_save_tdesc",
3702 .handler = handle_gdb_save_tdesc_command,
3703 .mode = COMMAND_EXEC,
3704 .help = "Save the target description file",
3707 COMMAND_REGISTRATION_DONE
3710 int gdb_register_commands(struct command_context *cmd_ctx)
3712 gdb_port = strdup("3333");
3713 gdb_port_next = strdup("3333");
3714 return register_commands(cmd_ctx, NULL, gdb_command_handlers);
3717 void gdb_service_free(void)
3720 free(gdb_port_next);