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 * This program is free software; you can redistribute it and/or modify *
18 * it under the terms of the GNU General Public License as published by *
19 * the Free Software Foundation; either version 2 of the License, or *
20 * (at your option) any later version. *
22 * This program is distributed in the hope that it will be useful, *
23 * but WITHOUT ANY WARRANTY; without even the implied warranty of *
24 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
25 * GNU General Public License for more details. *
27 * You should have received a copy of the GNU General Public License *
28 * along with this program; if not, write to the *
29 * Free Software Foundation, Inc., *
30 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. *
31 ***************************************************************************/
37 #include <target/breakpoints.h>
38 #include <target/target_request.h>
39 #include <target/register.h>
41 #include <flash/nor/core.h>
42 #include "gdb_server.h"
43 #include <target/image.h>
44 #include <jtag/jtag.h>
45 #include "rtos/rtos.h"
46 #include "target/smp.h"
50 * GDB server implementation.
52 * This implements the GDB Remote Serial Protocol, over TCP connections,
53 * giving GDB access to the JTAG or other hardware debugging facilities
54 * found in most modern embedded processors.
57 /* private connection data for GDB */
58 struct gdb_connection {
59 char buffer[GDB_BUFFER_SIZE];
63 enum target_state frontend_state;
64 struct image *vflash_image;
68 /* set flag to true if you want the next stepi to return immediately.
69 * allowing GDB to pick up a fresh set of register values from the target
70 * without modifying the target state. */
72 /* We delay reporting memory write errors until next step/continue or memory
73 * write. This improves performance of gdb load significantly as the GDB packet
74 * can be replied immediately and a new GDB packet will be ready without delay
75 * (ca. 10% or so...). */
77 /* with extended-remote it seems we need to better emulate attach/detach.
78 * what this means is we reply with a W stop reply after a kill packet,
79 * normally we reply with a S reply via gdb_last_signal_packet.
80 * as a side note this behaviour only effects gdb > 6.8 */
85 #define _DEBUG_GDB_IO_
88 static struct gdb_connection *current_gdb_connection;
90 static int gdb_breakpoint_override;
91 static enum breakpoint_type gdb_breakpoint_override_type;
93 static int gdb_error(struct connection *connection, int retval);
94 static const char *gdb_port;
95 static const char *gdb_port_next;
97 static void gdb_log_callback(void *priv, const char *file, unsigned line,
98 const char *function, const char *string);
100 /* number of gdb connections, mainly to suppress gdb related debugging spam
101 * in helper/log.c when no gdb connections are actually active */
102 int gdb_actual_connections;
104 /* set if we are sending a memory map to gdb
105 * via qXfer:memory-map:read packet */
106 /* enabled by default*/
107 static int gdb_use_memory_map = 1;
108 /* enabled by default*/
109 static int gdb_flash_program = 1;
111 /* if set, data aborts cause an error to be reported in memory read packets
112 * see the code in gdb_read_memory_packet() for further explanations.
113 * Disabled by default.
115 static int gdb_report_data_abort;
117 static int gdb_last_signal(struct target *target)
119 switch (target->debug_reason) {
120 case DBG_REASON_DBGRQ:
121 return 0x2; /* SIGINT */
122 case DBG_REASON_BREAKPOINT:
123 case DBG_REASON_WATCHPOINT:
124 case DBG_REASON_WPTANDBKPT:
125 return 0x05; /* SIGTRAP */
126 case DBG_REASON_SINGLESTEP:
127 return 0x05; /* SIGTRAP */
128 case DBG_REASON_NOTHALTED:
129 return 0x0; /* no signal... shouldn't happen */
131 LOG_USER("undefined debug reason %d - target needs reset",
132 target->debug_reason);
137 static int check_pending(struct connection *connection,
138 int timeout_s, int *got_data)
140 /* a non-blocking socket will block if there is 0 bytes available on the socket,
141 * but return with as many bytes as are available immediately
145 struct gdb_connection *gdb_con = connection->priv;
147 if (got_data == NULL)
151 if (gdb_con->buf_cnt > 0) {
157 FD_SET(connection->fd, &read_fds);
159 tv.tv_sec = timeout_s;
161 if (socket_select(connection->fd + 1, &read_fds, NULL, NULL, &tv) == 0) {
162 /* This can typically be because a "monitor" command took too long
163 * before printing any progress messages
166 return ERROR_GDB_TIMEOUT;
170 *got_data = FD_ISSET(connection->fd, &read_fds) != 0;
174 static int gdb_get_char_inner(struct connection *connection, int *next_char)
176 struct gdb_connection *gdb_con = connection->priv;
177 int retval = ERROR_OK;
179 #ifdef _DEBUG_GDB_IO_
183 if (connection->service->type != CONNECTION_TCP)
184 gdb_con->buf_cnt = read(connection->fd, gdb_con->buffer, GDB_BUFFER_SIZE);
186 retval = check_pending(connection, 1, NULL);
187 if (retval != ERROR_OK)
189 gdb_con->buf_cnt = read_socket(connection->fd,
194 if (gdb_con->buf_cnt > 0)
196 if (gdb_con->buf_cnt == 0) {
198 return ERROR_SERVER_REMOTE_CLOSED;
202 errno = WSAGetLastError();
208 case WSAECONNABORTED:
210 return ERROR_SERVER_REMOTE_CLOSED;
213 return ERROR_SERVER_REMOTE_CLOSED;
215 LOG_ERROR("read: %d", errno);
225 return ERROR_SERVER_REMOTE_CLOSED;
228 return ERROR_SERVER_REMOTE_CLOSED;
230 LOG_ERROR("read: %s", strerror(errno));
232 return ERROR_SERVER_REMOTE_CLOSED;
237 #ifdef _DEBUG_GDB_IO_
238 debug_buffer = strndup(gdb_con->buffer, gdb_con->buf_cnt);
239 LOG_DEBUG("received '%s'", debug_buffer);
243 gdb_con->buf_p = gdb_con->buffer;
245 *next_char = *(gdb_con->buf_p++);
246 if (gdb_con->buf_cnt > 0)
247 connection->input_pending = 1;
249 connection->input_pending = 0;
250 #ifdef _DEBUG_GDB_IO_
251 LOG_DEBUG("returned char '%c' (0x%2.2x)", *next_char, *next_char);
258 * The cool thing about this fn is that it allows buf_p and buf_cnt to be
259 * held in registers in the inner loop.
261 * For small caches and embedded systems this is important!
263 static inline int gdb_get_char_fast(struct connection *connection,
264 int *next_char, char **buf_p, int *buf_cnt)
266 int retval = ERROR_OK;
268 if ((*buf_cnt)-- > 0) {
269 *next_char = **buf_p;
272 connection->input_pending = 1;
274 connection->input_pending = 0;
276 #ifdef _DEBUG_GDB_IO_
277 LOG_DEBUG("returned char '%c' (0x%2.2x)", *next_char, *next_char);
283 struct gdb_connection *gdb_con = connection->priv;
284 gdb_con->buf_p = *buf_p;
285 gdb_con->buf_cnt = *buf_cnt;
286 retval = gdb_get_char_inner(connection, next_char);
287 *buf_p = gdb_con->buf_p;
288 *buf_cnt = gdb_con->buf_cnt;
293 static int gdb_get_char(struct connection *connection, int *next_char)
295 struct gdb_connection *gdb_con = connection->priv;
296 return gdb_get_char_fast(connection, next_char, &gdb_con->buf_p, &gdb_con->buf_cnt);
299 static int gdb_putback_char(struct connection *connection, int last_char)
301 struct gdb_connection *gdb_con = connection->priv;
303 if (gdb_con->buf_p > gdb_con->buffer) {
304 *(--gdb_con->buf_p) = last_char;
307 LOG_ERROR("BUG: couldn't put character back");
312 /* The only way we can detect that the socket is closed is the first time
313 * we write to it, we will fail. Subsequent write operations will
314 * succeed. Shudder! */
315 static int gdb_write(struct connection *connection, void *data, int len)
317 struct gdb_connection *gdb_con = connection->priv;
319 return ERROR_SERVER_REMOTE_CLOSED;
321 if (connection_write(connection, data, len) == len)
324 return ERROR_SERVER_REMOTE_CLOSED;
327 static int gdb_put_packet_inner(struct connection *connection,
328 char *buffer, int len)
331 unsigned char my_checksum = 0;
332 #ifdef _DEBUG_GDB_IO_
337 struct gdb_connection *gdb_con = connection->priv;
339 for (i = 0; i < len; i++)
340 my_checksum += buffer[i];
342 #ifdef _DEBUG_GDB_IO_
344 * At this point we should have nothing in the input queue from GDB,
345 * however sometimes '-' is sent even though we've already received
346 * an ACK (+) for everything we've sent off.
350 retval = check_pending(connection, 0, &gotdata);
351 if (retval != ERROR_OK)
355 retval = gdb_get_char(connection, &reply);
356 if (retval != ERROR_OK)
359 /* fix a problem with some IAR tools */
360 gdb_putback_char(connection, reply);
361 LOG_DEBUG("Unexpected start of new packet");
365 LOG_WARNING("Discard unexpected char %c", reply);
370 #ifdef _DEBUG_GDB_IO_
371 debug_buffer = strndup(buffer, len);
372 LOG_DEBUG("sending packet '$%s#%2.2x'", debug_buffer, my_checksum);
376 char local_buffer[1024];
377 local_buffer[0] = '$';
378 if ((size_t)len + 4 <= sizeof(local_buffer)) {
379 /* performance gain on smaller packets by only a single call to gdb_write() */
380 memcpy(local_buffer + 1, buffer, len++);
381 len += snprintf(local_buffer + len, sizeof(local_buffer) - len, "#%02x", my_checksum);
382 retval = gdb_write(connection, local_buffer, len);
383 if (retval != ERROR_OK)
386 /* larger packets are transmitted directly from caller supplied buffer
387 * by several calls to gdb_write() to avoid dynamic allocation */
388 snprintf(local_buffer + 1, sizeof(local_buffer) - 1, "#%02x", my_checksum);
389 retval = gdb_write(connection, local_buffer, 1);
390 if (retval != ERROR_OK)
392 retval = gdb_write(connection, buffer, len);
393 if (retval != ERROR_OK)
395 retval = gdb_write(connection, local_buffer + 1, 3);
396 if (retval != ERROR_OK)
400 if (gdb_con->noack_mode)
403 retval = gdb_get_char(connection, &reply);
404 if (retval != ERROR_OK)
409 else if (reply == '-') {
410 /* Stop sending output packets for now */
411 log_remove_callback(gdb_log_callback, connection);
412 LOG_WARNING("negative reply, retrying");
413 } else if (reply == 0x3) {
415 retval = gdb_get_char(connection, &reply);
416 if (retval != ERROR_OK)
420 else if (reply == '-') {
421 /* Stop sending output packets for now */
422 log_remove_callback(gdb_log_callback, connection);
423 LOG_WARNING("negative reply, retrying");
424 } else if (reply == '$') {
425 LOG_ERROR("GDB missing ack(1) - assumed good");
426 gdb_putback_char(connection, reply);
429 LOG_ERROR("unknown character(1) 0x%2.2x in reply, dropping connection", reply);
431 return ERROR_SERVER_REMOTE_CLOSED;
433 } else if (reply == '$') {
434 LOG_ERROR("GDB missing ack(2) - assumed good");
435 gdb_putback_char(connection, reply);
438 LOG_ERROR("unknown character(2) 0x%2.2x in reply, dropping connection",
441 return ERROR_SERVER_REMOTE_CLOSED;
445 return ERROR_SERVER_REMOTE_CLOSED;
450 int gdb_put_packet(struct connection *connection, char *buffer, int len)
452 struct gdb_connection *gdb_con = connection->priv;
454 int retval = gdb_put_packet_inner(connection, buffer, len);
457 /* we sent some data, reset timer for keep alive messages */
463 static inline int fetch_packet(struct connection *connection,
464 int *checksum_ok, int noack, int *len, char *buffer)
466 unsigned char my_checksum = 0;
469 int retval = ERROR_OK;
471 struct gdb_connection *gdb_con = connection->priv;
476 /* move this over into local variables to use registers and give the
477 * more freedom to optimize */
478 char *buf_p = gdb_con->buf_p;
479 int buf_cnt = gdb_con->buf_cnt;
482 /* The common case is that we have an entire packet with no escape chars.
483 * We need to leave at least 2 bytes in the buffer to have
484 * gdb_get_char() update various bits and bobs correctly.
486 if ((buf_cnt > 2) && ((buf_cnt + count) < *len)) {
487 /* The compiler will struggle a bit with constant propagation and
488 * aliasing, so we help it by showing that these values do not
489 * change inside the loop
493 int run = buf_cnt - 2;
499 if (character == '#') {
500 /* Danger! character can be '#' when esc is
501 * used so we need an explicit boolean for done here. */
506 if (character == '}') {
507 /* data transmitted in binary mode (X packet)
508 * uses 0x7d as escape character */
509 my_checksum += character & 0xff;
512 my_checksum += character & 0xff;
513 buffer[count++] = (character ^ 0x20) & 0xff;
515 my_checksum += character & 0xff;
516 buffer[count++] = character & 0xff;
525 LOG_ERROR("packet buffer too small");
526 retval = ERROR_GDB_BUFFER_TOO_SMALL;
530 retval = gdb_get_char_fast(connection, &character, &buf_p, &buf_cnt);
531 if (retval != ERROR_OK)
534 if (character == '#')
537 if (character == '}') {
538 /* data transmitted in binary mode (X packet)
539 * uses 0x7d as escape character */
540 my_checksum += character & 0xff;
542 retval = gdb_get_char_fast(connection, &character, &buf_p, &buf_cnt);
543 if (retval != ERROR_OK)
546 my_checksum += character & 0xff;
547 buffer[count++] = (character ^ 0x20) & 0xff;
549 my_checksum += character & 0xff;
550 buffer[count++] = character & 0xff;
554 gdb_con->buf_p = buf_p;
555 gdb_con->buf_cnt = buf_cnt;
557 if (retval != ERROR_OK)
562 retval = gdb_get_char(connection, &character);
563 if (retval != ERROR_OK)
565 checksum[0] = character;
566 retval = gdb_get_char(connection, &character);
567 if (retval != ERROR_OK)
569 checksum[1] = character;
573 *checksum_ok = (my_checksum == strtoul(checksum, NULL, 16));
578 static int gdb_get_packet_inner(struct connection *connection,
579 char *buffer, int *len)
583 struct gdb_connection *gdb_con = connection->priv;
587 retval = gdb_get_char(connection, &character);
588 if (retval != ERROR_OK)
591 #ifdef _DEBUG_GDB_IO_
592 LOG_DEBUG("character: '%c'", character);
599 /* gdb sends a dummy ack '+' at every remote connect - see
600 * remote_start_remote (remote.c)
601 * in case anyone tries to debug why they receive this
602 * warning every time */
603 LOG_WARNING("acknowledgment received, but no packet pending");
606 LOG_WARNING("negative acknowledgment, but no packet pending");
613 LOG_WARNING("ignoring character 0x%x", character);
616 } while (character != '$');
619 /* explicit code expansion here to get faster inlined code in -O3 by not
620 * calculating checksum */
621 if (gdb_con->noack_mode) {
622 retval = fetch_packet(connection, &checksum_ok, 1, len, buffer);
623 if (retval != ERROR_OK)
626 retval = fetch_packet(connection, &checksum_ok, 0, len, buffer);
627 if (retval != ERROR_OK)
631 if (gdb_con->noack_mode) {
632 /* checksum is not checked in noack mode */
636 retval = gdb_write(connection, "+", 1);
637 if (retval != ERROR_OK)
643 return ERROR_SERVER_REMOTE_CLOSED;
648 static int gdb_get_packet(struct connection *connection, char *buffer, int *len)
650 struct gdb_connection *gdb_con = connection->priv;
652 int retval = gdb_get_packet_inner(connection, buffer, len);
657 static int gdb_output_con(struct connection *connection, const char *line)
662 bin_size = strlen(line);
664 hex_buffer = malloc(bin_size * 2 + 2);
665 if (hex_buffer == NULL)
666 return ERROR_GDB_BUFFER_TOO_SMALL;
669 int pkt_len = hexify(hex_buffer + 1, line, bin_size, bin_size * 2 + 1);
670 int retval = gdb_put_packet(connection, hex_buffer, pkt_len + 1);
676 static int gdb_output(struct command_context *context, const char *line)
678 /* this will be dumped to the log and also sent as an O packet if possible */
679 LOG_USER_N("%s", line);
683 static void gdb_frontend_halted(struct target *target, struct connection *connection)
685 struct gdb_connection *gdb_connection = connection->priv;
687 /* In the GDB protocol when we are stepping or continuing execution,
688 * we have a lingering reply. Upon receiving a halted event
689 * when we have that lingering packet, we reply to the original
690 * step or continue packet.
692 * Executing monitor commands can bring the target in and
693 * out of the running state so we'll see lots of TARGET_EVENT_XXX
694 * that are to be ignored.
696 if (gdb_connection->frontend_state == TARGET_RUNNING) {
700 /* stop forwarding log packets! */
701 log_remove_callback(gdb_log_callback, connection);
703 if (gdb_connection->ctrl_c) {
705 gdb_connection->ctrl_c = 0;
707 signal_var = gdb_last_signal(target);
709 snprintf(sig_reply, 4, "T%2.2x", signal_var);
710 gdb_put_packet(connection, sig_reply, 3);
711 gdb_connection->frontend_state = TARGET_HALTED;
712 rtos_update_threads(target);
716 static int gdb_target_callback_event_handler(struct target *target,
717 enum target_event event, void *priv)
720 struct connection *connection = priv;
723 case TARGET_EVENT_GDB_HALT:
724 gdb_frontend_halted(target, connection);
726 case TARGET_EVENT_HALTED:
727 target_call_event_callbacks(target, TARGET_EVENT_GDB_END);
729 case TARGET_EVENT_GDB_FLASH_ERASE_START:
730 retval = jtag_execute_queue();
731 if (retval != ERROR_OK)
741 static int gdb_new_connection(struct connection *connection)
743 struct gdb_connection *gdb_connection = malloc(sizeof(struct gdb_connection));
744 struct gdb_service *gdb_service = connection->service->priv;
748 connection->priv = gdb_connection;
750 /* initialize gdb connection information */
751 gdb_connection->buf_p = gdb_connection->buffer;
752 gdb_connection->buf_cnt = 0;
753 gdb_connection->ctrl_c = 0;
754 gdb_connection->frontend_state = TARGET_HALTED;
755 gdb_connection->vflash_image = NULL;
756 gdb_connection->closed = 0;
757 gdb_connection->busy = 0;
758 gdb_connection->noack_mode = 0;
759 gdb_connection->sync = true;
760 gdb_connection->mem_write_error = false;
761 gdb_connection->attached = true;
763 /* send ACK to GDB for debug request */
764 gdb_write(connection, "+", 1);
766 /* output goes through gdb connection */
767 command_set_output_handler(connection->cmd_ctx, gdb_output, connection);
769 /* we must remove all breakpoints registered to the target as a previous
770 * GDB session could leave dangling breakpoints if e.g. communication
773 breakpoint_clear_target(gdb_service->target);
774 watchpoint_clear_target(gdb_service->target);
776 /* clean previous rtos session if supported*/
777 if ((gdb_service->target->rtos) && (gdb_service->target->rtos->type->clean))
778 gdb_service->target->rtos->type->clean(gdb_service->target);
780 /* remove the initial ACK from the incoming buffer */
781 retval = gdb_get_char(connection, &initial_ack);
782 if (retval != ERROR_OK)
785 /* FIX!!!??? would we actually ever receive a + here???
788 if (initial_ack != '+')
789 gdb_putback_char(connection, initial_ack);
790 target_call_event_callbacks(gdb_service->target, TARGET_EVENT_GDB_ATTACH);
792 if (gdb_use_memory_map) {
793 /* Connect must fail if the memory map can't be set up correctly.
795 * This will cause an auto_probe to be invoked, which is either
796 * a no-op or it will fail when the target isn't ready(e.g. not halted).
799 for (i = 0; i < flash_get_bank_count(); i++) {
800 struct flash_bank *p;
801 retval = get_flash_bank_by_num(i, &p);
802 if (retval != ERROR_OK) {
803 LOG_ERROR("Connect failed. Consider setting up a gdb-attach event for the target " \
804 "to prepare target for GDB connect, or use 'gdb_memory_map disable'.");
810 gdb_actual_connections++;
811 LOG_DEBUG("New GDB Connection: %d, Target %s, state: %s",
812 gdb_actual_connections,
813 target_name(gdb_service->target),
814 target_state_name(gdb_service->target));
816 /* DANGER! If we fail subsequently, we must remove this handler,
817 * otherwise we occasionally see crashes as the timer can invoke the
820 * register callback to be informed about target events */
821 target_register_event_callback(gdb_target_callback_event_handler, connection);
826 static int gdb_connection_closed(struct connection *connection)
828 struct gdb_service *gdb_service = connection->service->priv;
829 struct gdb_connection *gdb_connection = connection->priv;
831 /* we're done forwarding messages. Tear down callback before
832 * cleaning up connection.
834 log_remove_callback(gdb_log_callback, connection);
836 gdb_actual_connections--;
837 LOG_DEBUG("GDB Close, Target: %s, state: %s, gdb_actual_connections=%d",
838 target_name(gdb_service->target),
839 target_state_name(gdb_service->target),
840 gdb_actual_connections);
842 /* see if an image built with vFlash commands is left */
843 if (gdb_connection->vflash_image) {
844 image_close(gdb_connection->vflash_image);
845 free(gdb_connection->vflash_image);
846 gdb_connection->vflash_image = NULL;
849 /* if this connection registered a debug-message receiver delete it */
850 delete_debug_msg_receiver(connection->cmd_ctx, gdb_service->target);
852 if (connection->priv) {
853 free(connection->priv);
854 connection->priv = NULL;
856 LOG_ERROR("BUG: connection->priv == NULL");
858 target_unregister_event_callback(gdb_target_callback_event_handler, connection);
860 target_call_event_callbacks(gdb_service->target, TARGET_EVENT_GDB_END);
862 target_call_event_callbacks(gdb_service->target, TARGET_EVENT_GDB_DETACH);
867 static void gdb_send_error(struct connection *connection, uint8_t the_error)
870 snprintf(err, 4, "E%2.2X", the_error);
871 gdb_put_packet(connection, err, 3);
874 static int gdb_last_signal_packet(struct connection *connection,
875 char *packet, int packet_size)
877 struct target *target = get_target_from_connection(connection);
878 struct gdb_connection *gdb_con = connection->priv;
882 if (!gdb_con->attached) {
883 /* if we are here we have received a kill packet
884 * reply W stop reply otherwise gdb gets very unhappy */
885 gdb_put_packet(connection, "W00", 3);
889 signal_var = gdb_last_signal(target);
891 snprintf(sig_reply, 4, "S%2.2x", signal_var);
892 gdb_put_packet(connection, sig_reply, 3);
897 static inline int gdb_reg_pos(struct target *target, int pos, int len)
899 if (target->endianness == TARGET_LITTLE_ENDIAN)
902 return len - 1 - pos;
905 /* Convert register to string of bytes. NB! The # of bits in the
906 * register might be non-divisible by 8(a byte), in which
907 * case an entire byte is shown.
909 * NB! the format on the wire is the target endianness
911 * The format of reg->value is little endian
914 static void gdb_str_to_target(struct target *target,
915 char *tstr, struct reg *reg)
922 buf_len = DIV_ROUND_UP(reg->size, 8);
924 for (i = 0; i < buf_len; i++) {
925 int j = gdb_reg_pos(target, i, buf_len);
926 tstr += sprintf(tstr, "%02x", buf[j]);
930 /* copy over in register buffer */
931 static void gdb_target_to_reg(struct target *target,
932 char *tstr, int str_len, uint8_t *bin)
935 LOG_ERROR("BUG: gdb value with uneven number of characters encountered");
940 for (i = 0; i < str_len; i += 2) {
942 if (sscanf(tstr + i, "%02x", &t) != 1) {
943 LOG_ERROR("BUG: unable to convert register value");
947 int j = gdb_reg_pos(target, i/2, str_len/2);
952 static int gdb_get_registers_packet(struct connection *connection,
953 char *packet, int packet_size)
955 struct target *target = get_target_from_connection(connection);
956 struct reg **reg_list;
959 int reg_packet_size = 0;
964 #ifdef _DEBUG_GDB_IO_
968 if ((target->rtos != NULL) && (ERROR_OK == rtos_get_gdb_reg_list(connection)))
971 retval = target_get_gdb_reg_list(target, ®_list, ®_list_size);
972 if (retval != ERROR_OK)
973 return gdb_error(connection, retval);
975 for (i = 0; i < reg_list_size; i++)
976 reg_packet_size += DIV_ROUND_UP(reg_list[i]->size, 8) * 2;
978 assert(reg_packet_size > 0);
980 reg_packet = malloc(reg_packet_size + 1); /* plus one for string termination null */
981 reg_packet_p = reg_packet;
983 for (i = 0; i < reg_list_size; i++) {
984 if (!reg_list[i]->valid)
985 reg_list[i]->type->get(reg_list[i]);
986 gdb_str_to_target(target, reg_packet_p, reg_list[i]);
987 reg_packet_p += DIV_ROUND_UP(reg_list[i]->size, 8) * 2;
990 #ifdef _DEBUG_GDB_IO_
992 char *reg_packet_p_debug;
993 reg_packet_p_debug = strndup(reg_packet, reg_packet_size);
994 LOG_DEBUG("reg_packet: %s", reg_packet_p_debug);
995 free(reg_packet_p_debug);
999 gdb_put_packet(connection, reg_packet, reg_packet_size);
1007 static int gdb_set_registers_packet(struct connection *connection,
1008 char *packet, int packet_size)
1010 struct target *target = get_target_from_connection(connection);
1012 struct reg **reg_list;
1017 #ifdef _DEBUG_GDB_IO_
1021 /* skip command character */
1025 if (packet_size % 2) {
1026 LOG_WARNING("GDB set_registers packet with uneven characters received, dropping connection");
1027 return ERROR_SERVER_REMOTE_CLOSED;
1030 retval = target_get_gdb_reg_list(target, ®_list, ®_list_size);
1031 if (retval != ERROR_OK)
1032 return gdb_error(connection, retval);
1035 for (i = 0; i < reg_list_size; i++) {
1037 int chars = (DIV_ROUND_UP(reg_list[i]->size, 8) * 2);
1039 if (packet_p + chars > packet + packet_size)
1040 LOG_ERROR("BUG: register packet is too small for registers");
1042 bin_buf = malloc(DIV_ROUND_UP(reg_list[i]->size, 8));
1043 gdb_target_to_reg(target, packet_p, chars, bin_buf);
1045 reg_list[i]->type->set(reg_list[i], bin_buf);
1047 /* advance packet pointer */
1053 /* free struct reg *reg_list[] array allocated by get_gdb_reg_list */
1056 gdb_put_packet(connection, "OK", 2);
1061 static int gdb_get_register_packet(struct connection *connection,
1062 char *packet, int packet_size)
1064 struct target *target = get_target_from_connection(connection);
1066 int reg_num = strtoul(packet + 1, NULL, 16);
1067 struct reg **reg_list;
1071 #ifdef _DEBUG_GDB_IO_
1075 retval = target_get_gdb_reg_list(target, ®_list, ®_list_size);
1076 if (retval != ERROR_OK)
1077 return gdb_error(connection, retval);
1079 if (reg_list_size <= reg_num) {
1080 LOG_ERROR("gdb requested a non-existing register");
1081 return ERROR_SERVER_REMOTE_CLOSED;
1084 if (!reg_list[reg_num]->valid)
1085 reg_list[reg_num]->type->get(reg_list[reg_num]);
1087 reg_packet = malloc(DIV_ROUND_UP(reg_list[reg_num]->size, 8) * 2 + 1); /* plus one for string termination null */
1089 gdb_str_to_target(target, reg_packet, reg_list[reg_num]);
1091 gdb_put_packet(connection, reg_packet, DIV_ROUND_UP(reg_list[reg_num]->size, 8) * 2);
1099 static int gdb_set_register_packet(struct connection *connection,
1100 char *packet, int packet_size)
1102 struct target *target = get_target_from_connection(connection);
1105 int reg_num = strtoul(packet + 1, &separator, 16);
1106 struct reg **reg_list;
1112 retval = target_get_gdb_reg_list(target, ®_list, ®_list_size);
1113 if (retval != ERROR_OK)
1114 return gdb_error(connection, retval);
1116 if (reg_list_size <= reg_num) {
1117 LOG_ERROR("gdb requested a non-existing register");
1118 return ERROR_SERVER_REMOTE_CLOSED;
1121 if (*separator != '=') {
1122 LOG_ERROR("GDB 'set register packet', but no '=' following the register number");
1123 return ERROR_SERVER_REMOTE_CLOSED;
1126 /* convert from GDB-string (target-endian) to hex-string (big-endian) */
1127 bin_buf = malloc(DIV_ROUND_UP(reg_list[reg_num]->size, 8));
1128 int chars = (DIV_ROUND_UP(reg_list[reg_num]->size, 8) * 2);
1130 if ((unsigned int)chars != strlen(separator + 1)) {
1131 LOG_ERROR("gdb sent a packet with wrong register size");
1133 return ERROR_SERVER_REMOTE_CLOSED;
1136 gdb_target_to_reg(target, separator + 1, chars, bin_buf);
1138 reg_list[reg_num]->type->set(reg_list[reg_num], bin_buf);
1140 gdb_put_packet(connection, "OK", 2);
1148 /* No attempt is made to translate the "retval" to
1149 * GDB speak. This has to be done at the calling
1150 * site as no mapping really exists.
1152 static int gdb_error(struct connection *connection, int retval)
1154 LOG_DEBUG("Reporting %i to GDB as generic error", retval);
1155 gdb_send_error(connection, EFAULT);
1159 /* We don't have to worry about the default 2 second timeout for GDB packets,
1160 * because GDB breaks up large memory reads into smaller reads.
1162 * 8191 bytes by the looks of it. Why 8191 bytes instead of 8192?????
1164 static int gdb_read_memory_packet(struct connection *connection,
1165 char *packet, int packet_size)
1167 struct target *target = get_target_from_connection(connection);
1175 int retval = ERROR_OK;
1177 /* skip command character */
1180 addr = strtoul(packet, &separator, 16);
1182 if (*separator != ',') {
1183 LOG_ERROR("incomplete read memory packet received, dropping connection");
1184 return ERROR_SERVER_REMOTE_CLOSED;
1187 len = strtoul(separator + 1, NULL, 16);
1189 buffer = malloc(len);
1191 LOG_DEBUG("addr: 0x%8.8" PRIx32 ", len: 0x%8.8" PRIx32 "", addr, len);
1193 retval = target_read_buffer(target, addr, len, buffer);
1195 if ((retval != ERROR_OK) && !gdb_report_data_abort) {
1196 /* TODO : Here we have to lie and send back all zero's lest stack traces won't work.
1197 * At some point this might be fixed in GDB, in which case this code can be removed.
1199 * OpenOCD developers are acutely aware of this problem, but there is nothing
1200 * gained by involving the user in this problem that hopefully will get resolved
1203 * http://sourceware.org/cgi-bin/gnatsweb.pl? \
1204 * cmd = view%20audit-trail&database = gdb&pr = 2395
1206 * For now, the default is to fix up things to make current GDB versions work.
1207 * This can be overwritten using the gdb_report_data_abort <'enable'|'disable'> command.
1209 memset(buffer, 0, len);
1213 if (retval == ERROR_OK) {
1214 hex_buffer = malloc(len * 2 + 1);
1216 int pkt_len = hexify(hex_buffer, (char *)buffer, len, len * 2 + 1);
1218 gdb_put_packet(connection, hex_buffer, pkt_len);
1222 retval = gdb_error(connection, retval);
1229 static int gdb_write_memory_packet(struct connection *connection,
1230 char *packet, int packet_size)
1232 struct target *target = get_target_from_connection(connection);
1240 /* skip command character */
1243 addr = strtoul(packet, &separator, 16);
1245 if (*separator != ',') {
1246 LOG_ERROR("incomplete write memory packet received, dropping connection");
1247 return ERROR_SERVER_REMOTE_CLOSED;
1250 len = strtoul(separator + 1, &separator, 16);
1252 if (*(separator++) != ':') {
1253 LOG_ERROR("incomplete write memory packet received, dropping connection");
1254 return ERROR_SERVER_REMOTE_CLOSED;
1257 buffer = malloc(len);
1259 LOG_DEBUG("addr: 0x%8.8" PRIx32 ", len: 0x%8.8" PRIx32 "", addr, len);
1261 if (unhexify((char *)buffer, separator, len) != (int)len)
1262 LOG_ERROR("unable to decode memory packet");
1264 retval = target_write_buffer(target, addr, len, buffer);
1266 if (retval == ERROR_OK)
1267 gdb_put_packet(connection, "OK", 2);
1269 retval = gdb_error(connection, retval);
1276 static int gdb_write_memory_binary_packet(struct connection *connection,
1277 char *packet, int packet_size)
1279 struct target *target = get_target_from_connection(connection);
1284 int retval = ERROR_OK;
1286 /* skip command character */
1289 addr = strtoul(packet, &separator, 16);
1291 if (*separator != ',') {
1292 LOG_ERROR("incomplete write memory binary packet received, dropping connection");
1293 return ERROR_SERVER_REMOTE_CLOSED;
1296 len = strtoul(separator + 1, &separator, 16);
1298 if (*(separator++) != ':') {
1299 LOG_ERROR("incomplete write memory binary packet received, dropping connection");
1300 return ERROR_SERVER_REMOTE_CLOSED;
1303 struct gdb_connection *gdb_connection = connection->priv;
1305 if (gdb_connection->mem_write_error) {
1306 retval = ERROR_FAIL;
1307 /* now that we have reported the memory write error, we can clear the condition */
1308 gdb_connection->mem_write_error = false;
1311 /* By replying the packet *immediately* GDB will send us a new packet
1312 * while we write the last one to the target.
1314 if (retval == ERROR_OK)
1315 gdb_put_packet(connection, "OK", 2);
1317 retval = gdb_error(connection, retval);
1318 if (retval != ERROR_OK)
1323 LOG_DEBUG("addr: 0x%8.8" PRIx32 ", len: 0x%8.8" PRIx32 "", addr, len);
1325 retval = target_write_buffer(target, addr, len, (uint8_t *)separator);
1326 if (retval != ERROR_OK)
1327 gdb_connection->mem_write_error = true;
1333 static int gdb_step_continue_packet(struct connection *connection,
1334 char *packet, int packet_size)
1336 struct target *target = get_target_from_connection(connection);
1338 uint32_t address = 0x0;
1339 int retval = ERROR_OK;
1343 if (packet_size > 1) {
1344 packet[packet_size] = 0;
1345 address = strtoul(packet + 1, NULL, 16);
1349 if (packet[0] == 'c') {
1350 LOG_DEBUG("continue");
1351 /* resume at current address, don't handle breakpoints, not debugging */
1352 retval = target_resume(target, current, address, 0, 0);
1353 } else if (packet[0] == 's') {
1355 /* step at current or address, don't handle breakpoints */
1356 retval = target_step(target, current, address, 0);
1361 static int gdb_breakpoint_watchpoint_packet(struct connection *connection,
1362 char *packet, int packet_size)
1364 struct target *target = get_target_from_connection(connection);
1366 enum breakpoint_type bp_type = BKPT_SOFT /* dummy init to avoid warning */;
1367 enum watchpoint_rw wp_type = WPT_READ /* dummy init to avoid warning */;
1375 type = strtoul(packet + 1, &separator, 16);
1377 if (type == 0) /* memory breakpoint */
1378 bp_type = BKPT_SOFT;
1379 else if (type == 1) /* hardware breakpoint */
1380 bp_type = BKPT_HARD;
1381 else if (type == 2) /* write watchpoint */
1382 wp_type = WPT_WRITE;
1383 else if (type == 3) /* read watchpoint */
1385 else if (type == 4) /* access watchpoint */
1386 wp_type = WPT_ACCESS;
1388 LOG_ERROR("invalid gdb watch/breakpoint type(%d), dropping connection", type);
1389 return ERROR_SERVER_REMOTE_CLOSED;
1392 if (gdb_breakpoint_override && ((bp_type == BKPT_SOFT) || (bp_type == BKPT_HARD)))
1393 bp_type = gdb_breakpoint_override_type;
1395 if (*separator != ',') {
1396 LOG_ERROR("incomplete breakpoint/watchpoint packet received, dropping connection");
1397 return ERROR_SERVER_REMOTE_CLOSED;
1400 address = strtoul(separator + 1, &separator, 16);
1402 if (*separator != ',') {
1403 LOG_ERROR("incomplete breakpoint/watchpoint packet received, dropping connection");
1404 return ERROR_SERVER_REMOTE_CLOSED;
1407 size = strtoul(separator + 1, &separator, 16);
1412 if (packet[0] == 'Z') {
1413 retval = breakpoint_add(target, address, size, bp_type);
1414 if (retval != ERROR_OK) {
1415 retval = gdb_error(connection, retval);
1416 if (retval != ERROR_OK)
1419 gdb_put_packet(connection, "OK", 2);
1421 breakpoint_remove(target, address);
1422 gdb_put_packet(connection, "OK", 2);
1429 if (packet[0] == 'Z') {
1430 retval = watchpoint_add(target, address, size, wp_type, 0, 0xffffffffu);
1431 if (retval != ERROR_OK) {
1432 retval = gdb_error(connection, retval);
1433 if (retval != ERROR_OK)
1436 gdb_put_packet(connection, "OK", 2);
1438 watchpoint_remove(target, address);
1439 gdb_put_packet(connection, "OK", 2);
1450 /* print out a string and allocate more space as needed,
1451 * mainly used for XML at this point
1453 static void xml_printf(int *retval, char **xml, int *pos, int *size,
1454 const char *fmt, ...)
1456 if (*retval != ERROR_OK)
1461 if ((*xml == NULL) || (!first)) {
1462 /* start by 0 to exercise all the code paths.
1463 * Need minimum 2 bytes to fit 1 char and 0 terminator. */
1465 *size = *size * 2 + 2;
1467 *xml = realloc(*xml, *size);
1471 *retval = ERROR_SERVER_REMOTE_CLOSED;
1479 ret = vsnprintf(*xml + *pos, *size - *pos, fmt, ap);
1481 if ((ret > 0) && ((ret + 1) < *size - *pos)) {
1485 /* there was just enough or not enough space, allocate more. */
1490 static int decode_xfer_read(char *buf, char **annex, int *ofs, unsigned int *len)
1494 /* Extract and NUL-terminate the annex. */
1496 while (*buf && *buf != ':')
1502 /* After the read marker and annex, qXfer looks like a
1503 * traditional 'm' packet. */
1505 *ofs = strtoul(buf, &separator, 16);
1507 if (*separator != ',')
1510 *len = strtoul(separator + 1, NULL, 16);
1515 static int compare_bank(const void *a, const void *b)
1517 struct flash_bank *b1, *b2;
1518 b1 = *((struct flash_bank **)a);
1519 b2 = *((struct flash_bank **)b);
1521 if (b1->base == b2->base)
1523 else if (b1->base > b2->base)
1529 static int gdb_memory_map(struct connection *connection,
1530 char *packet, int packet_size)
1532 /* We get away with only specifying flash here. Regions that are not
1533 * specified are treated as if we provided no memory map(if not we
1534 * could detect the holes and mark them as RAM).
1535 * Normally we only execute this code once, but no big deal if we
1536 * have to regenerate it a couple of times.
1539 struct target *target = get_target_from_connection(connection);
1540 struct flash_bank *p;
1544 int retval = ERROR_OK;
1545 struct flash_bank **banks;
1549 uint32_t ram_start = 0;
1551 int target_flash_banks = 0;
1553 /* skip command character */
1556 offset = strtoul(packet, &separator, 16);
1557 length = strtoul(separator + 1, &separator, 16);
1559 xml_printf(&retval, &xml, &pos, &size, "<memory-map>\n");
1561 /* Sort banks in ascending order. We need to report non-flash
1562 * memory as ram (or rather read/write) by default for GDB, since
1563 * it has no concept of non-cacheable read/write memory (i/o etc).
1565 * FIXME Most non-flash addresses are *NOT* RAM! Don't lie.
1566 * Current versions of GDB assume unlisted addresses are RAM...
1568 banks = malloc(sizeof(struct flash_bank *)*flash_get_bank_count());
1570 for (i = 0; i < flash_get_bank_count(); i++) {
1571 retval = get_flash_bank_by_num(i, &p);
1572 if (retval != ERROR_OK) {
1574 gdb_error(connection, retval);
1577 if (p->target == target)
1578 banks[target_flash_banks++] = p;
1581 qsort(banks, target_flash_banks, sizeof(struct flash_bank *),
1584 for (i = 0; i < target_flash_banks; i++) {
1586 unsigned sector_size = 0;
1592 if (ram_start < p->base)
1593 xml_printf(&retval, &xml, &pos, &size,
1594 "<memory type=\"ram\" start=\"0x%x\" "
1595 "length=\"0x%x\"/>\n",
1596 ram_start, p->base - ram_start);
1598 /* Report adjacent groups of same-size sectors. So for
1599 * example top boot CFI flash will list an initial region
1600 * with several large sectors (maybe 128KB) and several
1601 * smaller ones at the end (maybe 32KB). STR7 will have
1602 * regions with 8KB, 32KB, and 64KB sectors; etc.
1604 for (j = 0; j < p->num_sectors; j++) {
1607 /* Maybe start a new group of sectors. */
1608 if (sector_size == 0) {
1609 start = p->base + p->sectors[j].offset;
1610 xml_printf(&retval, &xml, &pos, &size,
1611 "<memory type=\"flash\" "
1614 sector_size = p->sectors[j].size;
1617 /* Does this finish a group of sectors?
1618 * If not, continue an already-started group.
1620 if (j == p->num_sectors - 1)
1621 group_len = (p->base + p->size) - start;
1622 else if (p->sectors[j + 1].size != sector_size)
1623 group_len = p->base + p->sectors[j + 1].offset
1628 xml_printf(&retval, &xml, &pos, &size,
1629 "length=\"0x%x\">\n"
1630 "<property name=\"blocksize\">"
1638 ram_start = p->base + p->size;
1642 xml_printf(&retval, &xml, &pos, &size,
1643 "<memory type=\"ram\" start=\"0x%x\" "
1644 "length=\"0x%x\"/>\n",
1645 ram_start, 0-ram_start);
1646 /* ELSE a flash chip could be at the very end of the 32 bit address
1647 * space, in which case ram_start will be precisely 0
1653 xml_printf(&retval, &xml, &pos, &size, "</memory-map>\n");
1655 if (retval != ERROR_OK) {
1656 gdb_error(connection, retval);
1660 if (offset + length > pos)
1661 length = pos - offset;
1663 char *t = malloc(length + 1);
1665 memcpy(t + 1, xml + offset, length);
1666 gdb_put_packet(connection, t, length + 1);
1673 static int gdb_query_packet(struct connection *connection,
1674 char *packet, int packet_size)
1676 struct command_context *cmd_ctx = connection->cmd_ctx;
1677 struct gdb_connection *gdb_connection = connection->priv;
1678 struct target *target = get_target_from_connection(connection);
1680 if (strncmp(packet, "qRcmd,", 6) == 0) {
1681 if (packet_size > 6) {
1683 cmd = malloc((packet_size - 6) / 2 + 1);
1684 int len = unhexify(cmd, packet + 6, (packet_size - 6) / 2);
1687 /* We want to print all debug output to GDB connection */
1688 log_add_callback(gdb_log_callback, connection);
1689 target_call_timer_callbacks_now();
1690 /* some commands need to know the GDB connection, make note of current
1691 * GDB connection. */
1692 current_gdb_connection = gdb_connection;
1693 command_run_line(cmd_ctx, cmd);
1694 current_gdb_connection = NULL;
1695 target_call_timer_callbacks_now();
1696 log_remove_callback(gdb_log_callback, connection);
1699 gdb_put_packet(connection, "OK", 2);
1701 } else if (strncmp(packet, "qCRC:", 5) == 0) {
1702 if (packet_size > 5) {
1710 /* skip command character */
1713 addr = strtoul(packet, &separator, 16);
1715 if (*separator != ',') {
1716 LOG_ERROR("incomplete read memory packet received, dropping connection");
1717 return ERROR_SERVER_REMOTE_CLOSED;
1720 len = strtoul(separator + 1, NULL, 16);
1722 retval = target_checksum_memory(target, addr, len, &checksum);
1724 if (retval == ERROR_OK) {
1725 snprintf(gdb_reply, 10, "C%8.8" PRIx32 "", checksum);
1726 gdb_put_packet(connection, gdb_reply, 9);
1728 retval = gdb_error(connection, retval);
1729 if (retval != ERROR_OK)
1735 } else if (strncmp(packet, "qSupported", 10) == 0) {
1736 /* we currently support packet size and qXfer:memory-map:read (if enabled)
1737 * disable qXfer:features:read for the moment */
1738 int retval = ERROR_OK;
1739 char *buffer = NULL;
1747 "PacketSize=%x;qXfer:memory-map:read%c;qXfer:features:read-;QStartNoAckMode+",
1748 (GDB_BUFFER_SIZE - 1),
1749 ((gdb_use_memory_map == 1) && (flash_get_bank_count() > 0)) ? '+' : '-');
1751 if (retval != ERROR_OK) {
1752 gdb_send_error(connection, 01);
1756 gdb_put_packet(connection, buffer, strlen(buffer));
1760 } else if ((strncmp(packet, "qXfer:memory-map:read::", 23) == 0)
1761 && (flash_get_bank_count() > 0))
1762 return gdb_memory_map(connection, packet, packet_size);
1763 else if (strncmp(packet, "qXfer:features:read:", 20) == 0) {
1767 int retval = ERROR_OK;
1770 unsigned int length;
1773 /* skip command character */
1776 if (decode_xfer_read(packet, &annex, &offset, &length) < 0) {
1777 gdb_send_error(connection, 01);
1781 if (strcmp(annex, "target.xml") != 0) {
1782 gdb_send_error(connection, 01);
1790 "l < target version=\"1.0\">\n < architecture > arm</architecture>\n</target>\n");
1792 if (retval != ERROR_OK) {
1793 gdb_error(connection, retval);
1797 gdb_put_packet(connection, xml, strlen(xml));
1801 } else if (strncmp(packet, "QStartNoAckMode", 15) == 0) {
1802 gdb_connection->noack_mode = 1;
1803 gdb_put_packet(connection, "OK", 2);
1807 gdb_put_packet(connection, "", 0);
1811 static int gdb_v_packet(struct connection *connection,
1812 char *packet, int packet_size)
1814 struct gdb_connection *gdb_connection = connection->priv;
1815 struct gdb_service *gdb_service = connection->service->priv;
1818 /* if flash programming disabled - send a empty reply */
1820 if (gdb_flash_program == 0) {
1821 gdb_put_packet(connection, "", 0);
1825 if (strncmp(packet, "vFlashErase:", 12) == 0) {
1827 unsigned long length;
1829 char *parse = packet + 12;
1830 if (*parse == '\0') {
1831 LOG_ERROR("incomplete vFlashErase packet received, dropping connection");
1832 return ERROR_SERVER_REMOTE_CLOSED;
1835 addr = strtoul(parse, &parse, 16);
1837 if (*(parse++) != ',' || *parse == '\0') {
1838 LOG_ERROR("incomplete vFlashErase packet received, dropping connection");
1839 return ERROR_SERVER_REMOTE_CLOSED;
1842 length = strtoul(parse, &parse, 16);
1844 if (*parse != '\0') {
1845 LOG_ERROR("incomplete vFlashErase packet received, dropping connection");
1846 return ERROR_SERVER_REMOTE_CLOSED;
1849 /* assume all sectors need erasing - stops any problems
1850 * when flash_write is called multiple times */
1853 /* perform any target specific operations before the erase */
1854 target_call_event_callbacks(gdb_service->target,
1855 TARGET_EVENT_GDB_FLASH_ERASE_START);
1857 /* vFlashErase:addr,length messages require region start and
1858 * end to be "block" aligned ... if padding is ever needed,
1859 * GDB will have become dangerously confused.
1861 result = flash_erase_address_range(gdb_service->target,
1862 false, addr, length);
1864 /* perform any target specific operations after the erase */
1865 target_call_event_callbacks(gdb_service->target,
1866 TARGET_EVENT_GDB_FLASH_ERASE_END);
1869 if (result != ERROR_OK) {
1870 /* GDB doesn't evaluate the actual error number returned,
1871 * treat a failed erase as an I/O error
1873 gdb_send_error(connection, EIO);
1874 LOG_ERROR("flash_erase returned %i", result);
1876 gdb_put_packet(connection, "OK", 2);
1881 if (strncmp(packet, "vFlashWrite:", 12) == 0) {
1884 unsigned long length;
1885 char *parse = packet + 12;
1887 if (*parse == '\0') {
1888 LOG_ERROR("incomplete vFlashErase packet received, dropping connection");
1889 return ERROR_SERVER_REMOTE_CLOSED;
1891 addr = strtoul(parse, &parse, 16);
1892 if (*(parse++) != ':') {
1893 LOG_ERROR("incomplete vFlashErase packet received, dropping connection");
1894 return ERROR_SERVER_REMOTE_CLOSED;
1896 length = packet_size - (parse - packet);
1898 /* create a new image if there isn't already one */
1899 if (gdb_connection->vflash_image == NULL) {
1900 gdb_connection->vflash_image = malloc(sizeof(struct image));
1901 image_open(gdb_connection->vflash_image, "", "build");
1904 /* create new section with content from packet buffer */
1905 retval = image_add_section(gdb_connection->vflash_image,
1906 addr, length, 0x0, (uint8_t *)parse);
1907 if (retval != ERROR_OK)
1910 gdb_put_packet(connection, "OK", 2);
1915 if (strncmp(packet, "vFlashDone", 10) == 0) {
1918 /* process the flashing buffer. No need to erase as GDB
1919 * always issues a vFlashErase first. */
1920 target_call_event_callbacks(gdb_service->target,
1921 TARGET_EVENT_GDB_FLASH_WRITE_START);
1922 result = flash_write(gdb_service->target, gdb_connection->vflash_image, &written, 0);
1923 target_call_event_callbacks(gdb_service->target, TARGET_EVENT_GDB_FLASH_WRITE_END);
1924 if (result != ERROR_OK) {
1925 if (result == ERROR_FLASH_DST_OUT_OF_BANK)
1926 gdb_put_packet(connection, "E.memtype", 9);
1928 gdb_send_error(connection, EIO);
1930 LOG_DEBUG("wrote %u bytes from vFlash image to flash", (unsigned)written);
1931 gdb_put_packet(connection, "OK", 2);
1934 image_close(gdb_connection->vflash_image);
1935 free(gdb_connection->vflash_image);
1936 gdb_connection->vflash_image = NULL;
1941 gdb_put_packet(connection, "", 0);
1945 static int gdb_detach(struct connection *connection)
1947 struct gdb_service *gdb_service = connection->service->priv;
1949 target_call_event_callbacks(gdb_service->target, TARGET_EVENT_GDB_DETACH);
1951 return gdb_put_packet(connection, "OK", 2);
1954 static void gdb_log_callback(void *priv, const char *file, unsigned line,
1955 const char *function, const char *string)
1957 struct connection *connection = priv;
1958 struct gdb_connection *gdb_con = connection->priv;
1960 if (gdb_con->busy) {
1961 /* do not reply this using the O packet */
1965 gdb_output_con(connection, string);
1968 static void gdb_sig_halted(struct connection *connection)
1971 snprintf(sig_reply, 4, "T%2.2x", 2);
1972 gdb_put_packet(connection, sig_reply, 3);
1975 static int gdb_input_inner(struct connection *connection)
1977 /* Do not allocate this on the stack */
1978 static char gdb_packet_buffer[GDB_BUFFER_SIZE];
1980 struct gdb_service *gdb_service = connection->service->priv;
1981 struct target *target = gdb_service->target;
1982 char *packet = gdb_packet_buffer;
1985 struct gdb_connection *gdb_con = connection->priv;
1986 static int extended_protocol;
1988 /* drain input buffer. If one of the packets fail, then an error
1989 * packet is replied, if applicable.
1991 * This loop will terminate and the error code is returned.
1993 * The calling fn will check if this error is something that
1994 * can be recovered from, or if the connection must be closed.
1996 * If the error is recoverable, this fn is called again to
1997 * drain the rest of the buffer.
2000 packet_size = GDB_BUFFER_SIZE-1;
2001 retval = gdb_get_packet(connection, packet, &packet_size);
2002 if (retval != ERROR_OK)
2005 /* terminate with zero */
2006 packet[packet_size] = 0;
2008 if (LOG_LEVEL_IS(LOG_LVL_DEBUG)) {
2009 if (packet[0] == 'X') {
2010 /* binary packets spew junk into the debug log stream */
2013 for (x = 0; (x < 49) && (packet[x] != ':'); x++)
2016 LOG_DEBUG("received packet: '%s:<binary-data>'", buf);
2018 LOG_DEBUG("received packet: '%s'", packet);
2021 if (packet_size > 0) {
2023 switch (packet[0]) {
2024 case 'T': /* Is thread alive? */
2025 gdb_thread_packet(connection, packet, packet_size);
2027 case 'H': /* Set current thread ( 'c' for step and continue,
2028 * 'g' for all other operations ) */
2029 gdb_thread_packet(connection, packet, packet_size);
2033 retval = gdb_thread_packet(connection, packet, packet_size);
2034 if (retval == GDB_THREAD_PACKET_NOT_CONSUMED)
2035 retval = gdb_query_packet(connection, packet, packet_size);
2038 retval = gdb_get_registers_packet(connection, packet, packet_size);
2041 retval = gdb_set_registers_packet(connection, packet, packet_size);
2044 retval = gdb_get_register_packet(connection, packet, packet_size);
2047 retval = gdb_set_register_packet(connection, packet, packet_size);
2050 retval = gdb_read_memory_packet(connection, packet, packet_size);
2053 retval = gdb_write_memory_packet(connection, packet, packet_size);
2057 retval = gdb_breakpoint_watchpoint_packet(connection, packet, packet_size);
2060 gdb_last_signal_packet(connection, packet, packet_size);
2065 gdb_thread_packet(connection, packet, packet_size);
2066 log_add_callback(gdb_log_callback, connection);
2068 if (gdb_con->mem_write_error) {
2069 LOG_ERROR("Memory write failure!");
2071 /* now that we have reported the memory write error,
2072 * we can clear the condition */
2073 gdb_con->mem_write_error = false;
2076 bool nostep = false;
2077 bool already_running = false;
2078 if (target->state == TARGET_RUNNING) {
2079 LOG_WARNING("WARNING! The target is already running. "
2080 "All changes GDB did to registers will be discarded! "
2081 "Waiting for target to halt.");
2082 already_running = true;
2083 } else if (target->state != TARGET_HALTED) {
2084 LOG_WARNING("The target is not in the halted nor running stated, " \
2085 "stepi/continue ignored.");
2087 } else if ((packet[0] == 's') && gdb_con->sync) {
2088 /* Hmm..... when you issue a continue in GDB, then a "stepi" is
2089 * sent by GDB first to OpenOCD, thus defeating the check to
2090 * make only the single stepping have the sync feature...
2093 LOG_WARNING("stepi ignored. GDB will now fetch the register state " \
2094 "from the target.");
2096 gdb_con->sync = false;
2098 if (!already_running && nostep) {
2099 /* Either the target isn't in the halted state, then we can't
2100 * step/continue. This might be early setup, etc.
2102 * Or we want to allow GDB to pick up a fresh set of
2103 * register values without modifying the target state.
2106 gdb_sig_halted(connection);
2108 /* stop forwarding log packets! */
2109 log_remove_callback(gdb_log_callback, connection);
2111 /* We're running/stepping, in which case we can
2112 * forward log output until the target is halted
2114 gdb_con->frontend_state = TARGET_RUNNING;
2115 target_call_event_callbacks(target, TARGET_EVENT_GDB_START);
2117 if (!already_running) {
2118 /* Here we don't want packet processing to stop even if this fails,
2119 * so we use a local variable instead of retval. */
2120 retval = gdb_step_continue_packet(connection, packet, packet_size);
2121 if (retval != ERROR_OK) {
2122 /* we'll never receive a halted
2123 * condition... issue a false one..
2125 gdb_frontend_halted(target, connection);
2132 retval = gdb_v_packet(connection, packet, packet_size);
2135 retval = gdb_detach(connection);
2136 extended_protocol = 0;
2139 retval = gdb_write_memory_binary_packet(connection, packet, packet_size);
2140 if (retval != ERROR_OK)
2144 if (extended_protocol != 0) {
2145 gdb_con->attached = false;
2148 gdb_put_packet(connection, "OK", 2);
2149 return ERROR_SERVER_REMOTE_CLOSED;
2151 /* handle extended remote protocol */
2152 extended_protocol = 1;
2153 gdb_put_packet(connection, "OK", 2);
2156 /* handle extended restart packet */
2157 breakpoint_clear_target(gdb_service->target);
2158 watchpoint_clear_target(gdb_service->target);
2159 command_run_linef(connection->cmd_ctx, "ocd_gdb_restart %s",
2160 target_name(target));
2161 /* set connection as attached after reset */
2162 gdb_con->attached = true;
2163 /* info rtos parts */
2164 gdb_thread_packet(connection, packet, packet_size);
2168 /* packet supported only by smp target i.e cortex_a.c*/
2169 /* handle smp packet replying coreid played to gbd */
2170 gdb_read_smp_packet(connection, packet, packet_size);
2174 /* packet supported only by smp target i.e cortex_a.c */
2175 /* handle smp packet setting coreid to be played at next
2177 gdb_write_smp_packet(connection, packet, packet_size);
2181 /* ignore unknown packets */
2182 LOG_DEBUG("ignoring 0x%2.2x packet", packet[0]);
2183 gdb_put_packet(connection, NULL, 0);
2187 /* if a packet handler returned an error, exit input loop */
2188 if (retval != ERROR_OK)
2192 if (gdb_con->ctrl_c) {
2193 if (target->state == TARGET_RUNNING) {
2194 retval = target_halt(target);
2195 if (retval != ERROR_OK)
2196 target_call_event_callbacks(target, TARGET_EVENT_GDB_HALT);
2197 gdb_con->ctrl_c = 0;
2199 LOG_INFO("The target is not running when halt was requested, stopping GDB.");
2200 target_call_event_callbacks(target, TARGET_EVENT_GDB_HALT);
2204 } while (gdb_con->buf_cnt > 0);
2209 static int gdb_input(struct connection *connection)
2211 int retval = gdb_input_inner(connection);
2212 struct gdb_connection *gdb_con = connection->priv;
2213 if (retval == ERROR_SERVER_REMOTE_CLOSED)
2216 /* logging does not propagate the error, yet can set the gdb_con->closed flag */
2217 if (gdb_con->closed)
2218 return ERROR_SERVER_REMOTE_CLOSED;
2220 /* we'll recover from any other errors(e.g. temporary timeouts, etc.) */
2224 static int gdb_target_start(struct target *target, const char *port)
2226 struct gdb_service *gdb_service;
2228 gdb_service = malloc(sizeof(struct gdb_service));
2230 if (NULL == gdb_service)
2233 gdb_service->target = target;
2234 gdb_service->core[0] = -1;
2235 gdb_service->core[1] = -1;
2236 target->gdb_service = gdb_service;
2238 ret = add_service("gdb",
2239 port, 1, &gdb_new_connection, &gdb_input,
2240 &gdb_connection_closed, gdb_service);
2241 /* initialialize all targets gdb service with the same pointer */
2243 struct target_list *head;
2244 struct target *curr;
2245 head = target->head;
2246 while (head != (struct target_list *)NULL) {
2247 curr = head->target;
2249 curr->gdb_service = gdb_service;
2256 static int gdb_target_add_one(struct target *target)
2258 /* one gdb instance per smp list */
2259 if ((target->smp) && (target->gdb_service))
2261 int retval = gdb_target_start(target, gdb_port_next);
2262 if (retval == ERROR_OK) {
2264 /* If we can parse the port number
2265 * then we increment the port number for the next target.
2268 portnumber = strtol(gdb_port_next, &end, 0);
2270 if (parse_long(gdb_port_next, &portnumber) == ERROR_OK) {
2271 free((void *)gdb_port_next);
2272 gdb_port_next = alloc_printf("%d", portnumber+1);
2279 int gdb_target_add_all(struct target *target)
2281 if (NULL == target) {
2282 LOG_WARNING("gdb services need one or more targets defined");
2286 while (NULL != target) {
2287 int retval = gdb_target_add_one(target);
2288 if (ERROR_OK != retval)
2291 target = target->next;
2297 COMMAND_HANDLER(handle_gdb_sync_command)
2300 return ERROR_COMMAND_SYNTAX_ERROR;
2302 if (current_gdb_connection == NULL) {
2303 command_print(CMD_CTX,
2304 "gdb_sync command can only be run from within gdb using \"monitor gdb_sync\"");
2308 current_gdb_connection->sync = true;
2313 /* daemon configuration command gdb_port */
2314 COMMAND_HANDLER(handle_gdb_port_command)
2316 int retval = CALL_COMMAND_HANDLER(server_pipe_command, &gdb_port);
2317 if (ERROR_OK == retval) {
2318 free((void *)gdb_port_next);
2319 gdb_port_next = strdup(gdb_port);
2324 COMMAND_HANDLER(handle_gdb_memory_map_command)
2327 return ERROR_COMMAND_SYNTAX_ERROR;
2329 COMMAND_PARSE_ENABLE(CMD_ARGV[0], gdb_use_memory_map);
2333 COMMAND_HANDLER(handle_gdb_flash_program_command)
2336 return ERROR_COMMAND_SYNTAX_ERROR;
2338 COMMAND_PARSE_ENABLE(CMD_ARGV[0], gdb_flash_program);
2342 COMMAND_HANDLER(handle_gdb_report_data_abort_command)
2345 return ERROR_COMMAND_SYNTAX_ERROR;
2347 COMMAND_PARSE_ENABLE(CMD_ARGV[0], gdb_report_data_abort);
2351 /* gdb_breakpoint_override */
2352 COMMAND_HANDLER(handle_gdb_breakpoint_override_command)
2354 if (CMD_ARGC == 0) {
2356 } else if (CMD_ARGC == 1) {
2357 gdb_breakpoint_override = 1;
2358 if (strcmp(CMD_ARGV[0], "hard") == 0)
2359 gdb_breakpoint_override_type = BKPT_HARD;
2360 else if (strcmp(CMD_ARGV[0], "soft") == 0)
2361 gdb_breakpoint_override_type = BKPT_SOFT;
2362 else if (strcmp(CMD_ARGV[0], "disable") == 0)
2363 gdb_breakpoint_override = 0;
2365 return ERROR_COMMAND_SYNTAX_ERROR;
2366 if (gdb_breakpoint_override)
2367 LOG_USER("force %s breakpoints",
2368 (gdb_breakpoint_override_type == BKPT_HARD) ? "hard" : "soft");
2370 LOG_USER("breakpoint type is not overridden");
2375 static const struct command_registration gdb_command_handlers[] = {
2378 .handler = handle_gdb_sync_command,
2379 .mode = COMMAND_ANY,
2380 .help = "next stepi will return immediately allowing "
2381 "GDB to fetch register state without affecting "
2387 .handler = handle_gdb_port_command,
2388 .mode = COMMAND_ANY,
2389 .help = "Normally gdb listens to a TCP/IP port. Each subsequent GDB "
2390 "server listens for the next port number after the "
2391 "base port number specified. "
2392 "No arguments reports GDB port. \"pipe\" means listen to stdin "
2393 "output to stdout, an integer is base port number, \"disable\" disables "
2394 "port. Any other string is are interpreted as named pipe to listen to. "
2395 "Output pipe is the same name as input pipe, but with 'o' appended.",
2396 .usage = "[port_num]",
2399 .name = "gdb_memory_map",
2400 .handler = handle_gdb_memory_map_command,
2401 .mode = COMMAND_CONFIG,
2402 .help = "enable or disable memory map",
2403 .usage = "('enable'|'disable')"
2406 .name = "gdb_flash_program",
2407 .handler = handle_gdb_flash_program_command,
2408 .mode = COMMAND_CONFIG,
2409 .help = "enable or disable flash program",
2410 .usage = "('enable'|'disable')"
2413 .name = "gdb_report_data_abort",
2414 .handler = handle_gdb_report_data_abort_command,
2415 .mode = COMMAND_CONFIG,
2416 .help = "enable or disable reporting data aborts",
2417 .usage = "('enable'|'disable')"
2420 .name = "gdb_breakpoint_override",
2421 .handler = handle_gdb_breakpoint_override_command,
2422 .mode = COMMAND_ANY,
2423 .help = "Display or specify type of breakpoint "
2424 "to be used by gdb 'break' commands.",
2425 .usage = "('hard'|'soft'|'disable')"
2427 COMMAND_REGISTRATION_DONE
2430 int gdb_register_commands(struct command_context *cmd_ctx)
2432 gdb_port = strdup("3333");
2433 gdb_port_next = strdup("3333");
2434 return register_commands(cmd_ctx, NULL, gdb_command_handlers);