aarch64: use symbolic opcodes instead of hex values
[openocd.git] / src / server / gdb_server.c
blob483e5510b115234d5d4243fa5cb8c9e8d7b6a1e7
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 "server.h"
45 #include <flash/nor/core.h>
46 #include "gdb_server.h"
47 #include <target/image.h>
48 #include <jtag/jtag.h>
49 #include "rtos/rtos.h"
50 #include "target/smp.h"
52 /**
53 * @file
54 * GDB server implementation.
56 * This implements the GDB Remote Serial Protocol, over TCP connections,
57 * giving GDB access to the JTAG or other hardware debugging facilities
58 * found in most modern embedded processors.
61 struct target_desc_format {
62 char *tdesc;
63 uint32_t tdesc_length;
66 /* private connection data for GDB */
67 struct gdb_connection {
68 char buffer[GDB_BUFFER_SIZE];
69 char *buf_p;
70 int buf_cnt;
71 int ctrl_c;
72 enum target_state frontend_state;
73 struct image *vflash_image;
74 int closed;
75 int busy;
76 int noack_mode;
77 /* set flag to true if you want the next stepi to return immediately.
78 * allowing GDB to pick up a fresh set of register values from the target
79 * without modifying the target state. */
80 bool sync;
81 /* We delay reporting memory write errors until next step/continue or memory
82 * write. This improves performance of gdb load significantly as the GDB packet
83 * can be replied immediately and a new GDB packet will be ready without delay
84 * (ca. 10% or so...). */
85 bool mem_write_error;
86 /* with extended-remote it seems we need to better emulate attach/detach.
87 * what this means is we reply with a W stop reply after a kill packet,
88 * normally we reply with a S reply via gdb_last_signal_packet.
89 * as a side note this behaviour only effects gdb > 6.8 */
90 bool attached;
91 /* temporarily used for target description support */
92 struct target_desc_format target_desc;
93 /* temporarily used for thread list support */
94 char *thread_list;
97 #if 0
98 #define _DEBUG_GDB_IO_
99 #endif
101 static struct gdb_connection *current_gdb_connection;
103 static int gdb_breakpoint_override;
104 static enum breakpoint_type gdb_breakpoint_override_type;
106 static int gdb_error(struct connection *connection, int retval);
107 static char *gdb_port;
108 static char *gdb_port_next;
110 static void gdb_log_callback(void *priv, const char *file, unsigned line,
111 const char *function, const char *string);
113 /* number of gdb connections, mainly to suppress gdb related debugging spam
114 * in helper/log.c when no gdb connections are actually active */
115 int gdb_actual_connections;
117 /* set if we are sending a memory map to gdb
118 * via qXfer:memory-map:read packet */
119 /* enabled by default*/
120 static int gdb_use_memory_map = 1;
121 /* enabled by default*/
122 static int gdb_flash_program = 1;
124 /* if set, data aborts cause an error to be reported in memory read packets
125 * see the code in gdb_read_memory_packet() for further explanations.
126 * Disabled by default.
128 static int gdb_report_data_abort;
130 /* set if we are sending target descriptions to gdb
131 * via qXfer:features:read packet */
132 /* enabled by default */
133 static int gdb_use_target_description = 1;
135 /* current processing free-run type, used by file-I/O */
136 static char gdb_running_type;
138 static int gdb_last_signal(struct target *target)
140 switch (target->debug_reason) {
141 case DBG_REASON_DBGRQ:
142 return 0x2; /* SIGINT */
143 case DBG_REASON_BREAKPOINT:
144 case DBG_REASON_WATCHPOINT:
145 case DBG_REASON_WPTANDBKPT:
146 return 0x05; /* SIGTRAP */
147 case DBG_REASON_SINGLESTEP:
148 return 0x05; /* SIGTRAP */
149 case DBG_REASON_NOTHALTED:
150 return 0x0; /* no signal... shouldn't happen */
151 default:
152 LOG_USER("undefined debug reason %d - target needs reset",
153 target->debug_reason);
154 return 0x0;
158 static int check_pending(struct connection *connection,
159 int timeout_s, int *got_data)
161 /* a non-blocking socket will block if there is 0 bytes available on the socket,
162 * but return with as many bytes as are available immediately
164 struct timeval tv;
165 fd_set read_fds;
166 struct gdb_connection *gdb_con = connection->priv;
167 int t;
168 if (got_data == NULL)
169 got_data = &t;
170 *got_data = 0;
172 if (gdb_con->buf_cnt > 0) {
173 *got_data = 1;
174 return ERROR_OK;
177 FD_ZERO(&read_fds);
178 FD_SET(connection->fd, &read_fds);
180 tv.tv_sec = timeout_s;
181 tv.tv_usec = 0;
182 if (socket_select(connection->fd + 1, &read_fds, NULL, NULL, &tv) == 0) {
183 /* This can typically be because a "monitor" command took too long
184 * before printing any progress messages
186 if (timeout_s > 0)
187 return ERROR_GDB_TIMEOUT;
188 else
189 return ERROR_OK;
191 *got_data = FD_ISSET(connection->fd, &read_fds) != 0;
192 return ERROR_OK;
195 static int gdb_get_char_inner(struct connection *connection, int *next_char)
197 struct gdb_connection *gdb_con = connection->priv;
198 int retval = ERROR_OK;
200 #ifdef _DEBUG_GDB_IO_
201 char *debug_buffer;
202 #endif
203 for (;; ) {
204 if (connection->service->type != CONNECTION_TCP)
205 gdb_con->buf_cnt = read(connection->fd, gdb_con->buffer, GDB_BUFFER_SIZE);
206 else {
207 retval = check_pending(connection, 1, NULL);
208 if (retval != ERROR_OK)
209 return retval;
210 gdb_con->buf_cnt = read_socket(connection->fd,
211 gdb_con->buffer,
212 GDB_BUFFER_SIZE);
215 if (gdb_con->buf_cnt > 0)
216 break;
217 if (gdb_con->buf_cnt == 0) {
218 gdb_con->closed = 1;
219 return ERROR_SERVER_REMOTE_CLOSED;
222 #ifdef _WIN32
223 errno = WSAGetLastError();
225 switch (errno) {
226 case WSAEWOULDBLOCK:
227 usleep(1000);
228 break;
229 case WSAECONNABORTED:
230 gdb_con->closed = 1;
231 return ERROR_SERVER_REMOTE_CLOSED;
232 case WSAECONNRESET:
233 gdb_con->closed = 1;
234 return ERROR_SERVER_REMOTE_CLOSED;
235 default:
236 LOG_ERROR("read: %d", errno);
237 exit(-1);
239 #else
240 switch (errno) {
241 case EAGAIN:
242 usleep(1000);
243 break;
244 case ECONNABORTED:
245 gdb_con->closed = 1;
246 return ERROR_SERVER_REMOTE_CLOSED;
247 case ECONNRESET:
248 gdb_con->closed = 1;
249 return ERROR_SERVER_REMOTE_CLOSED;
250 default:
251 LOG_ERROR("read: %s", strerror(errno));
252 gdb_con->closed = 1;
253 return ERROR_SERVER_REMOTE_CLOSED;
255 #endif
258 #ifdef _DEBUG_GDB_IO_
259 debug_buffer = strndup(gdb_con->buffer, gdb_con->buf_cnt);
260 LOG_DEBUG("received '%s'", debug_buffer);
261 free(debug_buffer);
262 #endif
264 gdb_con->buf_p = gdb_con->buffer;
265 gdb_con->buf_cnt--;
266 *next_char = *(gdb_con->buf_p++);
267 if (gdb_con->buf_cnt > 0)
268 connection->input_pending = 1;
269 else
270 connection->input_pending = 0;
271 #ifdef _DEBUG_GDB_IO_
272 LOG_DEBUG("returned char '%c' (0x%2.2x)", *next_char, *next_char);
273 #endif
275 return retval;
279 * The cool thing about this fn is that it allows buf_p and buf_cnt to be
280 * held in registers in the inner loop.
282 * For small caches and embedded systems this is important!
284 static inline int gdb_get_char_fast(struct connection *connection,
285 int *next_char, char **buf_p, int *buf_cnt)
287 int retval = ERROR_OK;
289 if ((*buf_cnt)-- > 0) {
290 *next_char = **buf_p;
291 (*buf_p)++;
292 if (*buf_cnt > 0)
293 connection->input_pending = 1;
294 else
295 connection->input_pending = 0;
297 #ifdef _DEBUG_GDB_IO_
298 LOG_DEBUG("returned char '%c' (0x%2.2x)", *next_char, *next_char);
299 #endif
301 return ERROR_OK;
304 struct gdb_connection *gdb_con = connection->priv;
305 gdb_con->buf_p = *buf_p;
306 gdb_con->buf_cnt = *buf_cnt;
307 retval = gdb_get_char_inner(connection, next_char);
308 *buf_p = gdb_con->buf_p;
309 *buf_cnt = gdb_con->buf_cnt;
311 return retval;
314 static int gdb_get_char(struct connection *connection, int *next_char)
316 struct gdb_connection *gdb_con = connection->priv;
317 return gdb_get_char_fast(connection, next_char, &gdb_con->buf_p, &gdb_con->buf_cnt);
320 static int gdb_putback_char(struct connection *connection, int last_char)
322 struct gdb_connection *gdb_con = connection->priv;
324 if (gdb_con->buf_p > gdb_con->buffer) {
325 *(--gdb_con->buf_p) = last_char;
326 gdb_con->buf_cnt++;
327 } else
328 LOG_ERROR("BUG: couldn't put character back");
330 return ERROR_OK;
333 /* The only way we can detect that the socket is closed is the first time
334 * we write to it, we will fail. Subsequent write operations will
335 * succeed. Shudder! */
336 static int gdb_write(struct connection *connection, void *data, int len)
338 struct gdb_connection *gdb_con = connection->priv;
339 if (gdb_con->closed)
340 return ERROR_SERVER_REMOTE_CLOSED;
342 if (connection_write(connection, data, len) == len)
343 return ERROR_OK;
344 gdb_con->closed = 1;
345 return ERROR_SERVER_REMOTE_CLOSED;
348 static int gdb_put_packet_inner(struct connection *connection,
349 char *buffer, int len)
351 int i;
352 unsigned char my_checksum = 0;
353 #ifdef _DEBUG_GDB_IO_
354 char *debug_buffer;
355 #endif
356 int reply;
357 int retval;
358 struct gdb_connection *gdb_con = connection->priv;
360 for (i = 0; i < len; i++)
361 my_checksum += buffer[i];
363 #ifdef _DEBUG_GDB_IO_
365 * At this point we should have nothing in the input queue from GDB,
366 * however sometimes '-' is sent even though we've already received
367 * an ACK (+) for everything we've sent off.
369 int gotdata;
370 for (;; ) {
371 retval = check_pending(connection, 0, &gotdata);
372 if (retval != ERROR_OK)
373 return retval;
374 if (!gotdata)
375 break;
376 retval = gdb_get_char(connection, &reply);
377 if (retval != ERROR_OK)
378 return retval;
379 if (reply == '$') {
380 /* fix a problem with some IAR tools */
381 gdb_putback_char(connection, reply);
382 LOG_DEBUG("Unexpected start of new packet");
383 break;
386 LOG_WARNING("Discard unexpected char %c", reply);
388 #endif
390 while (1) {
391 #ifdef _DEBUG_GDB_IO_
392 debug_buffer = strndup(buffer, len);
393 LOG_DEBUG("sending packet '$%s#%2.2x'", debug_buffer, my_checksum);
394 free(debug_buffer);
395 #endif
397 char local_buffer[1024];
398 local_buffer[0] = '$';
399 if ((size_t)len + 4 <= sizeof(local_buffer)) {
400 /* performance gain on smaller packets by only a single call to gdb_write() */
401 memcpy(local_buffer + 1, buffer, len++);
402 len += snprintf(local_buffer + len, sizeof(local_buffer) - len, "#%02x", my_checksum);
403 retval = gdb_write(connection, local_buffer, len);
404 if (retval != ERROR_OK)
405 return retval;
406 } else {
407 /* larger packets are transmitted directly from caller supplied buffer
408 * by several calls to gdb_write() to avoid dynamic allocation */
409 snprintf(local_buffer + 1, sizeof(local_buffer) - 1, "#%02x", my_checksum);
410 retval = gdb_write(connection, local_buffer, 1);
411 if (retval != ERROR_OK)
412 return retval;
413 retval = gdb_write(connection, buffer, len);
414 if (retval != ERROR_OK)
415 return retval;
416 retval = gdb_write(connection, local_buffer + 1, 3);
417 if (retval != ERROR_OK)
418 return retval;
421 if (gdb_con->noack_mode)
422 break;
424 retval = gdb_get_char(connection, &reply);
425 if (retval != ERROR_OK)
426 return retval;
428 if (reply == '+')
429 break;
430 else if (reply == '-') {
431 /* Stop sending output packets for now */
432 log_remove_callback(gdb_log_callback, connection);
433 LOG_WARNING("negative reply, retrying");
434 } else if (reply == 0x3) {
435 gdb_con->ctrl_c = 1;
436 retval = gdb_get_char(connection, &reply);
437 if (retval != ERROR_OK)
438 return retval;
439 if (reply == '+')
440 break;
441 else if (reply == '-') {
442 /* Stop sending output packets for now */
443 log_remove_callback(gdb_log_callback, connection);
444 LOG_WARNING("negative reply, retrying");
445 } else if (reply == '$') {
446 LOG_ERROR("GDB missing ack(1) - assumed good");
447 gdb_putback_char(connection, reply);
448 return ERROR_OK;
449 } else {
450 LOG_ERROR("unknown character(1) 0x%2.2x in reply, dropping connection", reply);
451 gdb_con->closed = 1;
452 return ERROR_SERVER_REMOTE_CLOSED;
454 } else if (reply == '$') {
455 LOG_ERROR("GDB missing ack(2) - assumed good");
456 gdb_putback_char(connection, reply);
457 return ERROR_OK;
458 } else {
459 LOG_ERROR("unknown character(2) 0x%2.2x in reply, dropping connection",
460 reply);
461 gdb_con->closed = 1;
462 return ERROR_SERVER_REMOTE_CLOSED;
465 if (gdb_con->closed)
466 return ERROR_SERVER_REMOTE_CLOSED;
468 return ERROR_OK;
471 int gdb_put_packet(struct connection *connection, char *buffer, int len)
473 struct gdb_connection *gdb_con = connection->priv;
474 gdb_con->busy = 1;
475 int retval = gdb_put_packet_inner(connection, buffer, len);
476 gdb_con->busy = 0;
478 /* we sent some data, reset timer for keep alive messages */
479 kept_alive();
481 return retval;
484 static inline int fetch_packet(struct connection *connection,
485 int *checksum_ok, int noack, int *len, char *buffer)
487 unsigned char my_checksum = 0;
488 char checksum[3];
489 int character;
490 int retval = ERROR_OK;
492 struct gdb_connection *gdb_con = connection->priv;
493 my_checksum = 0;
494 int count = 0;
495 count = 0;
497 /* move this over into local variables to use registers and give the
498 * more freedom to optimize */
499 char *buf_p = gdb_con->buf_p;
500 int buf_cnt = gdb_con->buf_cnt;
502 for (;; ) {
503 /* The common case is that we have an entire packet with no escape chars.
504 * We need to leave at least 2 bytes in the buffer to have
505 * gdb_get_char() update various bits and bobs correctly.
507 if ((buf_cnt > 2) && ((buf_cnt + count) < *len)) {
508 /* The compiler will struggle a bit with constant propagation and
509 * aliasing, so we help it by showing that these values do not
510 * change inside the loop
512 int i;
513 char *buf = buf_p;
514 int run = buf_cnt - 2;
515 i = 0;
516 int done = 0;
517 while (i < run) {
518 character = *buf++;
519 i++;
520 if (character == '#') {
521 /* Danger! character can be '#' when esc is
522 * used so we need an explicit boolean for done here. */
523 done = 1;
524 break;
527 if (character == '}') {
528 /* data transmitted in binary mode (X packet)
529 * uses 0x7d as escape character */
530 my_checksum += character & 0xff;
531 character = *buf++;
532 i++;
533 my_checksum += character & 0xff;
534 buffer[count++] = (character ^ 0x20) & 0xff;
535 } else {
536 my_checksum += character & 0xff;
537 buffer[count++] = character & 0xff;
540 buf_p += i;
541 buf_cnt -= i;
542 if (done)
543 break;
545 if (count > *len) {
546 LOG_ERROR("packet buffer too small");
547 retval = ERROR_GDB_BUFFER_TOO_SMALL;
548 break;
551 retval = gdb_get_char_fast(connection, &character, &buf_p, &buf_cnt);
552 if (retval != ERROR_OK)
553 break;
555 if (character == '#')
556 break;
558 if (character == '}') {
559 /* data transmitted in binary mode (X packet)
560 * uses 0x7d as escape character */
561 my_checksum += character & 0xff;
563 retval = gdb_get_char_fast(connection, &character, &buf_p, &buf_cnt);
564 if (retval != ERROR_OK)
565 break;
567 my_checksum += character & 0xff;
568 buffer[count++] = (character ^ 0x20) & 0xff;
569 } else {
570 my_checksum += character & 0xff;
571 buffer[count++] = character & 0xff;
575 gdb_con->buf_p = buf_p;
576 gdb_con->buf_cnt = buf_cnt;
578 if (retval != ERROR_OK)
579 return retval;
581 *len = count;
583 retval = gdb_get_char(connection, &character);
584 if (retval != ERROR_OK)
585 return retval;
586 checksum[0] = character;
587 retval = gdb_get_char(connection, &character);
588 if (retval != ERROR_OK)
589 return retval;
590 checksum[1] = character;
591 checksum[2] = 0;
593 if (!noack)
594 *checksum_ok = (my_checksum == strtoul(checksum, NULL, 16));
596 return ERROR_OK;
599 static int gdb_get_packet_inner(struct connection *connection,
600 char *buffer, int *len)
602 int character;
603 int retval;
604 struct gdb_connection *gdb_con = connection->priv;
606 while (1) {
607 do {
608 retval = gdb_get_char(connection, &character);
609 if (retval != ERROR_OK)
610 return retval;
612 #ifdef _DEBUG_GDB_IO_
613 LOG_DEBUG("character: '%c'", character);
614 #endif
616 switch (character) {
617 case '$':
618 break;
619 case '+':
620 /* According to the GDB documentation
621 * (https://sourceware.org/gdb/onlinedocs/gdb/Packet-Acknowledgment.html):
622 * "gdb sends a final `+` acknowledgment of the stub's `OK`
623 * response, which can be safely ignored by the stub."
624 * However OpenOCD server already is in noack mode at this
625 * point and instead of ignoring this it was emitting a
626 * warning. This code makes server ignore the first ACK
627 * that will be received after going into noack mode,
628 * warning only about subsequent ACK's. */
629 if (gdb_con->noack_mode > 1) {
630 LOG_WARNING("acknowledgment received, but no packet pending");
631 } else if (gdb_con->noack_mode) {
632 LOG_DEBUG("Received first acknowledgment after entering noack mode. Ignoring it.");
633 gdb_con->noack_mode = 2;
635 break;
636 case '-':
637 LOG_WARNING("negative acknowledgment, but no packet pending");
638 break;
639 case 0x3:
640 gdb_con->ctrl_c = 1;
641 *len = 0;
642 return ERROR_OK;
643 default:
644 LOG_WARNING("ignoring character 0x%x", character);
645 break;
647 } while (character != '$');
649 int checksum_ok = 0;
650 /* explicit code expansion here to get faster inlined code in -O3 by not
651 * calculating checksum */
652 if (gdb_con->noack_mode) {
653 retval = fetch_packet(connection, &checksum_ok, 1, len, buffer);
654 if (retval != ERROR_OK)
655 return retval;
656 } else {
657 retval = fetch_packet(connection, &checksum_ok, 0, len, buffer);
658 if (retval != ERROR_OK)
659 return retval;
662 if (gdb_con->noack_mode) {
663 /* checksum is not checked in noack mode */
664 break;
666 if (checksum_ok) {
667 retval = gdb_write(connection, "+", 1);
668 if (retval != ERROR_OK)
669 return retval;
670 break;
673 if (gdb_con->closed)
674 return ERROR_SERVER_REMOTE_CLOSED;
676 return ERROR_OK;
679 static int gdb_get_packet(struct connection *connection, char *buffer, int *len)
681 struct gdb_connection *gdb_con = connection->priv;
682 gdb_con->busy = 1;
683 int retval = gdb_get_packet_inner(connection, buffer, len);
684 gdb_con->busy = 0;
685 return retval;
688 static int gdb_output_con(struct connection *connection, const char *line)
690 char *hex_buffer;
691 int bin_size;
693 bin_size = strlen(line);
695 hex_buffer = malloc(bin_size * 2 + 2);
696 if (hex_buffer == NULL)
697 return ERROR_GDB_BUFFER_TOO_SMALL;
699 hex_buffer[0] = 'O';
700 size_t pkt_len = hexify(hex_buffer + 1, (const uint8_t *)line, bin_size,
701 bin_size * 2 + 1);
702 int retval = gdb_put_packet(connection, hex_buffer, pkt_len + 1);
704 free(hex_buffer);
705 return retval;
708 static int gdb_output(struct command_context *context, const char *line)
710 /* this will be dumped to the log and also sent as an O packet if possible */
711 LOG_USER_N("%s", line);
712 return ERROR_OK;
715 static void gdb_signal_reply(struct target *target, struct connection *connection)
717 struct gdb_connection *gdb_connection = connection->priv;
718 char sig_reply[45];
719 char stop_reason[20];
720 char current_thread[25];
721 int sig_reply_len;
722 int signal_var;
724 rtos_update_threads(target);
726 if (target->debug_reason == DBG_REASON_EXIT) {
727 sig_reply_len = snprintf(sig_reply, sizeof(sig_reply), "W00");
728 } else {
729 if (gdb_connection->ctrl_c) {
730 signal_var = 0x2;
731 gdb_connection->ctrl_c = 0;
732 } else
733 signal_var = gdb_last_signal(target);
735 stop_reason[0] = '\0';
736 if (target->debug_reason == DBG_REASON_WATCHPOINT) {
737 enum watchpoint_rw hit_wp_type;
738 target_addr_t hit_wp_address;
740 if (watchpoint_hit(target, &hit_wp_type, &hit_wp_address) == ERROR_OK) {
742 switch (hit_wp_type) {
743 case WPT_WRITE:
744 snprintf(stop_reason, sizeof(stop_reason),
745 "watch:%08" TARGET_PRIxADDR ";", hit_wp_address);
746 break;
747 case WPT_READ:
748 snprintf(stop_reason, sizeof(stop_reason),
749 "rwatch:%08" TARGET_PRIxADDR ";", hit_wp_address);
750 break;
751 case WPT_ACCESS:
752 snprintf(stop_reason, sizeof(stop_reason),
753 "awatch:%08" TARGET_PRIxADDR ";", hit_wp_address);
754 break;
755 default:
756 break;
761 current_thread[0] = '\0';
762 if (target->rtos != NULL) {
763 snprintf(current_thread, sizeof(current_thread), "thread:%016" PRIx64 ";", target->rtos->current_thread);
764 target->rtos->current_threadid = target->rtos->current_thread;
767 sig_reply_len = snprintf(sig_reply, sizeof(sig_reply), "T%2.2x%s%s",
768 signal_var, stop_reason, current_thread);
771 gdb_put_packet(connection, sig_reply, sig_reply_len);
772 gdb_connection->frontend_state = TARGET_HALTED;
775 static void gdb_fileio_reply(struct target *target, struct connection *connection)
777 struct gdb_connection *gdb_connection = connection->priv;
778 char fileio_command[256];
779 int command_len;
780 bool program_exited = false;
782 if (strcmp(target->fileio_info->identifier, "open") == 0)
783 sprintf(fileio_command, "F%s,%" PRIx32 "/%" PRIx32 ",%" PRIx32 ",%" PRIx32, target->fileio_info->identifier,
784 target->fileio_info->param_1,
785 target->fileio_info->param_2,
786 target->fileio_info->param_3,
787 target->fileio_info->param_4);
788 else if (strcmp(target->fileio_info->identifier, "close") == 0)
789 sprintf(fileio_command, "F%s,%" PRIx32, target->fileio_info->identifier,
790 target->fileio_info->param_1);
791 else if (strcmp(target->fileio_info->identifier, "read") == 0)
792 sprintf(fileio_command, "F%s,%" PRIx32 ",%" PRIx32 ",%" PRIx32, target->fileio_info->identifier,
793 target->fileio_info->param_1,
794 target->fileio_info->param_2,
795 target->fileio_info->param_3);
796 else if (strcmp(target->fileio_info->identifier, "write") == 0)
797 sprintf(fileio_command, "F%s,%" PRIx32 ",%" PRIx32 ",%" PRIx32, target->fileio_info->identifier,
798 target->fileio_info->param_1,
799 target->fileio_info->param_2,
800 target->fileio_info->param_3);
801 else if (strcmp(target->fileio_info->identifier, "lseek") == 0)
802 sprintf(fileio_command, "F%s,%" PRIx32 ",%" PRIx32 ",%" PRIx32, target->fileio_info->identifier,
803 target->fileio_info->param_1,
804 target->fileio_info->param_2,
805 target->fileio_info->param_3);
806 else if (strcmp(target->fileio_info->identifier, "rename") == 0)
807 sprintf(fileio_command, "F%s,%" PRIx32 "/%" PRIx32 ",%" PRIx32 "/%" PRIx32, target->fileio_info->identifier,
808 target->fileio_info->param_1,
809 target->fileio_info->param_2,
810 target->fileio_info->param_3,
811 target->fileio_info->param_4);
812 else if (strcmp(target->fileio_info->identifier, "unlink") == 0)
813 sprintf(fileio_command, "F%s,%" PRIx32 "/%" PRIx32, target->fileio_info->identifier,
814 target->fileio_info->param_1,
815 target->fileio_info->param_2);
816 else if (strcmp(target->fileio_info->identifier, "stat") == 0)
817 sprintf(fileio_command, "F%s,%" PRIx32 "/%" PRIx32 ",%" PRIx32, target->fileio_info->identifier,
818 target->fileio_info->param_1,
819 target->fileio_info->param_2,
820 target->fileio_info->param_3);
821 else if (strcmp(target->fileio_info->identifier, "fstat") == 0)
822 sprintf(fileio_command, "F%s,%" PRIx32 ",%" PRIx32, target->fileio_info->identifier,
823 target->fileio_info->param_1,
824 target->fileio_info->param_2);
825 else if (strcmp(target->fileio_info->identifier, "gettimeofday") == 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, "isatty") == 0)
830 sprintf(fileio_command, "F%s,%" PRIx32, target->fileio_info->identifier,
831 target->fileio_info->param_1);
832 else if (strcmp(target->fileio_info->identifier, "system") == 0)
833 sprintf(fileio_command, "F%s,%" PRIx32 "/%" PRIx32, target->fileio_info->identifier,
834 target->fileio_info->param_1,
835 target->fileio_info->param_2);
836 else if (strcmp(target->fileio_info->identifier, "exit") == 0) {
837 /* If target hits exit syscall, report to GDB the program is terminated.
838 * In addition, let target run its own exit syscall handler. */
839 program_exited = true;
840 sprintf(fileio_command, "W%02" PRIx32, target->fileio_info->param_1);
841 } else {
842 LOG_DEBUG("Unknown syscall: %s", target->fileio_info->identifier);
844 /* encounter unknown syscall, continue */
845 gdb_connection->frontend_state = TARGET_RUNNING;
846 target_resume(target, 1, 0x0, 0, 0);
847 return;
850 command_len = strlen(fileio_command);
851 gdb_put_packet(connection, fileio_command, command_len);
853 if (program_exited) {
854 /* Use target_resume() to let target run its own exit syscall handler. */
855 gdb_connection->frontend_state = TARGET_RUNNING;
856 target_resume(target, 1, 0x0, 0, 0);
857 } else {
858 gdb_connection->frontend_state = TARGET_HALTED;
859 rtos_update_threads(target);
863 static void gdb_frontend_halted(struct target *target, struct connection *connection)
865 struct gdb_connection *gdb_connection = connection->priv;
867 /* In the GDB protocol when we are stepping or continuing execution,
868 * we have a lingering reply. Upon receiving a halted event
869 * when we have that lingering packet, we reply to the original
870 * step or continue packet.
872 * Executing monitor commands can bring the target in and
873 * out of the running state so we'll see lots of TARGET_EVENT_XXX
874 * that are to be ignored.
876 if (gdb_connection->frontend_state == TARGET_RUNNING) {
877 /* stop forwarding log packets! */
878 log_remove_callback(gdb_log_callback, connection);
880 /* check fileio first */
881 if (target_get_gdb_fileio_info(target, target->fileio_info) == ERROR_OK)
882 gdb_fileio_reply(target, connection);
883 else
884 gdb_signal_reply(target, connection);
888 static int gdb_target_callback_event_handler(struct target *target,
889 enum target_event event, void *priv)
891 int retval;
892 struct connection *connection = priv;
893 struct gdb_service *gdb_service = connection->service->priv;
895 if (gdb_service->target != target)
896 return ERROR_OK;
898 switch (event) {
899 case TARGET_EVENT_GDB_HALT:
900 gdb_frontend_halted(target, connection);
901 break;
902 case TARGET_EVENT_HALTED:
903 target_call_event_callbacks(target, TARGET_EVENT_GDB_END);
904 break;
905 case TARGET_EVENT_GDB_FLASH_ERASE_START:
906 retval = jtag_execute_queue();
907 if (retval != ERROR_OK)
908 return retval;
909 break;
910 default:
911 break;
914 return ERROR_OK;
917 static int gdb_new_connection(struct connection *connection)
919 struct gdb_connection *gdb_connection = malloc(sizeof(struct gdb_connection));
920 struct gdb_service *gdb_service = connection->service->priv;
921 int retval;
922 int initial_ack;
924 connection->priv = gdb_connection;
926 /* initialize gdb connection information */
927 gdb_connection->buf_p = gdb_connection->buffer;
928 gdb_connection->buf_cnt = 0;
929 gdb_connection->ctrl_c = 0;
930 gdb_connection->frontend_state = TARGET_HALTED;
931 gdb_connection->vflash_image = NULL;
932 gdb_connection->closed = 0;
933 gdb_connection->busy = 0;
934 gdb_connection->noack_mode = 0;
935 gdb_connection->sync = false;
936 gdb_connection->mem_write_error = false;
937 gdb_connection->attached = true;
938 gdb_connection->target_desc.tdesc = NULL;
939 gdb_connection->target_desc.tdesc_length = 0;
940 gdb_connection->thread_list = NULL;
942 /* send ACK to GDB for debug request */
943 gdb_write(connection, "+", 1);
945 /* output goes through gdb connection */
946 command_set_output_handler(connection->cmd_ctx, gdb_output, connection);
948 /* we must remove all breakpoints registered to the target as a previous
949 * GDB session could leave dangling breakpoints if e.g. communication
950 * timed out.
952 breakpoint_clear_target(gdb_service->target);
953 watchpoint_clear_target(gdb_service->target);
955 /* clean previous rtos session if supported*/
956 if ((gdb_service->target->rtos) && (gdb_service->target->rtos->type->clean))
957 gdb_service->target->rtos->type->clean(gdb_service->target);
959 /* remove the initial ACK from the incoming buffer */
960 retval = gdb_get_char(connection, &initial_ack);
961 if (retval != ERROR_OK)
962 return retval;
964 /* FIX!!!??? would we actually ever receive a + here???
965 * Not observed.
967 if (initial_ack != '+')
968 gdb_putback_char(connection, initial_ack);
969 target_call_event_callbacks(gdb_service->target, TARGET_EVENT_GDB_ATTACH);
971 if (gdb_use_memory_map) {
972 /* Connect must fail if the memory map can't be set up correctly.
974 * This will cause an auto_probe to be invoked, which is either
975 * a no-op or it will fail when the target isn't ready(e.g. not halted).
977 int i;
978 for (i = 0; i < flash_get_bank_count(); i++) {
979 struct flash_bank *p;
980 p = get_flash_bank_by_num_noprobe(i);
981 if (p->target != gdb_service->target)
982 continue;
983 retval = get_flash_bank_by_num(i, &p);
984 if (retval != ERROR_OK) {
985 LOG_ERROR("Connect failed. Consider setting up a gdb-attach event for the target " \
986 "to prepare target for GDB connect, or use 'gdb_memory_map disable'.");
987 return retval;
992 gdb_actual_connections++;
993 LOG_DEBUG("New GDB Connection: %d, Target %s, state: %s",
994 gdb_actual_connections,
995 target_name(gdb_service->target),
996 target_state_name(gdb_service->target));
998 /* DANGER! If we fail subsequently, we must remove this handler,
999 * otherwise we occasionally see crashes as the timer can invoke the
1000 * callback fn.
1002 * register callback to be informed about target events */
1003 target_register_event_callback(gdb_target_callback_event_handler, connection);
1005 return ERROR_OK;
1008 static int gdb_connection_closed(struct connection *connection)
1010 struct gdb_service *gdb_service = connection->service->priv;
1011 struct gdb_connection *gdb_connection = connection->priv;
1013 /* we're done forwarding messages. Tear down callback before
1014 * cleaning up connection.
1016 log_remove_callback(gdb_log_callback, connection);
1018 gdb_actual_connections--;
1019 LOG_DEBUG("GDB Close, Target: %s, state: %s, gdb_actual_connections=%d",
1020 target_name(gdb_service->target),
1021 target_state_name(gdb_service->target),
1022 gdb_actual_connections);
1024 /* see if an image built with vFlash commands is left */
1025 if (gdb_connection->vflash_image) {
1026 image_close(gdb_connection->vflash_image);
1027 free(gdb_connection->vflash_image);
1028 gdb_connection->vflash_image = NULL;
1031 /* if this connection registered a debug-message receiver delete it */
1032 delete_debug_msg_receiver(connection->cmd_ctx, gdb_service->target);
1034 if (connection->priv) {
1035 free(connection->priv);
1036 connection->priv = NULL;
1037 } else
1038 LOG_ERROR("BUG: connection->priv == NULL");
1040 target_unregister_event_callback(gdb_target_callback_event_handler, connection);
1042 target_call_event_callbacks(gdb_service->target, TARGET_EVENT_GDB_END);
1044 target_call_event_callbacks(gdb_service->target, TARGET_EVENT_GDB_DETACH);
1046 return ERROR_OK;
1049 static void gdb_send_error(struct connection *connection, uint8_t the_error)
1051 char err[4];
1052 snprintf(err, 4, "E%2.2X", the_error);
1053 gdb_put_packet(connection, err, 3);
1056 static int gdb_last_signal_packet(struct connection *connection,
1057 char const *packet, int packet_size)
1059 struct target *target = get_target_from_connection(connection);
1060 struct gdb_connection *gdb_con = connection->priv;
1061 char sig_reply[4];
1062 int signal_var;
1064 if (!gdb_con->attached) {
1065 /* if we are here we have received a kill packet
1066 * reply W stop reply otherwise gdb gets very unhappy */
1067 gdb_put_packet(connection, "W00", 3);
1068 return ERROR_OK;
1071 signal_var = gdb_last_signal(target);
1073 snprintf(sig_reply, 4, "S%2.2x", signal_var);
1074 gdb_put_packet(connection, sig_reply, 3);
1076 return ERROR_OK;
1079 static inline int gdb_reg_pos(struct target *target, int pos, int len)
1081 if (target->endianness == TARGET_LITTLE_ENDIAN)
1082 return pos;
1083 else
1084 return len - 1 - pos;
1087 /* Convert register to string of bytes. NB! The # of bits in the
1088 * register might be non-divisible by 8(a byte), in which
1089 * case an entire byte is shown.
1091 * NB! the format on the wire is the target endianness
1093 * The format of reg->value is little endian
1096 static void gdb_str_to_target(struct target *target,
1097 char *tstr, struct reg *reg)
1099 int i;
1101 uint8_t *buf;
1102 int buf_len;
1103 buf = reg->value;
1104 buf_len = DIV_ROUND_UP(reg->size, 8);
1106 for (i = 0; i < buf_len; i++) {
1107 int j = gdb_reg_pos(target, i, buf_len);
1108 tstr += sprintf(tstr, "%02x", buf[j]);
1112 /* copy over in register buffer */
1113 static void gdb_target_to_reg(struct target *target,
1114 char const *tstr, int str_len, uint8_t *bin)
1116 if (str_len % 2) {
1117 LOG_ERROR("BUG: gdb value with uneven number of characters encountered");
1118 exit(-1);
1121 int i;
1122 for (i = 0; i < str_len; i += 2) {
1123 unsigned t;
1124 if (sscanf(tstr + i, "%02x", &t) != 1) {
1125 LOG_ERROR("BUG: unable to convert register value");
1126 exit(-1);
1129 int j = gdb_reg_pos(target, i/2, str_len/2);
1130 bin[j] = t;
1134 static int gdb_get_registers_packet(struct connection *connection,
1135 char const *packet, int packet_size)
1137 struct target *target = get_target_from_connection(connection);
1138 struct reg **reg_list;
1139 int reg_list_size;
1140 int retval;
1141 int reg_packet_size = 0;
1142 char *reg_packet;
1143 char *reg_packet_p;
1144 int i;
1146 #ifdef _DEBUG_GDB_IO_
1147 LOG_DEBUG("-");
1148 #endif
1150 if ((target->rtos != NULL) && (ERROR_OK == rtos_get_gdb_reg_list(connection)))
1151 return ERROR_OK;
1153 retval = target_get_gdb_reg_list(target, &reg_list, &reg_list_size,
1154 REG_CLASS_GENERAL);
1155 if (retval != ERROR_OK)
1156 return gdb_error(connection, retval);
1158 for (i = 0; i < reg_list_size; i++)
1159 reg_packet_size += DIV_ROUND_UP(reg_list[i]->size, 8) * 2;
1161 assert(reg_packet_size > 0);
1163 reg_packet = malloc(reg_packet_size + 1); /* plus one for string termination null */
1164 if (reg_packet == NULL)
1165 return ERROR_FAIL;
1167 reg_packet_p = reg_packet;
1169 for (i = 0; i < reg_list_size; i++) {
1170 if (!reg_list[i]->valid)
1171 reg_list[i]->type->get(reg_list[i]);
1172 gdb_str_to_target(target, reg_packet_p, reg_list[i]);
1173 reg_packet_p += DIV_ROUND_UP(reg_list[i]->size, 8) * 2;
1176 #ifdef _DEBUG_GDB_IO_
1178 char *reg_packet_p_debug;
1179 reg_packet_p_debug = strndup(reg_packet, reg_packet_size);
1180 LOG_DEBUG("reg_packet: %s", reg_packet_p_debug);
1181 free(reg_packet_p_debug);
1183 #endif
1185 gdb_put_packet(connection, reg_packet, reg_packet_size);
1186 free(reg_packet);
1188 free(reg_list);
1190 return ERROR_OK;
1193 static int gdb_set_registers_packet(struct connection *connection,
1194 char const *packet, int packet_size)
1196 struct target *target = get_target_from_connection(connection);
1197 int i;
1198 struct reg **reg_list;
1199 int reg_list_size;
1200 int retval;
1201 char const *packet_p;
1203 #ifdef _DEBUG_GDB_IO_
1204 LOG_DEBUG("-");
1205 #endif
1207 /* skip command character */
1208 packet++;
1209 packet_size--;
1211 if (packet_size % 2) {
1212 LOG_WARNING("GDB set_registers packet with uneven characters received, dropping connection");
1213 return ERROR_SERVER_REMOTE_CLOSED;
1216 retval = target_get_gdb_reg_list(target, &reg_list, &reg_list_size,
1217 REG_CLASS_GENERAL);
1218 if (retval != ERROR_OK)
1219 return gdb_error(connection, retval);
1221 packet_p = packet;
1222 for (i = 0; i < reg_list_size; i++) {
1223 uint8_t *bin_buf;
1224 int chars = (DIV_ROUND_UP(reg_list[i]->size, 8) * 2);
1226 if (packet_p + chars > packet + packet_size)
1227 LOG_ERROR("BUG: register packet is too small for registers");
1229 bin_buf = malloc(DIV_ROUND_UP(reg_list[i]->size, 8));
1230 gdb_target_to_reg(target, packet_p, chars, bin_buf);
1232 reg_list[i]->type->set(reg_list[i], bin_buf);
1234 /* advance packet pointer */
1235 packet_p += chars;
1237 free(bin_buf);
1240 /* free struct reg *reg_list[] array allocated by get_gdb_reg_list */
1241 free(reg_list);
1243 gdb_put_packet(connection, "OK", 2);
1245 return ERROR_OK;
1248 static int gdb_get_register_packet(struct connection *connection,
1249 char const *packet, int packet_size)
1251 struct target *target = get_target_from_connection(connection);
1252 char *reg_packet;
1253 int reg_num = strtoul(packet + 1, NULL, 16);
1254 struct reg **reg_list;
1255 int reg_list_size;
1256 int retval;
1258 #ifdef _DEBUG_GDB_IO_
1259 LOG_DEBUG("-");
1260 #endif
1262 retval = target_get_gdb_reg_list(target, &reg_list, &reg_list_size,
1263 REG_CLASS_ALL);
1264 if (retval != ERROR_OK)
1265 return gdb_error(connection, retval);
1267 if (reg_list_size <= reg_num) {
1268 LOG_ERROR("gdb requested a non-existing register");
1269 return ERROR_SERVER_REMOTE_CLOSED;
1272 if (!reg_list[reg_num]->valid)
1273 reg_list[reg_num]->type->get(reg_list[reg_num]);
1275 reg_packet = malloc(DIV_ROUND_UP(reg_list[reg_num]->size, 8) * 2 + 1); /* plus one for string termination null */
1277 gdb_str_to_target(target, reg_packet, reg_list[reg_num]);
1279 gdb_put_packet(connection, reg_packet, DIV_ROUND_UP(reg_list[reg_num]->size, 8) * 2);
1281 free(reg_list);
1282 free(reg_packet);
1284 return ERROR_OK;
1287 static int gdb_set_register_packet(struct connection *connection,
1288 char const *packet, int packet_size)
1290 struct target *target = get_target_from_connection(connection);
1291 char *separator;
1292 uint8_t *bin_buf;
1293 int reg_num = strtoul(packet + 1, &separator, 16);
1294 struct reg **reg_list;
1295 int reg_list_size;
1296 int retval;
1298 LOG_DEBUG("-");
1300 retval = target_get_gdb_reg_list(target, &reg_list, &reg_list_size,
1301 REG_CLASS_ALL);
1302 if (retval != ERROR_OK)
1303 return gdb_error(connection, retval);
1305 if (reg_list_size <= reg_num) {
1306 LOG_ERROR("gdb requested a non-existing register");
1307 return ERROR_SERVER_REMOTE_CLOSED;
1310 if (*separator != '=') {
1311 LOG_ERROR("GDB 'set register packet', but no '=' following the register number");
1312 return ERROR_SERVER_REMOTE_CLOSED;
1315 /* convert from GDB-string (target-endian) to hex-string (big-endian) */
1316 bin_buf = malloc(DIV_ROUND_UP(reg_list[reg_num]->size, 8));
1317 int chars = (DIV_ROUND_UP(reg_list[reg_num]->size, 8) * 2);
1319 if ((unsigned int)chars != strlen(separator + 1)) {
1320 LOG_ERROR("gdb sent a packet with wrong register size");
1321 free(bin_buf);
1322 return ERROR_SERVER_REMOTE_CLOSED;
1325 gdb_target_to_reg(target, separator + 1, chars, bin_buf);
1327 reg_list[reg_num]->type->set(reg_list[reg_num], bin_buf);
1329 gdb_put_packet(connection, "OK", 2);
1331 free(bin_buf);
1332 free(reg_list);
1334 return ERROR_OK;
1337 /* No attempt is made to translate the "retval" to
1338 * GDB speak. This has to be done at the calling
1339 * site as no mapping really exists.
1341 static int gdb_error(struct connection *connection, int retval)
1343 LOG_DEBUG("Reporting %i to GDB as generic error", retval);
1344 gdb_send_error(connection, EFAULT);
1345 return ERROR_OK;
1348 /* We don't have to worry about the default 2 second timeout for GDB packets,
1349 * because GDB breaks up large memory reads into smaller reads.
1351 * 8191 bytes by the looks of it. Why 8191 bytes instead of 8192?????
1353 static int gdb_read_memory_packet(struct connection *connection,
1354 char const *packet, int packet_size)
1356 struct target *target = get_target_from_connection(connection);
1357 char *separator;
1358 uint64_t addr = 0;
1359 uint32_t len = 0;
1361 uint8_t *buffer;
1362 char *hex_buffer;
1364 int retval = ERROR_OK;
1366 /* skip command character */
1367 packet++;
1369 addr = strtoull(packet, &separator, 16);
1371 if (*separator != ',') {
1372 LOG_ERROR("incomplete read memory packet received, dropping connection");
1373 return ERROR_SERVER_REMOTE_CLOSED;
1376 len = strtoul(separator + 1, NULL, 16);
1378 if (!len) {
1379 LOG_WARNING("invalid read memory packet received (len == 0)");
1380 gdb_put_packet(connection, NULL, 0);
1381 return ERROR_OK;
1384 buffer = malloc(len);
1386 LOG_DEBUG("addr: 0x%16.16" PRIx64 ", len: 0x%8.8" PRIx32 "", addr, len);
1388 retval = target_read_buffer(target, addr, len, buffer);
1390 if ((retval != ERROR_OK) && !gdb_report_data_abort) {
1391 /* TODO : Here we have to lie and send back all zero's lest stack traces won't work.
1392 * At some point this might be fixed in GDB, in which case this code can be removed.
1394 * OpenOCD developers are acutely aware of this problem, but there is nothing
1395 * gained by involving the user in this problem that hopefully will get resolved
1396 * eventually
1398 * http://sourceware.org/cgi-bin/gnatsweb.pl? \
1399 * cmd = view%20audit-trail&database = gdb&pr = 2395
1401 * For now, the default is to fix up things to make current GDB versions work.
1402 * This can be overwritten using the gdb_report_data_abort <'enable'|'disable'> command.
1404 memset(buffer, 0, len);
1405 retval = ERROR_OK;
1408 if (retval == ERROR_OK) {
1409 hex_buffer = malloc(len * 2 + 1);
1411 size_t pkt_len = hexify(hex_buffer, buffer, len, len * 2 + 1);
1413 gdb_put_packet(connection, hex_buffer, pkt_len);
1415 free(hex_buffer);
1416 } else
1417 retval = gdb_error(connection, retval);
1419 free(buffer);
1421 return retval;
1424 static int gdb_write_memory_packet(struct connection *connection,
1425 char const *packet, int packet_size)
1427 struct target *target = get_target_from_connection(connection);
1428 char *separator;
1429 uint64_t addr = 0;
1430 uint32_t len = 0;
1432 uint8_t *buffer;
1433 int retval;
1435 /* skip command character */
1436 packet++;
1438 addr = strtoull(packet, &separator, 16);
1440 if (*separator != ',') {
1441 LOG_ERROR("incomplete write memory packet received, dropping connection");
1442 return ERROR_SERVER_REMOTE_CLOSED;
1445 len = strtoul(separator + 1, &separator, 16);
1447 if (*(separator++) != ':') {
1448 LOG_ERROR("incomplete write memory packet received, dropping connection");
1449 return ERROR_SERVER_REMOTE_CLOSED;
1452 buffer = malloc(len);
1454 LOG_DEBUG("addr: 0x%" PRIx64 ", len: 0x%8.8" PRIx32 "", addr, len);
1456 if (unhexify(buffer, separator, len) != len)
1457 LOG_ERROR("unable to decode memory packet");
1459 retval = target_write_buffer(target, addr, len, buffer);
1461 if (retval == ERROR_OK)
1462 gdb_put_packet(connection, "OK", 2);
1463 else
1464 retval = gdb_error(connection, retval);
1466 free(buffer);
1468 return retval;
1471 static int gdb_write_memory_binary_packet(struct connection *connection,
1472 char const *packet, int packet_size)
1474 struct target *target = get_target_from_connection(connection);
1475 char *separator;
1476 uint64_t addr = 0;
1477 uint32_t len = 0;
1479 int retval = ERROR_OK;
1480 /* Packets larger than fast_limit bytes will be acknowledged instantly on
1481 * the assumption that we're in a download and it's important to go as fast
1482 * as possible. */
1483 uint32_t fast_limit = 8;
1485 /* skip command character */
1486 packet++;
1488 addr = strtoull(packet, &separator, 16);
1490 if (*separator != ',') {
1491 LOG_ERROR("incomplete write memory binary packet received, dropping connection");
1492 return ERROR_SERVER_REMOTE_CLOSED;
1495 len = strtoul(separator + 1, &separator, 16);
1497 if (*(separator++) != ':') {
1498 LOG_ERROR("incomplete write memory binary packet received, dropping connection");
1499 return ERROR_SERVER_REMOTE_CLOSED;
1502 struct gdb_connection *gdb_connection = connection->priv;
1504 if (gdb_connection->mem_write_error)
1505 retval = ERROR_FAIL;
1507 if (retval == ERROR_OK) {
1508 if (len >= fast_limit) {
1509 /* By replying the packet *immediately* GDB will send us a new packet
1510 * while we write the last one to the target.
1511 * We only do this for larger writes, so that users who do something like:
1512 * p *((int*)0xdeadbeef)=8675309
1513 * will get immediate feedback that that write failed.
1515 gdb_put_packet(connection, "OK", 2);
1517 } else {
1518 retval = gdb_error(connection, retval);
1519 /* now that we have reported the memory write error, we can clear the condition */
1520 gdb_connection->mem_write_error = false;
1521 if (retval != ERROR_OK)
1522 return retval;
1525 if (len) {
1526 LOG_DEBUG("addr: 0x%" PRIx64 ", len: 0x%8.8" PRIx32 "", addr, len);
1528 retval = target_write_buffer(target, addr, len, (uint8_t *)separator);
1529 if (retval != ERROR_OK)
1530 gdb_connection->mem_write_error = true;
1533 if (len < fast_limit) {
1534 if (retval != ERROR_OK) {
1535 gdb_error(connection, retval);
1536 gdb_connection->mem_write_error = false;
1537 } else {
1538 gdb_put_packet(connection, "OK", 2);
1542 return ERROR_OK;
1545 static int gdb_step_continue_packet(struct connection *connection,
1546 char const *packet, int packet_size)
1548 struct target *target = get_target_from_connection(connection);
1549 int current = 0;
1550 uint64_t address = 0x0;
1551 int retval = ERROR_OK;
1553 LOG_DEBUG("-");
1555 if (packet_size > 1)
1556 address = strtoull(packet + 1, NULL, 16);
1557 else
1558 current = 1;
1560 gdb_running_type = packet[0];
1561 if (packet[0] == 'c') {
1562 LOG_DEBUG("continue");
1563 /* resume at current address, don't handle breakpoints, not debugging */
1564 retval = target_resume(target, current, address, 0, 0);
1565 } else if (packet[0] == 's') {
1566 LOG_DEBUG("step");
1567 /* step at current or address, don't handle breakpoints */
1568 retval = target_step(target, current, address, 0);
1570 return retval;
1573 static int gdb_breakpoint_watchpoint_packet(struct connection *connection,
1574 char const *packet, int packet_size)
1576 struct target *target = get_target_from_connection(connection);
1577 int type;
1578 enum breakpoint_type bp_type = BKPT_SOFT /* dummy init to avoid warning */;
1579 enum watchpoint_rw wp_type = WPT_READ /* dummy init to avoid warning */;
1580 uint64_t address;
1581 uint32_t size;
1582 char *separator;
1583 int retval;
1585 LOG_DEBUG("-");
1587 type = strtoul(packet + 1, &separator, 16);
1589 if (type == 0) /* memory breakpoint */
1590 bp_type = BKPT_SOFT;
1591 else if (type == 1) /* hardware breakpoint */
1592 bp_type = BKPT_HARD;
1593 else if (type == 2) /* write watchpoint */
1594 wp_type = WPT_WRITE;
1595 else if (type == 3) /* read watchpoint */
1596 wp_type = WPT_READ;
1597 else if (type == 4) /* access watchpoint */
1598 wp_type = WPT_ACCESS;
1599 else {
1600 LOG_ERROR("invalid gdb watch/breakpoint type(%d), dropping connection", type);
1601 return ERROR_SERVER_REMOTE_CLOSED;
1604 if (gdb_breakpoint_override && ((bp_type == BKPT_SOFT) || (bp_type == BKPT_HARD)))
1605 bp_type = gdb_breakpoint_override_type;
1607 if (*separator != ',') {
1608 LOG_ERROR("incomplete breakpoint/watchpoint packet received, dropping connection");
1609 return ERROR_SERVER_REMOTE_CLOSED;
1612 address = strtoull(separator + 1, &separator, 16);
1614 if (*separator != ',') {
1615 LOG_ERROR("incomplete breakpoint/watchpoint packet received, dropping connection");
1616 return ERROR_SERVER_REMOTE_CLOSED;
1619 size = strtoul(separator + 1, &separator, 16);
1621 switch (type) {
1622 case 0:
1623 case 1:
1624 if (packet[0] == 'Z') {
1625 retval = breakpoint_add(target, address, size, bp_type);
1626 if (retval != ERROR_OK) {
1627 retval = gdb_error(connection, retval);
1628 if (retval != ERROR_OK)
1629 return retval;
1630 } else
1631 gdb_put_packet(connection, "OK", 2);
1632 } else {
1633 breakpoint_remove(target, address);
1634 gdb_put_packet(connection, "OK", 2);
1636 break;
1637 case 2:
1638 case 3:
1639 case 4:
1641 if (packet[0] == 'Z') {
1642 retval = watchpoint_add(target, address, size, wp_type, 0, 0xffffffffu);
1643 if (retval != ERROR_OK) {
1644 retval = gdb_error(connection, retval);
1645 if (retval != ERROR_OK)
1646 return retval;
1647 } else
1648 gdb_put_packet(connection, "OK", 2);
1649 } else {
1650 watchpoint_remove(target, address);
1651 gdb_put_packet(connection, "OK", 2);
1653 break;
1655 default:
1656 break;
1659 return ERROR_OK;
1662 /* print out a string and allocate more space as needed,
1663 * mainly used for XML at this point
1665 static void xml_printf(int *retval, char **xml, int *pos, int *size,
1666 const char *fmt, ...)
1668 if (*retval != ERROR_OK)
1669 return;
1670 int first = 1;
1672 for (;; ) {
1673 if ((*xml == NULL) || (!first)) {
1674 /* start by 0 to exercise all the code paths.
1675 * Need minimum 2 bytes to fit 1 char and 0 terminator. */
1677 *size = *size * 2 + 2;
1678 char *t = *xml;
1679 *xml = realloc(*xml, *size);
1680 if (*xml == NULL) {
1681 if (t)
1682 free(t);
1683 *retval = ERROR_SERVER_REMOTE_CLOSED;
1684 return;
1688 va_list ap;
1689 int ret;
1690 va_start(ap, fmt);
1691 ret = vsnprintf(*xml + *pos, *size - *pos, fmt, ap);
1692 va_end(ap);
1693 if ((ret > 0) && ((ret + 1) < *size - *pos)) {
1694 *pos += ret;
1695 return;
1697 /* there was just enough or not enough space, allocate more. */
1698 first = 0;
1702 static int decode_xfer_read(char const *buf, char **annex, int *ofs, unsigned int *len)
1704 /* Locate the annex. */
1705 const char *annex_end = strchr(buf, ':');
1706 if (annex_end == NULL)
1707 return ERROR_FAIL;
1709 /* After the read marker and annex, qXfer looks like a
1710 * traditional 'm' packet. */
1711 char *separator;
1712 *ofs = strtoul(annex_end + 1, &separator, 16);
1714 if (*separator != ',')
1715 return ERROR_FAIL;
1717 *len = strtoul(separator + 1, NULL, 16);
1719 /* Extract the annex if needed */
1720 if (annex != NULL) {
1721 *annex = strndup(buf, annex_end - buf);
1722 if (*annex == NULL)
1723 return ERROR_FAIL;
1726 return ERROR_OK;
1729 static int compare_bank(const void *a, const void *b)
1731 struct flash_bank *b1, *b2;
1732 b1 = *((struct flash_bank **)a);
1733 b2 = *((struct flash_bank **)b);
1735 if (b1->base == b2->base)
1736 return 0;
1737 else if (b1->base > b2->base)
1738 return 1;
1739 else
1740 return -1;
1743 static int gdb_memory_map(struct connection *connection,
1744 char const *packet, int packet_size)
1746 /* We get away with only specifying flash here. Regions that are not
1747 * specified are treated as if we provided no memory map(if not we
1748 * could detect the holes and mark them as RAM).
1749 * Normally we only execute this code once, but no big deal if we
1750 * have to regenerate it a couple of times.
1753 struct target *target = get_target_from_connection(connection);
1754 struct flash_bank *p;
1755 char *xml = NULL;
1756 int size = 0;
1757 int pos = 0;
1758 int retval = ERROR_OK;
1759 struct flash_bank **banks;
1760 int offset;
1761 int length;
1762 char *separator;
1763 uint32_t ram_start = 0;
1764 int i;
1765 int target_flash_banks = 0;
1767 /* skip command character */
1768 packet += 23;
1770 offset = strtoul(packet, &separator, 16);
1771 length = strtoul(separator + 1, &separator, 16);
1773 xml_printf(&retval, &xml, &pos, &size, "<memory-map>\n");
1775 /* Sort banks in ascending order. We need to report non-flash
1776 * memory as ram (or rather read/write) by default for GDB, since
1777 * it has no concept of non-cacheable read/write memory (i/o etc).
1779 * FIXME Most non-flash addresses are *NOT* RAM! Don't lie.
1780 * Current versions of GDB assume unlisted addresses are RAM...
1782 banks = malloc(sizeof(struct flash_bank *)*flash_get_bank_count());
1784 for (i = 0; i < flash_get_bank_count(); i++) {
1785 p = get_flash_bank_by_num_noprobe(i);
1786 if (p->target != target)
1787 continue;
1788 retval = get_flash_bank_by_num(i, &p);
1789 if (retval != ERROR_OK) {
1790 free(banks);
1791 gdb_error(connection, retval);
1792 return retval;
1794 banks[target_flash_banks++] = p;
1797 qsort(banks, target_flash_banks, sizeof(struct flash_bank *),
1798 compare_bank);
1800 for (i = 0; i < target_flash_banks; i++) {
1801 int j;
1802 unsigned sector_size = 0;
1803 uint32_t start;
1805 p = banks[i];
1806 start = p->base;
1808 if (ram_start < p->base)
1809 xml_printf(&retval, &xml, &pos, &size,
1810 "<memory type=\"ram\" start=\"0x%x\" "
1811 "length=\"0x%x\"/>\n",
1812 ram_start, p->base - ram_start);
1814 /* Report adjacent groups of same-size sectors. So for
1815 * example top boot CFI flash will list an initial region
1816 * with several large sectors (maybe 128KB) and several
1817 * smaller ones at the end (maybe 32KB). STR7 will have
1818 * regions with 8KB, 32KB, and 64KB sectors; etc.
1820 for (j = 0; j < p->num_sectors; j++) {
1821 unsigned group_len;
1823 /* Maybe start a new group of sectors. */
1824 if (sector_size == 0) {
1825 start = p->base + p->sectors[j].offset;
1826 xml_printf(&retval, &xml, &pos, &size,
1827 "<memory type=\"flash\" "
1828 "start=\"0x%x\" ",
1829 start);
1830 sector_size = p->sectors[j].size;
1833 /* Does this finish a group of sectors?
1834 * If not, continue an already-started group.
1836 if (j == p->num_sectors - 1)
1837 group_len = (p->base + p->size) - start;
1838 else if (p->sectors[j + 1].size != sector_size)
1839 group_len = p->base + p->sectors[j + 1].offset
1840 - start;
1841 else
1842 continue;
1844 xml_printf(&retval, &xml, &pos, &size,
1845 "length=\"0x%x\">\n"
1846 "<property name=\"blocksize\">"
1847 "0x%x</property>\n"
1848 "</memory>\n",
1849 group_len,
1850 sector_size);
1851 sector_size = 0;
1854 ram_start = p->base + p->size;
1857 if (ram_start != 0)
1858 xml_printf(&retval, &xml, &pos, &size,
1859 "<memory type=\"ram\" start=\"0x%x\" "
1860 "length=\"0x%x\"/>\n",
1861 ram_start, 0-ram_start);
1862 /* ELSE a flash chip could be at the very end of the 32 bit address
1863 * space, in which case ram_start will be precisely 0
1866 free(banks);
1867 banks = NULL;
1869 xml_printf(&retval, &xml, &pos, &size, "</memory-map>\n");
1871 if (retval != ERROR_OK) {
1872 gdb_error(connection, retval);
1873 return retval;
1876 if (offset + length > pos)
1877 length = pos - offset;
1879 char *t = malloc(length + 1);
1880 t[0] = 'l';
1881 memcpy(t + 1, xml + offset, length);
1882 gdb_put_packet(connection, t, length + 1);
1884 free(t);
1885 free(xml);
1886 return ERROR_OK;
1889 static const char *gdb_get_reg_type_name(enum reg_type type)
1891 switch (type) {
1892 case REG_TYPE_INT:
1893 return "int";
1894 case REG_TYPE_INT8:
1895 return "int8";
1896 case REG_TYPE_INT16:
1897 return "int16";
1898 case REG_TYPE_INT32:
1899 return "int32";
1900 case REG_TYPE_INT64:
1901 return "int64";
1902 case REG_TYPE_INT128:
1903 return "int128";
1904 case REG_TYPE_UINT8:
1905 return "uint8";
1906 case REG_TYPE_UINT16:
1907 return "uint16";
1908 case REG_TYPE_UINT32:
1909 return "uint32";
1910 case REG_TYPE_UINT64:
1911 return "uint64";
1912 case REG_TYPE_UINT128:
1913 return "uint128";
1914 case REG_TYPE_CODE_PTR:
1915 return "code_ptr";
1916 case REG_TYPE_DATA_PTR:
1917 return "data_ptr";
1918 case REG_TYPE_FLOAT:
1919 return "float";
1920 case REG_TYPE_IEEE_SINGLE:
1921 return "ieee_single";
1922 case REG_TYPE_IEEE_DOUBLE:
1923 return "ieee_double";
1924 case REG_TYPE_ARCH_DEFINED:
1925 return "int"; /* return arbitrary string to avoid compile warning. */
1928 return "int"; /* "int" as default value */
1931 static int gdb_generate_reg_type_description(struct target *target,
1932 char **tdesc, int *pos, int *size, struct reg_data_type *type)
1934 int retval = ERROR_OK;
1936 if (type->type_class == REG_TYPE_CLASS_VECTOR) {
1937 /* <vector id="id" type="type" count="count"/> */
1938 xml_printf(&retval, tdesc, pos, size,
1939 "<vector id=\"%s\" type=\"%s\" count=\"%d\"/>\n",
1940 type->id, type->reg_type_vector->type->id,
1941 type->reg_type_vector->count);
1943 } else if (type->type_class == REG_TYPE_CLASS_UNION) {
1944 /* <union id="id">
1945 * <field name="name" type="type"/> ...
1946 * </union> */
1947 xml_printf(&retval, tdesc, pos, size,
1948 "<union id=\"%s\">\n",
1949 type->id);
1951 struct reg_data_type_union_field *field;
1952 field = type->reg_type_union->fields;
1953 while (field != NULL) {
1954 xml_printf(&retval, tdesc, pos, size,
1955 "<field name=\"%s\" type=\"%s\"/>\n",
1956 field->name, field->type->id);
1958 field = field->next;
1961 xml_printf(&retval, tdesc, pos, size,
1962 "</union>\n");
1964 } else if (type->type_class == REG_TYPE_CLASS_STRUCT) {
1965 struct reg_data_type_struct_field *field;
1966 field = type->reg_type_struct->fields;
1968 if (field->use_bitfields) {
1969 /* <struct id="id" size="size">
1970 * <field name="name" start="start" end="end"/> ...
1971 * </struct> */
1972 xml_printf(&retval, tdesc, pos, size,
1973 "<struct id=\"%s\" size=\"%d\">\n",
1974 type->id, type->reg_type_struct->size);
1975 while (field != NULL) {
1976 xml_printf(&retval, tdesc, pos, size,
1977 "<field name=\"%s\" start=\"%d\" end=\"%d\"/>\n",
1978 field->name, field->bitfield->start,
1979 field->bitfield->end);
1981 field = field->next;
1983 } else {
1984 /* <struct id="id">
1985 * <field name="name" type="type"/> ...
1986 * </struct> */
1987 xml_printf(&retval, tdesc, pos, size,
1988 "<struct id=\"%s\">\n",
1989 type->id);
1990 while (field != NULL) {
1991 xml_printf(&retval, tdesc, pos, size,
1992 "<field name=\"%s\" type=\"%s\"/>\n",
1993 field->name, field->type->id);
1995 field = field->next;
1999 xml_printf(&retval, tdesc, pos, size,
2000 "</struct>\n");
2002 } else if (type->type_class == REG_TYPE_CLASS_FLAGS) {
2003 /* <flags id="id" size="size">
2004 * <field name="name" start="start" end="end"/> ...
2005 * </flags> */
2006 xml_printf(&retval, tdesc, pos, size,
2007 "<flags id=\"%s\" size=\"%d\">\n",
2008 type->id, type->reg_type_flags->size);
2010 struct reg_data_type_flags_field *field;
2011 field = type->reg_type_flags->fields;
2012 while (field != NULL) {
2013 xml_printf(&retval, tdesc, pos, size,
2014 "<field name=\"%s\" start=\"%d\" end=\"%d\"/>\n",
2015 field->name, field->bitfield->start, field->bitfield->end);
2017 field = field->next;
2020 xml_printf(&retval, tdesc, pos, size,
2021 "</flags>\n");
2025 return ERROR_OK;
2028 /* Get a list of available target registers features. feature_list must
2029 * be freed by caller.
2031 static int get_reg_features_list(struct target *target, char const **feature_list[], int *feature_list_size,
2032 struct reg **reg_list, int reg_list_size)
2034 int tbl_sz = 0;
2036 /* Start with only one element */
2037 *feature_list = calloc(1, sizeof(char *));
2039 for (int i = 0; i < reg_list_size; i++) {
2040 if (reg_list[i]->exist == false)
2041 continue;
2043 if (reg_list[i]->feature != NULL
2044 && reg_list[i]->feature->name != NULL
2045 && (strcmp(reg_list[i]->feature->name, ""))) {
2046 /* We found a feature, check if the feature is already in the
2047 * table. If not, allocate a new entry for the table and
2048 * put the new feature in it.
2050 for (int j = 0; j < (tbl_sz + 1); j++) {
2051 if (!((*feature_list)[j])) {
2052 (*feature_list)[tbl_sz++] = reg_list[i]->feature->name;
2053 *feature_list = realloc(*feature_list, sizeof(char *) * (tbl_sz + 1));
2054 (*feature_list)[tbl_sz] = NULL;
2055 break;
2056 } else {
2057 if (!strcmp((*feature_list)[j], reg_list[i]->feature->name))
2058 break;
2064 if (feature_list_size)
2065 *feature_list_size = tbl_sz;
2067 return ERROR_OK;
2070 static int gdb_generate_target_description(struct target *target, char **tdesc_out)
2072 int retval = ERROR_OK;
2073 struct reg **reg_list = NULL;
2074 int reg_list_size;
2075 char const **features = NULL;
2076 int feature_list_size = 0;
2077 char *tdesc = NULL;
2078 int pos = 0;
2079 int size = 0;
2081 retval = target_get_gdb_reg_list(target, &reg_list,
2082 &reg_list_size, REG_CLASS_ALL);
2084 if (retval != ERROR_OK) {
2085 LOG_ERROR("get register list failed");
2086 retval = ERROR_FAIL;
2087 goto error;
2090 if (reg_list_size <= 0) {
2091 LOG_ERROR("get register list failed");
2092 retval = ERROR_FAIL;
2093 goto error;
2096 /* Get a list of available target registers features */
2097 retval = get_reg_features_list(target, &features, &feature_list_size, reg_list, reg_list_size);
2098 if (retval != ERROR_OK) {
2099 LOG_ERROR("Can't get the registers feature list");
2100 retval = ERROR_FAIL;
2101 goto error;
2104 /* If we found some features associated with registers, create sections */
2105 int current_feature = 0;
2107 xml_printf(&retval, &tdesc, &pos, &size,
2108 "<?xml version=\"1.0\"?>\n"
2109 "<!DOCTYPE target SYSTEM \"gdb-target.dtd\">\n"
2110 "<target version=\"1.0\">\n");
2112 /* generate target description according to register list */
2113 if (features != NULL) {
2114 while (features[current_feature]) {
2116 xml_printf(&retval, &tdesc, &pos, &size,
2117 "<feature name=\"%s\">\n",
2118 features[current_feature]);
2120 int i;
2121 for (i = 0; i < reg_list_size; i++) {
2123 if (reg_list[i]->exist == false)
2124 continue;
2126 if (strcmp(reg_list[i]->feature->name, features[current_feature]))
2127 continue;
2129 const char *type_str;
2130 if (reg_list[i]->reg_data_type != NULL) {
2131 if (reg_list[i]->reg_data_type->type == REG_TYPE_ARCH_DEFINED) {
2132 /* generate <type... first, if there are architecture-defined types. */
2133 gdb_generate_reg_type_description(target, &tdesc, &pos, &size,
2134 reg_list[i]->reg_data_type);
2136 type_str = reg_list[i]->reg_data_type->id;
2137 } else {
2138 /* predefined type */
2139 type_str = gdb_get_reg_type_name(
2140 reg_list[i]->reg_data_type->type);
2142 } else {
2143 /* Default type is "int" */
2144 type_str = "int";
2147 xml_printf(&retval, &tdesc, &pos, &size,
2148 "<reg name=\"%s\"", reg_list[i]->name);
2149 xml_printf(&retval, &tdesc, &pos, &size,
2150 " bitsize=\"%d\"", reg_list[i]->size);
2151 xml_printf(&retval, &tdesc, &pos, &size,
2152 " regnum=\"%d\"", reg_list[i]->number);
2153 if (reg_list[i]->caller_save)
2154 xml_printf(&retval, &tdesc, &pos, &size,
2155 " save-restore=\"yes\"");
2156 else
2157 xml_printf(&retval, &tdesc, &pos, &size,
2158 " save-restore=\"no\"");
2160 xml_printf(&retval, &tdesc, &pos, &size,
2161 " type=\"%s\"", type_str);
2163 if (reg_list[i]->group != NULL)
2164 xml_printf(&retval, &tdesc, &pos, &size,
2165 " group=\"%s\"", reg_list[i]->group);
2167 xml_printf(&retval, &tdesc, &pos, &size,
2168 "/>\n");
2171 xml_printf(&retval, &tdesc, &pos, &size,
2172 "</feature>\n");
2174 current_feature++;
2178 xml_printf(&retval, &tdesc, &pos, &size,
2179 "</target>\n");
2181 error:
2182 free(features);
2183 free(reg_list);
2185 if (retval == ERROR_OK)
2186 *tdesc_out = tdesc;
2187 else
2188 free(tdesc);
2190 return retval;
2193 static int gdb_get_target_description_chunk(struct target *target, struct target_desc_format *target_desc,
2194 char **chunk, int32_t offset, uint32_t length)
2196 if (target_desc == NULL) {
2197 LOG_ERROR("Unable to Generate Target Description");
2198 return ERROR_FAIL;
2201 char *tdesc = target_desc->tdesc;
2202 uint32_t tdesc_length = target_desc->tdesc_length;
2204 if (tdesc == NULL) {
2205 int retval = gdb_generate_target_description(target, &tdesc);
2206 if (retval != ERROR_OK) {
2207 LOG_ERROR("Unable to Generate Target Description");
2208 return ERROR_FAIL;
2211 tdesc_length = strlen(tdesc);
2214 char transfer_type;
2216 if (length < (tdesc_length - offset))
2217 transfer_type = 'm';
2218 else
2219 transfer_type = 'l';
2221 *chunk = malloc(length + 2);
2222 if (*chunk == NULL) {
2223 LOG_ERROR("Unable to allocate memory");
2224 return ERROR_FAIL;
2227 (*chunk)[0] = transfer_type;
2228 if (transfer_type == 'm') {
2229 strncpy((*chunk) + 1, tdesc + offset, length);
2230 (*chunk)[1 + length] = '\0';
2231 } else {
2232 strncpy((*chunk) + 1, tdesc + offset, tdesc_length - offset);
2233 (*chunk)[1 + (tdesc_length - offset)] = '\0';
2235 /* After gdb-server sends out last chunk, invalidate tdesc. */
2236 free(tdesc);
2237 tdesc = NULL;
2238 tdesc_length = 0;
2241 target_desc->tdesc = tdesc;
2242 target_desc->tdesc_length = tdesc_length;
2244 return ERROR_OK;
2247 static int gdb_target_description_supported(struct target *target, int *supported)
2249 int retval = ERROR_OK;
2250 struct reg **reg_list = NULL;
2251 int reg_list_size = 0;
2252 char const **features = NULL;
2253 int feature_list_size = 0;
2255 retval = target_get_gdb_reg_list(target, &reg_list,
2256 &reg_list_size, REG_CLASS_ALL);
2257 if (retval != ERROR_OK) {
2258 LOG_ERROR("get register list failed");
2259 goto error;
2262 if (reg_list_size <= 0) {
2263 LOG_ERROR("get register list failed");
2264 retval = ERROR_FAIL;
2265 goto error;
2268 /* Get a list of available target registers features */
2269 retval = get_reg_features_list(target, &features, &feature_list_size, reg_list, reg_list_size);
2270 if (retval != ERROR_OK) {
2271 LOG_ERROR("Can't get the registers feature list");
2272 goto error;
2275 if (supported) {
2276 if (feature_list_size)
2277 *supported = 1;
2278 else
2279 *supported = 0;
2282 error:
2283 free(features);
2285 free(reg_list);
2287 return retval;
2290 static int gdb_generate_thread_list(struct target *target, char **thread_list_out)
2292 struct rtos *rtos = target->rtos;
2293 int retval = ERROR_OK;
2294 char *thread_list = NULL;
2295 int pos = 0;
2296 int size = 0;
2298 xml_printf(&retval, &thread_list, &pos, &size,
2299 "<?xml version=\"1.0\"?>\n"
2300 "<threads>\n");
2302 if (rtos != NULL) {
2303 for (int i = 0; i < rtos->thread_count; i++) {
2304 struct thread_detail *thread_detail = &rtos->thread_details[i];
2306 if (!thread_detail->exists)
2307 continue;
2309 xml_printf(&retval, &thread_list, &pos, &size,
2310 "<thread id=\"%" PRIx64 "\">", thread_detail->threadid);
2312 if (thread_detail->thread_name_str != NULL)
2313 xml_printf(&retval, &thread_list, &pos, &size,
2314 "Name: %s", thread_detail->thread_name_str);
2316 if (thread_detail->extra_info_str != NULL) {
2317 if (thread_detail->thread_name_str != NULL)
2318 xml_printf(&retval, &thread_list, &pos, &size,
2319 ", ");
2320 xml_printf(&retval, &thread_list, &pos, &size,
2321 thread_detail->extra_info_str);
2324 xml_printf(&retval, &thread_list, &pos, &size,
2325 "</thread>\n");
2329 xml_printf(&retval, &thread_list, &pos, &size,
2330 "</threads>\n");
2332 if (retval == ERROR_OK)
2333 *thread_list_out = thread_list;
2334 else
2335 free(thread_list);
2337 return retval;
2340 static int gdb_get_thread_list_chunk(struct target *target, char **thread_list,
2341 char **chunk, int32_t offset, uint32_t length)
2343 if (*thread_list == NULL) {
2344 int retval = gdb_generate_thread_list(target, thread_list);
2345 if (retval != ERROR_OK) {
2346 LOG_ERROR("Unable to Generate Thread List");
2347 return ERROR_FAIL;
2351 size_t thread_list_length = strlen(*thread_list);
2352 char transfer_type;
2354 length = MIN(length, thread_list_length - offset);
2355 if (length < (thread_list_length - offset))
2356 transfer_type = 'm';
2357 else
2358 transfer_type = 'l';
2360 *chunk = malloc(length + 2);
2361 if (*chunk == NULL) {
2362 LOG_ERROR("Unable to allocate memory");
2363 return ERROR_FAIL;
2366 (*chunk)[0] = transfer_type;
2367 strncpy((*chunk) + 1, (*thread_list) + offset, length);
2368 (*chunk)[1 + length] = '\0';
2370 /* After gdb-server sends out last chunk, invalidate thread list. */
2371 if (transfer_type == 'l') {
2372 free(*thread_list);
2373 *thread_list = NULL;
2376 return ERROR_OK;
2379 static int gdb_query_packet(struct connection *connection,
2380 char const *packet, int packet_size)
2382 struct command_context *cmd_ctx = connection->cmd_ctx;
2383 struct gdb_connection *gdb_connection = connection->priv;
2384 struct target *target = get_target_from_connection(connection);
2386 if (strncmp(packet, "qRcmd,", 6) == 0) {
2387 if (packet_size > 6) {
2388 char *cmd;
2389 cmd = malloc((packet_size - 6) / 2 + 1);
2390 size_t len = unhexify((uint8_t *)cmd, packet + 6, (packet_size - 6) / 2);
2391 cmd[len] = 0;
2393 /* We want to print all debug output to GDB connection */
2394 log_add_callback(gdb_log_callback, connection);
2395 target_call_timer_callbacks_now();
2396 /* some commands need to know the GDB connection, make note of current
2397 * GDB connection. */
2398 current_gdb_connection = gdb_connection;
2399 command_run_line(cmd_ctx, cmd);
2400 current_gdb_connection = NULL;
2401 target_call_timer_callbacks_now();
2402 log_remove_callback(gdb_log_callback, connection);
2403 free(cmd);
2405 gdb_put_packet(connection, "OK", 2);
2406 return ERROR_OK;
2407 } else if (strncmp(packet, "qCRC:", 5) == 0) {
2408 if (packet_size > 5) {
2409 int retval;
2410 char gdb_reply[10];
2411 char *separator;
2412 uint32_t checksum;
2413 uint32_t addr = 0;
2414 uint32_t len = 0;
2416 /* skip command character */
2417 packet += 5;
2419 addr = strtoul(packet, &separator, 16);
2421 if (*separator != ',') {
2422 LOG_ERROR("incomplete read memory packet received, dropping connection");
2423 return ERROR_SERVER_REMOTE_CLOSED;
2426 len = strtoul(separator + 1, NULL, 16);
2428 retval = target_checksum_memory(target, addr, len, &checksum);
2430 if (retval == ERROR_OK) {
2431 snprintf(gdb_reply, 10, "C%8.8" PRIx32 "", checksum);
2432 gdb_put_packet(connection, gdb_reply, 9);
2433 } else {
2434 retval = gdb_error(connection, retval);
2435 if (retval != ERROR_OK)
2436 return retval;
2439 return ERROR_OK;
2441 } else if (strncmp(packet, "qSupported", 10) == 0) {
2442 /* we currently support packet size and qXfer:memory-map:read (if enabled)
2443 * qXfer:features:read is supported for some targets */
2444 int retval = ERROR_OK;
2445 char *buffer = NULL;
2446 int pos = 0;
2447 int size = 0;
2448 int gdb_target_desc_supported = 0;
2450 /* we need to test that the target supports target descriptions */
2451 retval = gdb_target_description_supported(target, &gdb_target_desc_supported);
2452 if (retval != ERROR_OK) {
2453 LOG_INFO("Failed detecting Target Description Support, disabling");
2454 gdb_target_desc_supported = 0;
2457 /* support may be disabled globally */
2458 if (gdb_use_target_description == 0) {
2459 if (gdb_target_desc_supported)
2460 LOG_WARNING("Target Descriptions Supported, but disabled");
2461 gdb_target_desc_supported = 0;
2464 xml_printf(&retval,
2465 &buffer,
2466 &pos,
2467 &size,
2468 "PacketSize=%x;qXfer:memory-map:read%c;qXfer:features:read%c;qXfer:threads:read+;QStartNoAckMode+",
2469 (GDB_BUFFER_SIZE - 1),
2470 ((gdb_use_memory_map == 1) && (flash_get_bank_count() > 0)) ? '+' : '-',
2471 (gdb_target_desc_supported == 1) ? '+' : '-');
2473 if (retval != ERROR_OK) {
2474 gdb_send_error(connection, 01);
2475 return ERROR_OK;
2478 gdb_put_packet(connection, buffer, strlen(buffer));
2479 free(buffer);
2481 return ERROR_OK;
2482 } else if ((strncmp(packet, "qXfer:memory-map:read::", 23) == 0)
2483 && (flash_get_bank_count() > 0))
2484 return gdb_memory_map(connection, packet, packet_size);
2485 else if (strncmp(packet, "qXfer:features:read:", 20) == 0) {
2486 char *xml = NULL;
2487 int retval = ERROR_OK;
2489 int offset;
2490 unsigned int length;
2492 /* skip command character */
2493 packet += 20;
2495 if (decode_xfer_read(packet, NULL, &offset, &length) < 0) {
2496 gdb_send_error(connection, 01);
2497 return ERROR_OK;
2500 /* Target should prepare correct target description for annex.
2501 * The first character of returned xml is 'm' or 'l'. 'm' for
2502 * there are *more* chunks to transfer. 'l' for it is the *last*
2503 * chunk of target description.
2505 retval = gdb_get_target_description_chunk(target, &gdb_connection->target_desc,
2506 &xml, offset, length);
2507 if (retval != ERROR_OK) {
2508 gdb_error(connection, retval);
2509 return retval;
2512 gdb_put_packet(connection, xml, strlen(xml));
2514 free(xml);
2515 return ERROR_OK;
2516 } else if (strncmp(packet, "qXfer:threads:read:", 19) == 0) {
2517 char *xml = NULL;
2518 int retval = ERROR_OK;
2520 int offset;
2521 unsigned int length;
2523 /* skip command character */
2524 packet += 19;
2526 if (decode_xfer_read(packet, NULL, &offset, &length) < 0) {
2527 gdb_send_error(connection, 01);
2528 return ERROR_OK;
2531 /* Target should prepare correct thread list for annex.
2532 * The first character of returned xml is 'm' or 'l'. 'm' for
2533 * there are *more* chunks to transfer. 'l' for it is the *last*
2534 * chunk of target description.
2536 retval = gdb_get_thread_list_chunk(target, &gdb_connection->thread_list,
2537 &xml, offset, length);
2538 if (retval != ERROR_OK) {
2539 gdb_error(connection, retval);
2540 return retval;
2543 gdb_put_packet(connection, xml, strlen(xml));
2545 free(xml);
2546 return ERROR_OK;
2547 } else if (strncmp(packet, "QStartNoAckMode", 15) == 0) {
2548 gdb_connection->noack_mode = 1;
2549 gdb_put_packet(connection, "OK", 2);
2550 return ERROR_OK;
2553 gdb_put_packet(connection, "", 0);
2554 return ERROR_OK;
2557 static int gdb_v_packet(struct connection *connection,
2558 char const *packet, int packet_size)
2560 struct gdb_connection *gdb_connection = connection->priv;
2561 struct gdb_service *gdb_service = connection->service->priv;
2562 int result;
2564 /* if flash programming disabled - send a empty reply */
2566 if (gdb_flash_program == 0) {
2567 gdb_put_packet(connection, "", 0);
2568 return ERROR_OK;
2571 if (strncmp(packet, "vFlashErase:", 12) == 0) {
2572 unsigned long addr;
2573 unsigned long length;
2575 char const *parse = packet + 12;
2576 if (*parse == '\0') {
2577 LOG_ERROR("incomplete vFlashErase packet received, dropping connection");
2578 return ERROR_SERVER_REMOTE_CLOSED;
2581 addr = strtoul(parse, (char **)&parse, 16);
2583 if (*(parse++) != ',' || *parse == '\0') {
2584 LOG_ERROR("incomplete vFlashErase packet received, dropping connection");
2585 return ERROR_SERVER_REMOTE_CLOSED;
2588 length = strtoul(parse, (char **)&parse, 16);
2590 if (*parse != '\0') {
2591 LOG_ERROR("incomplete vFlashErase packet received, dropping connection");
2592 return ERROR_SERVER_REMOTE_CLOSED;
2595 /* assume all sectors need erasing - stops any problems
2596 * when flash_write is called multiple times */
2597 flash_set_dirty();
2599 /* perform any target specific operations before the erase */
2600 target_call_event_callbacks(gdb_service->target,
2601 TARGET_EVENT_GDB_FLASH_ERASE_START);
2603 /* vFlashErase:addr,length messages require region start and
2604 * end to be "block" aligned ... if padding is ever needed,
2605 * GDB will have become dangerously confused.
2607 result = flash_erase_address_range(gdb_service->target,
2608 false, addr, length);
2610 /* perform any target specific operations after the erase */
2611 target_call_event_callbacks(gdb_service->target,
2612 TARGET_EVENT_GDB_FLASH_ERASE_END);
2614 /* perform erase */
2615 if (result != ERROR_OK) {
2616 /* GDB doesn't evaluate the actual error number returned,
2617 * treat a failed erase as an I/O error
2619 gdb_send_error(connection, EIO);
2620 LOG_ERROR("flash_erase returned %i", result);
2621 } else
2622 gdb_put_packet(connection, "OK", 2);
2624 return ERROR_OK;
2627 if (strncmp(packet, "vFlashWrite:", 12) == 0) {
2628 int retval;
2629 unsigned long addr;
2630 unsigned long length;
2631 char const *parse = packet + 12;
2633 if (*parse == '\0') {
2634 LOG_ERROR("incomplete vFlashErase packet received, dropping connection");
2635 return ERROR_SERVER_REMOTE_CLOSED;
2637 addr = strtoul(parse, (char **)&parse, 16);
2638 if (*(parse++) != ':') {
2639 LOG_ERROR("incomplete vFlashErase packet received, dropping connection");
2640 return ERROR_SERVER_REMOTE_CLOSED;
2642 length = packet_size - (parse - packet);
2644 /* create a new image if there isn't already one */
2645 if (gdb_connection->vflash_image == NULL) {
2646 gdb_connection->vflash_image = malloc(sizeof(struct image));
2647 image_open(gdb_connection->vflash_image, "", "build");
2650 /* create new section with content from packet buffer */
2651 retval = image_add_section(gdb_connection->vflash_image,
2652 addr, length, 0x0, (uint8_t const *)parse);
2653 if (retval != ERROR_OK)
2654 return retval;
2656 gdb_put_packet(connection, "OK", 2);
2658 return ERROR_OK;
2661 if (strncmp(packet, "vFlashDone", 10) == 0) {
2662 uint32_t written;
2664 /* process the flashing buffer. No need to erase as GDB
2665 * always issues a vFlashErase first. */
2666 target_call_event_callbacks(gdb_service->target,
2667 TARGET_EVENT_GDB_FLASH_WRITE_START);
2668 result = flash_write(gdb_service->target, gdb_connection->vflash_image, &written, 0);
2669 target_call_event_callbacks(gdb_service->target, TARGET_EVENT_GDB_FLASH_WRITE_END);
2670 if (result != ERROR_OK) {
2671 if (result == ERROR_FLASH_DST_OUT_OF_BANK)
2672 gdb_put_packet(connection, "E.memtype", 9);
2673 else
2674 gdb_send_error(connection, EIO);
2675 } else {
2676 LOG_DEBUG("wrote %u bytes from vFlash image to flash", (unsigned)written);
2677 gdb_put_packet(connection, "OK", 2);
2680 image_close(gdb_connection->vflash_image);
2681 free(gdb_connection->vflash_image);
2682 gdb_connection->vflash_image = NULL;
2684 return ERROR_OK;
2687 gdb_put_packet(connection, "", 0);
2688 return ERROR_OK;
2691 static int gdb_detach(struct connection *connection)
2693 struct gdb_service *gdb_service = connection->service->priv;
2695 target_call_event_callbacks(gdb_service->target, TARGET_EVENT_GDB_DETACH);
2697 return gdb_put_packet(connection, "OK", 2);
2700 /* The format of 'F' response packet is
2701 * Fretcode,errno,Ctrl-C flag;call-specific attachment
2703 static int gdb_fileio_response_packet(struct connection *connection,
2704 char const *packet, int packet_size)
2706 struct target *target = get_target_from_connection(connection);
2707 char *separator;
2708 char *parsing_point;
2709 int fileio_retcode = strtoul(packet + 1, &separator, 16);
2710 int fileio_errno = 0;
2711 bool fileio_ctrl_c = false;
2712 int retval;
2714 LOG_DEBUG("-");
2716 if (*separator == ',') {
2717 parsing_point = separator + 1;
2718 fileio_errno = strtoul(parsing_point, &separator, 16);
2719 if (*separator == ',') {
2720 if (*(separator + 1) == 'C') {
2721 /* TODO: process ctrl-c */
2722 fileio_ctrl_c = true;
2727 LOG_DEBUG("File-I/O response, retcode: 0x%x, errno: 0x%x, ctrl-c: %s",
2728 fileio_retcode, fileio_errno, fileio_ctrl_c ? "true" : "false");
2730 retval = target_gdb_fileio_end(target, fileio_retcode, fileio_errno, fileio_ctrl_c);
2731 if (retval != ERROR_OK)
2732 return ERROR_FAIL;
2734 /* After File-I/O ends, keep continue or step */
2735 if (gdb_running_type == 'c')
2736 retval = target_resume(target, 1, 0x0, 0, 0);
2737 else if (gdb_running_type == 's')
2738 retval = target_step(target, 1, 0x0, 0);
2739 else
2740 retval = ERROR_FAIL;
2742 if (retval != ERROR_OK)
2743 return ERROR_FAIL;
2745 return ERROR_OK;
2748 static void gdb_log_callback(void *priv, const char *file, unsigned line,
2749 const char *function, const char *string)
2751 struct connection *connection = priv;
2752 struct gdb_connection *gdb_con = connection->priv;
2754 if (gdb_con->busy) {
2755 /* do not reply this using the O packet */
2756 return;
2759 gdb_output_con(connection, string);
2762 static void gdb_sig_halted(struct connection *connection)
2764 char sig_reply[4];
2765 snprintf(sig_reply, 4, "T%2.2x", 2);
2766 gdb_put_packet(connection, sig_reply, 3);
2769 static int gdb_input_inner(struct connection *connection)
2771 /* Do not allocate this on the stack */
2772 static char gdb_packet_buffer[GDB_BUFFER_SIZE];
2774 struct gdb_service *gdb_service = connection->service->priv;
2775 struct target *target = gdb_service->target;
2776 char const *packet = gdb_packet_buffer;
2777 int packet_size;
2778 int retval;
2779 struct gdb_connection *gdb_con = connection->priv;
2780 static int extended_protocol;
2782 /* drain input buffer. If one of the packets fail, then an error
2783 * packet is replied, if applicable.
2785 * This loop will terminate and the error code is returned.
2787 * The calling fn will check if this error is something that
2788 * can be recovered from, or if the connection must be closed.
2790 * If the error is recoverable, this fn is called again to
2791 * drain the rest of the buffer.
2793 do {
2794 packet_size = GDB_BUFFER_SIZE-1;
2795 retval = gdb_get_packet(connection, gdb_packet_buffer, &packet_size);
2796 if (retval != ERROR_OK)
2797 return retval;
2799 /* terminate with zero */
2800 gdb_packet_buffer[packet_size] = '\0';
2802 if (LOG_LEVEL_IS(LOG_LVL_DEBUG)) {
2803 if (packet[0] == 'X') {
2804 /* binary packets spew junk into the debug log stream */
2805 char buf[50];
2806 int x;
2807 for (x = 0; (x < 49) && (packet[x] != ':'); x++)
2808 buf[x] = packet[x];
2809 buf[x] = 0;
2810 LOG_DEBUG("received packet: '%s:<binary-data>'", buf);
2811 } else
2812 LOG_DEBUG("received packet: '%s'", packet);
2815 if (packet_size > 0) {
2816 retval = ERROR_OK;
2817 switch (packet[0]) {
2818 case 'T': /* Is thread alive? */
2819 gdb_thread_packet(connection, packet, packet_size);
2820 break;
2821 case 'H': /* Set current thread ( 'c' for step and continue,
2822 * 'g' for all other operations ) */
2823 gdb_thread_packet(connection, packet, packet_size);
2824 break;
2825 case 'q':
2826 case 'Q':
2827 retval = gdb_thread_packet(connection, packet, packet_size);
2828 if (retval == GDB_THREAD_PACKET_NOT_CONSUMED)
2829 retval = gdb_query_packet(connection, packet, packet_size);
2830 break;
2831 case 'g':
2832 retval = gdb_get_registers_packet(connection, packet, packet_size);
2833 break;
2834 case 'G':
2835 retval = gdb_set_registers_packet(connection, packet, packet_size);
2836 break;
2837 case 'p':
2838 retval = gdb_get_register_packet(connection, packet, packet_size);
2839 break;
2840 case 'P':
2841 retval = gdb_set_register_packet(connection, packet, packet_size);
2842 break;
2843 case 'm':
2844 retval = gdb_read_memory_packet(connection, packet, packet_size);
2845 break;
2846 case 'M':
2847 retval = gdb_write_memory_packet(connection, packet, packet_size);
2848 break;
2849 case 'z':
2850 case 'Z':
2851 retval = gdb_breakpoint_watchpoint_packet(connection, packet, packet_size);
2852 break;
2853 case '?':
2854 gdb_last_signal_packet(connection, packet, packet_size);
2855 break;
2856 case 'c':
2857 case 's':
2859 gdb_thread_packet(connection, packet, packet_size);
2860 log_add_callback(gdb_log_callback, connection);
2862 if (gdb_con->mem_write_error) {
2863 LOG_ERROR("Memory write failure!");
2865 /* now that we have reported the memory write error,
2866 * we can clear the condition */
2867 gdb_con->mem_write_error = false;
2870 bool nostep = false;
2871 bool already_running = false;
2872 if (target->state == TARGET_RUNNING) {
2873 LOG_WARNING("WARNING! The target is already running. "
2874 "All changes GDB did to registers will be discarded! "
2875 "Waiting for target to halt.");
2876 already_running = true;
2877 } else if (target->state != TARGET_HALTED) {
2878 LOG_WARNING("The target is not in the halted nor running stated, " \
2879 "stepi/continue ignored.");
2880 nostep = true;
2881 } else if ((packet[0] == 's') && gdb_con->sync) {
2882 /* Hmm..... when you issue a continue in GDB, then a "stepi" is
2883 * sent by GDB first to OpenOCD, thus defeating the check to
2884 * make only the single stepping have the sync feature...
2886 nostep = true;
2887 LOG_WARNING("stepi ignored. GDB will now fetch the register state " \
2888 "from the target.");
2890 gdb_con->sync = false;
2892 if (!already_running && nostep) {
2893 /* Either the target isn't in the halted state, then we can't
2894 * step/continue. This might be early setup, etc.
2896 * Or we want to allow GDB to pick up a fresh set of
2897 * register values without modifying the target state.
2900 gdb_sig_halted(connection);
2902 /* stop forwarding log packets! */
2903 log_remove_callback(gdb_log_callback, connection);
2904 } else {
2905 /* We're running/stepping, in which case we can
2906 * forward log output until the target is halted
2908 gdb_con->frontend_state = TARGET_RUNNING;
2909 target_call_event_callbacks(target, TARGET_EVENT_GDB_START);
2911 if (!already_running) {
2912 /* Here we don't want packet processing to stop even if this fails,
2913 * so we use a local variable instead of retval. */
2914 retval = gdb_step_continue_packet(connection, packet, packet_size);
2915 if (retval != ERROR_OK) {
2916 /* we'll never receive a halted
2917 * condition... issue a false one..
2919 gdb_frontend_halted(target, connection);
2924 break;
2925 case 'v':
2926 retval = gdb_v_packet(connection, packet, packet_size);
2927 break;
2928 case 'D':
2929 retval = gdb_detach(connection);
2930 extended_protocol = 0;
2931 break;
2932 case 'X':
2933 retval = gdb_write_memory_binary_packet(connection, packet, packet_size);
2934 if (retval != ERROR_OK)
2935 return retval;
2936 break;
2937 case 'k':
2938 if (extended_protocol != 0) {
2939 gdb_con->attached = false;
2940 break;
2942 gdb_put_packet(connection, "OK", 2);
2943 return ERROR_SERVER_REMOTE_CLOSED;
2944 case '!':
2945 /* handle extended remote protocol */
2946 extended_protocol = 1;
2947 gdb_put_packet(connection, "OK", 2);
2948 break;
2949 case 'R':
2950 /* handle extended restart packet */
2951 breakpoint_clear_target(gdb_service->target);
2952 watchpoint_clear_target(gdb_service->target);
2953 command_run_linef(connection->cmd_ctx, "ocd_gdb_restart %s",
2954 target_name(target));
2955 /* set connection as attached after reset */
2956 gdb_con->attached = true;
2957 /* info rtos parts */
2958 gdb_thread_packet(connection, packet, packet_size);
2959 break;
2961 case 'j':
2962 /* packet supported only by smp target i.e cortex_a.c*/
2963 /* handle smp packet replying coreid played to gbd */
2964 gdb_read_smp_packet(connection, packet, packet_size);
2965 break;
2967 case 'J':
2968 /* packet supported only by smp target i.e cortex_a.c */
2969 /* handle smp packet setting coreid to be played at next
2970 * resume to gdb */
2971 gdb_write_smp_packet(connection, packet, packet_size);
2972 break;
2974 case 'F':
2975 /* File-I/O extension */
2976 /* After gdb uses host-side syscall to complete target file
2977 * I/O, gdb sends host-side syscall return value to target
2978 * by 'F' packet.
2979 * The format of 'F' response packet is
2980 * Fretcode,errno,Ctrl-C flag;call-specific attachment
2982 gdb_con->frontend_state = TARGET_RUNNING;
2983 log_add_callback(gdb_log_callback, connection);
2984 gdb_fileio_response_packet(connection, packet, packet_size);
2985 break;
2987 default:
2988 /* ignore unknown packets */
2989 LOG_DEBUG("ignoring 0x%2.2x packet", packet[0]);
2990 gdb_put_packet(connection, NULL, 0);
2991 break;
2994 /* if a packet handler returned an error, exit input loop */
2995 if (retval != ERROR_OK)
2996 return retval;
2999 if (gdb_con->ctrl_c) {
3000 if (target->state == TARGET_RUNNING) {
3001 retval = target_halt(target);
3002 if (retval != ERROR_OK)
3003 target_call_event_callbacks(target, TARGET_EVENT_GDB_HALT);
3004 gdb_con->ctrl_c = 0;
3005 } else {
3006 LOG_INFO("The target is not running when halt was requested, stopping GDB.");
3007 target_call_event_callbacks(target, TARGET_EVENT_GDB_HALT);
3011 } while (gdb_con->buf_cnt > 0);
3013 return ERROR_OK;
3016 static int gdb_input(struct connection *connection)
3018 int retval = gdb_input_inner(connection);
3019 struct gdb_connection *gdb_con = connection->priv;
3020 if (retval == ERROR_SERVER_REMOTE_CLOSED)
3021 return retval;
3023 /* logging does not propagate the error, yet can set the gdb_con->closed flag */
3024 if (gdb_con->closed)
3025 return ERROR_SERVER_REMOTE_CLOSED;
3027 /* we'll recover from any other errors(e.g. temporary timeouts, etc.) */
3028 return ERROR_OK;
3031 static int gdb_target_start(struct target *target, const char *port)
3033 struct gdb_service *gdb_service;
3034 int ret;
3035 gdb_service = malloc(sizeof(struct gdb_service));
3037 if (NULL == gdb_service)
3038 return -ENOMEM;
3040 gdb_service->target = target;
3041 gdb_service->core[0] = -1;
3042 gdb_service->core[1] = -1;
3043 target->gdb_service = gdb_service;
3045 ret = add_service("gdb",
3046 port, 1, &gdb_new_connection, &gdb_input,
3047 &gdb_connection_closed, gdb_service);
3048 /* initialialize all targets gdb service with the same pointer */
3050 struct target_list *head;
3051 struct target *curr;
3052 head = target->head;
3053 while (head != (struct target_list *)NULL) {
3054 curr = head->target;
3055 if (curr != target)
3056 curr->gdb_service = gdb_service;
3057 head = head->next;
3060 return ret;
3063 static int gdb_target_add_one(struct target *target)
3065 if (strcmp(gdb_port, "disabled") == 0) {
3066 LOG_INFO("gdb port disabled");
3067 return ERROR_OK;
3070 /* one gdb instance per smp list */
3071 if ((target->smp) && (target->gdb_service))
3072 return ERROR_OK;
3073 int retval = gdb_target_start(target, gdb_port_next);
3074 if (retval == ERROR_OK) {
3075 long portnumber;
3076 /* If we can parse the port number
3077 * then we increment the port number for the next target.
3079 char *end;
3080 portnumber = strtol(gdb_port_next, &end, 0);
3081 if (!*end) {
3082 if (parse_long(gdb_port_next, &portnumber) == ERROR_OK) {
3083 free(gdb_port_next);
3084 gdb_port_next = alloc_printf("%d", portnumber+1);
3088 return retval;
3091 int gdb_target_add_all(struct target *target)
3093 if (strcmp(gdb_port, "disabled") == 0) {
3094 LOG_INFO("gdb server disabled");
3095 return ERROR_OK;
3098 if (NULL == target) {
3099 LOG_WARNING("gdb services need one or more targets defined");
3100 return ERROR_OK;
3103 while (NULL != target) {
3104 int retval = gdb_target_add_one(target);
3105 if (ERROR_OK != retval)
3106 return retval;
3108 target = target->next;
3111 return ERROR_OK;
3114 COMMAND_HANDLER(handle_gdb_sync_command)
3116 if (CMD_ARGC != 0)
3117 return ERROR_COMMAND_SYNTAX_ERROR;
3119 if (current_gdb_connection == NULL) {
3120 command_print(CMD_CTX,
3121 "gdb_sync command can only be run from within gdb using \"monitor gdb_sync\"");
3122 return ERROR_FAIL;
3125 current_gdb_connection->sync = true;
3127 return ERROR_OK;
3130 /* daemon configuration command gdb_port */
3131 COMMAND_HANDLER(handle_gdb_port_command)
3133 int retval = CALL_COMMAND_HANDLER(server_pipe_command, &gdb_port);
3134 if (ERROR_OK == retval) {
3135 free(gdb_port_next);
3136 gdb_port_next = strdup(gdb_port);
3138 return retval;
3141 COMMAND_HANDLER(handle_gdb_memory_map_command)
3143 if (CMD_ARGC != 1)
3144 return ERROR_COMMAND_SYNTAX_ERROR;
3146 COMMAND_PARSE_ENABLE(CMD_ARGV[0], gdb_use_memory_map);
3147 return ERROR_OK;
3150 COMMAND_HANDLER(handle_gdb_flash_program_command)
3152 if (CMD_ARGC != 1)
3153 return ERROR_COMMAND_SYNTAX_ERROR;
3155 COMMAND_PARSE_ENABLE(CMD_ARGV[0], gdb_flash_program);
3156 return ERROR_OK;
3159 COMMAND_HANDLER(handle_gdb_report_data_abort_command)
3161 if (CMD_ARGC != 1)
3162 return ERROR_COMMAND_SYNTAX_ERROR;
3164 COMMAND_PARSE_ENABLE(CMD_ARGV[0], gdb_report_data_abort);
3165 return ERROR_OK;
3168 /* gdb_breakpoint_override */
3169 COMMAND_HANDLER(handle_gdb_breakpoint_override_command)
3171 if (CMD_ARGC == 0) {
3172 /* nothing */
3173 } else if (CMD_ARGC == 1) {
3174 gdb_breakpoint_override = 1;
3175 if (strcmp(CMD_ARGV[0], "hard") == 0)
3176 gdb_breakpoint_override_type = BKPT_HARD;
3177 else if (strcmp(CMD_ARGV[0], "soft") == 0)
3178 gdb_breakpoint_override_type = BKPT_SOFT;
3179 else if (strcmp(CMD_ARGV[0], "disable") == 0)
3180 gdb_breakpoint_override = 0;
3181 } else
3182 return ERROR_COMMAND_SYNTAX_ERROR;
3183 if (gdb_breakpoint_override)
3184 LOG_USER("force %s breakpoints",
3185 (gdb_breakpoint_override_type == BKPT_HARD) ? "hard" : "soft");
3186 else
3187 LOG_USER("breakpoint type is not overridden");
3189 return ERROR_OK;
3192 COMMAND_HANDLER(handle_gdb_target_description_command)
3194 if (CMD_ARGC != 1)
3195 return ERROR_COMMAND_SYNTAX_ERROR;
3197 COMMAND_PARSE_ENABLE(CMD_ARGV[0], gdb_use_target_description);
3198 return ERROR_OK;
3201 COMMAND_HANDLER(handle_gdb_save_tdesc_command)
3203 char *tdesc;
3204 uint32_t tdesc_length;
3205 struct target *target = get_current_target(CMD_CTX);
3207 int retval = gdb_generate_target_description(target, &tdesc);
3208 if (retval != ERROR_OK) {
3209 LOG_ERROR("Unable to Generate Target Description");
3210 return ERROR_FAIL;
3213 tdesc_length = strlen(tdesc);
3215 struct fileio *fileio;
3216 size_t size_written;
3218 char *tdesc_filename = alloc_printf("%s.xml", target_type_name(target));
3219 if (tdesc_filename == NULL) {
3220 retval = ERROR_FAIL;
3221 goto out;
3224 retval = fileio_open(&fileio, tdesc_filename, FILEIO_WRITE, FILEIO_TEXT);
3226 if (retval != ERROR_OK) {
3227 LOG_ERROR("Can't open %s for writing", tdesc_filename);
3228 goto out;
3231 retval = fileio_write(fileio, tdesc_length, tdesc, &size_written);
3233 fileio_close(fileio);
3235 if (retval != ERROR_OK)
3236 LOG_ERROR("Error while writing the tdesc file");
3238 out:
3239 free(tdesc_filename);
3240 free(tdesc);
3242 return retval;
3245 static const struct command_registration gdb_command_handlers[] = {
3247 .name = "gdb_sync",
3248 .handler = handle_gdb_sync_command,
3249 .mode = COMMAND_ANY,
3250 .help = "next stepi will return immediately allowing "
3251 "GDB to fetch register state without affecting "
3252 "target state",
3253 .usage = ""
3256 .name = "gdb_port",
3257 .handler = handle_gdb_port_command,
3258 .mode = COMMAND_ANY,
3259 .help = "Normally gdb listens to a TCP/IP port. Each subsequent GDB "
3260 "server listens for the next port number after the "
3261 "base port number specified. "
3262 "No arguments reports GDB port. \"pipe\" means listen to stdin "
3263 "output to stdout, an integer is base port number, \"disabled\" disables "
3264 "port. Any other string is are interpreted as named pipe to listen to. "
3265 "Output pipe is the same name as input pipe, but with 'o' appended.",
3266 .usage = "[port_num]",
3269 .name = "gdb_memory_map",
3270 .handler = handle_gdb_memory_map_command,
3271 .mode = COMMAND_CONFIG,
3272 .help = "enable or disable memory map",
3273 .usage = "('enable'|'disable')"
3276 .name = "gdb_flash_program",
3277 .handler = handle_gdb_flash_program_command,
3278 .mode = COMMAND_CONFIG,
3279 .help = "enable or disable flash program",
3280 .usage = "('enable'|'disable')"
3283 .name = "gdb_report_data_abort",
3284 .handler = handle_gdb_report_data_abort_command,
3285 .mode = COMMAND_CONFIG,
3286 .help = "enable or disable reporting data aborts",
3287 .usage = "('enable'|'disable')"
3290 .name = "gdb_breakpoint_override",
3291 .handler = handle_gdb_breakpoint_override_command,
3292 .mode = COMMAND_ANY,
3293 .help = "Display or specify type of breakpoint "
3294 "to be used by gdb 'break' commands.",
3295 .usage = "('hard'|'soft'|'disable')"
3298 .name = "gdb_target_description",
3299 .handler = handle_gdb_target_description_command,
3300 .mode = COMMAND_CONFIG,
3301 .help = "enable or disable target description",
3302 .usage = "('enable'|'disable')"
3305 .name = "gdb_save_tdesc",
3306 .handler = handle_gdb_save_tdesc_command,
3307 .mode = COMMAND_EXEC,
3308 .help = "Save the target description file",
3310 COMMAND_REGISTRATION_DONE
3313 int gdb_register_commands(struct command_context *cmd_ctx)
3315 gdb_port = strdup("3333");
3316 gdb_port_next = strdup("3333");
3317 return register_commands(cmd_ctx, NULL, gdb_command_handlers);