gdb_server: add support for vCont
[openocd.git] / src / server / gdb_server.c
blobd866fc6e2a4641167875f2294e4aae2bcd2cb980
1 /***************************************************************************
2 * Copyright (C) 2005 by Dominic Rath *
3 * Dominic.Rath@gmx.de *
4 * *
5 * Copyright (C) 2007-2010 Øyvind Harboe *
6 * oyvind.harboe@zylin.com *
7 * *
8 * Copyright (C) 2008 by Spencer Oliver *
9 * spen@spen-soft.co.uk *
10 * *
11 * Copyright (C) 2011 by Broadcom Corporation *
12 * Evan Hunter - ehunter@broadcom.com *
13 * *
14 * Copyright (C) ST-Ericsson SA 2011 *
15 * michel.jaouen@stericsson.com : smp minimum support *
16 * *
17 * Copyright (C) 2013 Andes Technology *
18 * Hsiangkai Wang <hkwang@andestech.com> *
19 * *
20 * Copyright (C) 2013 Franck Jullien *
21 * elec4fun@gmail.com *
22 * *
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. *
27 * *
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. *
32 * *
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 ***************************************************************************/
37 #ifdef HAVE_CONFIG_H
38 #include "config.h"
39 #endif
41 #include <target/breakpoints.h>
42 #include <target/target_request.h>
43 #include <target/register.h>
44 #include <target/target.h>
45 #include <target/target_type.h>
46 #include "server.h"
47 #include <flash/nor/core.h>
48 #include "gdb_server.h"
49 #include <target/image.h>
50 #include <jtag/jtag.h>
51 #include "rtos/rtos.h"
52 #include "target/smp.h"
54 /**
55 * @file
56 * GDB server implementation.
58 * This implements the GDB Remote Serial Protocol, over TCP connections,
59 * giving GDB access to the JTAG or other hardware debugging facilities
60 * found in most modern embedded processors.
63 struct target_desc_format {
64 char *tdesc;
65 uint32_t tdesc_length;
68 /* private connection data for GDB */
69 struct gdb_connection {
70 char buffer[GDB_BUFFER_SIZE];
71 char *buf_p;
72 int buf_cnt;
73 int ctrl_c;
74 enum target_state frontend_state;
75 struct image *vflash_image;
76 bool closed;
77 bool busy;
78 int noack_mode;
79 /* set flag to true if you want the next stepi to return immediately.
80 * allowing GDB to pick up a fresh set of register values from the target
81 * without modifying the target state. */
82 bool sync;
83 /* We delay reporting memory write errors until next step/continue or memory
84 * write. This improves performance of gdb load significantly as the GDB packet
85 * can be replied immediately and a new GDB packet will be ready without delay
86 * (ca. 10% or so...). */
87 bool mem_write_error;
88 /* with extended-remote it seems we need to better emulate attach/detach.
89 * what this means is we reply with a W stop reply after a kill packet,
90 * normally we reply with a S reply via gdb_last_signal_packet.
91 * as a side note this behaviour only effects gdb > 6.8 */
92 bool attached;
93 /* temporarily used for target description support */
94 struct target_desc_format target_desc;
95 /* temporarily used for thread list support */
96 char *thread_list;
99 #if 0
100 #define _DEBUG_GDB_IO_
101 #endif
103 static struct gdb_connection *current_gdb_connection;
105 static int gdb_breakpoint_override;
106 static enum breakpoint_type gdb_breakpoint_override_type;
108 static int gdb_error(struct connection *connection, int retval);
109 static char *gdb_port;
110 static char *gdb_port_next;
112 static void gdb_log_callback(void *priv, const char *file, unsigned line,
113 const char *function, const char *string);
115 static void gdb_sig_halted(struct connection *connection);
117 /* number of gdb connections, mainly to suppress gdb related debugging spam
118 * in helper/log.c when no gdb connections are actually active */
119 int gdb_actual_connections;
121 /* set if we are sending a memory map to gdb
122 * via qXfer:memory-map:read packet */
123 /* enabled by default*/
124 static int gdb_use_memory_map = 1;
125 /* enabled by default*/
126 static int gdb_flash_program = 1;
128 /* if set, data aborts cause an error to be reported in memory read packets
129 * see the code in gdb_read_memory_packet() for further explanations.
130 * Disabled by default.
132 static int gdb_report_data_abort;
134 /* set if we are sending target descriptions to gdb
135 * via qXfer:features:read packet */
136 /* enabled by default */
137 static int gdb_use_target_description = 1;
139 /* current processing free-run type, used by file-I/O */
140 static char gdb_running_type;
142 static int gdb_last_signal(struct target *target)
144 switch (target->debug_reason) {
145 case DBG_REASON_DBGRQ:
146 return 0x2; /* SIGINT */
147 case DBG_REASON_BREAKPOINT:
148 case DBG_REASON_WATCHPOINT:
149 case DBG_REASON_WPTANDBKPT:
150 return 0x05; /* SIGTRAP */
151 case DBG_REASON_SINGLESTEP:
152 return 0x05; /* SIGTRAP */
153 case DBG_REASON_NOTHALTED:
154 return 0x0; /* no signal... shouldn't happen */
155 default:
156 LOG_USER("undefined debug reason %d - target needs reset",
157 target->debug_reason);
158 return 0x0;
162 static int check_pending(struct connection *connection,
163 int timeout_s, int *got_data)
165 /* a non-blocking socket will block if there is 0 bytes available on the socket,
166 * but return with as many bytes as are available immediately
168 struct timeval tv;
169 fd_set read_fds;
170 struct gdb_connection *gdb_con = connection->priv;
171 int t;
172 if (got_data == NULL)
173 got_data = &t;
174 *got_data = 0;
176 if (gdb_con->buf_cnt > 0) {
177 *got_data = 1;
178 return ERROR_OK;
181 FD_ZERO(&read_fds);
182 FD_SET(connection->fd, &read_fds);
184 tv.tv_sec = timeout_s;
185 tv.tv_usec = 0;
186 if (socket_select(connection->fd + 1, &read_fds, NULL, NULL, &tv) == 0) {
187 /* This can typically be because a "monitor" command took too long
188 * before printing any progress messages
190 if (timeout_s > 0)
191 return ERROR_GDB_TIMEOUT;
192 else
193 return ERROR_OK;
195 *got_data = FD_ISSET(connection->fd, &read_fds) != 0;
196 return ERROR_OK;
199 static int gdb_get_char_inner(struct connection *connection, int *next_char)
201 struct gdb_connection *gdb_con = connection->priv;
202 int retval = ERROR_OK;
204 #ifdef _DEBUG_GDB_IO_
205 char *debug_buffer;
206 #endif
207 for (;; ) {
208 if (connection->service->type != CONNECTION_TCP)
209 gdb_con->buf_cnt = read(connection->fd, gdb_con->buffer, GDB_BUFFER_SIZE);
210 else {
211 retval = check_pending(connection, 1, NULL);
212 if (retval != ERROR_OK)
213 return retval;
214 gdb_con->buf_cnt = read_socket(connection->fd,
215 gdb_con->buffer,
216 GDB_BUFFER_SIZE);
219 if (gdb_con->buf_cnt > 0)
220 break;
221 if (gdb_con->buf_cnt == 0) {
222 gdb_con->closed = true;
223 return ERROR_SERVER_REMOTE_CLOSED;
226 #ifdef _WIN32
227 errno = WSAGetLastError();
229 switch (errno) {
230 case WSAEWOULDBLOCK:
231 usleep(1000);
232 break;
233 case WSAECONNABORTED:
234 gdb_con->closed = true;
235 return ERROR_SERVER_REMOTE_CLOSED;
236 case WSAECONNRESET:
237 gdb_con->closed = true;
238 return ERROR_SERVER_REMOTE_CLOSED;
239 default:
240 LOG_ERROR("read: %d", errno);
241 exit(-1);
243 #else
244 switch (errno) {
245 case EAGAIN:
246 usleep(1000);
247 break;
248 case ECONNABORTED:
249 gdb_con->closed = true;
250 return ERROR_SERVER_REMOTE_CLOSED;
251 case ECONNRESET:
252 gdb_con->closed = true;
253 return ERROR_SERVER_REMOTE_CLOSED;
254 default:
255 LOG_ERROR("read: %s", strerror(errno));
256 gdb_con->closed = true;
257 return ERROR_SERVER_REMOTE_CLOSED;
259 #endif
262 #ifdef _DEBUG_GDB_IO_
263 debug_buffer = strndup(gdb_con->buffer, gdb_con->buf_cnt);
264 LOG_DEBUG("received '%s'", debug_buffer);
265 free(debug_buffer);
266 #endif
268 gdb_con->buf_p = gdb_con->buffer;
269 gdb_con->buf_cnt--;
270 *next_char = *(gdb_con->buf_p++);
271 if (gdb_con->buf_cnt > 0)
272 connection->input_pending = 1;
273 else
274 connection->input_pending = 0;
275 #ifdef _DEBUG_GDB_IO_
276 LOG_DEBUG("returned char '%c' (0x%2.2x)", *next_char, *next_char);
277 #endif
279 return retval;
283 * The cool thing about this fn is that it allows buf_p and buf_cnt to be
284 * held in registers in the inner loop.
286 * For small caches and embedded systems this is important!
288 static inline int gdb_get_char_fast(struct connection *connection,
289 int *next_char, char **buf_p, int *buf_cnt)
291 int retval = ERROR_OK;
293 if ((*buf_cnt)-- > 0) {
294 *next_char = **buf_p;
295 (*buf_p)++;
296 if (*buf_cnt > 0)
297 connection->input_pending = 1;
298 else
299 connection->input_pending = 0;
301 #ifdef _DEBUG_GDB_IO_
302 LOG_DEBUG("returned char '%c' (0x%2.2x)", *next_char, *next_char);
303 #endif
305 return ERROR_OK;
308 struct gdb_connection *gdb_con = connection->priv;
309 gdb_con->buf_p = *buf_p;
310 gdb_con->buf_cnt = *buf_cnt;
311 retval = gdb_get_char_inner(connection, next_char);
312 *buf_p = gdb_con->buf_p;
313 *buf_cnt = gdb_con->buf_cnt;
315 return retval;
318 static int gdb_get_char(struct connection *connection, int *next_char)
320 struct gdb_connection *gdb_con = connection->priv;
321 return gdb_get_char_fast(connection, next_char, &gdb_con->buf_p, &gdb_con->buf_cnt);
324 static int gdb_putback_char(struct connection *connection, int last_char)
326 struct gdb_connection *gdb_con = connection->priv;
328 if (gdb_con->buf_p > gdb_con->buffer) {
329 *(--gdb_con->buf_p) = last_char;
330 gdb_con->buf_cnt++;
331 } else
332 LOG_ERROR("BUG: couldn't put character back");
334 return ERROR_OK;
337 /* The only way we can detect that the socket is closed is the first time
338 * we write to it, we will fail. Subsequent write operations will
339 * succeed. Shudder! */
340 static int gdb_write(struct connection *connection, void *data, int len)
342 struct gdb_connection *gdb_con = connection->priv;
343 if (gdb_con->closed)
344 return ERROR_SERVER_REMOTE_CLOSED;
346 if (connection_write(connection, data, len) == len)
347 return ERROR_OK;
348 gdb_con->closed = true;
349 return ERROR_SERVER_REMOTE_CLOSED;
352 static int gdb_put_packet_inner(struct connection *connection,
353 char *buffer, int len)
355 int i;
356 unsigned char my_checksum = 0;
357 #ifdef _DEBUG_GDB_IO_
358 char *debug_buffer;
359 #endif
360 int reply;
361 int retval;
362 struct gdb_connection *gdb_con = connection->priv;
364 for (i = 0; i < len; i++)
365 my_checksum += buffer[i];
367 #ifdef _DEBUG_GDB_IO_
369 * At this point we should have nothing in the input queue from GDB,
370 * however sometimes '-' is sent even though we've already received
371 * an ACK (+) for everything we've sent off.
373 int gotdata;
374 for (;; ) {
375 retval = check_pending(connection, 0, &gotdata);
376 if (retval != ERROR_OK)
377 return retval;
378 if (!gotdata)
379 break;
380 retval = gdb_get_char(connection, &reply);
381 if (retval != ERROR_OK)
382 return retval;
383 if (reply == '$') {
384 /* fix a problem with some IAR tools */
385 gdb_putback_char(connection, reply);
386 LOG_DEBUG("Unexpected start of new packet");
387 break;
390 LOG_WARNING("Discard unexpected char %c", reply);
392 #endif
394 while (1) {
395 #ifdef _DEBUG_GDB_IO_
396 debug_buffer = strndup(buffer, len);
397 LOG_DEBUG("sending packet '$%s#%2.2x'", debug_buffer, my_checksum);
398 free(debug_buffer);
399 #endif
401 char local_buffer[1024];
402 local_buffer[0] = '$';
403 if ((size_t)len + 4 <= sizeof(local_buffer)) {
404 /* performance gain on smaller packets by only a single call to gdb_write() */
405 memcpy(local_buffer + 1, buffer, len++);
406 len += snprintf(local_buffer + len, sizeof(local_buffer) - len, "#%02x", my_checksum);
407 retval = gdb_write(connection, local_buffer, len);
408 if (retval != ERROR_OK)
409 return retval;
410 } else {
411 /* larger packets are transmitted directly from caller supplied buffer
412 * by several calls to gdb_write() to avoid dynamic allocation */
413 snprintf(local_buffer + 1, sizeof(local_buffer) - 1, "#%02x", my_checksum);
414 retval = gdb_write(connection, local_buffer, 1);
415 if (retval != ERROR_OK)
416 return retval;
417 retval = gdb_write(connection, buffer, len);
418 if (retval != ERROR_OK)
419 return retval;
420 retval = gdb_write(connection, local_buffer + 1, 3);
421 if (retval != ERROR_OK)
422 return retval;
425 if (gdb_con->noack_mode)
426 break;
428 retval = gdb_get_char(connection, &reply);
429 if (retval != ERROR_OK)
430 return retval;
432 if (reply == '+')
433 break;
434 else if (reply == '-') {
435 /* Stop sending output packets for now */
436 log_remove_callback(gdb_log_callback, connection);
437 LOG_WARNING("negative reply, retrying");
438 } else if (reply == 0x3) {
439 gdb_con->ctrl_c = 1;
440 retval = gdb_get_char(connection, &reply);
441 if (retval != ERROR_OK)
442 return retval;
443 if (reply == '+')
444 break;
445 else if (reply == '-') {
446 /* Stop sending output packets for now */
447 log_remove_callback(gdb_log_callback, connection);
448 LOG_WARNING("negative reply, retrying");
449 } else if (reply == '$') {
450 LOG_ERROR("GDB missing ack(1) - assumed good");
451 gdb_putback_char(connection, reply);
452 return ERROR_OK;
453 } else {
454 LOG_ERROR("unknown character(1) 0x%2.2x in reply, dropping connection", reply);
455 gdb_con->closed = true;
456 return ERROR_SERVER_REMOTE_CLOSED;
458 } else if (reply == '$') {
459 LOG_ERROR("GDB missing ack(2) - assumed good");
460 gdb_putback_char(connection, reply);
461 return ERROR_OK;
462 } else {
463 LOG_ERROR("unknown character(2) 0x%2.2x in reply, dropping connection",
464 reply);
465 gdb_con->closed = true;
466 return ERROR_SERVER_REMOTE_CLOSED;
469 if (gdb_con->closed)
470 return ERROR_SERVER_REMOTE_CLOSED;
472 return ERROR_OK;
475 int gdb_put_packet(struct connection *connection, char *buffer, int len)
477 struct gdb_connection *gdb_con = connection->priv;
478 gdb_con->busy = true;
479 int retval = gdb_put_packet_inner(connection, buffer, len);
480 gdb_con->busy = false;
482 /* we sent some data, reset timer for keep alive messages */
483 kept_alive();
485 return retval;
488 static inline int fetch_packet(struct connection *connection,
489 int *checksum_ok, int noack, int *len, char *buffer)
491 unsigned char my_checksum = 0;
492 char checksum[3];
493 int character;
494 int retval = ERROR_OK;
496 struct gdb_connection *gdb_con = connection->priv;
497 my_checksum = 0;
498 int count = 0;
499 count = 0;
501 /* move this over into local variables to use registers and give the
502 * more freedom to optimize */
503 char *buf_p = gdb_con->buf_p;
504 int buf_cnt = gdb_con->buf_cnt;
506 for (;; ) {
507 /* The common case is that we have an entire packet with no escape chars.
508 * We need to leave at least 2 bytes in the buffer to have
509 * gdb_get_char() update various bits and bobs correctly.
511 if ((buf_cnt > 2) && ((buf_cnt + count) < *len)) {
512 /* The compiler will struggle a bit with constant propagation and
513 * aliasing, so we help it by showing that these values do not
514 * change inside the loop
516 int i;
517 char *buf = buf_p;
518 int run = buf_cnt - 2;
519 i = 0;
520 int done = 0;
521 while (i < run) {
522 character = *buf++;
523 i++;
524 if (character == '#') {
525 /* Danger! character can be '#' when esc is
526 * used so we need an explicit boolean for done here. */
527 done = 1;
528 break;
531 if (character == '}') {
532 /* data transmitted in binary mode (X packet)
533 * uses 0x7d as escape character */
534 my_checksum += character & 0xff;
535 character = *buf++;
536 i++;
537 my_checksum += character & 0xff;
538 buffer[count++] = (character ^ 0x20) & 0xff;
539 } else {
540 my_checksum += character & 0xff;
541 buffer[count++] = character & 0xff;
544 buf_p += i;
545 buf_cnt -= i;
546 if (done)
547 break;
549 if (count > *len) {
550 LOG_ERROR("packet buffer too small");
551 retval = ERROR_GDB_BUFFER_TOO_SMALL;
552 break;
555 retval = gdb_get_char_fast(connection, &character, &buf_p, &buf_cnt);
556 if (retval != ERROR_OK)
557 break;
559 if (character == '#')
560 break;
562 if (character == '}') {
563 /* data transmitted in binary mode (X packet)
564 * uses 0x7d as escape character */
565 my_checksum += character & 0xff;
567 retval = gdb_get_char_fast(connection, &character, &buf_p, &buf_cnt);
568 if (retval != ERROR_OK)
569 break;
571 my_checksum += character & 0xff;
572 buffer[count++] = (character ^ 0x20) & 0xff;
573 } else {
574 my_checksum += character & 0xff;
575 buffer[count++] = character & 0xff;
579 gdb_con->buf_p = buf_p;
580 gdb_con->buf_cnt = buf_cnt;
582 if (retval != ERROR_OK)
583 return retval;
585 *len = count;
587 retval = gdb_get_char(connection, &character);
588 if (retval != ERROR_OK)
589 return retval;
590 checksum[0] = character;
591 retval = gdb_get_char(connection, &character);
592 if (retval != ERROR_OK)
593 return retval;
594 checksum[1] = character;
595 checksum[2] = 0;
597 if (!noack)
598 *checksum_ok = (my_checksum == strtoul(checksum, NULL, 16));
600 return ERROR_OK;
603 static int gdb_get_packet_inner(struct connection *connection,
604 char *buffer, int *len)
606 int character;
607 int retval;
608 struct gdb_connection *gdb_con = connection->priv;
610 while (1) {
611 do {
612 retval = gdb_get_char(connection, &character);
613 if (retval != ERROR_OK)
614 return retval;
616 #ifdef _DEBUG_GDB_IO_
617 LOG_DEBUG("character: '%c'", character);
618 #endif
620 switch (character) {
621 case '$':
622 break;
623 case '+':
624 /* According to the GDB documentation
625 * (https://sourceware.org/gdb/onlinedocs/gdb/Packet-Acknowledgment.html):
626 * "gdb sends a final `+` acknowledgment of the stub's `OK`
627 * response, which can be safely ignored by the stub."
628 * However OpenOCD server already is in noack mode at this
629 * point and instead of ignoring this it was emitting a
630 * warning. This code makes server ignore the first ACK
631 * that will be received after going into noack mode,
632 * warning only about subsequent ACK's. */
633 if (gdb_con->noack_mode > 1) {
634 LOG_WARNING("acknowledgment received, but no packet pending");
635 } else if (gdb_con->noack_mode) {
636 LOG_DEBUG("Received first acknowledgment after entering noack mode. Ignoring it.");
637 gdb_con->noack_mode = 2;
639 break;
640 case '-':
641 LOG_WARNING("negative acknowledgment, but no packet pending");
642 break;
643 case 0x3:
644 gdb_con->ctrl_c = 1;
645 *len = 0;
646 return ERROR_OK;
647 default:
648 LOG_WARNING("ignoring character 0x%x", character);
649 break;
651 } while (character != '$');
653 int checksum_ok = 0;
654 /* explicit code expansion here to get faster inlined code in -O3 by not
655 * calculating checksum */
656 if (gdb_con->noack_mode) {
657 retval = fetch_packet(connection, &checksum_ok, 1, len, buffer);
658 if (retval != ERROR_OK)
659 return retval;
660 } else {
661 retval = fetch_packet(connection, &checksum_ok, 0, len, buffer);
662 if (retval != ERROR_OK)
663 return retval;
666 if (gdb_con->noack_mode) {
667 /* checksum is not checked in noack mode */
668 break;
670 if (checksum_ok) {
671 retval = gdb_write(connection, "+", 1);
672 if (retval != ERROR_OK)
673 return retval;
674 break;
677 if (gdb_con->closed)
678 return ERROR_SERVER_REMOTE_CLOSED;
680 return ERROR_OK;
683 static int gdb_get_packet(struct connection *connection, char *buffer, int *len)
685 struct gdb_connection *gdb_con = connection->priv;
686 gdb_con->busy = true;
687 int retval = gdb_get_packet_inner(connection, buffer, len);
688 gdb_con->busy = false;
689 return retval;
692 static int gdb_output_con(struct connection *connection, const char *line)
694 char *hex_buffer;
695 int bin_size;
697 bin_size = strlen(line);
699 hex_buffer = malloc(bin_size * 2 + 2);
700 if (hex_buffer == NULL)
701 return ERROR_GDB_BUFFER_TOO_SMALL;
703 hex_buffer[0] = 'O';
704 size_t pkt_len = hexify(hex_buffer + 1, (const uint8_t *)line, bin_size,
705 bin_size * 2 + 1);
706 int retval = gdb_put_packet(connection, hex_buffer, pkt_len + 1);
708 free(hex_buffer);
709 return retval;
712 static int gdb_output(struct command_context *context, const char *line)
714 /* this will be dumped to the log and also sent as an O packet if possible */
715 LOG_USER_N("%s", line);
716 return ERROR_OK;
719 static void gdb_signal_reply(struct target *target, struct connection *connection)
721 struct gdb_connection *gdb_connection = connection->priv;
722 char sig_reply[45];
723 char stop_reason[20];
724 char current_thread[25];
725 int sig_reply_len;
726 int signal_var;
728 rtos_update_threads(target);
730 if (target->debug_reason == DBG_REASON_EXIT) {
731 sig_reply_len = snprintf(sig_reply, sizeof(sig_reply), "W00");
732 } else {
733 if (gdb_connection->ctrl_c) {
734 signal_var = 0x2;
735 gdb_connection->ctrl_c = 0;
736 } else
737 signal_var = gdb_last_signal(target);
739 stop_reason[0] = '\0';
740 if (target->debug_reason == DBG_REASON_WATCHPOINT) {
741 enum watchpoint_rw hit_wp_type;
742 target_addr_t hit_wp_address;
744 if (watchpoint_hit(target, &hit_wp_type, &hit_wp_address) == ERROR_OK) {
746 switch (hit_wp_type) {
747 case WPT_WRITE:
748 snprintf(stop_reason, sizeof(stop_reason),
749 "watch:%08" TARGET_PRIxADDR ";", hit_wp_address);
750 break;
751 case WPT_READ:
752 snprintf(stop_reason, sizeof(stop_reason),
753 "rwatch:%08" TARGET_PRIxADDR ";", hit_wp_address);
754 break;
755 case WPT_ACCESS:
756 snprintf(stop_reason, sizeof(stop_reason),
757 "awatch:%08" TARGET_PRIxADDR ";", hit_wp_address);
758 break;
759 default:
760 break;
765 current_thread[0] = '\0';
766 if (target->rtos != NULL) {
767 snprintf(current_thread, sizeof(current_thread), "thread:%016" PRIx64 ";", target->rtos->current_thread);
768 target->rtos->current_threadid = target->rtos->current_thread;
771 sig_reply_len = snprintf(sig_reply, sizeof(sig_reply), "T%2.2x%s%s",
772 signal_var, stop_reason, current_thread);
775 gdb_put_packet(connection, sig_reply, sig_reply_len);
776 gdb_connection->frontend_state = TARGET_HALTED;
779 static void gdb_fileio_reply(struct target *target, struct connection *connection)
781 struct gdb_connection *gdb_connection = connection->priv;
782 char fileio_command[256];
783 int command_len;
784 bool program_exited = false;
786 if (strcmp(target->fileio_info->identifier, "open") == 0)
787 sprintf(fileio_command, "F%s,%" PRIx32 "/%" PRIx32 ",%" PRIx32 ",%" PRIx32, target->fileio_info->identifier,
788 target->fileio_info->param_1,
789 target->fileio_info->param_2,
790 target->fileio_info->param_3,
791 target->fileio_info->param_4);
792 else if (strcmp(target->fileio_info->identifier, "close") == 0)
793 sprintf(fileio_command, "F%s,%" PRIx32, target->fileio_info->identifier,
794 target->fileio_info->param_1);
795 else if (strcmp(target->fileio_info->identifier, "read") == 0)
796 sprintf(fileio_command, "F%s,%" PRIx32 ",%" PRIx32 ",%" PRIx32, target->fileio_info->identifier,
797 target->fileio_info->param_1,
798 target->fileio_info->param_2,
799 target->fileio_info->param_3);
800 else if (strcmp(target->fileio_info->identifier, "write") == 0)
801 sprintf(fileio_command, "F%s,%" PRIx32 ",%" PRIx32 ",%" PRIx32, target->fileio_info->identifier,
802 target->fileio_info->param_1,
803 target->fileio_info->param_2,
804 target->fileio_info->param_3);
805 else if (strcmp(target->fileio_info->identifier, "lseek") == 0)
806 sprintf(fileio_command, "F%s,%" PRIx32 ",%" PRIx32 ",%" PRIx32, target->fileio_info->identifier,
807 target->fileio_info->param_1,
808 target->fileio_info->param_2,
809 target->fileio_info->param_3);
810 else if (strcmp(target->fileio_info->identifier, "rename") == 0)
811 sprintf(fileio_command, "F%s,%" PRIx32 "/%" PRIx32 ",%" PRIx32 "/%" PRIx32, target->fileio_info->identifier,
812 target->fileio_info->param_1,
813 target->fileio_info->param_2,
814 target->fileio_info->param_3,
815 target->fileio_info->param_4);
816 else if (strcmp(target->fileio_info->identifier, "unlink") == 0)
817 sprintf(fileio_command, "F%s,%" PRIx32 "/%" PRIx32, target->fileio_info->identifier,
818 target->fileio_info->param_1,
819 target->fileio_info->param_2);
820 else if (strcmp(target->fileio_info->identifier, "stat") == 0)
821 sprintf(fileio_command, "F%s,%" PRIx32 "/%" PRIx32 ",%" PRIx32, target->fileio_info->identifier,
822 target->fileio_info->param_1,
823 target->fileio_info->param_2,
824 target->fileio_info->param_3);
825 else if (strcmp(target->fileio_info->identifier, "fstat") == 0)
826 sprintf(fileio_command, "F%s,%" PRIx32 ",%" PRIx32, target->fileio_info->identifier,
827 target->fileio_info->param_1,
828 target->fileio_info->param_2);
829 else if (strcmp(target->fileio_info->identifier, "gettimeofday") == 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, "isatty") == 0)
834 sprintf(fileio_command, "F%s,%" PRIx32, target->fileio_info->identifier,
835 target->fileio_info->param_1);
836 else if (strcmp(target->fileio_info->identifier, "system") == 0)
837 sprintf(fileio_command, "F%s,%" PRIx32 "/%" PRIx32, target->fileio_info->identifier,
838 target->fileio_info->param_1,
839 target->fileio_info->param_2);
840 else if (strcmp(target->fileio_info->identifier, "exit") == 0) {
841 /* If target hits exit syscall, report to GDB the program is terminated.
842 * In addition, let target run its own exit syscall handler. */
843 program_exited = true;
844 sprintf(fileio_command, "W%02" PRIx32, target->fileio_info->param_1);
845 } else {
846 LOG_DEBUG("Unknown syscall: %s", target->fileio_info->identifier);
848 /* encounter unknown syscall, continue */
849 gdb_connection->frontend_state = TARGET_RUNNING;
850 target_resume(target, 1, 0x0, 0, 0);
851 return;
854 command_len = strlen(fileio_command);
855 gdb_put_packet(connection, fileio_command, command_len);
857 if (program_exited) {
858 /* Use target_resume() to let target run its own exit syscall handler. */
859 gdb_connection->frontend_state = TARGET_RUNNING;
860 target_resume(target, 1, 0x0, 0, 0);
861 } else {
862 gdb_connection->frontend_state = TARGET_HALTED;
863 rtos_update_threads(target);
867 static void gdb_frontend_halted(struct target *target, struct connection *connection)
869 struct gdb_connection *gdb_connection = connection->priv;
871 /* In the GDB protocol when we are stepping or continuing execution,
872 * we have a lingering reply. Upon receiving a halted event
873 * when we have that lingering packet, we reply to the original
874 * step or continue packet.
876 * Executing monitor commands can bring the target in and
877 * out of the running state so we'll see lots of TARGET_EVENT_XXX
878 * that are to be ignored.
880 if (gdb_connection->frontend_state == TARGET_RUNNING) {
881 /* stop forwarding log packets! */
882 log_remove_callback(gdb_log_callback, connection);
884 /* check fileio first */
885 if (target_get_gdb_fileio_info(target, target->fileio_info) == ERROR_OK)
886 gdb_fileio_reply(target, connection);
887 else
888 gdb_signal_reply(target, connection);
892 static int gdb_target_callback_event_handler(struct target *target,
893 enum target_event event, void *priv)
895 int retval;
896 struct connection *connection = priv;
897 struct gdb_service *gdb_service = connection->service->priv;
899 if (gdb_service->target != target)
900 return ERROR_OK;
902 switch (event) {
903 case TARGET_EVENT_GDB_HALT:
904 gdb_frontend_halted(target, connection);
905 break;
906 case TARGET_EVENT_HALTED:
907 target_call_event_callbacks(target, TARGET_EVENT_GDB_END);
908 break;
909 case TARGET_EVENT_GDB_FLASH_ERASE_START:
910 retval = jtag_execute_queue();
911 if (retval != ERROR_OK)
912 return retval;
913 break;
914 default:
915 break;
918 return ERROR_OK;
921 static int gdb_new_connection(struct connection *connection)
923 struct gdb_connection *gdb_connection = malloc(sizeof(struct gdb_connection));
924 struct target *target;
925 int retval;
926 int initial_ack;
928 target = get_target_from_connection(connection);
929 connection->priv = gdb_connection;
931 /* initialize gdb connection information */
932 gdb_connection->buf_p = gdb_connection->buffer;
933 gdb_connection->buf_cnt = 0;
934 gdb_connection->ctrl_c = 0;
935 gdb_connection->frontend_state = TARGET_HALTED;
936 gdb_connection->vflash_image = NULL;
937 gdb_connection->closed = false;
938 gdb_connection->busy = false;
939 gdb_connection->noack_mode = 0;
940 gdb_connection->sync = false;
941 gdb_connection->mem_write_error = false;
942 gdb_connection->attached = true;
943 gdb_connection->target_desc.tdesc = NULL;
944 gdb_connection->target_desc.tdesc_length = 0;
945 gdb_connection->thread_list = NULL;
947 /* send ACK to GDB for debug request */
948 gdb_write(connection, "+", 1);
950 /* output goes through gdb connection */
951 command_set_output_handler(connection->cmd_ctx, gdb_output, connection);
953 /* we must remove all breakpoints registered to the target as a previous
954 * GDB session could leave dangling breakpoints if e.g. communication
955 * timed out.
957 breakpoint_clear_target(target);
958 watchpoint_clear_target(target);
960 /* clean previous rtos session if supported*/
961 if ((target->rtos) && (target->rtos->type->clean))
962 target->rtos->type->clean(target);
964 /* remove the initial ACK from the incoming buffer */
965 retval = gdb_get_char(connection, &initial_ack);
966 if (retval != ERROR_OK)
967 return retval;
969 /* FIX!!!??? would we actually ever receive a + here???
970 * Not observed.
972 if (initial_ack != '+')
973 gdb_putback_char(connection, initial_ack);
974 target_call_event_callbacks(target, TARGET_EVENT_GDB_ATTACH);
976 if (gdb_use_memory_map) {
977 /* Connect must fail if the memory map can't be set up correctly.
979 * This will cause an auto_probe to be invoked, which is either
980 * a no-op or it will fail when the target isn't ready(e.g. not halted).
982 int i;
983 for (i = 0; i < flash_get_bank_count(); i++) {
984 struct flash_bank *p;
985 p = get_flash_bank_by_num_noprobe(i);
986 if (p->target != target)
987 continue;
988 retval = get_flash_bank_by_num(i, &p);
989 if (retval != ERROR_OK) {
990 LOG_ERROR("Connect failed. Consider setting up a gdb-attach event for the target " \
991 "to prepare target for GDB connect, or use 'gdb_memory_map disable'.");
992 return retval;
997 gdb_actual_connections++;
998 log_printf_lf(all_targets->next != NULL ? LOG_LVL_INFO : LOG_LVL_DEBUG,
999 __FILE__, __LINE__, __func__,
1000 "New GDB Connection: %d, Target %s, state: %s",
1001 gdb_actual_connections,
1002 target_name(target),
1003 target_state_name(target));
1005 /* DANGER! If we fail subsequently, we must remove this handler,
1006 * otherwise we occasionally see crashes as the timer can invoke the
1007 * callback fn.
1009 * register callback to be informed about target events */
1010 target_register_event_callback(gdb_target_callback_event_handler, connection);
1012 return ERROR_OK;
1015 static int gdb_connection_closed(struct connection *connection)
1017 struct target *target;
1018 struct gdb_connection *gdb_connection = connection->priv;
1020 target = get_target_from_connection(connection);
1022 /* we're done forwarding messages. Tear down callback before
1023 * cleaning up connection.
1025 log_remove_callback(gdb_log_callback, connection);
1027 gdb_actual_connections--;
1028 LOG_DEBUG("GDB Close, Target: %s, state: %s, gdb_actual_connections=%d",
1029 target_name(target),
1030 target_state_name(target),
1031 gdb_actual_connections);
1033 /* see if an image built with vFlash commands is left */
1034 if (gdb_connection->vflash_image) {
1035 image_close(gdb_connection->vflash_image);
1036 free(gdb_connection->vflash_image);
1037 gdb_connection->vflash_image = NULL;
1040 /* if this connection registered a debug-message receiver delete it */
1041 delete_debug_msg_receiver(connection->cmd_ctx, target);
1043 if (connection->priv) {
1044 free(connection->priv);
1045 connection->priv = NULL;
1046 } else
1047 LOG_ERROR("BUG: connection->priv == NULL");
1049 target_unregister_event_callback(gdb_target_callback_event_handler, connection);
1051 target_call_event_callbacks(target, TARGET_EVENT_GDB_END);
1053 target_call_event_callbacks(target, TARGET_EVENT_GDB_DETACH);
1055 return ERROR_OK;
1058 static void gdb_send_error(struct connection *connection, uint8_t the_error)
1060 char err[4];
1061 snprintf(err, 4, "E%2.2X", the_error);
1062 gdb_put_packet(connection, err, 3);
1065 static int gdb_last_signal_packet(struct connection *connection,
1066 char const *packet, int packet_size)
1068 struct target *target = get_target_from_connection(connection);
1069 struct gdb_connection *gdb_con = connection->priv;
1070 char sig_reply[4];
1071 int signal_var;
1073 if (!gdb_con->attached) {
1074 /* if we are here we have received a kill packet
1075 * reply W stop reply otherwise gdb gets very unhappy */
1076 gdb_put_packet(connection, "W00", 3);
1077 return ERROR_OK;
1080 signal_var = gdb_last_signal(target);
1082 snprintf(sig_reply, 4, "S%2.2x", signal_var);
1083 gdb_put_packet(connection, sig_reply, 3);
1085 return ERROR_OK;
1088 static inline int gdb_reg_pos(struct target *target, int pos, int len)
1090 if (target->endianness == TARGET_LITTLE_ENDIAN)
1091 return pos;
1092 else
1093 return len - 1 - pos;
1096 /* Convert register to string of bytes. NB! The # of bits in the
1097 * register might be non-divisible by 8(a byte), in which
1098 * case an entire byte is shown.
1100 * NB! the format on the wire is the target endianness
1102 * The format of reg->value is little endian
1105 static void gdb_str_to_target(struct target *target,
1106 char *tstr, struct reg *reg)
1108 int i;
1110 uint8_t *buf;
1111 int buf_len;
1112 buf = reg->value;
1113 buf_len = DIV_ROUND_UP(reg->size, 8);
1115 for (i = 0; i < buf_len; i++) {
1116 int j = gdb_reg_pos(target, i, buf_len);
1117 tstr += sprintf(tstr, "%02x", buf[j]);
1121 /* copy over in register buffer */
1122 static void gdb_target_to_reg(struct target *target,
1123 char const *tstr, int str_len, uint8_t *bin)
1125 if (str_len % 2) {
1126 LOG_ERROR("BUG: gdb value with uneven number of characters encountered");
1127 exit(-1);
1130 int i;
1131 for (i = 0; i < str_len; i += 2) {
1132 unsigned t;
1133 if (sscanf(tstr + i, "%02x", &t) != 1) {
1134 LOG_ERROR("BUG: unable to convert register value");
1135 exit(-1);
1138 int j = gdb_reg_pos(target, i/2, str_len/2);
1139 bin[j] = t;
1143 static int gdb_get_registers_packet(struct connection *connection,
1144 char const *packet, int packet_size)
1146 struct target *target = get_target_from_connection(connection);
1147 struct reg **reg_list;
1148 int reg_list_size;
1149 int retval;
1150 int reg_packet_size = 0;
1151 char *reg_packet;
1152 char *reg_packet_p;
1153 int i;
1155 #ifdef _DEBUG_GDB_IO_
1156 LOG_DEBUG("-");
1157 #endif
1159 if ((target->rtos != NULL) && (ERROR_OK == rtos_get_gdb_reg_list(connection)))
1160 return ERROR_OK;
1162 retval = target_get_gdb_reg_list(target, &reg_list, &reg_list_size,
1163 REG_CLASS_GENERAL);
1164 if (retval != ERROR_OK)
1165 return gdb_error(connection, retval);
1167 for (i = 0; i < reg_list_size; i++)
1168 reg_packet_size += DIV_ROUND_UP(reg_list[i]->size, 8) * 2;
1170 assert(reg_packet_size > 0);
1172 reg_packet = malloc(reg_packet_size + 1); /* plus one for string termination null */
1173 if (reg_packet == NULL)
1174 return ERROR_FAIL;
1176 reg_packet_p = reg_packet;
1178 for (i = 0; i < reg_list_size; i++) {
1179 if (!reg_list[i]->valid)
1180 reg_list[i]->type->get(reg_list[i]);
1181 gdb_str_to_target(target, reg_packet_p, reg_list[i]);
1182 reg_packet_p += DIV_ROUND_UP(reg_list[i]->size, 8) * 2;
1185 #ifdef _DEBUG_GDB_IO_
1187 char *reg_packet_p_debug;
1188 reg_packet_p_debug = strndup(reg_packet, reg_packet_size);
1189 LOG_DEBUG("reg_packet: %s", reg_packet_p_debug);
1190 free(reg_packet_p_debug);
1192 #endif
1194 gdb_put_packet(connection, reg_packet, reg_packet_size);
1195 free(reg_packet);
1197 free(reg_list);
1199 return ERROR_OK;
1202 static int gdb_set_registers_packet(struct connection *connection,
1203 char const *packet, int packet_size)
1205 struct target *target = get_target_from_connection(connection);
1206 int i;
1207 struct reg **reg_list;
1208 int reg_list_size;
1209 int retval;
1210 char const *packet_p;
1212 #ifdef _DEBUG_GDB_IO_
1213 LOG_DEBUG("-");
1214 #endif
1216 /* skip command character */
1217 packet++;
1218 packet_size--;
1220 if (packet_size % 2) {
1221 LOG_WARNING("GDB set_registers packet with uneven characters received, dropping connection");
1222 return ERROR_SERVER_REMOTE_CLOSED;
1225 retval = target_get_gdb_reg_list(target, &reg_list, &reg_list_size,
1226 REG_CLASS_GENERAL);
1227 if (retval != ERROR_OK)
1228 return gdb_error(connection, retval);
1230 packet_p = packet;
1231 for (i = 0; i < reg_list_size; i++) {
1232 uint8_t *bin_buf;
1233 int chars = (DIV_ROUND_UP(reg_list[i]->size, 8) * 2);
1235 if (packet_p + chars > packet + packet_size)
1236 LOG_ERROR("BUG: register packet is too small for registers");
1238 bin_buf = malloc(DIV_ROUND_UP(reg_list[i]->size, 8));
1239 gdb_target_to_reg(target, packet_p, chars, bin_buf);
1241 reg_list[i]->type->set(reg_list[i], bin_buf);
1243 /* advance packet pointer */
1244 packet_p += chars;
1246 free(bin_buf);
1249 /* free struct reg *reg_list[] array allocated by get_gdb_reg_list */
1250 free(reg_list);
1252 gdb_put_packet(connection, "OK", 2);
1254 return ERROR_OK;
1257 static int gdb_get_register_packet(struct connection *connection,
1258 char const *packet, int packet_size)
1260 struct target *target = get_target_from_connection(connection);
1261 char *reg_packet;
1262 int reg_num = strtoul(packet + 1, NULL, 16);
1263 struct reg **reg_list;
1264 int reg_list_size;
1265 int retval;
1267 #ifdef _DEBUG_GDB_IO_
1268 LOG_DEBUG("-");
1269 #endif
1271 retval = target_get_gdb_reg_list(target, &reg_list, &reg_list_size,
1272 REG_CLASS_ALL);
1273 if (retval != ERROR_OK)
1274 return gdb_error(connection, retval);
1276 if (reg_list_size <= reg_num) {
1277 LOG_ERROR("gdb requested a non-existing register");
1278 return ERROR_SERVER_REMOTE_CLOSED;
1281 if (!reg_list[reg_num]->valid)
1282 reg_list[reg_num]->type->get(reg_list[reg_num]);
1284 reg_packet = malloc(DIV_ROUND_UP(reg_list[reg_num]->size, 8) * 2 + 1); /* plus one for string termination null */
1286 gdb_str_to_target(target, reg_packet, reg_list[reg_num]);
1288 gdb_put_packet(connection, reg_packet, DIV_ROUND_UP(reg_list[reg_num]->size, 8) * 2);
1290 free(reg_list);
1291 free(reg_packet);
1293 return ERROR_OK;
1296 static int gdb_set_register_packet(struct connection *connection,
1297 char const *packet, int packet_size)
1299 struct target *target = get_target_from_connection(connection);
1300 char *separator;
1301 uint8_t *bin_buf;
1302 int reg_num = strtoul(packet + 1, &separator, 16);
1303 struct reg **reg_list;
1304 int reg_list_size;
1305 int retval;
1307 LOG_DEBUG("-");
1309 retval = target_get_gdb_reg_list(target, &reg_list, &reg_list_size,
1310 REG_CLASS_ALL);
1311 if (retval != ERROR_OK)
1312 return gdb_error(connection, retval);
1314 if (reg_list_size <= reg_num) {
1315 LOG_ERROR("gdb requested a non-existing register");
1316 return ERROR_SERVER_REMOTE_CLOSED;
1319 if (*separator != '=') {
1320 LOG_ERROR("GDB 'set register packet', but no '=' following the register number");
1321 return ERROR_SERVER_REMOTE_CLOSED;
1324 /* convert from GDB-string (target-endian) to hex-string (big-endian) */
1325 bin_buf = malloc(DIV_ROUND_UP(reg_list[reg_num]->size, 8));
1326 int chars = (DIV_ROUND_UP(reg_list[reg_num]->size, 8) * 2);
1328 if ((unsigned int)chars != strlen(separator + 1)) {
1329 LOG_ERROR("gdb sent a packet with wrong register size");
1330 free(bin_buf);
1331 return ERROR_SERVER_REMOTE_CLOSED;
1334 gdb_target_to_reg(target, separator + 1, chars, bin_buf);
1336 reg_list[reg_num]->type->set(reg_list[reg_num], bin_buf);
1338 gdb_put_packet(connection, "OK", 2);
1340 free(bin_buf);
1341 free(reg_list);
1343 return ERROR_OK;
1346 /* No attempt is made to translate the "retval" to
1347 * GDB speak. This has to be done at the calling
1348 * site as no mapping really exists.
1350 static int gdb_error(struct connection *connection, int retval)
1352 LOG_DEBUG("Reporting %i to GDB as generic error", retval);
1353 gdb_send_error(connection, EFAULT);
1354 return ERROR_OK;
1357 /* We don't have to worry about the default 2 second timeout for GDB packets,
1358 * because GDB breaks up large memory reads into smaller reads.
1360 * 8191 bytes by the looks of it. Why 8191 bytes instead of 8192?????
1362 static int gdb_read_memory_packet(struct connection *connection,
1363 char const *packet, int packet_size)
1365 struct target *target = get_target_from_connection(connection);
1366 char *separator;
1367 uint64_t addr = 0;
1368 uint32_t len = 0;
1370 uint8_t *buffer;
1371 char *hex_buffer;
1373 int retval = ERROR_OK;
1375 /* skip command character */
1376 packet++;
1378 addr = strtoull(packet, &separator, 16);
1380 if (*separator != ',') {
1381 LOG_ERROR("incomplete read memory packet received, dropping connection");
1382 return ERROR_SERVER_REMOTE_CLOSED;
1385 len = strtoul(separator + 1, NULL, 16);
1387 if (!len) {
1388 LOG_WARNING("invalid read memory packet received (len == 0)");
1389 gdb_put_packet(connection, NULL, 0);
1390 return ERROR_OK;
1393 buffer = malloc(len);
1395 LOG_DEBUG("addr: 0x%16.16" PRIx64 ", len: 0x%8.8" PRIx32 "", addr, len);
1397 retval = target_read_buffer(target, addr, len, buffer);
1399 if ((retval != ERROR_OK) && !gdb_report_data_abort) {
1400 /* TODO : Here we have to lie and send back all zero's lest stack traces won't work.
1401 * At some point this might be fixed in GDB, in which case this code can be removed.
1403 * OpenOCD developers are acutely aware of this problem, but there is nothing
1404 * gained by involving the user in this problem that hopefully will get resolved
1405 * eventually
1407 * http://sourceware.org/cgi-bin/gnatsweb.pl? \
1408 * cmd = view%20audit-trail&database = gdb&pr = 2395
1410 * For now, the default is to fix up things to make current GDB versions work.
1411 * This can be overwritten using the gdb_report_data_abort <'enable'|'disable'> command.
1413 memset(buffer, 0, len);
1414 retval = ERROR_OK;
1417 if (retval == ERROR_OK) {
1418 hex_buffer = malloc(len * 2 + 1);
1420 size_t pkt_len = hexify(hex_buffer, buffer, len, len * 2 + 1);
1422 gdb_put_packet(connection, hex_buffer, pkt_len);
1424 free(hex_buffer);
1425 } else
1426 retval = gdb_error(connection, retval);
1428 free(buffer);
1430 return retval;
1433 static int gdb_write_memory_packet(struct connection *connection,
1434 char const *packet, int packet_size)
1436 struct target *target = get_target_from_connection(connection);
1437 char *separator;
1438 uint64_t addr = 0;
1439 uint32_t len = 0;
1441 uint8_t *buffer;
1442 int retval;
1444 /* skip command character */
1445 packet++;
1447 addr = strtoull(packet, &separator, 16);
1449 if (*separator != ',') {
1450 LOG_ERROR("incomplete write memory packet received, dropping connection");
1451 return ERROR_SERVER_REMOTE_CLOSED;
1454 len = strtoul(separator + 1, &separator, 16);
1456 if (*(separator++) != ':') {
1457 LOG_ERROR("incomplete write memory packet received, dropping connection");
1458 return ERROR_SERVER_REMOTE_CLOSED;
1461 buffer = malloc(len);
1463 LOG_DEBUG("addr: 0x%" PRIx64 ", len: 0x%8.8" PRIx32 "", addr, len);
1465 if (unhexify(buffer, separator, len) != len)
1466 LOG_ERROR("unable to decode memory packet");
1468 retval = target_write_buffer(target, addr, len, buffer);
1470 if (retval == ERROR_OK)
1471 gdb_put_packet(connection, "OK", 2);
1472 else
1473 retval = gdb_error(connection, retval);
1475 free(buffer);
1477 return retval;
1480 static int gdb_write_memory_binary_packet(struct connection *connection,
1481 char const *packet, int packet_size)
1483 struct target *target = get_target_from_connection(connection);
1484 char *separator;
1485 uint64_t addr = 0;
1486 uint32_t len = 0;
1488 int retval = ERROR_OK;
1489 /* Packets larger than fast_limit bytes will be acknowledged instantly on
1490 * the assumption that we're in a download and it's important to go as fast
1491 * as possible. */
1492 uint32_t fast_limit = 8;
1494 /* skip command character */
1495 packet++;
1497 addr = strtoull(packet, &separator, 16);
1499 if (*separator != ',') {
1500 LOG_ERROR("incomplete write memory binary packet received, dropping connection");
1501 return ERROR_SERVER_REMOTE_CLOSED;
1504 len = strtoul(separator + 1, &separator, 16);
1506 if (*(separator++) != ':') {
1507 LOG_ERROR("incomplete write memory binary packet received, dropping connection");
1508 return ERROR_SERVER_REMOTE_CLOSED;
1511 struct gdb_connection *gdb_connection = connection->priv;
1513 if (gdb_connection->mem_write_error)
1514 retval = ERROR_FAIL;
1516 if (retval == ERROR_OK) {
1517 if (len >= fast_limit) {
1518 /* By replying the packet *immediately* GDB will send us a new packet
1519 * while we write the last one to the target.
1520 * We only do this for larger writes, so that users who do something like:
1521 * p *((int*)0xdeadbeef)=8675309
1522 * will get immediate feedback that that write failed.
1524 gdb_put_packet(connection, "OK", 2);
1526 } else {
1527 retval = gdb_error(connection, retval);
1528 /* now that we have reported the memory write error, we can clear the condition */
1529 gdb_connection->mem_write_error = false;
1530 if (retval != ERROR_OK)
1531 return retval;
1534 if (len) {
1535 LOG_DEBUG("addr: 0x%" PRIx64 ", len: 0x%8.8" PRIx32 "", addr, len);
1537 retval = target_write_buffer(target, addr, len, (uint8_t *)separator);
1538 if (retval != ERROR_OK)
1539 gdb_connection->mem_write_error = true;
1542 if (len < fast_limit) {
1543 if (retval != ERROR_OK) {
1544 gdb_error(connection, retval);
1545 gdb_connection->mem_write_error = false;
1546 } else {
1547 gdb_put_packet(connection, "OK", 2);
1551 return ERROR_OK;
1554 static int gdb_step_continue_packet(struct connection *connection,
1555 char const *packet, int packet_size)
1557 struct target *target = get_target_from_connection(connection);
1558 int current = 0;
1559 uint64_t address = 0x0;
1560 int retval = ERROR_OK;
1562 LOG_DEBUG("-");
1564 if (packet_size > 1)
1565 address = strtoull(packet + 1, NULL, 16);
1566 else
1567 current = 1;
1569 gdb_running_type = packet[0];
1570 if (packet[0] == 'c') {
1571 LOG_DEBUG("continue");
1572 /* resume at current address, don't handle breakpoints, not debugging */
1573 retval = target_resume(target, current, address, 0, 0);
1574 } else if (packet[0] == 's') {
1575 LOG_DEBUG("step");
1576 /* step at current or address, don't handle breakpoints */
1577 retval = target_step(target, current, address, 0);
1579 return retval;
1582 static int gdb_breakpoint_watchpoint_packet(struct connection *connection,
1583 char const *packet, int packet_size)
1585 struct target *target = get_target_from_connection(connection);
1586 int type;
1587 enum breakpoint_type bp_type = BKPT_SOFT /* dummy init to avoid warning */;
1588 enum watchpoint_rw wp_type = WPT_READ /* dummy init to avoid warning */;
1589 uint64_t address;
1590 uint32_t size;
1591 char *separator;
1592 int retval;
1594 LOG_DEBUG("-");
1596 type = strtoul(packet + 1, &separator, 16);
1598 if (type == 0) /* memory breakpoint */
1599 bp_type = BKPT_SOFT;
1600 else if (type == 1) /* hardware breakpoint */
1601 bp_type = BKPT_HARD;
1602 else if (type == 2) /* write watchpoint */
1603 wp_type = WPT_WRITE;
1604 else if (type == 3) /* read watchpoint */
1605 wp_type = WPT_READ;
1606 else if (type == 4) /* access watchpoint */
1607 wp_type = WPT_ACCESS;
1608 else {
1609 LOG_ERROR("invalid gdb watch/breakpoint type(%d), dropping connection", type);
1610 return ERROR_SERVER_REMOTE_CLOSED;
1613 if (gdb_breakpoint_override && ((bp_type == BKPT_SOFT) || (bp_type == BKPT_HARD)))
1614 bp_type = gdb_breakpoint_override_type;
1616 if (*separator != ',') {
1617 LOG_ERROR("incomplete breakpoint/watchpoint packet received, dropping connection");
1618 return ERROR_SERVER_REMOTE_CLOSED;
1621 address = strtoull(separator + 1, &separator, 16);
1623 if (*separator != ',') {
1624 LOG_ERROR("incomplete breakpoint/watchpoint packet received, dropping connection");
1625 return ERROR_SERVER_REMOTE_CLOSED;
1628 size = strtoul(separator + 1, &separator, 16);
1630 switch (type) {
1631 case 0:
1632 case 1:
1633 if (packet[0] == 'Z') {
1634 retval = breakpoint_add(target, address, size, bp_type);
1635 if (retval != ERROR_OK) {
1636 retval = gdb_error(connection, retval);
1637 if (retval != ERROR_OK)
1638 return retval;
1639 } else
1640 gdb_put_packet(connection, "OK", 2);
1641 } else {
1642 breakpoint_remove(target, address);
1643 gdb_put_packet(connection, "OK", 2);
1645 break;
1646 case 2:
1647 case 3:
1648 case 4:
1650 if (packet[0] == 'Z') {
1651 retval = watchpoint_add(target, address, size, wp_type, 0, 0xffffffffu);
1652 if (retval != ERROR_OK) {
1653 retval = gdb_error(connection, retval);
1654 if (retval != ERROR_OK)
1655 return retval;
1656 } else
1657 gdb_put_packet(connection, "OK", 2);
1658 } else {
1659 watchpoint_remove(target, address);
1660 gdb_put_packet(connection, "OK", 2);
1662 break;
1664 default:
1665 break;
1668 return ERROR_OK;
1671 /* print out a string and allocate more space as needed,
1672 * mainly used for XML at this point
1674 static void xml_printf(int *retval, char **xml, int *pos, int *size,
1675 const char *fmt, ...)
1677 if (*retval != ERROR_OK)
1678 return;
1679 int first = 1;
1681 for (;; ) {
1682 if ((*xml == NULL) || (!first)) {
1683 /* start by 0 to exercise all the code paths.
1684 * Need minimum 2 bytes to fit 1 char and 0 terminator. */
1686 *size = *size * 2 + 2;
1687 char *t = *xml;
1688 *xml = realloc(*xml, *size);
1689 if (*xml == NULL) {
1690 if (t)
1691 free(t);
1692 *retval = ERROR_SERVER_REMOTE_CLOSED;
1693 return;
1697 va_list ap;
1698 int ret;
1699 va_start(ap, fmt);
1700 ret = vsnprintf(*xml + *pos, *size - *pos, fmt, ap);
1701 va_end(ap);
1702 if ((ret > 0) && ((ret + 1) < *size - *pos)) {
1703 *pos += ret;
1704 return;
1706 /* there was just enough or not enough space, allocate more. */
1707 first = 0;
1711 static int decode_xfer_read(char const *buf, char **annex, int *ofs, unsigned int *len)
1713 /* Locate the annex. */
1714 const char *annex_end = strchr(buf, ':');
1715 if (annex_end == NULL)
1716 return ERROR_FAIL;
1718 /* After the read marker and annex, qXfer looks like a
1719 * traditional 'm' packet. */
1720 char *separator;
1721 *ofs = strtoul(annex_end + 1, &separator, 16);
1723 if (*separator != ',')
1724 return ERROR_FAIL;
1726 *len = strtoul(separator + 1, NULL, 16);
1728 /* Extract the annex if needed */
1729 if (annex != NULL) {
1730 *annex = strndup(buf, annex_end - buf);
1731 if (*annex == NULL)
1732 return ERROR_FAIL;
1735 return ERROR_OK;
1738 static int compare_bank(const void *a, const void *b)
1740 struct flash_bank *b1, *b2;
1741 b1 = *((struct flash_bank **)a);
1742 b2 = *((struct flash_bank **)b);
1744 if (b1->base == b2->base)
1745 return 0;
1746 else if (b1->base > b2->base)
1747 return 1;
1748 else
1749 return -1;
1752 static int gdb_memory_map(struct connection *connection,
1753 char const *packet, int packet_size)
1755 /* We get away with only specifying flash here. Regions that are not
1756 * specified are treated as if we provided no memory map(if not we
1757 * could detect the holes and mark them as RAM).
1758 * Normally we only execute this code once, but no big deal if we
1759 * have to regenerate it a couple of times.
1762 struct target *target = get_target_from_connection(connection);
1763 struct flash_bank *p;
1764 char *xml = NULL;
1765 int size = 0;
1766 int pos = 0;
1767 int retval = ERROR_OK;
1768 struct flash_bank **banks;
1769 int offset;
1770 int length;
1771 char *separator;
1772 uint32_t ram_start = 0;
1773 int i;
1774 int target_flash_banks = 0;
1776 /* skip command character */
1777 packet += 23;
1779 offset = strtoul(packet, &separator, 16);
1780 length = strtoul(separator + 1, &separator, 16);
1782 xml_printf(&retval, &xml, &pos, &size, "<memory-map>\n");
1784 /* Sort banks in ascending order. We need to report non-flash
1785 * memory as ram (or rather read/write) by default for GDB, since
1786 * it has no concept of non-cacheable read/write memory (i/o etc).
1788 * FIXME Most non-flash addresses are *NOT* RAM! Don't lie.
1789 * Current versions of GDB assume unlisted addresses are RAM...
1791 banks = malloc(sizeof(struct flash_bank *)*flash_get_bank_count());
1793 for (i = 0; i < flash_get_bank_count(); i++) {
1794 p = get_flash_bank_by_num_noprobe(i);
1795 if (p->target != target)
1796 continue;
1797 retval = get_flash_bank_by_num(i, &p);
1798 if (retval != ERROR_OK) {
1799 free(banks);
1800 gdb_error(connection, retval);
1801 return retval;
1803 banks[target_flash_banks++] = p;
1806 qsort(banks, target_flash_banks, sizeof(struct flash_bank *),
1807 compare_bank);
1809 for (i = 0; i < target_flash_banks; i++) {
1810 int j;
1811 unsigned sector_size = 0;
1812 uint32_t start;
1814 p = banks[i];
1815 start = p->base;
1817 if (ram_start < p->base)
1818 xml_printf(&retval, &xml, &pos, &size,
1819 "<memory type=\"ram\" start=\"0x%x\" "
1820 "length=\"0x%x\"/>\n",
1821 ram_start, p->base - ram_start);
1823 /* Report adjacent groups of same-size sectors. So for
1824 * example top boot CFI flash will list an initial region
1825 * with several large sectors (maybe 128KB) and several
1826 * smaller ones at the end (maybe 32KB). STR7 will have
1827 * regions with 8KB, 32KB, and 64KB sectors; etc.
1829 for (j = 0; j < p->num_sectors; j++) {
1830 unsigned group_len;
1832 /* Maybe start a new group of sectors. */
1833 if (sector_size == 0) {
1834 start = p->base + p->sectors[j].offset;
1835 xml_printf(&retval, &xml, &pos, &size,
1836 "<memory type=\"flash\" "
1837 "start=\"0x%x\" ",
1838 start);
1839 sector_size = p->sectors[j].size;
1842 /* Does this finish a group of sectors?
1843 * If not, continue an already-started group.
1845 if (j == p->num_sectors - 1)
1846 group_len = (p->base + p->size) - start;
1847 else if (p->sectors[j + 1].size != sector_size)
1848 group_len = p->base + p->sectors[j + 1].offset
1849 - start;
1850 else
1851 continue;
1853 xml_printf(&retval, &xml, &pos, &size,
1854 "length=\"0x%x\">\n"
1855 "<property name=\"blocksize\">"
1856 "0x%x</property>\n"
1857 "</memory>\n",
1858 group_len,
1859 sector_size);
1860 sector_size = 0;
1863 ram_start = p->base + p->size;
1866 if (ram_start != 0)
1867 xml_printf(&retval, &xml, &pos, &size,
1868 "<memory type=\"ram\" start=\"0x%x\" "
1869 "length=\"0x%x\"/>\n",
1870 ram_start, 0-ram_start);
1871 /* ELSE a flash chip could be at the very end of the 32 bit address
1872 * space, in which case ram_start will be precisely 0
1875 free(banks);
1876 banks = NULL;
1878 xml_printf(&retval, &xml, &pos, &size, "</memory-map>\n");
1880 if (retval != ERROR_OK) {
1881 gdb_error(connection, retval);
1882 return retval;
1885 if (offset + length > pos)
1886 length = pos - offset;
1888 char *t = malloc(length + 1);
1889 t[0] = 'l';
1890 memcpy(t + 1, xml + offset, length);
1891 gdb_put_packet(connection, t, length + 1);
1893 free(t);
1894 free(xml);
1895 return ERROR_OK;
1898 static const char *gdb_get_reg_type_name(enum reg_type type)
1900 switch (type) {
1901 case REG_TYPE_INT:
1902 return "int";
1903 case REG_TYPE_INT8:
1904 return "int8";
1905 case REG_TYPE_INT16:
1906 return "int16";
1907 case REG_TYPE_INT32:
1908 return "int32";
1909 case REG_TYPE_INT64:
1910 return "int64";
1911 case REG_TYPE_INT128:
1912 return "int128";
1913 case REG_TYPE_UINT8:
1914 return "uint8";
1915 case REG_TYPE_UINT16:
1916 return "uint16";
1917 case REG_TYPE_UINT32:
1918 return "uint32";
1919 case REG_TYPE_UINT64:
1920 return "uint64";
1921 case REG_TYPE_UINT128:
1922 return "uint128";
1923 case REG_TYPE_CODE_PTR:
1924 return "code_ptr";
1925 case REG_TYPE_DATA_PTR:
1926 return "data_ptr";
1927 case REG_TYPE_FLOAT:
1928 return "float";
1929 case REG_TYPE_IEEE_SINGLE:
1930 return "ieee_single";
1931 case REG_TYPE_IEEE_DOUBLE:
1932 return "ieee_double";
1933 case REG_TYPE_ARCH_DEFINED:
1934 return "int"; /* return arbitrary string to avoid compile warning. */
1937 return "int"; /* "int" as default value */
1940 static int gdb_generate_reg_type_description(struct target *target,
1941 char **tdesc, int *pos, int *size, struct reg_data_type *type)
1943 int retval = ERROR_OK;
1945 if (type->type_class == REG_TYPE_CLASS_VECTOR) {
1946 /* <vector id="id" type="type" count="count"/> */
1947 xml_printf(&retval, tdesc, pos, size,
1948 "<vector id=\"%s\" type=\"%s\" count=\"%d\"/>\n",
1949 type->id, type->reg_type_vector->type->id,
1950 type->reg_type_vector->count);
1952 } else if (type->type_class == REG_TYPE_CLASS_UNION) {
1953 /* <union id="id">
1954 * <field name="name" type="type"/> ...
1955 * </union> */
1956 xml_printf(&retval, tdesc, pos, size,
1957 "<union id=\"%s\">\n",
1958 type->id);
1960 struct reg_data_type_union_field *field;
1961 field = type->reg_type_union->fields;
1962 while (field != NULL) {
1963 xml_printf(&retval, tdesc, pos, size,
1964 "<field name=\"%s\" type=\"%s\"/>\n",
1965 field->name, field->type->id);
1967 field = field->next;
1970 xml_printf(&retval, tdesc, pos, size,
1971 "</union>\n");
1973 } else if (type->type_class == REG_TYPE_CLASS_STRUCT) {
1974 struct reg_data_type_struct_field *field;
1975 field = type->reg_type_struct->fields;
1977 if (field->use_bitfields) {
1978 /* <struct id="id" size="size">
1979 * <field name="name" start="start" end="end"/> ...
1980 * </struct> */
1981 xml_printf(&retval, tdesc, pos, size,
1982 "<struct id=\"%s\" size=\"%d\">\n",
1983 type->id, type->reg_type_struct->size);
1984 while (field != NULL) {
1985 xml_printf(&retval, tdesc, pos, size,
1986 "<field name=\"%s\" start=\"%d\" end=\"%d\"/>\n",
1987 field->name, field->bitfield->start,
1988 field->bitfield->end);
1990 field = field->next;
1992 } else {
1993 /* <struct id="id">
1994 * <field name="name" type="type"/> ...
1995 * </struct> */
1996 xml_printf(&retval, tdesc, pos, size,
1997 "<struct id=\"%s\">\n",
1998 type->id);
1999 while (field != NULL) {
2000 xml_printf(&retval, tdesc, pos, size,
2001 "<field name=\"%s\" type=\"%s\"/>\n",
2002 field->name, field->type->id);
2004 field = field->next;
2008 xml_printf(&retval, tdesc, pos, size,
2009 "</struct>\n");
2011 } else if (type->type_class == REG_TYPE_CLASS_FLAGS) {
2012 /* <flags id="id" size="size">
2013 * <field name="name" start="start" end="end"/> ...
2014 * </flags> */
2015 xml_printf(&retval, tdesc, pos, size,
2016 "<flags id=\"%s\" size=\"%d\">\n",
2017 type->id, type->reg_type_flags->size);
2019 struct reg_data_type_flags_field *field;
2020 field = type->reg_type_flags->fields;
2021 while (field != NULL) {
2022 xml_printf(&retval, tdesc, pos, size,
2023 "<field name=\"%s\" start=\"%d\" end=\"%d\"/>\n",
2024 field->name, field->bitfield->start, field->bitfield->end);
2026 field = field->next;
2029 xml_printf(&retval, tdesc, pos, size,
2030 "</flags>\n");
2034 return ERROR_OK;
2037 /* Get a list of available target registers features. feature_list must
2038 * be freed by caller.
2040 static int get_reg_features_list(struct target *target, char const **feature_list[], int *feature_list_size,
2041 struct reg **reg_list, int reg_list_size)
2043 int tbl_sz = 0;
2045 /* Start with only one element */
2046 *feature_list = calloc(1, sizeof(char *));
2048 for (int i = 0; i < reg_list_size; i++) {
2049 if (reg_list[i]->exist == false)
2050 continue;
2052 if (reg_list[i]->feature != NULL
2053 && reg_list[i]->feature->name != NULL
2054 && (strcmp(reg_list[i]->feature->name, ""))) {
2055 /* We found a feature, check if the feature is already in the
2056 * table. If not, allocate a new entry for the table and
2057 * put the new feature in it.
2059 for (int j = 0; j < (tbl_sz + 1); j++) {
2060 if (!((*feature_list)[j])) {
2061 (*feature_list)[tbl_sz++] = reg_list[i]->feature->name;
2062 *feature_list = realloc(*feature_list, sizeof(char *) * (tbl_sz + 1));
2063 (*feature_list)[tbl_sz] = NULL;
2064 break;
2065 } else {
2066 if (!strcmp((*feature_list)[j], reg_list[i]->feature->name))
2067 break;
2073 if (feature_list_size)
2074 *feature_list_size = tbl_sz;
2076 return ERROR_OK;
2079 static int gdb_generate_target_description(struct target *target, char **tdesc_out)
2081 int retval = ERROR_OK;
2082 struct reg **reg_list = NULL;
2083 int reg_list_size;
2084 char const **features = NULL;
2085 int feature_list_size = 0;
2086 char *tdesc = NULL;
2087 int pos = 0;
2088 int size = 0;
2090 retval = target_get_gdb_reg_list(target, &reg_list,
2091 &reg_list_size, REG_CLASS_ALL);
2093 if (retval != ERROR_OK) {
2094 LOG_ERROR("get register list failed");
2095 retval = ERROR_FAIL;
2096 goto error;
2099 if (reg_list_size <= 0) {
2100 LOG_ERROR("get register list failed");
2101 retval = ERROR_FAIL;
2102 goto error;
2105 /* Get a list of available target registers features */
2106 retval = get_reg_features_list(target, &features, &feature_list_size, reg_list, reg_list_size);
2107 if (retval != ERROR_OK) {
2108 LOG_ERROR("Can't get the registers feature list");
2109 retval = ERROR_FAIL;
2110 goto error;
2113 /* If we found some features associated with registers, create sections */
2114 int current_feature = 0;
2116 xml_printf(&retval, &tdesc, &pos, &size,
2117 "<?xml version=\"1.0\"?>\n"
2118 "<!DOCTYPE target SYSTEM \"gdb-target.dtd\">\n"
2119 "<target version=\"1.0\">\n");
2121 /* generate target description according to register list */
2122 if (features != NULL) {
2123 while (features[current_feature]) {
2125 xml_printf(&retval, &tdesc, &pos, &size,
2126 "<feature name=\"%s\">\n",
2127 features[current_feature]);
2129 int i;
2130 for (i = 0; i < reg_list_size; i++) {
2132 if (reg_list[i]->exist == false)
2133 continue;
2135 if (strcmp(reg_list[i]->feature->name, features[current_feature]))
2136 continue;
2138 const char *type_str;
2139 if (reg_list[i]->reg_data_type != NULL) {
2140 if (reg_list[i]->reg_data_type->type == REG_TYPE_ARCH_DEFINED) {
2141 /* generate <type... first, if there are architecture-defined types. */
2142 gdb_generate_reg_type_description(target, &tdesc, &pos, &size,
2143 reg_list[i]->reg_data_type);
2145 type_str = reg_list[i]->reg_data_type->id;
2146 } else {
2147 /* predefined type */
2148 type_str = gdb_get_reg_type_name(
2149 reg_list[i]->reg_data_type->type);
2151 } else {
2152 /* Default type is "int" */
2153 type_str = "int";
2156 xml_printf(&retval, &tdesc, &pos, &size,
2157 "<reg name=\"%s\"", reg_list[i]->name);
2158 xml_printf(&retval, &tdesc, &pos, &size,
2159 " bitsize=\"%d\"", reg_list[i]->size);
2160 xml_printf(&retval, &tdesc, &pos, &size,
2161 " regnum=\"%d\"", reg_list[i]->number);
2162 if (reg_list[i]->caller_save)
2163 xml_printf(&retval, &tdesc, &pos, &size,
2164 " save-restore=\"yes\"");
2165 else
2166 xml_printf(&retval, &tdesc, &pos, &size,
2167 " save-restore=\"no\"");
2169 xml_printf(&retval, &tdesc, &pos, &size,
2170 " type=\"%s\"", type_str);
2172 if (reg_list[i]->group != NULL)
2173 xml_printf(&retval, &tdesc, &pos, &size,
2174 " group=\"%s\"", reg_list[i]->group);
2176 xml_printf(&retval, &tdesc, &pos, &size,
2177 "/>\n");
2180 xml_printf(&retval, &tdesc, &pos, &size,
2181 "</feature>\n");
2183 current_feature++;
2187 xml_printf(&retval, &tdesc, &pos, &size,
2188 "</target>\n");
2190 error:
2191 free(features);
2192 free(reg_list);
2194 if (retval == ERROR_OK)
2195 *tdesc_out = tdesc;
2196 else
2197 free(tdesc);
2199 return retval;
2202 static int gdb_get_target_description_chunk(struct target *target, struct target_desc_format *target_desc,
2203 char **chunk, int32_t offset, uint32_t length)
2205 if (target_desc == NULL) {
2206 LOG_ERROR("Unable to Generate Target Description");
2207 return ERROR_FAIL;
2210 char *tdesc = target_desc->tdesc;
2211 uint32_t tdesc_length = target_desc->tdesc_length;
2213 if (tdesc == NULL) {
2214 int retval = gdb_generate_target_description(target, &tdesc);
2215 if (retval != ERROR_OK) {
2216 LOG_ERROR("Unable to Generate Target Description");
2217 return ERROR_FAIL;
2220 tdesc_length = strlen(tdesc);
2223 char transfer_type;
2225 if (length < (tdesc_length - offset))
2226 transfer_type = 'm';
2227 else
2228 transfer_type = 'l';
2230 *chunk = malloc(length + 2);
2231 if (*chunk == NULL) {
2232 LOG_ERROR("Unable to allocate memory");
2233 return ERROR_FAIL;
2236 (*chunk)[0] = transfer_type;
2237 if (transfer_type == 'm') {
2238 strncpy((*chunk) + 1, tdesc + offset, length);
2239 (*chunk)[1 + length] = '\0';
2240 } else {
2241 strncpy((*chunk) + 1, tdesc + offset, tdesc_length - offset);
2242 (*chunk)[1 + (tdesc_length - offset)] = '\0';
2244 /* After gdb-server sends out last chunk, invalidate tdesc. */
2245 free(tdesc);
2246 tdesc = NULL;
2247 tdesc_length = 0;
2250 target_desc->tdesc = tdesc;
2251 target_desc->tdesc_length = tdesc_length;
2253 return ERROR_OK;
2256 static int gdb_target_description_supported(struct target *target, int *supported)
2258 int retval = ERROR_OK;
2259 struct reg **reg_list = NULL;
2260 int reg_list_size = 0;
2261 char const **features = NULL;
2262 int feature_list_size = 0;
2264 retval = target_get_gdb_reg_list(target, &reg_list,
2265 &reg_list_size, REG_CLASS_ALL);
2266 if (retval != ERROR_OK) {
2267 LOG_ERROR("get register list failed");
2268 goto error;
2271 if (reg_list_size <= 0) {
2272 LOG_ERROR("get register list failed");
2273 retval = ERROR_FAIL;
2274 goto error;
2277 /* Get a list of available target registers features */
2278 retval = get_reg_features_list(target, &features, &feature_list_size, reg_list, reg_list_size);
2279 if (retval != ERROR_OK) {
2280 LOG_ERROR("Can't get the registers feature list");
2281 goto error;
2284 if (supported) {
2285 if (feature_list_size)
2286 *supported = 1;
2287 else
2288 *supported = 0;
2291 error:
2292 free(features);
2294 free(reg_list);
2296 return retval;
2299 static int gdb_generate_thread_list(struct target *target, char **thread_list_out)
2301 struct rtos *rtos = target->rtos;
2302 int retval = ERROR_OK;
2303 char *thread_list = NULL;
2304 int pos = 0;
2305 int size = 0;
2307 xml_printf(&retval, &thread_list, &pos, &size,
2308 "<?xml version=\"1.0\"?>\n"
2309 "<threads>\n");
2311 if (rtos != NULL) {
2312 for (int i = 0; i < rtos->thread_count; i++) {
2313 struct thread_detail *thread_detail = &rtos->thread_details[i];
2315 if (!thread_detail->exists)
2316 continue;
2318 xml_printf(&retval, &thread_list, &pos, &size,
2319 "<thread id=\"%" PRIx64 "\">", thread_detail->threadid);
2321 if (thread_detail->thread_name_str != NULL)
2322 xml_printf(&retval, &thread_list, &pos, &size,
2323 "Name: %s", thread_detail->thread_name_str);
2325 if (thread_detail->extra_info_str != NULL) {
2326 if (thread_detail->thread_name_str != NULL)
2327 xml_printf(&retval, &thread_list, &pos, &size,
2328 ", ");
2329 xml_printf(&retval, &thread_list, &pos, &size,
2330 thread_detail->extra_info_str);
2333 xml_printf(&retval, &thread_list, &pos, &size,
2334 "</thread>\n");
2338 xml_printf(&retval, &thread_list, &pos, &size,
2339 "</threads>\n");
2341 if (retval == ERROR_OK)
2342 *thread_list_out = thread_list;
2343 else
2344 free(thread_list);
2346 return retval;
2349 static int gdb_get_thread_list_chunk(struct target *target, char **thread_list,
2350 char **chunk, int32_t offset, uint32_t length)
2352 if (*thread_list == NULL) {
2353 int retval = gdb_generate_thread_list(target, thread_list);
2354 if (retval != ERROR_OK) {
2355 LOG_ERROR("Unable to Generate Thread List");
2356 return ERROR_FAIL;
2360 size_t thread_list_length = strlen(*thread_list);
2361 char transfer_type;
2363 length = MIN(length, thread_list_length - offset);
2364 if (length < (thread_list_length - offset))
2365 transfer_type = 'm';
2366 else
2367 transfer_type = 'l';
2369 *chunk = malloc(length + 2);
2370 if (*chunk == NULL) {
2371 LOG_ERROR("Unable to allocate memory");
2372 return ERROR_FAIL;
2375 (*chunk)[0] = transfer_type;
2376 strncpy((*chunk) + 1, (*thread_list) + offset, length);
2377 (*chunk)[1 + length] = '\0';
2379 /* After gdb-server sends out last chunk, invalidate thread list. */
2380 if (transfer_type == 'l') {
2381 free(*thread_list);
2382 *thread_list = NULL;
2385 return ERROR_OK;
2388 static int gdb_query_packet(struct connection *connection,
2389 char const *packet, int packet_size)
2391 struct command_context *cmd_ctx = connection->cmd_ctx;
2392 struct gdb_connection *gdb_connection = connection->priv;
2393 struct target *target = get_target_from_connection(connection);
2395 if (strncmp(packet, "qRcmd,", 6) == 0) {
2396 if (packet_size > 6) {
2397 char *cmd;
2398 cmd = malloc((packet_size - 6) / 2 + 1);
2399 size_t len = unhexify((uint8_t *)cmd, packet + 6, (packet_size - 6) / 2);
2400 cmd[len] = 0;
2402 /* We want to print all debug output to GDB connection */
2403 log_add_callback(gdb_log_callback, connection);
2404 target_call_timer_callbacks_now();
2405 /* some commands need to know the GDB connection, make note of current
2406 * GDB connection. */
2407 current_gdb_connection = gdb_connection;
2408 command_run_line(cmd_ctx, cmd);
2409 current_gdb_connection = NULL;
2410 target_call_timer_callbacks_now();
2411 log_remove_callback(gdb_log_callback, connection);
2412 free(cmd);
2414 gdb_put_packet(connection, "OK", 2);
2415 return ERROR_OK;
2416 } else if (strncmp(packet, "qCRC:", 5) == 0) {
2417 if (packet_size > 5) {
2418 int retval;
2419 char gdb_reply[10];
2420 char *separator;
2421 uint32_t checksum;
2422 target_addr_t addr = 0;
2423 uint32_t len = 0;
2425 /* skip command character */
2426 packet += 5;
2428 addr = strtoull(packet, &separator, 16);
2430 if (*separator != ',') {
2431 LOG_ERROR("incomplete read memory packet received, dropping connection");
2432 return ERROR_SERVER_REMOTE_CLOSED;
2435 len = strtoul(separator + 1, NULL, 16);
2437 retval = target_checksum_memory(target, addr, len, &checksum);
2439 if (retval == ERROR_OK) {
2440 snprintf(gdb_reply, 10, "C%8.8" PRIx32 "", checksum);
2441 gdb_put_packet(connection, gdb_reply, 9);
2442 } else {
2443 retval = gdb_error(connection, retval);
2444 if (retval != ERROR_OK)
2445 return retval;
2448 return ERROR_OK;
2450 } else if (strncmp(packet, "qSupported", 10) == 0) {
2451 /* we currently support packet size and qXfer:memory-map:read (if enabled)
2452 * qXfer:features:read is supported for some targets */
2453 int retval = ERROR_OK;
2454 char *buffer = NULL;
2455 int pos = 0;
2456 int size = 0;
2457 int gdb_target_desc_supported = 0;
2459 /* we need to test that the target supports target descriptions */
2460 retval = gdb_target_description_supported(target, &gdb_target_desc_supported);
2461 if (retval != ERROR_OK) {
2462 LOG_INFO("Failed detecting Target Description Support, disabling");
2463 gdb_target_desc_supported = 0;
2466 /* support may be disabled globally */
2467 if (gdb_use_target_description == 0) {
2468 if (gdb_target_desc_supported)
2469 LOG_WARNING("Target Descriptions Supported, but disabled");
2470 gdb_target_desc_supported = 0;
2473 xml_printf(&retval,
2474 &buffer,
2475 &pos,
2476 &size,
2477 "PacketSize=%x;qXfer:memory-map:read%c;qXfer:features:read%c;qXfer:threads:read+;QStartNoAckMode+;vContSupported+",
2478 (GDB_BUFFER_SIZE - 1),
2479 ((gdb_use_memory_map == 1) && (flash_get_bank_count() > 0)) ? '+' : '-',
2480 (gdb_target_desc_supported == 1) ? '+' : '-');
2482 if (retval != ERROR_OK) {
2483 gdb_send_error(connection, 01);
2484 return ERROR_OK;
2487 gdb_put_packet(connection, buffer, strlen(buffer));
2488 free(buffer);
2490 return ERROR_OK;
2491 } else if ((strncmp(packet, "qXfer:memory-map:read::", 23) == 0)
2492 && (flash_get_bank_count() > 0))
2493 return gdb_memory_map(connection, packet, packet_size);
2494 else if (strncmp(packet, "qXfer:features:read:", 20) == 0) {
2495 char *xml = NULL;
2496 int retval = ERROR_OK;
2498 int offset;
2499 unsigned int length;
2501 /* skip command character */
2502 packet += 20;
2504 if (decode_xfer_read(packet, NULL, &offset, &length) < 0) {
2505 gdb_send_error(connection, 01);
2506 return ERROR_OK;
2509 /* Target should prepare correct target description for annex.
2510 * The first character of returned xml is 'm' or 'l'. 'm' for
2511 * there are *more* chunks to transfer. 'l' for it is the *last*
2512 * chunk of target description.
2514 retval = gdb_get_target_description_chunk(target, &gdb_connection->target_desc,
2515 &xml, offset, length);
2516 if (retval != ERROR_OK) {
2517 gdb_error(connection, retval);
2518 return retval;
2521 gdb_put_packet(connection, xml, strlen(xml));
2523 free(xml);
2524 return ERROR_OK;
2525 } else if (strncmp(packet, "qXfer:threads:read:", 19) == 0) {
2526 char *xml = NULL;
2527 int retval = ERROR_OK;
2529 int offset;
2530 unsigned int length;
2532 /* skip command character */
2533 packet += 19;
2535 if (decode_xfer_read(packet, NULL, &offset, &length) < 0) {
2536 gdb_send_error(connection, 01);
2537 return ERROR_OK;
2540 /* Target should prepare correct thread list for annex.
2541 * The first character of returned xml is 'm' or 'l'. 'm' for
2542 * there are *more* chunks to transfer. 'l' for it is the *last*
2543 * chunk of target description.
2545 retval = gdb_get_thread_list_chunk(target, &gdb_connection->thread_list,
2546 &xml, offset, length);
2547 if (retval != ERROR_OK) {
2548 gdb_error(connection, retval);
2549 return retval;
2552 gdb_put_packet(connection, xml, strlen(xml));
2554 free(xml);
2555 return ERROR_OK;
2556 } else if (strncmp(packet, "QStartNoAckMode", 15) == 0) {
2557 gdb_connection->noack_mode = 1;
2558 gdb_put_packet(connection, "OK", 2);
2559 return ERROR_OK;
2562 gdb_put_packet(connection, "", 0);
2563 return ERROR_OK;
2566 static bool gdb_handle_vcont_packet(struct connection *connection, const char *packet, int packet_size)
2568 struct gdb_connection *gdb_connection = connection->priv;
2569 struct target *target = get_target_from_connection(connection);
2570 const char *parse = packet;
2571 int retval;
2573 /* query for vCont supported */
2574 if (parse[0] == '?') {
2575 if (target->type->step != NULL) {
2576 /* gdb doesn't accept c without C and s without S */
2577 gdb_put_packet(connection, "vCont;c;C;s;S", 13);
2578 return true;
2580 return false;
2583 if (parse[0] == ';') {
2584 ++parse;
2585 --packet_size;
2588 /* simple case, a continue packet */
2589 if (parse[0] == 'c') {
2590 LOG_DEBUG("target %s continue", target_name(target));
2591 log_add_callback(gdb_log_callback, connection);
2592 retval = target_resume(target, 1, 0, 0, 0);
2593 if (retval == ERROR_OK) {
2594 gdb_connection->frontend_state = TARGET_RUNNING;
2595 target_call_event_callbacks(target, TARGET_EVENT_GDB_START);
2597 return true;
2600 /* single-step or step-over-breakpoint */
2601 if (parse[0] == 's') {
2602 if (strncmp(parse, "s:", 2) == 0) {
2603 int handle_breakpoint = 1;
2604 struct target *ct = target;
2605 int64_t thread_id;
2606 char *endp;
2608 parse += 2;
2609 packet_size -= 2;
2611 thread_id = strtoll(parse, &endp, 16);
2612 if (endp != NULL) {
2613 packet_size -= endp - parse;
2614 parse = endp;
2617 if (parse[0] == ';') {
2618 ++parse;
2619 --packet_size;
2621 if (parse[0] == 'c') {
2622 parse += 1;
2623 packet_size -= 1;
2625 handle_breakpoint = 0;
2629 LOG_DEBUG("target %s single-step thread %"PRId64, target_name(ct), thread_id);
2630 retval = target_step(ct, 1, 0, handle_breakpoint);
2631 if (retval == ERROR_OK) {
2632 gdb_signal_reply(target, connection);
2633 /* stop forwarding log packets! */
2634 log_remove_callback(gdb_log_callback, connection);
2635 } else
2636 if (retval == ERROR_TARGET_TIMEOUT) {
2637 gdb_connection->frontend_state = TARGET_RUNNING;
2638 target_call_event_callbacks(ct, TARGET_EVENT_GDB_START);
2640 } else {
2641 LOG_ERROR("Unknown vCont packet");
2642 return false;
2644 return true;
2647 return false;
2650 static int gdb_v_packet(struct connection *connection,
2651 char const *packet, int packet_size)
2653 struct gdb_connection *gdb_connection = connection->priv;
2654 struct target *target;
2655 int result;
2657 target = get_target_from_connection(connection);
2659 if (strncmp(packet, "vCont", 5) == 0) {
2660 bool handled;
2662 packet += 5;
2663 packet_size -= 5;
2665 handled = gdb_handle_vcont_packet(connection, packet, packet_size);
2666 if (!handled)
2667 gdb_put_packet(connection, "", 0);
2669 return ERROR_OK;
2672 /* if flash programming disabled - send a empty reply */
2674 if (gdb_flash_program == 0) {
2675 gdb_put_packet(connection, "", 0);
2676 return ERROR_OK;
2679 if (strncmp(packet, "vFlashErase:", 12) == 0) {
2680 unsigned long addr;
2681 unsigned long length;
2683 char const *parse = packet + 12;
2684 if (*parse == '\0') {
2685 LOG_ERROR("incomplete vFlashErase packet received, dropping connection");
2686 return ERROR_SERVER_REMOTE_CLOSED;
2689 addr = strtoul(parse, (char **)&parse, 16);
2691 if (*(parse++) != ',' || *parse == '\0') {
2692 LOG_ERROR("incomplete vFlashErase packet received, dropping connection");
2693 return ERROR_SERVER_REMOTE_CLOSED;
2696 length = strtoul(parse, (char **)&parse, 16);
2698 if (*parse != '\0') {
2699 LOG_ERROR("incomplete vFlashErase packet received, dropping connection");
2700 return ERROR_SERVER_REMOTE_CLOSED;
2703 /* assume all sectors need erasing - stops any problems
2704 * when flash_write is called multiple times */
2705 flash_set_dirty();
2707 /* perform any target specific operations before the erase */
2708 target_call_event_callbacks(target,
2709 TARGET_EVENT_GDB_FLASH_ERASE_START);
2711 /* vFlashErase:addr,length messages require region start and
2712 * end to be "block" aligned ... if padding is ever needed,
2713 * GDB will have become dangerously confused.
2715 result = flash_erase_address_range(target, false, addr,
2716 length);
2718 /* perform any target specific operations after the erase */
2719 target_call_event_callbacks(target,
2720 TARGET_EVENT_GDB_FLASH_ERASE_END);
2722 /* perform erase */
2723 if (result != ERROR_OK) {
2724 /* GDB doesn't evaluate the actual error number returned,
2725 * treat a failed erase as an I/O error
2727 gdb_send_error(connection, EIO);
2728 LOG_ERROR("flash_erase returned %i", result);
2729 } else
2730 gdb_put_packet(connection, "OK", 2);
2732 return ERROR_OK;
2735 if (strncmp(packet, "vFlashWrite:", 12) == 0) {
2736 int retval;
2737 unsigned long addr;
2738 unsigned long length;
2739 char const *parse = packet + 12;
2741 if (*parse == '\0') {
2742 LOG_ERROR("incomplete vFlashErase packet received, dropping connection");
2743 return ERROR_SERVER_REMOTE_CLOSED;
2745 addr = strtoul(parse, (char **)&parse, 16);
2746 if (*(parse++) != ':') {
2747 LOG_ERROR("incomplete vFlashErase packet received, dropping connection");
2748 return ERROR_SERVER_REMOTE_CLOSED;
2750 length = packet_size - (parse - packet);
2752 /* create a new image if there isn't already one */
2753 if (gdb_connection->vflash_image == NULL) {
2754 gdb_connection->vflash_image = malloc(sizeof(struct image));
2755 image_open(gdb_connection->vflash_image, "", "build");
2758 /* create new section with content from packet buffer */
2759 retval = image_add_section(gdb_connection->vflash_image,
2760 addr, length, 0x0, (uint8_t const *)parse);
2761 if (retval != ERROR_OK)
2762 return retval;
2764 gdb_put_packet(connection, "OK", 2);
2766 return ERROR_OK;
2769 if (strncmp(packet, "vFlashDone", 10) == 0) {
2770 uint32_t written;
2772 /* process the flashing buffer. No need to erase as GDB
2773 * always issues a vFlashErase first. */
2774 target_call_event_callbacks(target,
2775 TARGET_EVENT_GDB_FLASH_WRITE_START);
2776 result = flash_write(target, gdb_connection->vflash_image,
2777 &written, 0);
2778 target_call_event_callbacks(target,
2779 TARGET_EVENT_GDB_FLASH_WRITE_END);
2780 if (result != ERROR_OK) {
2781 if (result == ERROR_FLASH_DST_OUT_OF_BANK)
2782 gdb_put_packet(connection, "E.memtype", 9);
2783 else
2784 gdb_send_error(connection, EIO);
2785 } else {
2786 LOG_DEBUG("wrote %u bytes from vFlash image to flash", (unsigned)written);
2787 gdb_put_packet(connection, "OK", 2);
2790 image_close(gdb_connection->vflash_image);
2791 free(gdb_connection->vflash_image);
2792 gdb_connection->vflash_image = NULL;
2794 return ERROR_OK;
2797 gdb_put_packet(connection, "", 0);
2798 return ERROR_OK;
2801 static int gdb_detach(struct connection *connection)
2803 target_call_event_callbacks(get_target_from_connection(connection),
2804 TARGET_EVENT_GDB_DETACH);
2806 return gdb_put_packet(connection, "OK", 2);
2809 /* The format of 'F' response packet is
2810 * Fretcode,errno,Ctrl-C flag;call-specific attachment
2812 static int gdb_fileio_response_packet(struct connection *connection,
2813 char const *packet, int packet_size)
2815 struct target *target = get_target_from_connection(connection);
2816 char *separator;
2817 char *parsing_point;
2818 int fileio_retcode = strtoul(packet + 1, &separator, 16);
2819 int fileio_errno = 0;
2820 bool fileio_ctrl_c = false;
2821 int retval;
2823 LOG_DEBUG("-");
2825 if (*separator == ',') {
2826 parsing_point = separator + 1;
2827 fileio_errno = strtoul(parsing_point, &separator, 16);
2828 if (*separator == ',') {
2829 if (*(separator + 1) == 'C') {
2830 /* TODO: process ctrl-c */
2831 fileio_ctrl_c = true;
2836 LOG_DEBUG("File-I/O response, retcode: 0x%x, errno: 0x%x, ctrl-c: %s",
2837 fileio_retcode, fileio_errno, fileio_ctrl_c ? "true" : "false");
2839 retval = target_gdb_fileio_end(target, fileio_retcode, fileio_errno, fileio_ctrl_c);
2840 if (retval != ERROR_OK)
2841 return ERROR_FAIL;
2843 /* After File-I/O ends, keep continue or step */
2844 if (gdb_running_type == 'c')
2845 retval = target_resume(target, 1, 0x0, 0, 0);
2846 else if (gdb_running_type == 's')
2847 retval = target_step(target, 1, 0x0, 0);
2848 else
2849 retval = ERROR_FAIL;
2851 if (retval != ERROR_OK)
2852 return ERROR_FAIL;
2854 return ERROR_OK;
2857 static void gdb_log_callback(void *priv, const char *file, unsigned line,
2858 const char *function, const char *string)
2860 struct connection *connection = priv;
2861 struct gdb_connection *gdb_con = connection->priv;
2863 if (gdb_con->busy) {
2864 /* do not reply this using the O packet */
2865 return;
2868 gdb_output_con(connection, string);
2871 static void gdb_sig_halted(struct connection *connection)
2873 char sig_reply[4];
2874 snprintf(sig_reply, 4, "T%2.2x", 2);
2875 gdb_put_packet(connection, sig_reply, 3);
2878 static int gdb_input_inner(struct connection *connection)
2880 /* Do not allocate this on the stack */
2881 static char gdb_packet_buffer[GDB_BUFFER_SIZE];
2883 struct target *target;
2884 char const *packet = gdb_packet_buffer;
2885 int packet_size;
2886 int retval;
2887 struct gdb_connection *gdb_con = connection->priv;
2888 static int extended_protocol;
2890 target = get_target_from_connection(connection);
2892 /* drain input buffer. If one of the packets fail, then an error
2893 * packet is replied, if applicable.
2895 * This loop will terminate and the error code is returned.
2897 * The calling fn will check if this error is something that
2898 * can be recovered from, or if the connection must be closed.
2900 * If the error is recoverable, this fn is called again to
2901 * drain the rest of the buffer.
2903 do {
2904 packet_size = GDB_BUFFER_SIZE-1;
2905 retval = gdb_get_packet(connection, gdb_packet_buffer, &packet_size);
2906 if (retval != ERROR_OK)
2907 return retval;
2909 /* terminate with zero */
2910 gdb_packet_buffer[packet_size] = '\0';
2912 if (LOG_LEVEL_IS(LOG_LVL_DEBUG)) {
2913 if (packet[0] == 'X') {
2914 /* binary packets spew junk into the debug log stream */
2915 char buf[50];
2916 int x;
2917 for (x = 0; (x < 49) && (packet[x] != ':'); x++)
2918 buf[x] = packet[x];
2919 buf[x] = 0;
2920 LOG_DEBUG("received packet: '%s:<binary-data>'", buf);
2921 } else
2922 LOG_DEBUG("received packet: '%s'", packet);
2925 if (packet_size > 0) {
2926 retval = ERROR_OK;
2927 switch (packet[0]) {
2928 case 'T': /* Is thread alive? */
2929 gdb_thread_packet(connection, packet, packet_size);
2930 break;
2931 case 'H': /* Set current thread ( 'c' for step and continue,
2932 * 'g' for all other operations ) */
2933 gdb_thread_packet(connection, packet, packet_size);
2934 break;
2935 case 'q':
2936 case 'Q':
2937 retval = gdb_thread_packet(connection, packet, packet_size);
2938 if (retval == GDB_THREAD_PACKET_NOT_CONSUMED)
2939 retval = gdb_query_packet(connection, packet, packet_size);
2940 break;
2941 case 'g':
2942 retval = gdb_get_registers_packet(connection, packet, packet_size);
2943 break;
2944 case 'G':
2945 retval = gdb_set_registers_packet(connection, packet, packet_size);
2946 break;
2947 case 'p':
2948 retval = gdb_get_register_packet(connection, packet, packet_size);
2949 break;
2950 case 'P':
2951 retval = gdb_set_register_packet(connection, packet, packet_size);
2952 break;
2953 case 'm':
2954 retval = gdb_read_memory_packet(connection, packet, packet_size);
2955 break;
2956 case 'M':
2957 retval = gdb_write_memory_packet(connection, packet, packet_size);
2958 break;
2959 case 'z':
2960 case 'Z':
2961 retval = gdb_breakpoint_watchpoint_packet(connection, packet, packet_size);
2962 break;
2963 case '?':
2964 gdb_last_signal_packet(connection, packet, packet_size);
2965 break;
2966 case 'c':
2967 case 's':
2969 gdb_thread_packet(connection, packet, packet_size);
2970 log_add_callback(gdb_log_callback, connection);
2972 if (gdb_con->mem_write_error) {
2973 LOG_ERROR("Memory write failure!");
2975 /* now that we have reported the memory write error,
2976 * we can clear the condition */
2977 gdb_con->mem_write_error = false;
2980 bool nostep = false;
2981 bool already_running = false;
2982 if (target->state == TARGET_RUNNING) {
2983 LOG_WARNING("WARNING! The target is already running. "
2984 "All changes GDB did to registers will be discarded! "
2985 "Waiting for target to halt.");
2986 already_running = true;
2987 } else if (target->state != TARGET_HALTED) {
2988 LOG_WARNING("The target is not in the halted nor running stated, " \
2989 "stepi/continue ignored.");
2990 nostep = true;
2991 } else if ((packet[0] == 's') && gdb_con->sync) {
2992 /* Hmm..... when you issue a continue in GDB, then a "stepi" is
2993 * sent by GDB first to OpenOCD, thus defeating the check to
2994 * make only the single stepping have the sync feature...
2996 nostep = true;
2997 LOG_WARNING("stepi ignored. GDB will now fetch the register state " \
2998 "from the target.");
3000 gdb_con->sync = false;
3002 if (!already_running && nostep) {
3003 /* Either the target isn't in the halted state, then we can't
3004 * step/continue. This might be early setup, etc.
3006 * Or we want to allow GDB to pick up a fresh set of
3007 * register values without modifying the target state.
3010 gdb_sig_halted(connection);
3012 /* stop forwarding log packets! */
3013 log_remove_callback(gdb_log_callback, connection);
3014 } else {
3015 /* We're running/stepping, in which case we can
3016 * forward log output until the target is halted
3018 gdb_con->frontend_state = TARGET_RUNNING;
3019 target_call_event_callbacks(target, TARGET_EVENT_GDB_START);
3021 if (!already_running) {
3022 /* Here we don't want packet processing to stop even if this fails,
3023 * so we use a local variable instead of retval. */
3024 retval = gdb_step_continue_packet(connection, packet, packet_size);
3025 if (retval != ERROR_OK) {
3026 /* we'll never receive a halted
3027 * condition... issue a false one..
3029 gdb_frontend_halted(target, connection);
3034 break;
3035 case 'v':
3036 retval = gdb_v_packet(connection, packet, packet_size);
3037 break;
3038 case 'D':
3039 retval = gdb_detach(connection);
3040 extended_protocol = 0;
3041 break;
3042 case 'X':
3043 retval = gdb_write_memory_binary_packet(connection, packet, packet_size);
3044 if (retval != ERROR_OK)
3045 return retval;
3046 break;
3047 case 'k':
3048 if (extended_protocol != 0) {
3049 gdb_con->attached = false;
3050 break;
3052 gdb_put_packet(connection, "OK", 2);
3053 return ERROR_SERVER_REMOTE_CLOSED;
3054 case '!':
3055 /* handle extended remote protocol */
3056 extended_protocol = 1;
3057 gdb_put_packet(connection, "OK", 2);
3058 break;
3059 case 'R':
3060 /* handle extended restart packet */
3061 breakpoint_clear_target(target);
3062 watchpoint_clear_target(target);
3063 command_run_linef(connection->cmd_ctx, "ocd_gdb_restart %s",
3064 target_name(target));
3065 /* set connection as attached after reset */
3066 gdb_con->attached = true;
3067 /* info rtos parts */
3068 gdb_thread_packet(connection, packet, packet_size);
3069 break;
3071 case 'j':
3072 /* packet supported only by smp target i.e cortex_a.c*/
3073 /* handle smp packet replying coreid played to gbd */
3074 gdb_read_smp_packet(connection, packet, packet_size);
3075 break;
3077 case 'J':
3078 /* packet supported only by smp target i.e cortex_a.c */
3079 /* handle smp packet setting coreid to be played at next
3080 * resume to gdb */
3081 gdb_write_smp_packet(connection, packet, packet_size);
3082 break;
3084 case 'F':
3085 /* File-I/O extension */
3086 /* After gdb uses host-side syscall to complete target file
3087 * I/O, gdb sends host-side syscall return value to target
3088 * by 'F' packet.
3089 * The format of 'F' response packet is
3090 * Fretcode,errno,Ctrl-C flag;call-specific attachment
3092 gdb_con->frontend_state = TARGET_RUNNING;
3093 log_add_callback(gdb_log_callback, connection);
3094 gdb_fileio_response_packet(connection, packet, packet_size);
3095 break;
3097 default:
3098 /* ignore unknown packets */
3099 LOG_DEBUG("ignoring 0x%2.2x packet", packet[0]);
3100 gdb_put_packet(connection, NULL, 0);
3101 break;
3104 /* if a packet handler returned an error, exit input loop */
3105 if (retval != ERROR_OK)
3106 return retval;
3109 if (gdb_con->ctrl_c) {
3110 if (target->state == TARGET_RUNNING) {
3111 retval = target_halt(target);
3112 if (retval != ERROR_OK)
3113 target_call_event_callbacks(target, TARGET_EVENT_GDB_HALT);
3114 gdb_con->ctrl_c = 0;
3115 } else {
3116 LOG_INFO("The target is not running when halt was requested, stopping GDB.");
3117 target_call_event_callbacks(target, TARGET_EVENT_GDB_HALT);
3121 } while (gdb_con->buf_cnt > 0);
3123 return ERROR_OK;
3126 static int gdb_input(struct connection *connection)
3128 int retval = gdb_input_inner(connection);
3129 struct gdb_connection *gdb_con = connection->priv;
3130 if (retval == ERROR_SERVER_REMOTE_CLOSED)
3131 return retval;
3133 /* logging does not propagate the error, yet can set the gdb_con->closed flag */
3134 if (gdb_con->closed)
3135 return ERROR_SERVER_REMOTE_CLOSED;
3137 /* we'll recover from any other errors(e.g. temporary timeouts, etc.) */
3138 return ERROR_OK;
3141 static int gdb_target_start(struct target *target, const char *port)
3143 struct gdb_service *gdb_service;
3144 int ret;
3145 gdb_service = malloc(sizeof(struct gdb_service));
3147 if (NULL == gdb_service)
3148 return -ENOMEM;
3150 gdb_service->target = target;
3151 gdb_service->core[0] = -1;
3152 gdb_service->core[1] = -1;
3153 target->gdb_service = gdb_service;
3155 ret = add_service("gdb",
3156 port, 1, &gdb_new_connection, &gdb_input,
3157 &gdb_connection_closed, gdb_service);
3158 /* initialialize all targets gdb service with the same pointer */
3160 struct target_list *head;
3161 struct target *curr;
3162 head = target->head;
3163 while (head != (struct target_list *)NULL) {
3164 curr = head->target;
3165 if (curr != target)
3166 curr->gdb_service = gdb_service;
3167 head = head->next;
3170 return ret;
3173 static int gdb_target_add_one(struct target *target)
3175 if (strcmp(gdb_port, "disabled") == 0) {
3176 LOG_INFO("gdb port disabled");
3177 return ERROR_OK;
3180 /* one gdb instance per smp list */
3181 if ((target->smp) && (target->gdb_service))
3182 return ERROR_OK;
3183 int retval = gdb_target_start(target, gdb_port_next);
3184 if (retval == ERROR_OK) {
3185 long portnumber;
3186 /* If we can parse the port number
3187 * then we increment the port number for the next target.
3189 char *end;
3190 portnumber = strtol(gdb_port_next, &end, 0);
3191 if (!*end) {
3192 if (parse_long(gdb_port_next, &portnumber) == ERROR_OK) {
3193 free(gdb_port_next);
3194 if (portnumber) {
3195 gdb_port_next = alloc_printf("%d", portnumber+1);
3196 } else {
3197 /* Don't increment if gdb_port is 0, since we're just
3198 * trying to allocate an unused port. */
3199 gdb_port_next = strdup("0");
3204 return retval;
3207 int gdb_target_add_all(struct target *target)
3209 if (strcmp(gdb_port, "disabled") == 0) {
3210 LOG_INFO("gdb server disabled");
3211 return ERROR_OK;
3214 if (NULL == target) {
3215 LOG_WARNING("gdb services need one or more targets defined");
3216 return ERROR_OK;
3219 while (NULL != target) {
3220 int retval = gdb_target_add_one(target);
3221 if (ERROR_OK != retval)
3222 return retval;
3224 target = target->next;
3227 return ERROR_OK;
3230 COMMAND_HANDLER(handle_gdb_sync_command)
3232 if (CMD_ARGC != 0)
3233 return ERROR_COMMAND_SYNTAX_ERROR;
3235 if (current_gdb_connection == NULL) {
3236 command_print(CMD_CTX,
3237 "gdb_sync command can only be run from within gdb using \"monitor gdb_sync\"");
3238 return ERROR_FAIL;
3241 current_gdb_connection->sync = true;
3243 return ERROR_OK;
3246 /* daemon configuration command gdb_port */
3247 COMMAND_HANDLER(handle_gdb_port_command)
3249 int retval = CALL_COMMAND_HANDLER(server_pipe_command, &gdb_port);
3250 if (ERROR_OK == retval) {
3251 free(gdb_port_next);
3252 gdb_port_next = strdup(gdb_port);
3254 return retval;
3257 COMMAND_HANDLER(handle_gdb_memory_map_command)
3259 if (CMD_ARGC != 1)
3260 return ERROR_COMMAND_SYNTAX_ERROR;
3262 COMMAND_PARSE_ENABLE(CMD_ARGV[0], gdb_use_memory_map);
3263 return ERROR_OK;
3266 COMMAND_HANDLER(handle_gdb_flash_program_command)
3268 if (CMD_ARGC != 1)
3269 return ERROR_COMMAND_SYNTAX_ERROR;
3271 COMMAND_PARSE_ENABLE(CMD_ARGV[0], gdb_flash_program);
3272 return ERROR_OK;
3275 COMMAND_HANDLER(handle_gdb_report_data_abort_command)
3277 if (CMD_ARGC != 1)
3278 return ERROR_COMMAND_SYNTAX_ERROR;
3280 COMMAND_PARSE_ENABLE(CMD_ARGV[0], gdb_report_data_abort);
3281 return ERROR_OK;
3284 /* gdb_breakpoint_override */
3285 COMMAND_HANDLER(handle_gdb_breakpoint_override_command)
3287 if (CMD_ARGC == 0) {
3288 /* nothing */
3289 } else if (CMD_ARGC == 1) {
3290 gdb_breakpoint_override = 1;
3291 if (strcmp(CMD_ARGV[0], "hard") == 0)
3292 gdb_breakpoint_override_type = BKPT_HARD;
3293 else if (strcmp(CMD_ARGV[0], "soft") == 0)
3294 gdb_breakpoint_override_type = BKPT_SOFT;
3295 else if (strcmp(CMD_ARGV[0], "disable") == 0)
3296 gdb_breakpoint_override = 0;
3297 } else
3298 return ERROR_COMMAND_SYNTAX_ERROR;
3299 if (gdb_breakpoint_override)
3300 LOG_USER("force %s breakpoints",
3301 (gdb_breakpoint_override_type == BKPT_HARD) ? "hard" : "soft");
3302 else
3303 LOG_USER("breakpoint type is not overridden");
3305 return ERROR_OK;
3308 COMMAND_HANDLER(handle_gdb_target_description_command)
3310 if (CMD_ARGC != 1)
3311 return ERROR_COMMAND_SYNTAX_ERROR;
3313 COMMAND_PARSE_ENABLE(CMD_ARGV[0], gdb_use_target_description);
3314 return ERROR_OK;
3317 COMMAND_HANDLER(handle_gdb_save_tdesc_command)
3319 char *tdesc;
3320 uint32_t tdesc_length;
3321 struct target *target = get_current_target(CMD_CTX);
3323 int retval = gdb_generate_target_description(target, &tdesc);
3324 if (retval != ERROR_OK) {
3325 LOG_ERROR("Unable to Generate Target Description");
3326 return ERROR_FAIL;
3329 tdesc_length = strlen(tdesc);
3331 struct fileio *fileio;
3332 size_t size_written;
3334 char *tdesc_filename = alloc_printf("%s.xml", target_type_name(target));
3335 if (tdesc_filename == NULL) {
3336 retval = ERROR_FAIL;
3337 goto out;
3340 retval = fileio_open(&fileio, tdesc_filename, FILEIO_WRITE, FILEIO_TEXT);
3342 if (retval != ERROR_OK) {
3343 LOG_ERROR("Can't open %s for writing", tdesc_filename);
3344 goto out;
3347 retval = fileio_write(fileio, tdesc_length, tdesc, &size_written);
3349 fileio_close(fileio);
3351 if (retval != ERROR_OK)
3352 LOG_ERROR("Error while writing the tdesc file");
3354 out:
3355 free(tdesc_filename);
3356 free(tdesc);
3358 return retval;
3361 static const struct command_registration gdb_command_handlers[] = {
3363 .name = "gdb_sync",
3364 .handler = handle_gdb_sync_command,
3365 .mode = COMMAND_ANY,
3366 .help = "next stepi will return immediately allowing "
3367 "GDB to fetch register state without affecting "
3368 "target state",
3369 .usage = ""
3372 .name = "gdb_port",
3373 .handler = handle_gdb_port_command,
3374 .mode = COMMAND_ANY,
3375 .help = "Normally gdb listens to a TCP/IP port. Each subsequent GDB "
3376 "server listens for the next port number after the "
3377 "base port number specified. "
3378 "No arguments reports GDB port. \"pipe\" means listen to stdin "
3379 "output to stdout, an integer is base port number, \"disabled\" disables "
3380 "port. Any other string is are interpreted as named pipe to listen to. "
3381 "Output pipe is the same name as input pipe, but with 'o' appended.",
3382 .usage = "[port_num]",
3385 .name = "gdb_memory_map",
3386 .handler = handle_gdb_memory_map_command,
3387 .mode = COMMAND_CONFIG,
3388 .help = "enable or disable memory map",
3389 .usage = "('enable'|'disable')"
3392 .name = "gdb_flash_program",
3393 .handler = handle_gdb_flash_program_command,
3394 .mode = COMMAND_CONFIG,
3395 .help = "enable or disable flash program",
3396 .usage = "('enable'|'disable')"
3399 .name = "gdb_report_data_abort",
3400 .handler = handle_gdb_report_data_abort_command,
3401 .mode = COMMAND_CONFIG,
3402 .help = "enable or disable reporting data aborts",
3403 .usage = "('enable'|'disable')"
3406 .name = "gdb_breakpoint_override",
3407 .handler = handle_gdb_breakpoint_override_command,
3408 .mode = COMMAND_ANY,
3409 .help = "Display or specify type of breakpoint "
3410 "to be used by gdb 'break' commands.",
3411 .usage = "('hard'|'soft'|'disable')"
3414 .name = "gdb_target_description",
3415 .handler = handle_gdb_target_description_command,
3416 .mode = COMMAND_CONFIG,
3417 .help = "enable or disable target description",
3418 .usage = "('enable'|'disable')"
3421 .name = "gdb_save_tdesc",
3422 .handler = handle_gdb_save_tdesc_command,
3423 .mode = COMMAND_EXEC,
3424 .help = "Save the target description file",
3426 COMMAND_REGISTRATION_DONE
3429 int gdb_register_commands(struct command_context *cmd_ctx)
3431 gdb_port = strdup("3333");
3432 gdb_port_next = strdup("3333");
3433 return register_commands(cmd_ctx, NULL, gdb_command_handlers);