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>
45 #include <flash/nor/core.h>
46 #include "gdb_server.h"
47 #include <target/image.h>
48 #include <jtag/jtag.h>
49 #include "rtos/rtos.h"
50 #include "target/smp.h"
54 * GDB server implementation.
56 * This implements the GDB Remote Serial Protocol, over TCP connections,
57 * giving GDB access to the JTAG or other hardware debugging facilities
58 * found in most modern embedded processors.
61 struct target_desc_format {
63 uint32_t tdesc_length;
66 /* private connection data for GDB */
67 struct gdb_connection {
68 char buffer[GDB_BUFFER_SIZE];
72 enum target_state frontend_state;
73 struct image *vflash_image;
77 /* set flag to true if you want the next stepi to return immediately.
78 * allowing GDB to pick up a fresh set of register values from the target
79 * without modifying the target state. */
81 /* We delay reporting memory write errors until next step/continue or memory
82 * write. This improves performance of gdb load significantly as the GDB packet
83 * can be replied immediately and a new GDB packet will be ready without delay
84 * (ca. 10% or so...). */
86 /* with extended-remote it seems we need to better emulate attach/detach.
87 * what this means is we reply with a W stop reply after a kill packet,
88 * normally we reply with a S reply via gdb_last_signal_packet.
89 * as a side note this behaviour only effects gdb > 6.8 */
91 /* temporarily used for target description support */
92 struct target_desc_format target_desc;
96 #define _DEBUG_GDB_IO_
99 static struct gdb_connection *current_gdb_connection;
101 static int gdb_breakpoint_override;
102 static enum breakpoint_type gdb_breakpoint_override_type;
104 static int gdb_error(struct connection *connection, int retval);
105 static char *gdb_port;
106 static char *gdb_port_next;
108 static void gdb_log_callback(void *priv, const char *file, unsigned line,
109 const char *function, const char *string);
111 /* number of gdb connections, mainly to suppress gdb related debugging spam
112 * in helper/log.c when no gdb connections are actually active */
113 int gdb_actual_connections;
115 /* set if we are sending a memory map to gdb
116 * via qXfer:memory-map:read packet */
117 /* enabled by default*/
118 static int gdb_use_memory_map = 1;
119 /* enabled by default*/
120 static int gdb_flash_program = 1;
122 /* if set, data aborts cause an error to be reported in memory read packets
123 * see the code in gdb_read_memory_packet() for further explanations.
124 * Disabled by default.
126 static int gdb_report_data_abort;
128 /* set if we are sending target descriptions to gdb
129 * via qXfer:features:read packet */
130 /* enabled by default */
131 static int gdb_use_target_description = 1;
133 /* current processing free-run type, used by file-I/O */
134 static char gdb_running_type;
136 static int gdb_last_signal(struct target *target)
138 switch (target->debug_reason) {
139 case DBG_REASON_DBGRQ:
140 return 0x2; /* SIGINT */
141 case DBG_REASON_BREAKPOINT:
142 case DBG_REASON_WATCHPOINT:
143 case DBG_REASON_WPTANDBKPT:
144 return 0x05; /* SIGTRAP */
145 case DBG_REASON_SINGLESTEP:
146 return 0x05; /* SIGTRAP */
147 case DBG_REASON_NOTHALTED:
148 return 0x0; /* no signal... shouldn't happen */
150 LOG_USER("undefined debug reason %d - target needs reset",
151 target->debug_reason);
156 static int check_pending(struct connection *connection,
157 int timeout_s, int *got_data)
159 /* a non-blocking socket will block if there is 0 bytes available on the socket,
160 * but return with as many bytes as are available immediately
164 struct gdb_connection *gdb_con = connection->priv;
166 if (got_data == NULL)
170 if (gdb_con->buf_cnt > 0) {
176 FD_SET(connection->fd, &read_fds);
178 tv.tv_sec = timeout_s;
180 if (socket_select(connection->fd + 1, &read_fds, NULL, NULL, &tv) == 0) {
181 /* This can typically be because a "monitor" command took too long
182 * before printing any progress messages
185 return ERROR_GDB_TIMEOUT;
189 *got_data = FD_ISSET(connection->fd, &read_fds) != 0;
193 static int gdb_get_char_inner(struct connection *connection, int *next_char)
195 struct gdb_connection *gdb_con = connection->priv;
196 int retval = ERROR_OK;
198 #ifdef _DEBUG_GDB_IO_
202 if (connection->service->type != CONNECTION_TCP)
203 gdb_con->buf_cnt = read(connection->fd, gdb_con->buffer, GDB_BUFFER_SIZE);
205 retval = check_pending(connection, 1, NULL);
206 if (retval != ERROR_OK)
208 gdb_con->buf_cnt = read_socket(connection->fd,
213 if (gdb_con->buf_cnt > 0)
215 if (gdb_con->buf_cnt == 0) {
217 return ERROR_SERVER_REMOTE_CLOSED;
221 errno = WSAGetLastError();
227 case WSAECONNABORTED:
229 return ERROR_SERVER_REMOTE_CLOSED;
232 return ERROR_SERVER_REMOTE_CLOSED;
234 LOG_ERROR("read: %d", errno);
244 return ERROR_SERVER_REMOTE_CLOSED;
247 return ERROR_SERVER_REMOTE_CLOSED;
249 LOG_ERROR("read: %s", strerror(errno));
251 return ERROR_SERVER_REMOTE_CLOSED;
256 #ifdef _DEBUG_GDB_IO_
257 debug_buffer = strndup(gdb_con->buffer, gdb_con->buf_cnt);
258 LOG_DEBUG("received '%s'", debug_buffer);
262 gdb_con->buf_p = gdb_con->buffer;
264 *next_char = *(gdb_con->buf_p++);
265 if (gdb_con->buf_cnt > 0)
266 connection->input_pending = 1;
268 connection->input_pending = 0;
269 #ifdef _DEBUG_GDB_IO_
270 LOG_DEBUG("returned char '%c' (0x%2.2x)", *next_char, *next_char);
277 * The cool thing about this fn is that it allows buf_p and buf_cnt to be
278 * held in registers in the inner loop.
280 * For small caches and embedded systems this is important!
282 static inline int gdb_get_char_fast(struct connection *connection,
283 int *next_char, char **buf_p, int *buf_cnt)
285 int retval = ERROR_OK;
287 if ((*buf_cnt)-- > 0) {
288 *next_char = **buf_p;
291 connection->input_pending = 1;
293 connection->input_pending = 0;
295 #ifdef _DEBUG_GDB_IO_
296 LOG_DEBUG("returned char '%c' (0x%2.2x)", *next_char, *next_char);
302 struct gdb_connection *gdb_con = connection->priv;
303 gdb_con->buf_p = *buf_p;
304 gdb_con->buf_cnt = *buf_cnt;
305 retval = gdb_get_char_inner(connection, next_char);
306 *buf_p = gdb_con->buf_p;
307 *buf_cnt = gdb_con->buf_cnt;
312 static int gdb_get_char(struct connection *connection, int *next_char)
314 struct gdb_connection *gdb_con = connection->priv;
315 return gdb_get_char_fast(connection, next_char, &gdb_con->buf_p, &gdb_con->buf_cnt);
318 static int gdb_putback_char(struct connection *connection, int last_char)
320 struct gdb_connection *gdb_con = connection->priv;
322 if (gdb_con->buf_p > gdb_con->buffer) {
323 *(--gdb_con->buf_p) = last_char;
326 LOG_ERROR("BUG: couldn't put character back");
331 /* The only way we can detect that the socket is closed is the first time
332 * we write to it, we will fail. Subsequent write operations will
333 * succeed. Shudder! */
334 static int gdb_write(struct connection *connection, void *data, int len)
336 struct gdb_connection *gdb_con = connection->priv;
338 return ERROR_SERVER_REMOTE_CLOSED;
340 if (connection_write(connection, data, len) == len)
343 return ERROR_SERVER_REMOTE_CLOSED;
346 static int gdb_put_packet_inner(struct connection *connection,
347 char *buffer, int len)
350 unsigned char my_checksum = 0;
351 #ifdef _DEBUG_GDB_IO_
356 struct gdb_connection *gdb_con = connection->priv;
358 for (i = 0; i < len; i++)
359 my_checksum += buffer[i];
361 #ifdef _DEBUG_GDB_IO_
363 * At this point we should have nothing in the input queue from GDB,
364 * however sometimes '-' is sent even though we've already received
365 * an ACK (+) for everything we've sent off.
369 retval = check_pending(connection, 0, &gotdata);
370 if (retval != ERROR_OK)
374 retval = gdb_get_char(connection, &reply);
375 if (retval != ERROR_OK)
378 /* fix a problem with some IAR tools */
379 gdb_putback_char(connection, reply);
380 LOG_DEBUG("Unexpected start of new packet");
384 LOG_WARNING("Discard unexpected char %c", reply);
389 #ifdef _DEBUG_GDB_IO_
390 debug_buffer = strndup(buffer, len);
391 LOG_DEBUG("sending packet '$%s#%2.2x'", debug_buffer, my_checksum);
395 char local_buffer[1024];
396 local_buffer[0] = '$';
397 if ((size_t)len + 4 <= sizeof(local_buffer)) {
398 /* performance gain on smaller packets by only a single call to gdb_write() */
399 memcpy(local_buffer + 1, buffer, len++);
400 len += snprintf(local_buffer + len, sizeof(local_buffer) - len, "#%02x", my_checksum);
401 retval = gdb_write(connection, local_buffer, len);
402 if (retval != ERROR_OK)
405 /* larger packets are transmitted directly from caller supplied buffer
406 * by several calls to gdb_write() to avoid dynamic allocation */
407 snprintf(local_buffer + 1, sizeof(local_buffer) - 1, "#%02x", my_checksum);
408 retval = gdb_write(connection, local_buffer, 1);
409 if (retval != ERROR_OK)
411 retval = gdb_write(connection, buffer, len);
412 if (retval != ERROR_OK)
414 retval = gdb_write(connection, local_buffer + 1, 3);
415 if (retval != ERROR_OK)
419 if (gdb_con->noack_mode)
422 retval = gdb_get_char(connection, &reply);
423 if (retval != ERROR_OK)
428 else if (reply == '-') {
429 /* Stop sending output packets for now */
430 log_remove_callback(gdb_log_callback, connection);
431 LOG_WARNING("negative reply, retrying");
432 } else if (reply == 0x3) {
434 retval = gdb_get_char(connection, &reply);
435 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 == '$') {
444 LOG_ERROR("GDB missing ack(1) - assumed good");
445 gdb_putback_char(connection, reply);
448 LOG_ERROR("unknown character(1) 0x%2.2x in reply, dropping connection", reply);
450 return ERROR_SERVER_REMOTE_CLOSED;
452 } else if (reply == '$') {
453 LOG_ERROR("GDB missing ack(2) - assumed good");
454 gdb_putback_char(connection, reply);
457 LOG_ERROR("unknown character(2) 0x%2.2x in reply, dropping connection",
460 return ERROR_SERVER_REMOTE_CLOSED;
464 return ERROR_SERVER_REMOTE_CLOSED;
469 int gdb_put_packet(struct connection *connection, char *buffer, int len)
471 struct gdb_connection *gdb_con = connection->priv;
473 int retval = gdb_put_packet_inner(connection, buffer, len);
476 /* we sent some data, reset timer for keep alive messages */
482 static inline int fetch_packet(struct connection *connection,
483 int *checksum_ok, int noack, int *len, char *buffer)
485 unsigned char my_checksum = 0;
488 int retval = ERROR_OK;
490 struct gdb_connection *gdb_con = connection->priv;
495 /* move this over into local variables to use registers and give the
496 * more freedom to optimize */
497 char *buf_p = gdb_con->buf_p;
498 int buf_cnt = gdb_con->buf_cnt;
501 /* The common case is that we have an entire packet with no escape chars.
502 * We need to leave at least 2 bytes in the buffer to have
503 * gdb_get_char() update various bits and bobs correctly.
505 if ((buf_cnt > 2) && ((buf_cnt + count) < *len)) {
506 /* The compiler will struggle a bit with constant propagation and
507 * aliasing, so we help it by showing that these values do not
508 * change inside the loop
512 int run = buf_cnt - 2;
518 if (character == '#') {
519 /* Danger! character can be '#' when esc is
520 * used so we need an explicit boolean for done here. */
525 if (character == '}') {
526 /* data transmitted in binary mode (X packet)
527 * uses 0x7d as escape character */
528 my_checksum += character & 0xff;
531 my_checksum += character & 0xff;
532 buffer[count++] = (character ^ 0x20) & 0xff;
534 my_checksum += character & 0xff;
535 buffer[count++] = character & 0xff;
544 LOG_ERROR("packet buffer too small");
545 retval = ERROR_GDB_BUFFER_TOO_SMALL;
549 retval = gdb_get_char_fast(connection, &character, &buf_p, &buf_cnt);
550 if (retval != ERROR_OK)
553 if (character == '#')
556 if (character == '}') {
557 /* data transmitted in binary mode (X packet)
558 * uses 0x7d as escape character */
559 my_checksum += character & 0xff;
561 retval = gdb_get_char_fast(connection, &character, &buf_p, &buf_cnt);
562 if (retval != ERROR_OK)
565 my_checksum += character & 0xff;
566 buffer[count++] = (character ^ 0x20) & 0xff;
568 my_checksum += character & 0xff;
569 buffer[count++] = character & 0xff;
573 gdb_con->buf_p = buf_p;
574 gdb_con->buf_cnt = buf_cnt;
576 if (retval != ERROR_OK)
581 retval = gdb_get_char(connection, &character);
582 if (retval != ERROR_OK)
584 checksum[0] = character;
585 retval = gdb_get_char(connection, &character);
586 if (retval != ERROR_OK)
588 checksum[1] = character;
592 *checksum_ok = (my_checksum == strtoul(checksum, NULL, 16));
597 static int gdb_get_packet_inner(struct connection *connection,
598 char *buffer, int *len)
602 struct gdb_connection *gdb_con = connection->priv;
606 retval = gdb_get_char(connection, &character);
607 if (retval != ERROR_OK)
610 #ifdef _DEBUG_GDB_IO_
611 LOG_DEBUG("character: '%c'", character);
618 /* According to the GDB documentation
619 * (https://sourceware.org/gdb/onlinedocs/gdb/Packet-Acknowledgment.html):
620 * "gdb sends a final `+` acknowledgment of the stub's `OK`
621 * response, which can be safely ignored by the stub."
622 * However OpenOCD server already is in noack mode at this
623 * point and instead of ignoring this it was emitting a
624 * warning. This code makes server ignore the first ACK
625 * that will be received after going into noack mode,
626 * warning only about subsequent ACK's. */
627 if (gdb_con->noack_mode > 1) {
628 LOG_WARNING("acknowledgment received, but no packet pending");
629 } else if (gdb_con->noack_mode) {
630 LOG_DEBUG("Received first acknowledgment after entering noack mode. Ignoring it.");
631 gdb_con->noack_mode = 2;
635 LOG_WARNING("negative acknowledgment, but no packet pending");
642 LOG_WARNING("ignoring character 0x%x", character);
645 } while (character != '$');
648 /* explicit code expansion here to get faster inlined code in -O3 by not
649 * calculating checksum */
650 if (gdb_con->noack_mode) {
651 retval = fetch_packet(connection, &checksum_ok, 1, len, buffer);
652 if (retval != ERROR_OK)
655 retval = fetch_packet(connection, &checksum_ok, 0, len, buffer);
656 if (retval != ERROR_OK)
660 if (gdb_con->noack_mode) {
661 /* checksum is not checked in noack mode */
665 retval = gdb_write(connection, "+", 1);
666 if (retval != ERROR_OK)
672 return ERROR_SERVER_REMOTE_CLOSED;
677 static int gdb_get_packet(struct connection *connection, char *buffer, int *len)
679 struct gdb_connection *gdb_con = connection->priv;
681 int retval = gdb_get_packet_inner(connection, buffer, len);
686 static int gdb_output_con(struct connection *connection, const char *line)
691 bin_size = strlen(line);
693 hex_buffer = malloc(bin_size * 2 + 2);
694 if (hex_buffer == NULL)
695 return ERROR_GDB_BUFFER_TOO_SMALL;
698 int pkt_len = hexify(hex_buffer + 1, line, bin_size, bin_size * 2 + 1);
699 int retval = gdb_put_packet(connection, hex_buffer, pkt_len + 1);
705 static int gdb_output(struct command_context *context, const char *line)
707 /* this will be dumped to the log and also sent as an O packet if possible */
708 LOG_USER_N("%s", line);
712 static void gdb_signal_reply(struct target *target, struct connection *connection)
714 struct gdb_connection *gdb_connection = connection->priv;
716 char stop_reason[20];
717 char current_thread[25];
721 rtos_update_threads(target);
723 if (target->debug_reason == DBG_REASON_EXIT) {
724 sig_reply_len = snprintf(sig_reply, sizeof(sig_reply), "W00");
726 if (gdb_connection->ctrl_c) {
728 gdb_connection->ctrl_c = 0;
730 signal_var = gdb_last_signal(target);
732 stop_reason[0] = '\0';
733 if (target->debug_reason == DBG_REASON_WATCHPOINT) {
734 enum watchpoint_rw hit_wp_type;
735 uint32_t hit_wp_address;
737 if (watchpoint_hit(target, &hit_wp_type, &hit_wp_address) == ERROR_OK) {
739 switch (hit_wp_type) {
741 snprintf(stop_reason, sizeof(stop_reason),
742 "watch:%08" PRIx32 ";", hit_wp_address);
745 snprintf(stop_reason, sizeof(stop_reason),
746 "rwatch:%08" PRIx32 ";", hit_wp_address);
749 snprintf(stop_reason, sizeof(stop_reason),
750 "awatch:%08" PRIx32 ";", hit_wp_address);
758 current_thread[0] = '\0';
759 if (target->rtos != NULL) {
760 snprintf(current_thread, sizeof(current_thread), "thread:%016" PRIx64 ";", target->rtos->current_thread);
761 target->rtos->current_threadid = target->rtos->current_thread;
764 sig_reply_len = snprintf(sig_reply, sizeof(sig_reply), "T%2.2x%s%s",
765 signal_var, stop_reason, current_thread);
768 gdb_put_packet(connection, sig_reply, sig_reply_len);
769 gdb_connection->frontend_state = TARGET_HALTED;
772 static void gdb_fileio_reply(struct target *target, struct connection *connection)
774 struct gdb_connection *gdb_connection = connection->priv;
775 char fileio_command[256];
777 bool program_exited = false;
779 if (strcmp(target->fileio_info->identifier, "open") == 0)
780 sprintf(fileio_command, "F%s,%" PRIx32 "/%" PRIx32 ",%" PRIx32 ",%" PRIx32, target->fileio_info->identifier,
781 target->fileio_info->param_1,
782 target->fileio_info->param_2,
783 target->fileio_info->param_3,
784 target->fileio_info->param_4);
785 else if (strcmp(target->fileio_info->identifier, "close") == 0)
786 sprintf(fileio_command, "F%s,%" PRIx32, target->fileio_info->identifier,
787 target->fileio_info->param_1);
788 else if (strcmp(target->fileio_info->identifier, "read") == 0)
789 sprintf(fileio_command, "F%s,%" PRIx32 ",%" PRIx32 ",%" PRIx32, target->fileio_info->identifier,
790 target->fileio_info->param_1,
791 target->fileio_info->param_2,
792 target->fileio_info->param_3);
793 else if (strcmp(target->fileio_info->identifier, "write") == 0)
794 sprintf(fileio_command, "F%s,%" PRIx32 ",%" PRIx32 ",%" PRIx32, target->fileio_info->identifier,
795 target->fileio_info->param_1,
796 target->fileio_info->param_2,
797 target->fileio_info->param_3);
798 else if (strcmp(target->fileio_info->identifier, "lseek") == 0)
799 sprintf(fileio_command, "F%s,%" PRIx32 ",%" PRIx32 ",%" PRIx32, target->fileio_info->identifier,
800 target->fileio_info->param_1,
801 target->fileio_info->param_2,
802 target->fileio_info->param_3);
803 else if (strcmp(target->fileio_info->identifier, "rename") == 0)
804 sprintf(fileio_command, "F%s,%" PRIx32 "/%" PRIx32 ",%" PRIx32 "/%" PRIx32, target->fileio_info->identifier,
805 target->fileio_info->param_1,
806 target->fileio_info->param_2,
807 target->fileio_info->param_3,
808 target->fileio_info->param_4);
809 else if (strcmp(target->fileio_info->identifier, "unlink") == 0)
810 sprintf(fileio_command, "F%s,%" PRIx32 "/%" PRIx32, target->fileio_info->identifier,
811 target->fileio_info->param_1,
812 target->fileio_info->param_2);
813 else if (strcmp(target->fileio_info->identifier, "stat") == 0)
814 sprintf(fileio_command, "F%s,%" PRIx32 "/%" PRIx32 ",%" PRIx32, 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, "fstat") == 0)
819 sprintf(fileio_command, "F%s,%" PRIx32 ",%" PRIx32, target->fileio_info->identifier,
820 target->fileio_info->param_1,
821 target->fileio_info->param_2);
822 else if (strcmp(target->fileio_info->identifier, "gettimeofday") == 0)
823 sprintf(fileio_command, "F%s,%" PRIx32 ",%" PRIx32, target->fileio_info->identifier,
824 target->fileio_info->param_1,
825 target->fileio_info->param_2);
826 else if (strcmp(target->fileio_info->identifier, "isatty") == 0)
827 sprintf(fileio_command, "F%s,%" PRIx32, target->fileio_info->identifier,
828 target->fileio_info->param_1);
829 else if (strcmp(target->fileio_info->identifier, "system") == 0)
830 sprintf(fileio_command, "F%s,%" PRIx32 "/%" PRIx32, target->fileio_info->identifier,
831 target->fileio_info->param_1,
832 target->fileio_info->param_2);
833 else if (strcmp(target->fileio_info->identifier, "exit") == 0) {
834 /* If target hits exit syscall, report to GDB the program is terminated.
835 * In addition, let target run its own exit syscall handler. */
836 program_exited = true;
837 sprintf(fileio_command, "W%02" PRIx32, target->fileio_info->param_1);
839 LOG_DEBUG("Unknown syscall: %s", target->fileio_info->identifier);
841 /* encounter unknown syscall, continue */
842 gdb_connection->frontend_state = TARGET_RUNNING;
843 target_resume(target, 1, 0x0, 0, 0);
847 command_len = strlen(fileio_command);
848 gdb_put_packet(connection, fileio_command, command_len);
850 if (program_exited) {
851 /* Use target_resume() to let target run its own exit syscall handler. */
852 gdb_connection->frontend_state = TARGET_RUNNING;
853 target_resume(target, 1, 0x0, 0, 0);
855 gdb_connection->frontend_state = TARGET_HALTED;
856 rtos_update_threads(target);
860 static void gdb_frontend_halted(struct target *target, struct connection *connection)
862 struct gdb_connection *gdb_connection = connection->priv;
864 /* In the GDB protocol when we are stepping or continuing execution,
865 * we have a lingering reply. Upon receiving a halted event
866 * when we have that lingering packet, we reply to the original
867 * step or continue packet.
869 * Executing monitor commands can bring the target in and
870 * out of the running state so we'll see lots of TARGET_EVENT_XXX
871 * that are to be ignored.
873 if (gdb_connection->frontend_state == TARGET_RUNNING) {
874 /* stop forwarding log packets! */
875 log_remove_callback(gdb_log_callback, connection);
877 /* check fileio first */
878 if (target_get_gdb_fileio_info(target, target->fileio_info) == ERROR_OK)
879 gdb_fileio_reply(target, connection);
881 gdb_signal_reply(target, connection);
885 static int gdb_target_callback_event_handler(struct target *target,
886 enum target_event event, void *priv)
889 struct connection *connection = priv;
890 struct gdb_service *gdb_service = connection->service->priv;
892 if (gdb_service->target != target)
896 case TARGET_EVENT_GDB_HALT:
897 gdb_frontend_halted(target, connection);
899 case TARGET_EVENT_HALTED:
900 target_call_event_callbacks(target, TARGET_EVENT_GDB_END);
902 case TARGET_EVENT_GDB_FLASH_ERASE_START:
903 retval = jtag_execute_queue();
904 if (retval != ERROR_OK)
914 static int gdb_new_connection(struct connection *connection)
916 struct gdb_connection *gdb_connection = malloc(sizeof(struct gdb_connection));
917 struct gdb_service *gdb_service = connection->service->priv;
921 connection->priv = gdb_connection;
923 /* initialize gdb connection information */
924 gdb_connection->buf_p = gdb_connection->buffer;
925 gdb_connection->buf_cnt = 0;
926 gdb_connection->ctrl_c = 0;
927 gdb_connection->frontend_state = TARGET_HALTED;
928 gdb_connection->vflash_image = NULL;
929 gdb_connection->closed = 0;
930 gdb_connection->busy = 0;
931 gdb_connection->noack_mode = 0;
932 gdb_connection->sync = false;
933 gdb_connection->mem_write_error = false;
934 gdb_connection->attached = true;
935 gdb_connection->target_desc.tdesc = NULL;
936 gdb_connection->target_desc.tdesc_length = 0;
938 /* send ACK to GDB for debug request */
939 gdb_write(connection, "+", 1);
941 /* output goes through gdb connection */
942 command_set_output_handler(connection->cmd_ctx, gdb_output, connection);
944 /* we must remove all breakpoints registered to the target as a previous
945 * GDB session could leave dangling breakpoints if e.g. communication
948 breakpoint_clear_target(gdb_service->target);
949 watchpoint_clear_target(gdb_service->target);
951 /* clean previous rtos session if supported*/
952 if ((gdb_service->target->rtos) && (gdb_service->target->rtos->type->clean))
953 gdb_service->target->rtos->type->clean(gdb_service->target);
955 /* remove the initial ACK from the incoming buffer */
956 retval = gdb_get_char(connection, &initial_ack);
957 if (retval != ERROR_OK)
960 /* FIX!!!??? would we actually ever receive a + here???
963 if (initial_ack != '+')
964 gdb_putback_char(connection, initial_ack);
965 target_call_event_callbacks(gdb_service->target, TARGET_EVENT_GDB_ATTACH);
967 if (gdb_use_memory_map) {
968 /* Connect must fail if the memory map can't be set up correctly.
970 * This will cause an auto_probe to be invoked, which is either
971 * a no-op or it will fail when the target isn't ready(e.g. not halted).
974 for (i = 0; i < flash_get_bank_count(); i++) {
975 struct flash_bank *p;
976 p = get_flash_bank_by_num_noprobe(i);
977 if (p->target != gdb_service->target)
979 retval = get_flash_bank_by_num(i, &p);
980 if (retval != ERROR_OK) {
981 LOG_ERROR("Connect failed. Consider setting up a gdb-attach event for the target " \
982 "to prepare target for GDB connect, or use 'gdb_memory_map disable'.");
988 gdb_actual_connections++;
989 LOG_DEBUG("New GDB Connection: %d, Target %s, state: %s",
990 gdb_actual_connections,
991 target_name(gdb_service->target),
992 target_state_name(gdb_service->target));
994 /* DANGER! If we fail subsequently, we must remove this handler,
995 * otherwise we occasionally see crashes as the timer can invoke the
998 * register callback to be informed about target events */
999 target_register_event_callback(gdb_target_callback_event_handler, connection);
1004 static int gdb_connection_closed(struct connection *connection)
1006 struct gdb_service *gdb_service = connection->service->priv;
1007 struct gdb_connection *gdb_connection = connection->priv;
1009 /* we're done forwarding messages. Tear down callback before
1010 * cleaning up connection.
1012 log_remove_callback(gdb_log_callback, connection);
1014 gdb_actual_connections--;
1015 LOG_DEBUG("GDB Close, Target: %s, state: %s, gdb_actual_connections=%d",
1016 target_name(gdb_service->target),
1017 target_state_name(gdb_service->target),
1018 gdb_actual_connections);
1020 /* see if an image built with vFlash commands is left */
1021 if (gdb_connection->vflash_image) {
1022 image_close(gdb_connection->vflash_image);
1023 free(gdb_connection->vflash_image);
1024 gdb_connection->vflash_image = NULL;
1027 /* if this connection registered a debug-message receiver delete it */
1028 delete_debug_msg_receiver(connection->cmd_ctx, gdb_service->target);
1030 if (connection->priv) {
1031 free(connection->priv);
1032 connection->priv = NULL;
1034 LOG_ERROR("BUG: connection->priv == NULL");
1036 target_unregister_event_callback(gdb_target_callback_event_handler, connection);
1038 target_call_event_callbacks(gdb_service->target, TARGET_EVENT_GDB_END);
1040 target_call_event_callbacks(gdb_service->target, TARGET_EVENT_GDB_DETACH);
1045 static void gdb_send_error(struct connection *connection, uint8_t the_error)
1048 snprintf(err, 4, "E%2.2X", the_error);
1049 gdb_put_packet(connection, err, 3);
1052 static int gdb_last_signal_packet(struct connection *connection,
1053 char const *packet, int packet_size)
1055 struct target *target = get_target_from_connection(connection);
1056 struct gdb_connection *gdb_con = connection->priv;
1060 if (!gdb_con->attached) {
1061 /* if we are here we have received a kill packet
1062 * reply W stop reply otherwise gdb gets very unhappy */
1063 gdb_put_packet(connection, "W00", 3);
1067 signal_var = gdb_last_signal(target);
1069 snprintf(sig_reply, 4, "S%2.2x", signal_var);
1070 gdb_put_packet(connection, sig_reply, 3);
1075 static inline int gdb_reg_pos(struct target *target, int pos, int len)
1077 if (target->endianness == TARGET_LITTLE_ENDIAN)
1080 return len - 1 - pos;
1083 /* Convert register to string of bytes. NB! The # of bits in the
1084 * register might be non-divisible by 8(a byte), in which
1085 * case an entire byte is shown.
1087 * NB! the format on the wire is the target endianness
1089 * The format of reg->value is little endian
1092 static void gdb_str_to_target(struct target *target,
1093 char *tstr, struct reg *reg)
1100 buf_len = DIV_ROUND_UP(reg->size, 8);
1102 for (i = 0; i < buf_len; i++) {
1103 int j = gdb_reg_pos(target, i, buf_len);
1104 tstr += sprintf(tstr, "%02x", buf[j]);
1108 /* copy over in register buffer */
1109 static void gdb_target_to_reg(struct target *target,
1110 char const *tstr, int str_len, uint8_t *bin)
1113 LOG_ERROR("BUG: gdb value with uneven number of characters encountered");
1118 for (i = 0; i < str_len; i += 2) {
1120 if (sscanf(tstr + i, "%02x", &t) != 1) {
1121 LOG_ERROR("BUG: unable to convert register value");
1125 int j = gdb_reg_pos(target, i/2, str_len/2);
1130 static int gdb_get_registers_packet(struct connection *connection,
1131 char const *packet, int packet_size)
1133 struct target *target = get_target_from_connection(connection);
1134 struct reg **reg_list;
1137 int reg_packet_size = 0;
1142 #ifdef _DEBUG_GDB_IO_
1146 if ((target->rtos != NULL) && (ERROR_OK == rtos_get_gdb_reg_list(connection)))
1149 retval = target_get_gdb_reg_list(target, ®_list, ®_list_size,
1151 if (retval != ERROR_OK)
1152 return gdb_error(connection, retval);
1154 for (i = 0; i < reg_list_size; i++)
1155 reg_packet_size += DIV_ROUND_UP(reg_list[i]->size, 8) * 2;
1157 assert(reg_packet_size > 0);
1159 reg_packet = malloc(reg_packet_size + 1); /* plus one for string termination null */
1160 if (reg_packet == NULL)
1163 reg_packet_p = reg_packet;
1165 for (i = 0; i < reg_list_size; i++) {
1166 if (!reg_list[i]->valid)
1167 reg_list[i]->type->get(reg_list[i]);
1168 gdb_str_to_target(target, reg_packet_p, reg_list[i]);
1169 reg_packet_p += DIV_ROUND_UP(reg_list[i]->size, 8) * 2;
1172 #ifdef _DEBUG_GDB_IO_
1174 char *reg_packet_p_debug;
1175 reg_packet_p_debug = strndup(reg_packet, reg_packet_size);
1176 LOG_DEBUG("reg_packet: %s", reg_packet_p_debug);
1177 free(reg_packet_p_debug);
1181 gdb_put_packet(connection, reg_packet, reg_packet_size);
1189 static int gdb_set_registers_packet(struct connection *connection,
1190 char const *packet, int packet_size)
1192 struct target *target = get_target_from_connection(connection);
1194 struct reg **reg_list;
1197 char const *packet_p;
1199 #ifdef _DEBUG_GDB_IO_
1203 /* skip command character */
1207 if (packet_size % 2) {
1208 LOG_WARNING("GDB set_registers packet with uneven characters received, dropping connection");
1209 return ERROR_SERVER_REMOTE_CLOSED;
1212 retval = target_get_gdb_reg_list(target, ®_list, ®_list_size,
1214 if (retval != ERROR_OK)
1215 return gdb_error(connection, retval);
1218 for (i = 0; i < reg_list_size; i++) {
1220 int chars = (DIV_ROUND_UP(reg_list[i]->size, 8) * 2);
1222 if (packet_p + chars > packet + packet_size)
1223 LOG_ERROR("BUG: register packet is too small for registers");
1225 bin_buf = malloc(DIV_ROUND_UP(reg_list[i]->size, 8));
1226 gdb_target_to_reg(target, packet_p, chars, bin_buf);
1228 reg_list[i]->type->set(reg_list[i], bin_buf);
1230 /* advance packet pointer */
1236 /* free struct reg *reg_list[] array allocated by get_gdb_reg_list */
1239 gdb_put_packet(connection, "OK", 2);
1244 static int gdb_get_register_packet(struct connection *connection,
1245 char const *packet, int packet_size)
1247 struct target *target = get_target_from_connection(connection);
1249 int reg_num = strtoul(packet + 1, NULL, 16);
1250 struct reg **reg_list;
1254 #ifdef _DEBUG_GDB_IO_
1258 retval = target_get_gdb_reg_list(target, ®_list, ®_list_size,
1260 if (retval != ERROR_OK)
1261 return gdb_error(connection, retval);
1263 if (reg_list_size <= reg_num) {
1264 LOG_ERROR("gdb requested a non-existing register");
1265 return ERROR_SERVER_REMOTE_CLOSED;
1268 if (!reg_list[reg_num]->valid)
1269 reg_list[reg_num]->type->get(reg_list[reg_num]);
1271 reg_packet = malloc(DIV_ROUND_UP(reg_list[reg_num]->size, 8) * 2 + 1); /* plus one for string termination null */
1273 gdb_str_to_target(target, reg_packet, reg_list[reg_num]);
1275 gdb_put_packet(connection, reg_packet, DIV_ROUND_UP(reg_list[reg_num]->size, 8) * 2);
1283 static int gdb_set_register_packet(struct connection *connection,
1284 char const *packet, int packet_size)
1286 struct target *target = get_target_from_connection(connection);
1289 int reg_num = strtoul(packet + 1, &separator, 16);
1290 struct reg **reg_list;
1296 retval = target_get_gdb_reg_list(target, ®_list, ®_list_size,
1298 if (retval != ERROR_OK)
1299 return gdb_error(connection, retval);
1301 if (reg_list_size <= reg_num) {
1302 LOG_ERROR("gdb requested a non-existing register");
1303 return ERROR_SERVER_REMOTE_CLOSED;
1306 if (*separator != '=') {
1307 LOG_ERROR("GDB 'set register packet', but no '=' following the register number");
1308 return ERROR_SERVER_REMOTE_CLOSED;
1311 /* convert from GDB-string (target-endian) to hex-string (big-endian) */
1312 bin_buf = malloc(DIV_ROUND_UP(reg_list[reg_num]->size, 8));
1313 int chars = (DIV_ROUND_UP(reg_list[reg_num]->size, 8) * 2);
1315 if ((unsigned int)chars != strlen(separator + 1)) {
1316 LOG_ERROR("gdb sent a packet with wrong register size");
1318 return ERROR_SERVER_REMOTE_CLOSED;
1321 gdb_target_to_reg(target, separator + 1, chars, bin_buf);
1323 reg_list[reg_num]->type->set(reg_list[reg_num], bin_buf);
1325 gdb_put_packet(connection, "OK", 2);
1333 /* No attempt is made to translate the "retval" to
1334 * GDB speak. This has to be done at the calling
1335 * site as no mapping really exists.
1337 static int gdb_error(struct connection *connection, int retval)
1339 LOG_DEBUG("Reporting %i to GDB as generic error", retval);
1340 gdb_send_error(connection, EFAULT);
1344 /* We don't have to worry about the default 2 second timeout for GDB packets,
1345 * because GDB breaks up large memory reads into smaller reads.
1347 * 8191 bytes by the looks of it. Why 8191 bytes instead of 8192?????
1349 static int gdb_read_memory_packet(struct connection *connection,
1350 char const *packet, int packet_size)
1352 struct target *target = get_target_from_connection(connection);
1360 int retval = ERROR_OK;
1362 /* skip command character */
1365 addr = strtoul(packet, &separator, 16);
1367 if (*separator != ',') {
1368 LOG_ERROR("incomplete read memory packet received, dropping connection");
1369 return ERROR_SERVER_REMOTE_CLOSED;
1372 len = strtoul(separator + 1, NULL, 16);
1375 LOG_WARNING("invalid read memory packet received (len == 0)");
1376 gdb_put_packet(connection, NULL, 0);
1380 buffer = malloc(len);
1382 LOG_DEBUG("addr: 0x%8.8" PRIx32 ", len: 0x%8.8" PRIx32 "", addr, len);
1384 retval = target_read_buffer(target, addr, len, buffer);
1386 if ((retval != ERROR_OK) && !gdb_report_data_abort) {
1387 /* TODO : Here we have to lie and send back all zero's lest stack traces won't work.
1388 * At some point this might be fixed in GDB, in which case this code can be removed.
1390 * OpenOCD developers are acutely aware of this problem, but there is nothing
1391 * gained by involving the user in this problem that hopefully will get resolved
1394 * http://sourceware.org/cgi-bin/gnatsweb.pl? \
1395 * cmd = view%20audit-trail&database = gdb&pr = 2395
1397 * For now, the default is to fix up things to make current GDB versions work.
1398 * This can be overwritten using the gdb_report_data_abort <'enable'|'disable'> command.
1400 memset(buffer, 0, len);
1404 if (retval == ERROR_OK) {
1405 hex_buffer = malloc(len * 2 + 1);
1407 int pkt_len = hexify(hex_buffer, (char *)buffer, len, len * 2 + 1);
1409 gdb_put_packet(connection, hex_buffer, pkt_len);
1413 retval = gdb_error(connection, retval);
1420 static int gdb_write_memory_packet(struct connection *connection,
1421 char const *packet, int packet_size)
1423 struct target *target = get_target_from_connection(connection);
1431 /* skip command character */
1434 addr = strtoul(packet, &separator, 16);
1436 if (*separator != ',') {
1437 LOG_ERROR("incomplete write memory packet received, dropping connection");
1438 return ERROR_SERVER_REMOTE_CLOSED;
1441 len = strtoul(separator + 1, &separator, 16);
1443 if (*(separator++) != ':') {
1444 LOG_ERROR("incomplete write memory packet received, dropping connection");
1445 return ERROR_SERVER_REMOTE_CLOSED;
1448 buffer = malloc(len);
1450 LOG_DEBUG("addr: 0x%8.8" PRIx32 ", len: 0x%8.8" PRIx32 "", addr, len);
1452 if (unhexify((char *)buffer, separator, len) != (int)len)
1453 LOG_ERROR("unable to decode memory packet");
1455 retval = target_write_buffer(target, addr, len, buffer);
1457 if (retval == ERROR_OK)
1458 gdb_put_packet(connection, "OK", 2);
1460 retval = gdb_error(connection, retval);
1467 static int gdb_write_memory_binary_packet(struct connection *connection,
1468 char const *packet, int packet_size)
1470 struct target *target = get_target_from_connection(connection);
1475 int retval = ERROR_OK;
1477 /* skip command character */
1480 addr = strtoul(packet, &separator, 16);
1482 if (*separator != ',') {
1483 LOG_ERROR("incomplete write memory binary packet received, dropping connection");
1484 return ERROR_SERVER_REMOTE_CLOSED;
1487 len = strtoul(separator + 1, &separator, 16);
1489 if (*(separator++) != ':') {
1490 LOG_ERROR("incomplete write memory binary packet received, dropping connection");
1491 return ERROR_SERVER_REMOTE_CLOSED;
1494 struct gdb_connection *gdb_connection = connection->priv;
1496 if (gdb_connection->mem_write_error) {
1497 retval = ERROR_FAIL;
1498 /* now that we have reported the memory write error, we can clear the condition */
1499 gdb_connection->mem_write_error = false;
1502 /* By replying the packet *immediately* GDB will send us a new packet
1503 * while we write the last one to the target.
1505 if (retval == ERROR_OK)
1506 gdb_put_packet(connection, "OK", 2);
1508 retval = gdb_error(connection, retval);
1509 if (retval != ERROR_OK)
1514 LOG_DEBUG("addr: 0x%8.8" PRIx32 ", len: 0x%8.8" PRIx32 "", addr, len);
1516 retval = target_write_buffer(target, addr, len, (uint8_t *)separator);
1517 if (retval != ERROR_OK)
1518 gdb_connection->mem_write_error = true;
1524 static int gdb_step_continue_packet(struct connection *connection,
1525 char const *packet, int packet_size)
1527 struct target *target = get_target_from_connection(connection);
1529 uint32_t address = 0x0;
1530 int retval = ERROR_OK;
1534 if (packet_size > 1)
1535 address = strtoul(packet + 1, NULL, 16);
1539 gdb_running_type = packet[0];
1540 if (packet[0] == 'c') {
1541 LOG_DEBUG("continue");
1542 /* resume at current address, don't handle breakpoints, not debugging */
1543 retval = target_resume(target, current, address, 0, 0);
1544 } else if (packet[0] == 's') {
1546 /* step at current or address, don't handle breakpoints */
1547 retval = target_step(target, current, address, 0);
1552 static int gdb_breakpoint_watchpoint_packet(struct connection *connection,
1553 char const *packet, int packet_size)
1555 struct target *target = get_target_from_connection(connection);
1557 enum breakpoint_type bp_type = BKPT_SOFT /* dummy init to avoid warning */;
1558 enum watchpoint_rw wp_type = WPT_READ /* dummy init to avoid warning */;
1566 type = strtoul(packet + 1, &separator, 16);
1568 if (type == 0) /* memory breakpoint */
1569 bp_type = BKPT_SOFT;
1570 else if (type == 1) /* hardware breakpoint */
1571 bp_type = BKPT_HARD;
1572 else if (type == 2) /* write watchpoint */
1573 wp_type = WPT_WRITE;
1574 else if (type == 3) /* read watchpoint */
1576 else if (type == 4) /* access watchpoint */
1577 wp_type = WPT_ACCESS;
1579 LOG_ERROR("invalid gdb watch/breakpoint type(%d), dropping connection", type);
1580 return ERROR_SERVER_REMOTE_CLOSED;
1583 if (gdb_breakpoint_override && ((bp_type == BKPT_SOFT) || (bp_type == BKPT_HARD)))
1584 bp_type = gdb_breakpoint_override_type;
1586 if (*separator != ',') {
1587 LOG_ERROR("incomplete breakpoint/watchpoint packet received, dropping connection");
1588 return ERROR_SERVER_REMOTE_CLOSED;
1591 address = strtoul(separator + 1, &separator, 16);
1593 if (*separator != ',') {
1594 LOG_ERROR("incomplete breakpoint/watchpoint packet received, dropping connection");
1595 return ERROR_SERVER_REMOTE_CLOSED;
1598 size = strtoul(separator + 1, &separator, 16);
1603 if (packet[0] == 'Z') {
1604 retval = breakpoint_add(target, address, size, bp_type);
1605 if (retval != ERROR_OK) {
1606 retval = gdb_error(connection, retval);
1607 if (retval != ERROR_OK)
1610 gdb_put_packet(connection, "OK", 2);
1612 breakpoint_remove(target, address);
1613 gdb_put_packet(connection, "OK", 2);
1620 if (packet[0] == 'Z') {
1621 retval = watchpoint_add(target, address, size, wp_type, 0, 0xffffffffu);
1622 if (retval != ERROR_OK) {
1623 retval = gdb_error(connection, retval);
1624 if (retval != ERROR_OK)
1627 gdb_put_packet(connection, "OK", 2);
1629 watchpoint_remove(target, address);
1630 gdb_put_packet(connection, "OK", 2);
1641 /* print out a string and allocate more space as needed,
1642 * mainly used for XML at this point
1644 static void xml_printf(int *retval, char **xml, int *pos, int *size,
1645 const char *fmt, ...)
1647 if (*retval != ERROR_OK)
1652 if ((*xml == NULL) || (!first)) {
1653 /* start by 0 to exercise all the code paths.
1654 * Need minimum 2 bytes to fit 1 char and 0 terminator. */
1656 *size = *size * 2 + 2;
1658 *xml = realloc(*xml, *size);
1662 *retval = ERROR_SERVER_REMOTE_CLOSED;
1670 ret = vsnprintf(*xml + *pos, *size - *pos, fmt, ap);
1672 if ((ret > 0) && ((ret + 1) < *size - *pos)) {
1676 /* there was just enough or not enough space, allocate more. */
1681 static int decode_xfer_read(char const *buf, char **annex, int *ofs, unsigned int *len)
1683 /* Locate the annex. */
1684 const char *annex_end = strchr(buf, ':');
1685 if (annex_end == NULL)
1688 /* After the read marker and annex, qXfer looks like a
1689 * traditional 'm' packet. */
1691 *ofs = strtoul(annex_end + 1, &separator, 16);
1693 if (*separator != ',')
1696 *len = strtoul(separator + 1, NULL, 16);
1698 /* Extract the annex if needed */
1699 if (annex != NULL) {
1700 *annex = strndup(buf, annex_end - buf);
1708 static int compare_bank(const void *a, const void *b)
1710 struct flash_bank *b1, *b2;
1711 b1 = *((struct flash_bank **)a);
1712 b2 = *((struct flash_bank **)b);
1714 if (b1->base == b2->base)
1716 else if (b1->base > b2->base)
1722 static int gdb_memory_map(struct connection *connection,
1723 char const *packet, int packet_size)
1725 /* We get away with only specifying flash here. Regions that are not
1726 * specified are treated as if we provided no memory map(if not we
1727 * could detect the holes and mark them as RAM).
1728 * Normally we only execute this code once, but no big deal if we
1729 * have to regenerate it a couple of times.
1732 struct target *target = get_target_from_connection(connection);
1733 struct flash_bank *p;
1737 int retval = ERROR_OK;
1738 struct flash_bank **banks;
1742 uint32_t ram_start = 0;
1744 int target_flash_banks = 0;
1746 /* skip command character */
1749 offset = strtoul(packet, &separator, 16);
1750 length = strtoul(separator + 1, &separator, 16);
1752 xml_printf(&retval, &xml, &pos, &size, "<memory-map>\n");
1754 /* Sort banks in ascending order. We need to report non-flash
1755 * memory as ram (or rather read/write) by default for GDB, since
1756 * it has no concept of non-cacheable read/write memory (i/o etc).
1758 * FIXME Most non-flash addresses are *NOT* RAM! Don't lie.
1759 * Current versions of GDB assume unlisted addresses are RAM...
1761 banks = malloc(sizeof(struct flash_bank *)*flash_get_bank_count());
1763 for (i = 0; i < flash_get_bank_count(); i++) {
1764 p = get_flash_bank_by_num_noprobe(i);
1765 if (p->target != target)
1767 retval = get_flash_bank_by_num(i, &p);
1768 if (retval != ERROR_OK) {
1770 gdb_error(connection, retval);
1773 banks[target_flash_banks++] = p;
1776 qsort(banks, target_flash_banks, sizeof(struct flash_bank *),
1779 for (i = 0; i < target_flash_banks; i++) {
1781 unsigned sector_size = 0;
1787 if (ram_start < p->base)
1788 xml_printf(&retval, &xml, &pos, &size,
1789 "<memory type=\"ram\" start=\"0x%x\" "
1790 "length=\"0x%x\"/>\n",
1791 ram_start, p->base - ram_start);
1793 /* Report adjacent groups of same-size sectors. So for
1794 * example top boot CFI flash will list an initial region
1795 * with several large sectors (maybe 128KB) and several
1796 * smaller ones at the end (maybe 32KB). STR7 will have
1797 * regions with 8KB, 32KB, and 64KB sectors; etc.
1799 for (j = 0; j < p->num_sectors; j++) {
1802 /* Maybe start a new group of sectors. */
1803 if (sector_size == 0) {
1804 start = p->base + p->sectors[j].offset;
1805 xml_printf(&retval, &xml, &pos, &size,
1806 "<memory type=\"flash\" "
1809 sector_size = p->sectors[j].size;
1812 /* Does this finish a group of sectors?
1813 * If not, continue an already-started group.
1815 if (j == p->num_sectors - 1)
1816 group_len = (p->base + p->size) - start;
1817 else if (p->sectors[j + 1].size != sector_size)
1818 group_len = p->base + p->sectors[j + 1].offset
1823 xml_printf(&retval, &xml, &pos, &size,
1824 "length=\"0x%x\">\n"
1825 "<property name=\"blocksize\">"
1833 ram_start = p->base + p->size;
1837 xml_printf(&retval, &xml, &pos, &size,
1838 "<memory type=\"ram\" start=\"0x%x\" "
1839 "length=\"0x%x\"/>\n",
1840 ram_start, 0-ram_start);
1841 /* ELSE a flash chip could be at the very end of the 32 bit address
1842 * space, in which case ram_start will be precisely 0
1848 xml_printf(&retval, &xml, &pos, &size, "</memory-map>\n");
1850 if (retval != ERROR_OK) {
1851 gdb_error(connection, retval);
1855 if (offset + length > pos)
1856 length = pos - offset;
1858 char *t = malloc(length + 1);
1860 memcpy(t + 1, xml + offset, length);
1861 gdb_put_packet(connection, t, length + 1);
1868 static const char *gdb_get_reg_type_name(enum reg_type type)
1875 case REG_TYPE_INT16:
1877 case REG_TYPE_INT32:
1879 case REG_TYPE_INT64:
1881 case REG_TYPE_INT128:
1883 case REG_TYPE_UINT8:
1885 case REG_TYPE_UINT16:
1887 case REG_TYPE_UINT32:
1889 case REG_TYPE_UINT64:
1891 case REG_TYPE_UINT128:
1893 case REG_TYPE_CODE_PTR:
1895 case REG_TYPE_DATA_PTR:
1897 case REG_TYPE_FLOAT:
1899 case REG_TYPE_IEEE_SINGLE:
1900 return "ieee_single";
1901 case REG_TYPE_IEEE_DOUBLE:
1902 return "ieee_double";
1903 case REG_TYPE_ARCH_DEFINED:
1904 return "int"; /* return arbitrary string to avoid compile warning. */
1907 return "int"; /* "int" as default value */
1910 static int gdb_generate_reg_type_description(struct target *target,
1911 char **tdesc, int *pos, int *size, struct reg_data_type *type)
1913 int retval = ERROR_OK;
1915 if (type->type_class == REG_TYPE_CLASS_VECTOR) {
1916 /* <vector id="id" type="type" count="count"/> */
1917 xml_printf(&retval, tdesc, pos, size,
1918 "<vector id=\"%s\" type=\"%s\" count=\"%d\"/>\n",
1919 type->id, type->reg_type_vector->type->id,
1920 type->reg_type_vector->count);
1922 } else if (type->type_class == REG_TYPE_CLASS_UNION) {
1924 * <field name="name" type="type"/> ...
1926 xml_printf(&retval, tdesc, pos, size,
1927 "<union id=\"%s\">\n",
1930 struct reg_data_type_union_field *field;
1931 field = type->reg_type_union->fields;
1932 while (field != NULL) {
1933 xml_printf(&retval, tdesc, pos, size,
1934 "<field name=\"%s\" type=\"%s\"/>\n",
1935 field->name, field->type->id);
1937 field = field->next;
1940 xml_printf(&retval, tdesc, pos, size,
1943 } else if (type->type_class == REG_TYPE_CLASS_STRUCT) {
1944 struct reg_data_type_struct_field *field;
1945 field = type->reg_type_struct->fields;
1947 if (field->use_bitfields) {
1948 /* <struct id="id" size="size">
1949 * <field name="name" start="start" end="end"/> ...
1951 xml_printf(&retval, tdesc, pos, size,
1952 "<struct id=\"%s\" size=\"%d\">\n",
1953 type->id, type->reg_type_struct->size);
1954 while (field != NULL) {
1955 xml_printf(&retval, tdesc, pos, size,
1956 "<field name=\"%s\" start=\"%d\" end=\"%d\"/>\n",
1957 field->name, field->bitfield->start,
1958 field->bitfield->end);
1960 field = field->next;
1964 * <field name="name" type="type"/> ...
1966 xml_printf(&retval, tdesc, pos, size,
1967 "<struct id=\"%s\">\n",
1969 while (field != NULL) {
1970 xml_printf(&retval, tdesc, pos, size,
1971 "<field name=\"%s\" type=\"%s\"/>\n",
1972 field->name, field->type->id);
1974 field = field->next;
1978 xml_printf(&retval, tdesc, pos, size,
1981 } else if (type->type_class == REG_TYPE_CLASS_FLAGS) {
1982 /* <flags id="id" size="size">
1983 * <field name="name" start="start" end="end"/> ...
1985 xml_printf(&retval, tdesc, pos, size,
1986 "<flags id=\"%s\" size=\"%d\">\n",
1987 type->id, type->reg_type_flags->size);
1989 struct reg_data_type_flags_field *field;
1990 field = type->reg_type_flags->fields;
1991 while (field != NULL) {
1992 xml_printf(&retval, tdesc, pos, size,
1993 "<field name=\"%s\" start=\"%d\" end=\"%d\"/>\n",
1994 field->name, field->bitfield->start, field->bitfield->end);
1996 field = field->next;
1999 xml_printf(&retval, tdesc, pos, size,
2007 /* Get a list of available target registers features. feature_list must
2008 * be freed by caller.
2010 static int get_reg_features_list(struct target *target, char const **feature_list[], int *feature_list_size,
2011 struct reg **reg_list, int reg_list_size)
2015 /* Start with only one element */
2016 *feature_list = calloc(1, sizeof(char *));
2018 for (int i = 0; i < reg_list_size; i++) {
2019 if (reg_list[i]->exist == false)
2022 if (reg_list[i]->feature != NULL
2023 && reg_list[i]->feature->name != NULL
2024 && (strcmp(reg_list[i]->feature->name, ""))) {
2025 /* We found a feature, check if the feature is already in the
2026 * table. If not, allocate a new entry for the table and
2027 * put the new feature in it.
2029 for (int j = 0; j < (tbl_sz + 1); j++) {
2030 if (!((*feature_list)[j])) {
2031 (*feature_list)[tbl_sz++] = reg_list[i]->feature->name;
2032 *feature_list = realloc(*feature_list, sizeof(char *) * (tbl_sz + 1));
2033 (*feature_list)[tbl_sz] = NULL;
2036 if (!strcmp((*feature_list)[j], reg_list[i]->feature->name))
2043 if (feature_list_size)
2044 *feature_list_size = tbl_sz;
2049 static int gdb_generate_target_description(struct target *target, char **tdesc_out)
2051 int retval = ERROR_OK;
2052 struct reg **reg_list = NULL;
2054 char const **features = NULL;
2055 int feature_list_size = 0;
2060 retval = target_get_gdb_reg_list(target, ®_list,
2061 ®_list_size, REG_CLASS_ALL);
2063 if (retval != ERROR_OK) {
2064 LOG_ERROR("get register list failed");
2065 retval = ERROR_FAIL;
2069 if (reg_list_size <= 0) {
2070 LOG_ERROR("get register list failed");
2071 retval = ERROR_FAIL;
2075 /* Get a list of available target registers features */
2076 retval = get_reg_features_list(target, &features, &feature_list_size, reg_list, reg_list_size);
2077 if (retval != ERROR_OK) {
2078 LOG_ERROR("Can't get the registers feature list");
2079 retval = ERROR_FAIL;
2083 /* If we found some features associated with registers, create sections */
2084 int current_feature = 0;
2086 xml_printf(&retval, &tdesc, &pos, &size,
2087 "<?xml version=\"1.0\"?>\n"
2088 "<!DOCTYPE target SYSTEM \"gdb-target.dtd\">\n"
2089 "<target version=\"1.0\">\n");
2091 /* generate target description according to register list */
2092 if (features != NULL) {
2093 while (features[current_feature]) {
2095 xml_printf(&retval, &tdesc, &pos, &size,
2096 "<feature name=\"%s\">\n",
2097 features[current_feature]);
2100 for (i = 0; i < reg_list_size; i++) {
2102 if (reg_list[i]->exist == false)
2105 if (strcmp(reg_list[i]->feature->name, features[current_feature]))
2108 const char *type_str;
2109 if (reg_list[i]->reg_data_type != NULL) {
2110 if (reg_list[i]->reg_data_type->type == REG_TYPE_ARCH_DEFINED) {
2111 /* generate <type... first, if there are architecture-defined types. */
2112 gdb_generate_reg_type_description(target, &tdesc, &pos, &size,
2113 reg_list[i]->reg_data_type);
2115 type_str = reg_list[i]->reg_data_type->id;
2117 /* predefined type */
2118 type_str = gdb_get_reg_type_name(
2119 reg_list[i]->reg_data_type->type);
2122 /* Default type is "int" */
2126 xml_printf(&retval, &tdesc, &pos, &size,
2127 "<reg name=\"%s\"", reg_list[i]->name);
2128 xml_printf(&retval, &tdesc, &pos, &size,
2129 " bitsize=\"%d\"", reg_list[i]->size);
2130 xml_printf(&retval, &tdesc, &pos, &size,
2131 " regnum=\"%d\"", reg_list[i]->number);
2132 if (reg_list[i]->caller_save)
2133 xml_printf(&retval, &tdesc, &pos, &size,
2134 " save-restore=\"yes\"");
2136 xml_printf(&retval, &tdesc, &pos, &size,
2137 " save-restore=\"no\"");
2139 xml_printf(&retval, &tdesc, &pos, &size,
2140 " type=\"%s\"", type_str);
2142 if (reg_list[i]->group != NULL)
2143 xml_printf(&retval, &tdesc, &pos, &size,
2144 " group=\"%s\"", reg_list[i]->group);
2146 xml_printf(&retval, &tdesc, &pos, &size,
2150 xml_printf(&retval, &tdesc, &pos, &size,
2157 xml_printf(&retval, &tdesc, &pos, &size,
2164 if (retval == ERROR_OK)
2172 static int gdb_get_target_description_chunk(struct target *target, struct target_desc_format *target_desc,
2173 char **chunk, int32_t offset, uint32_t length)
2175 if (target_desc == NULL) {
2176 LOG_ERROR("Unable to Generate Target Description");
2180 char *tdesc = target_desc->tdesc;
2181 uint32_t tdesc_length = target_desc->tdesc_length;
2183 if (tdesc == NULL) {
2184 int retval = gdb_generate_target_description(target, &tdesc);
2185 if (retval != ERROR_OK) {
2186 LOG_ERROR("Unable to Generate Target Description");
2190 tdesc_length = strlen(tdesc);
2195 if (length < (tdesc_length - offset))
2196 transfer_type = 'm';
2198 transfer_type = 'l';
2200 *chunk = malloc(length + 2);
2201 if (*chunk == NULL) {
2202 LOG_ERROR("Unable to allocate memory");
2206 (*chunk)[0] = transfer_type;
2207 if (transfer_type == 'm') {
2208 strncpy((*chunk) + 1, tdesc + offset, length);
2209 (*chunk)[1 + length] = '\0';
2211 strncpy((*chunk) + 1, tdesc + offset, tdesc_length - offset);
2212 (*chunk)[1 + (tdesc_length - offset)] = '\0';
2214 /* After gdb-server sends out last chunk, invalidate tdesc. */
2220 target_desc->tdesc = tdesc;
2221 target_desc->tdesc_length = tdesc_length;
2226 static int gdb_target_description_supported(struct target *target, int *supported)
2228 int retval = ERROR_OK;
2229 struct reg **reg_list = NULL;
2230 int reg_list_size = 0;
2231 char const **features = NULL;
2232 int feature_list_size = 0;
2234 retval = target_get_gdb_reg_list(target, ®_list,
2235 ®_list_size, REG_CLASS_ALL);
2236 if (retval != ERROR_OK) {
2237 LOG_ERROR("get register list failed");
2241 if (reg_list_size <= 0) {
2242 LOG_ERROR("get register list failed");
2243 retval = ERROR_FAIL;
2247 /* Get a list of available target registers features */
2248 retval = get_reg_features_list(target, &features, &feature_list_size, reg_list, reg_list_size);
2249 if (retval != ERROR_OK) {
2250 LOG_ERROR("Can't get the registers feature list");
2255 if (feature_list_size)
2269 static int gdb_query_packet(struct connection *connection,
2270 char const *packet, int packet_size)
2272 struct command_context *cmd_ctx = connection->cmd_ctx;
2273 struct gdb_connection *gdb_connection = connection->priv;
2274 struct target *target = get_target_from_connection(connection);
2276 if (strncmp(packet, "qRcmd,", 6) == 0) {
2277 if (packet_size > 6) {
2279 cmd = malloc((packet_size - 6) / 2 + 1);
2280 int len = unhexify(cmd, packet + 6, (packet_size - 6) / 2);
2283 /* We want to print all debug output to GDB connection */
2284 log_add_callback(gdb_log_callback, connection);
2285 target_call_timer_callbacks_now();
2286 /* some commands need to know the GDB connection, make note of current
2287 * GDB connection. */
2288 current_gdb_connection = gdb_connection;
2289 command_run_line(cmd_ctx, cmd);
2290 current_gdb_connection = NULL;
2291 target_call_timer_callbacks_now();
2292 log_remove_callback(gdb_log_callback, connection);
2295 gdb_put_packet(connection, "OK", 2);
2297 } else if (strncmp(packet, "qCRC:", 5) == 0) {
2298 if (packet_size > 5) {
2306 /* skip command character */
2309 addr = strtoul(packet, &separator, 16);
2311 if (*separator != ',') {
2312 LOG_ERROR("incomplete read memory packet received, dropping connection");
2313 return ERROR_SERVER_REMOTE_CLOSED;
2316 len = strtoul(separator + 1, NULL, 16);
2318 retval = target_checksum_memory(target, addr, len, &checksum);
2320 if (retval == ERROR_OK) {
2321 snprintf(gdb_reply, 10, "C%8.8" PRIx32 "", checksum);
2322 gdb_put_packet(connection, gdb_reply, 9);
2324 retval = gdb_error(connection, retval);
2325 if (retval != ERROR_OK)
2331 } else if (strncmp(packet, "qSupported", 10) == 0) {
2332 /* we currently support packet size and qXfer:memory-map:read (if enabled)
2333 * qXfer:features:read is supported for some targets */
2334 int retval = ERROR_OK;
2335 char *buffer = NULL;
2338 int gdb_target_desc_supported = 0;
2340 /* we need to test that the target supports target descriptions */
2341 retval = gdb_target_description_supported(target, &gdb_target_desc_supported);
2342 if (retval != ERROR_OK) {
2343 LOG_INFO("Failed detecting Target Description Support, disabling");
2344 gdb_target_desc_supported = 0;
2347 /* support may be disabled globally */
2348 if (gdb_use_target_description == 0) {
2349 if (gdb_target_desc_supported)
2350 LOG_WARNING("Target Descriptions Supported, but disabled");
2351 gdb_target_desc_supported = 0;
2358 "PacketSize=%x;qXfer:memory-map:read%c;qXfer:features:read%c;QStartNoAckMode+",
2359 (GDB_BUFFER_SIZE - 1),
2360 ((gdb_use_memory_map == 1) && (flash_get_bank_count() > 0)) ? '+' : '-',
2361 (gdb_target_desc_supported == 1) ? '+' : '-');
2363 if (retval != ERROR_OK) {
2364 gdb_send_error(connection, 01);
2368 gdb_put_packet(connection, buffer, strlen(buffer));
2372 } else if ((strncmp(packet, "qXfer:memory-map:read::", 23) == 0)
2373 && (flash_get_bank_count() > 0))
2374 return gdb_memory_map(connection, packet, packet_size);
2375 else if (strncmp(packet, "qXfer:features:read:", 20) == 0) {
2377 int retval = ERROR_OK;
2380 unsigned int length;
2382 /* skip command character */
2385 if (decode_xfer_read(packet, NULL, &offset, &length) < 0) {
2386 gdb_send_error(connection, 01);
2390 /* Target should prepare correct target description for annex.
2391 * The first character of returned xml is 'm' or 'l'. 'm' for
2392 * there are *more* chunks to transfer. 'l' for it is the *last*
2393 * chunk of target description.
2395 retval = gdb_get_target_description_chunk(target, &gdb_connection->target_desc,
2396 &xml, offset, length);
2397 if (retval != ERROR_OK) {
2398 gdb_error(connection, retval);
2402 gdb_put_packet(connection, xml, strlen(xml));
2406 } else if (strncmp(packet, "QStartNoAckMode", 15) == 0) {
2407 gdb_connection->noack_mode = 1;
2408 gdb_put_packet(connection, "OK", 2);
2412 gdb_put_packet(connection, "", 0);
2416 static int gdb_v_packet(struct connection *connection,
2417 char const *packet, int packet_size)
2419 struct gdb_connection *gdb_connection = connection->priv;
2420 struct gdb_service *gdb_service = connection->service->priv;
2423 /* if flash programming disabled - send a empty reply */
2425 if (gdb_flash_program == 0) {
2426 gdb_put_packet(connection, "", 0);
2430 if (strncmp(packet, "vFlashErase:", 12) == 0) {
2432 unsigned long length;
2434 char const *parse = packet + 12;
2435 if (*parse == '\0') {
2436 LOG_ERROR("incomplete vFlashErase packet received, dropping connection");
2437 return ERROR_SERVER_REMOTE_CLOSED;
2440 addr = strtoul(parse, (char **)&parse, 16);
2442 if (*(parse++) != ',' || *parse == '\0') {
2443 LOG_ERROR("incomplete vFlashErase packet received, dropping connection");
2444 return ERROR_SERVER_REMOTE_CLOSED;
2447 length = strtoul(parse, (char **)&parse, 16);
2449 if (*parse != '\0') {
2450 LOG_ERROR("incomplete vFlashErase packet received, dropping connection");
2451 return ERROR_SERVER_REMOTE_CLOSED;
2454 /* assume all sectors need erasing - stops any problems
2455 * when flash_write is called multiple times */
2458 /* perform any target specific operations before the erase */
2459 target_call_event_callbacks(gdb_service->target,
2460 TARGET_EVENT_GDB_FLASH_ERASE_START);
2462 /* vFlashErase:addr,length messages require region start and
2463 * end to be "block" aligned ... if padding is ever needed,
2464 * GDB will have become dangerously confused.
2466 result = flash_erase_address_range(gdb_service->target,
2467 false, addr, length);
2469 /* perform any target specific operations after the erase */
2470 target_call_event_callbacks(gdb_service->target,
2471 TARGET_EVENT_GDB_FLASH_ERASE_END);
2474 if (result != ERROR_OK) {
2475 /* GDB doesn't evaluate the actual error number returned,
2476 * treat a failed erase as an I/O error
2478 gdb_send_error(connection, EIO);
2479 LOG_ERROR("flash_erase returned %i", result);
2481 gdb_put_packet(connection, "OK", 2);
2486 if (strncmp(packet, "vFlashWrite:", 12) == 0) {
2489 unsigned long length;
2490 char const *parse = packet + 12;
2492 if (*parse == '\0') {
2493 LOG_ERROR("incomplete vFlashErase packet received, dropping connection");
2494 return ERROR_SERVER_REMOTE_CLOSED;
2496 addr = strtoul(parse, (char **)&parse, 16);
2497 if (*(parse++) != ':') {
2498 LOG_ERROR("incomplete vFlashErase packet received, dropping connection");
2499 return ERROR_SERVER_REMOTE_CLOSED;
2501 length = packet_size - (parse - packet);
2503 /* create a new image if there isn't already one */
2504 if (gdb_connection->vflash_image == NULL) {
2505 gdb_connection->vflash_image = malloc(sizeof(struct image));
2506 image_open(gdb_connection->vflash_image, "", "build");
2509 /* create new section with content from packet buffer */
2510 retval = image_add_section(gdb_connection->vflash_image,
2511 addr, length, 0x0, (uint8_t const *)parse);
2512 if (retval != ERROR_OK)
2515 gdb_put_packet(connection, "OK", 2);
2520 if (strncmp(packet, "vFlashDone", 10) == 0) {
2523 /* process the flashing buffer. No need to erase as GDB
2524 * always issues a vFlashErase first. */
2525 target_call_event_callbacks(gdb_service->target,
2526 TARGET_EVENT_GDB_FLASH_WRITE_START);
2527 result = flash_write(gdb_service->target, gdb_connection->vflash_image, &written, 0);
2528 target_call_event_callbacks(gdb_service->target, TARGET_EVENT_GDB_FLASH_WRITE_END);
2529 if (result != ERROR_OK) {
2530 if (result == ERROR_FLASH_DST_OUT_OF_BANK)
2531 gdb_put_packet(connection, "E.memtype", 9);
2533 gdb_send_error(connection, EIO);
2535 LOG_DEBUG("wrote %u bytes from vFlash image to flash", (unsigned)written);
2536 gdb_put_packet(connection, "OK", 2);
2539 image_close(gdb_connection->vflash_image);
2540 free(gdb_connection->vflash_image);
2541 gdb_connection->vflash_image = NULL;
2546 gdb_put_packet(connection, "", 0);
2550 static int gdb_detach(struct connection *connection)
2552 struct gdb_service *gdb_service = connection->service->priv;
2554 target_call_event_callbacks(gdb_service->target, TARGET_EVENT_GDB_DETACH);
2556 return gdb_put_packet(connection, "OK", 2);
2559 /* The format of 'F' response packet is
2560 * Fretcode,errno,Ctrl-C flag;call-specific attachment
2562 static int gdb_fileio_response_packet(struct connection *connection,
2563 char const *packet, int packet_size)
2565 struct target *target = get_target_from_connection(connection);
2567 char *parsing_point;
2568 int fileio_retcode = strtoul(packet + 1, &separator, 16);
2569 int fileio_errno = 0;
2570 bool fileio_ctrl_c = false;
2575 if (*separator == ',') {
2576 parsing_point = separator + 1;
2577 fileio_errno = strtoul(parsing_point, &separator, 16);
2578 if (*separator == ',') {
2579 if (*(separator + 1) == 'C') {
2580 /* TODO: process ctrl-c */
2581 fileio_ctrl_c = true;
2586 LOG_DEBUG("File-I/O response, retcode: 0x%x, errno: 0x%x, ctrl-c: %s",
2587 fileio_retcode, fileio_errno, fileio_ctrl_c ? "true" : "false");
2589 retval = target_gdb_fileio_end(target, fileio_retcode, fileio_errno, fileio_ctrl_c);
2590 if (retval != ERROR_OK)
2593 /* After File-I/O ends, keep continue or step */
2594 if (gdb_running_type == 'c')
2595 retval = target_resume(target, 1, 0x0, 0, 0);
2596 else if (gdb_running_type == 's')
2597 retval = target_step(target, 1, 0x0, 0);
2599 retval = ERROR_FAIL;
2601 if (retval != ERROR_OK)
2607 static void gdb_log_callback(void *priv, const char *file, unsigned line,
2608 const char *function, const char *string)
2610 struct connection *connection = priv;
2611 struct gdb_connection *gdb_con = connection->priv;
2613 if (gdb_con->busy) {
2614 /* do not reply this using the O packet */
2618 gdb_output_con(connection, string);
2621 static void gdb_sig_halted(struct connection *connection)
2624 snprintf(sig_reply, 4, "T%2.2x", 2);
2625 gdb_put_packet(connection, sig_reply, 3);
2628 static int gdb_input_inner(struct connection *connection)
2630 /* Do not allocate this on the stack */
2631 static char gdb_packet_buffer[GDB_BUFFER_SIZE];
2633 struct gdb_service *gdb_service = connection->service->priv;
2634 struct target *target = gdb_service->target;
2635 char const *packet = gdb_packet_buffer;
2638 struct gdb_connection *gdb_con = connection->priv;
2639 static int extended_protocol;
2641 /* drain input buffer. If one of the packets fail, then an error
2642 * packet is replied, if applicable.
2644 * This loop will terminate and the error code is returned.
2646 * The calling fn will check if this error is something that
2647 * can be recovered from, or if the connection must be closed.
2649 * If the error is recoverable, this fn is called again to
2650 * drain the rest of the buffer.
2653 packet_size = GDB_BUFFER_SIZE-1;
2654 retval = gdb_get_packet(connection, gdb_packet_buffer, &packet_size);
2655 if (retval != ERROR_OK)
2658 /* terminate with zero */
2659 gdb_packet_buffer[packet_size] = '\0';
2661 if (LOG_LEVEL_IS(LOG_LVL_DEBUG)) {
2662 if (packet[0] == 'X') {
2663 /* binary packets spew junk into the debug log stream */
2666 for (x = 0; (x < 49) && (packet[x] != ':'); x++)
2669 LOG_DEBUG("received packet: '%s:<binary-data>'", buf);
2671 LOG_DEBUG("received packet: '%s'", packet);
2674 if (packet_size > 0) {
2676 switch (packet[0]) {
2677 case 'T': /* Is thread alive? */
2678 gdb_thread_packet(connection, packet, packet_size);
2680 case 'H': /* Set current thread ( 'c' for step and continue,
2681 * 'g' for all other operations ) */
2682 gdb_thread_packet(connection, packet, packet_size);
2686 retval = gdb_thread_packet(connection, packet, packet_size);
2687 if (retval == GDB_THREAD_PACKET_NOT_CONSUMED)
2688 retval = gdb_query_packet(connection, packet, packet_size);
2691 retval = gdb_get_registers_packet(connection, packet, packet_size);
2694 retval = gdb_set_registers_packet(connection, packet, packet_size);
2697 retval = gdb_get_register_packet(connection, packet, packet_size);
2700 retval = gdb_set_register_packet(connection, packet, packet_size);
2703 retval = gdb_read_memory_packet(connection, packet, packet_size);
2706 retval = gdb_write_memory_packet(connection, packet, packet_size);
2710 retval = gdb_breakpoint_watchpoint_packet(connection, packet, packet_size);
2713 gdb_last_signal_packet(connection, packet, packet_size);
2718 gdb_thread_packet(connection, packet, packet_size);
2719 log_add_callback(gdb_log_callback, connection);
2721 if (gdb_con->mem_write_error) {
2722 LOG_ERROR("Memory write failure!");
2724 /* now that we have reported the memory write error,
2725 * we can clear the condition */
2726 gdb_con->mem_write_error = false;
2729 bool nostep = false;
2730 bool already_running = false;
2731 if (target->state == TARGET_RUNNING) {
2732 LOG_WARNING("WARNING! The target is already running. "
2733 "All changes GDB did to registers will be discarded! "
2734 "Waiting for target to halt.");
2735 already_running = true;
2736 } else if (target->state != TARGET_HALTED) {
2737 LOG_WARNING("The target is not in the halted nor running stated, " \
2738 "stepi/continue ignored.");
2740 } else if ((packet[0] == 's') && gdb_con->sync) {
2741 /* Hmm..... when you issue a continue in GDB, then a "stepi" is
2742 * sent by GDB first to OpenOCD, thus defeating the check to
2743 * make only the single stepping have the sync feature...
2746 LOG_WARNING("stepi ignored. GDB will now fetch the register state " \
2747 "from the target.");
2749 gdb_con->sync = false;
2751 if (!already_running && nostep) {
2752 /* Either the target isn't in the halted state, then we can't
2753 * step/continue. This might be early setup, etc.
2755 * Or we want to allow GDB to pick up a fresh set of
2756 * register values without modifying the target state.
2759 gdb_sig_halted(connection);
2761 /* stop forwarding log packets! */
2762 log_remove_callback(gdb_log_callback, connection);
2764 /* We're running/stepping, in which case we can
2765 * forward log output until the target is halted
2767 gdb_con->frontend_state = TARGET_RUNNING;
2768 target_call_event_callbacks(target, TARGET_EVENT_GDB_START);
2770 if (!already_running) {
2771 /* Here we don't want packet processing to stop even if this fails,
2772 * so we use a local variable instead of retval. */
2773 retval = gdb_step_continue_packet(connection, packet, packet_size);
2774 if (retval != ERROR_OK) {
2775 /* we'll never receive a halted
2776 * condition... issue a false one..
2778 gdb_frontend_halted(target, connection);
2785 retval = gdb_v_packet(connection, packet, packet_size);
2788 retval = gdb_detach(connection);
2789 extended_protocol = 0;
2792 retval = gdb_write_memory_binary_packet(connection, packet, packet_size);
2793 if (retval != ERROR_OK)
2797 if (extended_protocol != 0) {
2798 gdb_con->attached = false;
2801 gdb_put_packet(connection, "OK", 2);
2802 return ERROR_SERVER_REMOTE_CLOSED;
2804 /* handle extended remote protocol */
2805 extended_protocol = 1;
2806 gdb_put_packet(connection, "OK", 2);
2809 /* handle extended restart packet */
2810 breakpoint_clear_target(gdb_service->target);
2811 watchpoint_clear_target(gdb_service->target);
2812 command_run_linef(connection->cmd_ctx, "ocd_gdb_restart %s",
2813 target_name(target));
2814 /* set connection as attached after reset */
2815 gdb_con->attached = true;
2816 /* info rtos parts */
2817 gdb_thread_packet(connection, packet, packet_size);
2821 /* packet supported only by smp target i.e cortex_a.c*/
2822 /* handle smp packet replying coreid played to gbd */
2823 gdb_read_smp_packet(connection, packet, packet_size);
2827 /* packet supported only by smp target i.e cortex_a.c */
2828 /* handle smp packet setting coreid to be played at next
2830 gdb_write_smp_packet(connection, packet, packet_size);
2834 /* File-I/O extension */
2835 /* After gdb uses host-side syscall to complete target file
2836 * I/O, gdb sends host-side syscall return value to target
2838 * The format of 'F' response packet is
2839 * Fretcode,errno,Ctrl-C flag;call-specific attachment
2841 gdb_con->frontend_state = TARGET_RUNNING;
2842 log_add_callback(gdb_log_callback, connection);
2843 gdb_fileio_response_packet(connection, packet, packet_size);
2847 /* ignore unknown packets */
2848 LOG_DEBUG("ignoring 0x%2.2x packet", packet[0]);
2849 gdb_put_packet(connection, NULL, 0);
2853 /* if a packet handler returned an error, exit input loop */
2854 if (retval != ERROR_OK)
2858 if (gdb_con->ctrl_c) {
2859 if (target->state == TARGET_RUNNING) {
2860 retval = target_halt(target);
2861 if (retval != ERROR_OK)
2862 target_call_event_callbacks(target, TARGET_EVENT_GDB_HALT);
2863 gdb_con->ctrl_c = 0;
2865 LOG_INFO("The target is not running when halt was requested, stopping GDB.");
2866 target_call_event_callbacks(target, TARGET_EVENT_GDB_HALT);
2870 } while (gdb_con->buf_cnt > 0);
2875 static int gdb_input(struct connection *connection)
2877 int retval = gdb_input_inner(connection);
2878 struct gdb_connection *gdb_con = connection->priv;
2879 if (retval == ERROR_SERVER_REMOTE_CLOSED)
2882 /* logging does not propagate the error, yet can set the gdb_con->closed flag */
2883 if (gdb_con->closed)
2884 return ERROR_SERVER_REMOTE_CLOSED;
2886 /* we'll recover from any other errors(e.g. temporary timeouts, etc.) */
2890 static int gdb_target_start(struct target *target, const char *port)
2892 struct gdb_service *gdb_service;
2894 gdb_service = malloc(sizeof(struct gdb_service));
2896 if (NULL == gdb_service)
2899 gdb_service->target = target;
2900 gdb_service->core[0] = -1;
2901 gdb_service->core[1] = -1;
2902 target->gdb_service = gdb_service;
2904 ret = add_service("gdb",
2905 port, 1, &gdb_new_connection, &gdb_input,
2906 &gdb_connection_closed, gdb_service);
2907 /* initialialize all targets gdb service with the same pointer */
2909 struct target_list *head;
2910 struct target *curr;
2911 head = target->head;
2912 while (head != (struct target_list *)NULL) {
2913 curr = head->target;
2915 curr->gdb_service = gdb_service;
2922 static int gdb_target_add_one(struct target *target)
2924 /* one gdb instance per smp list */
2925 if ((target->smp) && (target->gdb_service))
2927 int retval = gdb_target_start(target, gdb_port_next);
2928 if (retval == ERROR_OK) {
2930 /* If we can parse the port number
2931 * then we increment the port number for the next target.
2934 portnumber = strtol(gdb_port_next, &end, 0);
2936 if (parse_long(gdb_port_next, &portnumber) == ERROR_OK) {
2937 free(gdb_port_next);
2938 gdb_port_next = alloc_printf("%d", portnumber+1);
2945 int gdb_target_add_all(struct target *target)
2947 if (strcmp(gdb_port, "disabled") == 0) {
2948 LOG_INFO("gdb server disabled");
2952 if (NULL == target) {
2953 LOG_WARNING("gdb services need one or more targets defined");
2957 while (NULL != target) {
2958 int retval = gdb_target_add_one(target);
2959 if (ERROR_OK != retval)
2962 target = target->next;
2968 COMMAND_HANDLER(handle_gdb_sync_command)
2971 return ERROR_COMMAND_SYNTAX_ERROR;
2973 if (current_gdb_connection == NULL) {
2974 command_print(CMD_CTX,
2975 "gdb_sync command can only be run from within gdb using \"monitor gdb_sync\"");
2979 current_gdb_connection->sync = true;
2984 /* daemon configuration command gdb_port */
2985 COMMAND_HANDLER(handle_gdb_port_command)
2987 int retval = CALL_COMMAND_HANDLER(server_pipe_command, &gdb_port);
2988 if (ERROR_OK == retval) {
2989 free(gdb_port_next);
2990 gdb_port_next = strdup(gdb_port);
2995 COMMAND_HANDLER(handle_gdb_memory_map_command)
2998 return ERROR_COMMAND_SYNTAX_ERROR;
3000 COMMAND_PARSE_ENABLE(CMD_ARGV[0], gdb_use_memory_map);
3004 COMMAND_HANDLER(handle_gdb_flash_program_command)
3007 return ERROR_COMMAND_SYNTAX_ERROR;
3009 COMMAND_PARSE_ENABLE(CMD_ARGV[0], gdb_flash_program);
3013 COMMAND_HANDLER(handle_gdb_report_data_abort_command)
3016 return ERROR_COMMAND_SYNTAX_ERROR;
3018 COMMAND_PARSE_ENABLE(CMD_ARGV[0], gdb_report_data_abort);
3022 /* gdb_breakpoint_override */
3023 COMMAND_HANDLER(handle_gdb_breakpoint_override_command)
3025 if (CMD_ARGC == 0) {
3027 } else if (CMD_ARGC == 1) {
3028 gdb_breakpoint_override = 1;
3029 if (strcmp(CMD_ARGV[0], "hard") == 0)
3030 gdb_breakpoint_override_type = BKPT_HARD;
3031 else if (strcmp(CMD_ARGV[0], "soft") == 0)
3032 gdb_breakpoint_override_type = BKPT_SOFT;
3033 else if (strcmp(CMD_ARGV[0], "disable") == 0)
3034 gdb_breakpoint_override = 0;
3036 return ERROR_COMMAND_SYNTAX_ERROR;
3037 if (gdb_breakpoint_override)
3038 LOG_USER("force %s breakpoints",
3039 (gdb_breakpoint_override_type == BKPT_HARD) ? "hard" : "soft");
3041 LOG_USER("breakpoint type is not overridden");
3046 COMMAND_HANDLER(handle_gdb_target_description_command)
3049 return ERROR_COMMAND_SYNTAX_ERROR;
3051 COMMAND_PARSE_ENABLE(CMD_ARGV[0], gdb_use_target_description);
3055 COMMAND_HANDLER(handle_gdb_save_tdesc_command)
3058 uint32_t tdesc_length;
3059 struct target *target = get_current_target(CMD_CTX);
3061 int retval = gdb_generate_target_description(target, &tdesc);
3062 if (retval != ERROR_OK) {
3063 LOG_ERROR("Unable to Generate Target Description");
3067 tdesc_length = strlen(tdesc);
3069 struct fileio *fileio;
3070 size_t size_written;
3072 char *tdesc_filename = alloc_printf("%s.xml", target_type_name(target));
3073 if (tdesc_filename == NULL) {
3074 retval = ERROR_FAIL;
3078 retval = fileio_open(&fileio, tdesc_filename, FILEIO_WRITE, FILEIO_TEXT);
3080 if (retval != ERROR_OK) {
3081 LOG_ERROR("Can't open %s for writing", tdesc_filename);
3085 retval = fileio_write(fileio, tdesc_length, tdesc, &size_written);
3087 fileio_close(fileio);
3089 if (retval != ERROR_OK)
3090 LOG_ERROR("Error while writing the tdesc file");
3093 free(tdesc_filename);
3099 static const struct command_registration gdb_command_handlers[] = {
3102 .handler = handle_gdb_sync_command,
3103 .mode = COMMAND_ANY,
3104 .help = "next stepi will return immediately allowing "
3105 "GDB to fetch register state without affecting "
3111 .handler = handle_gdb_port_command,
3112 .mode = COMMAND_ANY,
3113 .help = "Normally gdb listens to a TCP/IP port. Each subsequent GDB "
3114 "server listens for the next port number after the "
3115 "base port number specified. "
3116 "No arguments reports GDB port. \"pipe\" means listen to stdin "
3117 "output to stdout, an integer is base port number, \"disable\" disables "
3118 "port. Any other string is are interpreted as named pipe to listen to. "
3119 "Output pipe is the same name as input pipe, but with 'o' appended.",
3120 .usage = "[port_num]",
3123 .name = "gdb_memory_map",
3124 .handler = handle_gdb_memory_map_command,
3125 .mode = COMMAND_CONFIG,
3126 .help = "enable or disable memory map",
3127 .usage = "('enable'|'disable')"
3130 .name = "gdb_flash_program",
3131 .handler = handle_gdb_flash_program_command,
3132 .mode = COMMAND_CONFIG,
3133 .help = "enable or disable flash program",
3134 .usage = "('enable'|'disable')"
3137 .name = "gdb_report_data_abort",
3138 .handler = handle_gdb_report_data_abort_command,
3139 .mode = COMMAND_CONFIG,
3140 .help = "enable or disable reporting data aborts",
3141 .usage = "('enable'|'disable')"
3144 .name = "gdb_breakpoint_override",
3145 .handler = handle_gdb_breakpoint_override_command,
3146 .mode = COMMAND_ANY,
3147 .help = "Display or specify type of breakpoint "
3148 "to be used by gdb 'break' commands.",
3149 .usage = "('hard'|'soft'|'disable')"
3152 .name = "gdb_target_description",
3153 .handler = handle_gdb_target_description_command,
3154 .mode = COMMAND_CONFIG,
3155 .help = "enable or disable target description",
3156 .usage = "('enable'|'disable')"
3159 .name = "gdb_save_tdesc",
3160 .handler = handle_gdb_save_tdesc_command,
3161 .mode = COMMAND_EXEC,
3162 .help = "Save the target description file",
3164 COMMAND_REGISTRATION_DONE
3167 int gdb_register_commands(struct command_context *cmd_ctx)
3169 gdb_port = strdup("3333");
3170 gdb_port_next = strdup("3333");
3171 return register_commands(cmd_ctx, NULL, gdb_command_handlers);