Added system signal handling to Linux version
[openocd.git] / src / server / gdb_server.c
blob4a33a3022be34fa8290ccb414e761f38d055886c
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, write to the *
35 * Free Software Foundation, Inc., *
36 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. *
37 ***************************************************************************/
39 #ifdef HAVE_CONFIG_H
40 #include "config.h"
41 #endif
43 #include <target/breakpoints.h>
44 #include <target/target_request.h>
45 #include <target/register.h>
46 #include "server.h"
47 #include <flash/nor/core.h>
48 #include "gdb_server.h"
49 #include <target/image.h>
50 #include <jtag/jtag.h>
51 #include "rtos/rtos.h"
52 #include "target/smp.h"
54 /**
55 * @file
56 * GDB server implementation.
58 * This implements the GDB Remote Serial Protocol, over TCP connections,
59 * giving GDB access to the JTAG or other hardware debugging facilities
60 * found in most modern embedded processors.
63 struct target_desc_format {
64 char *tdesc;
65 uint32_t tdesc_length;
68 /* private connection data for GDB */
69 struct gdb_connection {
70 char buffer[GDB_BUFFER_SIZE];
71 char *buf_p;
72 int buf_cnt;
73 int ctrl_c;
74 enum target_state frontend_state;
75 struct image *vflash_image;
76 int closed;
77 int busy;
78 int noack_mode;
79 /* set flag to true if you want the next stepi to return immediately.
80 * allowing GDB to pick up a fresh set of register values from the target
81 * without modifying the target state. */
82 bool sync;
83 /* We delay reporting memory write errors until next step/continue or memory
84 * write. This improves performance of gdb load significantly as the GDB packet
85 * can be replied immediately and a new GDB packet will be ready without delay
86 * (ca. 10% or so...). */
87 bool mem_write_error;
88 /* with extended-remote it seems we need to better emulate attach/detach.
89 * what this means is we reply with a W stop reply after a kill packet,
90 * normally we reply with a S reply via gdb_last_signal_packet.
91 * as a side note this behaviour only effects gdb > 6.8 */
92 bool attached;
93 /* temporarily used for target description support */
94 struct target_desc_format target_desc;
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 int pkt_len = hexify(hex_buffer + 1, line, bin_size, bin_size * 2 + 1);
701 int retval = gdb_put_packet(connection, hex_buffer, pkt_len + 1);
703 free(hex_buffer);
704 return retval;
707 static int gdb_output(struct command_context *context, const char *line)
709 /* this will be dumped to the log and also sent as an O packet if possible */
710 LOG_USER_N("%s", line);
711 return ERROR_OK;
714 static void gdb_signal_reply(struct target *target, struct connection *connection)
716 struct gdb_connection *gdb_connection = connection->priv;
717 char sig_reply[45];
718 char stop_reason[20];
719 char current_thread[25];
720 int sig_reply_len;
721 int signal_var;
723 rtos_update_threads(target);
725 if (target->debug_reason == DBG_REASON_EXIT) {
726 sig_reply_len = snprintf(sig_reply, sizeof(sig_reply), "W00");
727 } else {
728 if (gdb_connection->ctrl_c) {
729 signal_var = 0x2;
730 gdb_connection->ctrl_c = 0;
731 } else
732 signal_var = gdb_last_signal(target);
734 stop_reason[0] = '\0';
735 if (target->debug_reason == DBG_REASON_WATCHPOINT) {
736 enum watchpoint_rw hit_wp_type;
737 uint32_t hit_wp_address;
739 if (watchpoint_hit(target, &hit_wp_type, &hit_wp_address) == ERROR_OK) {
741 switch (hit_wp_type) {
742 case WPT_WRITE:
743 snprintf(stop_reason, sizeof(stop_reason),
744 "watch:%08" PRIx32 ";", hit_wp_address);
745 break;
746 case WPT_READ:
747 snprintf(stop_reason, sizeof(stop_reason),
748 "rwatch:%08" PRIx32 ";", hit_wp_address);
749 break;
750 case WPT_ACCESS:
751 snprintf(stop_reason, sizeof(stop_reason),
752 "awatch:%08" PRIx32 ";", hit_wp_address);
753 break;
754 default:
755 break;
760 current_thread[0] = '\0';
761 if (target->rtos != NULL) {
762 snprintf(current_thread, sizeof(current_thread), "thread:%016" PRIx64 ";", target->rtos->current_thread);
763 target->rtos->current_threadid = target->rtos->current_thread;
766 sig_reply_len = snprintf(sig_reply, sizeof(sig_reply), "T%2.2x%s%s",
767 signal_var, stop_reason, current_thread);
770 gdb_put_packet(connection, sig_reply, sig_reply_len);
771 gdb_connection->frontend_state = TARGET_HALTED;
774 static void gdb_fileio_reply(struct target *target, struct connection *connection)
776 struct gdb_connection *gdb_connection = connection->priv;
777 char fileio_command[256];
778 int command_len;
779 bool program_exited = false;
781 if (strcmp(target->fileio_info->identifier, "open") == 0)
782 sprintf(fileio_command, "F%s,%" PRIx32 "/%" PRIx32 ",%" PRIx32 ",%" PRIx32, target->fileio_info->identifier,
783 target->fileio_info->param_1,
784 target->fileio_info->param_2,
785 target->fileio_info->param_3,
786 target->fileio_info->param_4);
787 else if (strcmp(target->fileio_info->identifier, "close") == 0)
788 sprintf(fileio_command, "F%s,%" PRIx32, target->fileio_info->identifier,
789 target->fileio_info->param_1);
790 else if (strcmp(target->fileio_info->identifier, "read") == 0)
791 sprintf(fileio_command, "F%s,%" PRIx32 ",%" PRIx32 ",%" PRIx32, target->fileio_info->identifier,
792 target->fileio_info->param_1,
793 target->fileio_info->param_2,
794 target->fileio_info->param_3);
795 else if (strcmp(target->fileio_info->identifier, "write") == 0)
796 sprintf(fileio_command, "F%s,%" PRIx32 ",%" PRIx32 ",%" PRIx32, target->fileio_info->identifier,
797 target->fileio_info->param_1,
798 target->fileio_info->param_2,
799 target->fileio_info->param_3);
800 else if (strcmp(target->fileio_info->identifier, "lseek") == 0)
801 sprintf(fileio_command, "F%s,%" PRIx32 ",%" PRIx32 ",%" PRIx32, target->fileio_info->identifier,
802 target->fileio_info->param_1,
803 target->fileio_info->param_2,
804 target->fileio_info->param_3);
805 else if (strcmp(target->fileio_info->identifier, "rename") == 0)
806 sprintf(fileio_command, "F%s,%" PRIx32 "/%" PRIx32 ",%" PRIx32 "/%" PRIx32, target->fileio_info->identifier,
807 target->fileio_info->param_1,
808 target->fileio_info->param_2,
809 target->fileio_info->param_3,
810 target->fileio_info->param_4);
811 else if (strcmp(target->fileio_info->identifier, "unlink") == 0)
812 sprintf(fileio_command, "F%s,%" PRIx32 "/%" PRIx32, target->fileio_info->identifier,
813 target->fileio_info->param_1,
814 target->fileio_info->param_2);
815 else if (strcmp(target->fileio_info->identifier, "stat") == 0)
816 sprintf(fileio_command, "F%s,%" PRIx32 "/%" PRIx32 ",%" PRIx32, target->fileio_info->identifier,
817 target->fileio_info->param_1,
818 target->fileio_info->param_2,
819 target->fileio_info->param_3);
820 else if (strcmp(target->fileio_info->identifier, "fstat") == 0)
821 sprintf(fileio_command, "F%s,%" PRIx32 ",%" PRIx32, target->fileio_info->identifier,
822 target->fileio_info->param_1,
823 target->fileio_info->param_2);
824 else if (strcmp(target->fileio_info->identifier, "gettimeofday") == 0)
825 sprintf(fileio_command, "F%s,%" PRIx32 ",%" PRIx32, target->fileio_info->identifier,
826 target->fileio_info->param_1,
827 target->fileio_info->param_2);
828 else if (strcmp(target->fileio_info->identifier, "isatty") == 0)
829 sprintf(fileio_command, "F%s,%" PRIx32, target->fileio_info->identifier,
830 target->fileio_info->param_1);
831 else if (strcmp(target->fileio_info->identifier, "system") == 0)
832 sprintf(fileio_command, "F%s,%" PRIx32 "/%" PRIx32, target->fileio_info->identifier,
833 target->fileio_info->param_1,
834 target->fileio_info->param_2);
835 else if (strcmp(target->fileio_info->identifier, "exit") == 0) {
836 /* If target hits exit syscall, report to GDB the program is terminated.
837 * In addition, let target run its own exit syscall handler. */
838 program_exited = true;
839 sprintf(fileio_command, "W%02" PRIx32, target->fileio_info->param_1);
840 } else {
841 LOG_DEBUG("Unknown syscall: %s", target->fileio_info->identifier);
843 /* encounter unknown syscall, continue */
844 gdb_connection->frontend_state = TARGET_RUNNING;
845 target_resume(target, 1, 0x0, 0, 0);
846 return;
849 command_len = strlen(fileio_command);
850 gdb_put_packet(connection, fileio_command, command_len);
852 if (program_exited) {
853 /* Use target_resume() to let target run its own exit syscall handler. */
854 gdb_connection->frontend_state = TARGET_RUNNING;
855 target_resume(target, 1, 0x0, 0, 0);
856 } else {
857 gdb_connection->frontend_state = TARGET_HALTED;
858 rtos_update_threads(target);
862 static void gdb_frontend_halted(struct target *target, struct connection *connection)
864 struct gdb_connection *gdb_connection = connection->priv;
866 /* In the GDB protocol when we are stepping or continuing execution,
867 * we have a lingering reply. Upon receiving a halted event
868 * when we have that lingering packet, we reply to the original
869 * step or continue packet.
871 * Executing monitor commands can bring the target in and
872 * out of the running state so we'll see lots of TARGET_EVENT_XXX
873 * that are to be ignored.
875 if (gdb_connection->frontend_state == TARGET_RUNNING) {
876 /* stop forwarding log packets! */
877 log_remove_callback(gdb_log_callback, connection);
879 /* check fileio first */
880 if (target_get_gdb_fileio_info(target, target->fileio_info) == ERROR_OK)
881 gdb_fileio_reply(target, connection);
882 else
883 gdb_signal_reply(target, connection);
887 static int gdb_target_callback_event_handler(struct target *target,
888 enum target_event event, void *priv)
890 int retval;
891 struct connection *connection = priv;
892 struct gdb_service *gdb_service = connection->service->priv;
894 if (gdb_service->target != target)
895 return ERROR_OK;
897 switch (event) {
898 case TARGET_EVENT_GDB_HALT:
899 gdb_frontend_halted(target, connection);
900 break;
901 case TARGET_EVENT_HALTED:
902 target_call_event_callbacks(target, TARGET_EVENT_GDB_END);
903 break;
904 case TARGET_EVENT_GDB_FLASH_ERASE_START:
905 retval = jtag_execute_queue();
906 if (retval != ERROR_OK)
907 return retval;
908 break;
909 default:
910 break;
913 return ERROR_OK;
916 static int gdb_new_connection(struct connection *connection)
918 struct gdb_connection *gdb_connection = malloc(sizeof(struct gdb_connection));
919 struct gdb_service *gdb_service = connection->service->priv;
920 int retval;
921 int initial_ack;
923 connection->priv = gdb_connection;
925 /* initialize gdb connection information */
926 gdb_connection->buf_p = gdb_connection->buffer;
927 gdb_connection->buf_cnt = 0;
928 gdb_connection->ctrl_c = 0;
929 gdb_connection->frontend_state = TARGET_HALTED;
930 gdb_connection->vflash_image = NULL;
931 gdb_connection->closed = 0;
932 gdb_connection->busy = 0;
933 gdb_connection->noack_mode = 0;
934 gdb_connection->sync = false;
935 gdb_connection->mem_write_error = false;
936 gdb_connection->attached = true;
937 gdb_connection->target_desc.tdesc = NULL;
938 gdb_connection->target_desc.tdesc_length = 0;
940 /* send ACK to GDB for debug request */
941 gdb_write(connection, "+", 1);
943 /* output goes through gdb connection */
944 command_set_output_handler(connection->cmd_ctx, gdb_output, connection);
946 /* we must remove all breakpoints registered to the target as a previous
947 * GDB session could leave dangling breakpoints if e.g. communication
948 * timed out.
950 breakpoint_clear_target(gdb_service->target);
951 watchpoint_clear_target(gdb_service->target);
953 /* clean previous rtos session if supported*/
954 if ((gdb_service->target->rtos) && (gdb_service->target->rtos->type->clean))
955 gdb_service->target->rtos->type->clean(gdb_service->target);
957 /* remove the initial ACK from the incoming buffer */
958 retval = gdb_get_char(connection, &initial_ack);
959 if (retval != ERROR_OK)
960 return retval;
962 /* FIX!!!??? would we actually ever receive a + here???
963 * Not observed.
965 if (initial_ack != '+')
966 gdb_putback_char(connection, initial_ack);
967 target_call_event_callbacks(gdb_service->target, TARGET_EVENT_GDB_ATTACH);
969 if (gdb_use_memory_map) {
970 /* Connect must fail if the memory map can't be set up correctly.
972 * This will cause an auto_probe to be invoked, which is either
973 * a no-op or it will fail when the target isn't ready(e.g. not halted).
975 int i;
976 for (i = 0; i < flash_get_bank_count(); i++) {
977 struct flash_bank *p;
978 p = get_flash_bank_by_num_noprobe(i);
979 if (p->target != gdb_service->target)
980 continue;
981 retval = get_flash_bank_by_num(i, &p);
982 if (retval != ERROR_OK) {
983 LOG_ERROR("Connect failed. Consider setting up a gdb-attach event for the target " \
984 "to prepare target for GDB connect, or use 'gdb_memory_map disable'.");
985 return retval;
990 gdb_actual_connections++;
991 LOG_DEBUG("New GDB Connection: %d, Target %s, state: %s",
992 gdb_actual_connections,
993 target_name(gdb_service->target),
994 target_state_name(gdb_service->target));
996 /* DANGER! If we fail subsequently, we must remove this handler,
997 * otherwise we occasionally see crashes as the timer can invoke the
998 * callback fn.
1000 * register callback to be informed about target events */
1001 target_register_event_callback(gdb_target_callback_event_handler, connection);
1003 return ERROR_OK;
1006 static int gdb_connection_closed(struct connection *connection)
1008 struct gdb_service *gdb_service = connection->service->priv;
1009 struct gdb_connection *gdb_connection = connection->priv;
1011 /* we're done forwarding messages. Tear down callback before
1012 * cleaning up connection.
1014 log_remove_callback(gdb_log_callback, connection);
1016 gdb_actual_connections--;
1017 LOG_DEBUG("GDB Close, Target: %s, state: %s, gdb_actual_connections=%d",
1018 target_name(gdb_service->target),
1019 target_state_name(gdb_service->target),
1020 gdb_actual_connections);
1022 /* see if an image built with vFlash commands is left */
1023 if (gdb_connection->vflash_image) {
1024 image_close(gdb_connection->vflash_image);
1025 free(gdb_connection->vflash_image);
1026 gdb_connection->vflash_image = NULL;
1029 /* if this connection registered a debug-message receiver delete it */
1030 delete_debug_msg_receiver(connection->cmd_ctx, gdb_service->target);
1032 if (connection->priv) {
1033 free(connection->priv);
1034 connection->priv = NULL;
1035 } else
1036 LOG_ERROR("BUG: connection->priv == NULL");
1038 target_unregister_event_callback(gdb_target_callback_event_handler, connection);
1040 target_call_event_callbacks(gdb_service->target, TARGET_EVENT_GDB_END);
1042 target_call_event_callbacks(gdb_service->target, TARGET_EVENT_GDB_DETACH);
1044 return ERROR_OK;
1047 static void gdb_send_error(struct connection *connection, uint8_t the_error)
1049 char err[4];
1050 snprintf(err, 4, "E%2.2X", the_error);
1051 gdb_put_packet(connection, err, 3);
1054 static int gdb_last_signal_packet(struct connection *connection,
1055 char const *packet, int packet_size)
1057 struct target *target = get_target_from_connection(connection);
1058 struct gdb_connection *gdb_con = connection->priv;
1059 char sig_reply[4];
1060 int signal_var;
1062 if (!gdb_con->attached) {
1063 /* if we are here we have received a kill packet
1064 * reply W stop reply otherwise gdb gets very unhappy */
1065 gdb_put_packet(connection, "W00", 3);
1066 return ERROR_OK;
1069 signal_var = gdb_last_signal(target);
1071 snprintf(sig_reply, 4, "S%2.2x", signal_var);
1072 gdb_put_packet(connection, sig_reply, 3);
1074 return ERROR_OK;
1077 static inline int gdb_reg_pos(struct target *target, int pos, int len)
1079 if (target->endianness == TARGET_LITTLE_ENDIAN)
1080 return pos;
1081 else
1082 return len - 1 - pos;
1085 /* Convert register to string of bytes. NB! The # of bits in the
1086 * register might be non-divisible by 8(a byte), in which
1087 * case an entire byte is shown.
1089 * NB! the format on the wire is the target endianness
1091 * The format of reg->value is little endian
1094 static void gdb_str_to_target(struct target *target,
1095 char *tstr, struct reg *reg)
1097 int i;
1099 uint8_t *buf;
1100 int buf_len;
1101 buf = reg->value;
1102 buf_len = DIV_ROUND_UP(reg->size, 8);
1104 for (i = 0; i < buf_len; i++) {
1105 int j = gdb_reg_pos(target, i, buf_len);
1106 tstr += sprintf(tstr, "%02x", buf[j]);
1110 /* copy over in register buffer */
1111 static void gdb_target_to_reg(struct target *target,
1112 char const *tstr, int str_len, uint8_t *bin)
1114 if (str_len % 2) {
1115 LOG_ERROR("BUG: gdb value with uneven number of characters encountered");
1116 exit(-1);
1119 int i;
1120 for (i = 0; i < str_len; i += 2) {
1121 unsigned t;
1122 if (sscanf(tstr + i, "%02x", &t) != 1) {
1123 LOG_ERROR("BUG: unable to convert register value");
1124 exit(-1);
1127 int j = gdb_reg_pos(target, i/2, str_len/2);
1128 bin[j] = t;
1132 static int gdb_get_registers_packet(struct connection *connection,
1133 char const *packet, int packet_size)
1135 struct target *target = get_target_from_connection(connection);
1136 struct reg **reg_list;
1137 int reg_list_size;
1138 int retval;
1139 int reg_packet_size = 0;
1140 char *reg_packet;
1141 char *reg_packet_p;
1142 int i;
1144 #ifdef _DEBUG_GDB_IO_
1145 LOG_DEBUG("-");
1146 #endif
1148 if ((target->rtos != NULL) && (ERROR_OK == rtos_get_gdb_reg_list(connection)))
1149 return ERROR_OK;
1151 retval = target_get_gdb_reg_list(target, &reg_list, &reg_list_size,
1152 REG_CLASS_GENERAL);
1153 if (retval != ERROR_OK)
1154 return gdb_error(connection, retval);
1156 for (i = 0; i < reg_list_size; i++)
1157 reg_packet_size += DIV_ROUND_UP(reg_list[i]->size, 8) * 2;
1159 assert(reg_packet_size > 0);
1161 reg_packet = malloc(reg_packet_size + 1); /* plus one for string termination null */
1162 reg_packet_p = reg_packet;
1164 for (i = 0; i < reg_list_size; i++) {
1165 if (!reg_list[i]->valid)
1166 reg_list[i]->type->get(reg_list[i]);
1167 gdb_str_to_target(target, reg_packet_p, reg_list[i]);
1168 reg_packet_p += DIV_ROUND_UP(reg_list[i]->size, 8) * 2;
1171 #ifdef _DEBUG_GDB_IO_
1173 char *reg_packet_p_debug;
1174 reg_packet_p_debug = strndup(reg_packet, reg_packet_size);
1175 LOG_DEBUG("reg_packet: %s", reg_packet_p_debug);
1176 free(reg_packet_p_debug);
1178 #endif
1180 gdb_put_packet(connection, reg_packet, reg_packet_size);
1181 free(reg_packet);
1183 free(reg_list);
1185 return ERROR_OK;
1188 static int gdb_set_registers_packet(struct connection *connection,
1189 char const *packet, int packet_size)
1191 struct target *target = get_target_from_connection(connection);
1192 int i;
1193 struct reg **reg_list;
1194 int reg_list_size;
1195 int retval;
1196 char const *packet_p;
1198 #ifdef _DEBUG_GDB_IO_
1199 LOG_DEBUG("-");
1200 #endif
1202 /* skip command character */
1203 packet++;
1204 packet_size--;
1206 if (packet_size % 2) {
1207 LOG_WARNING("GDB set_registers packet with uneven characters received, dropping connection");
1208 return ERROR_SERVER_REMOTE_CLOSED;
1211 retval = target_get_gdb_reg_list(target, &reg_list, &reg_list_size,
1212 REG_CLASS_GENERAL);
1213 if (retval != ERROR_OK)
1214 return gdb_error(connection, retval);
1216 packet_p = packet;
1217 for (i = 0; i < reg_list_size; i++) {
1218 uint8_t *bin_buf;
1219 int chars = (DIV_ROUND_UP(reg_list[i]->size, 8) * 2);
1221 if (packet_p + chars > packet + packet_size)
1222 LOG_ERROR("BUG: register packet is too small for registers");
1224 bin_buf = malloc(DIV_ROUND_UP(reg_list[i]->size, 8));
1225 gdb_target_to_reg(target, packet_p, chars, bin_buf);
1227 reg_list[i]->type->set(reg_list[i], bin_buf);
1229 /* advance packet pointer */
1230 packet_p += chars;
1232 free(bin_buf);
1235 /* free struct reg *reg_list[] array allocated by get_gdb_reg_list */
1236 free(reg_list);
1238 gdb_put_packet(connection, "OK", 2);
1240 return ERROR_OK;
1243 static int gdb_get_register_packet(struct connection *connection,
1244 char const *packet, int packet_size)
1246 struct target *target = get_target_from_connection(connection);
1247 char *reg_packet;
1248 int reg_num = strtoul(packet + 1, NULL, 16);
1249 struct reg **reg_list;
1250 int reg_list_size;
1251 int retval;
1253 #ifdef _DEBUG_GDB_IO_
1254 LOG_DEBUG("-");
1255 #endif
1257 retval = target_get_gdb_reg_list(target, &reg_list, &reg_list_size,
1258 REG_CLASS_ALL);
1259 if (retval != ERROR_OK)
1260 return gdb_error(connection, retval);
1262 if (reg_list_size <= reg_num) {
1263 LOG_ERROR("gdb requested a non-existing register");
1264 return ERROR_SERVER_REMOTE_CLOSED;
1267 if (!reg_list[reg_num]->valid)
1268 reg_list[reg_num]->type->get(reg_list[reg_num]);
1270 reg_packet = malloc(DIV_ROUND_UP(reg_list[reg_num]->size, 8) * 2 + 1); /* plus one for string termination null */
1272 gdb_str_to_target(target, reg_packet, reg_list[reg_num]);
1274 gdb_put_packet(connection, reg_packet, DIV_ROUND_UP(reg_list[reg_num]->size, 8) * 2);
1276 free(reg_list);
1277 free(reg_packet);
1279 return ERROR_OK;
1282 static int gdb_set_register_packet(struct connection *connection,
1283 char const *packet, int packet_size)
1285 struct target *target = get_target_from_connection(connection);
1286 char *separator;
1287 uint8_t *bin_buf;
1288 int reg_num = strtoul(packet + 1, &separator, 16);
1289 struct reg **reg_list;
1290 int reg_list_size;
1291 int retval;
1293 LOG_DEBUG("-");
1295 retval = target_get_gdb_reg_list(target, &reg_list, &reg_list_size,
1296 REG_CLASS_ALL);
1297 if (retval != ERROR_OK)
1298 return gdb_error(connection, retval);
1300 if (reg_list_size <= reg_num) {
1301 LOG_ERROR("gdb requested a non-existing register");
1302 return ERROR_SERVER_REMOTE_CLOSED;
1305 if (*separator != '=') {
1306 LOG_ERROR("GDB 'set register packet', but no '=' following the register number");
1307 return ERROR_SERVER_REMOTE_CLOSED;
1310 /* convert from GDB-string (target-endian) to hex-string (big-endian) */
1311 bin_buf = malloc(DIV_ROUND_UP(reg_list[reg_num]->size, 8));
1312 int chars = (DIV_ROUND_UP(reg_list[reg_num]->size, 8) * 2);
1314 if ((unsigned int)chars != strlen(separator + 1)) {
1315 LOG_ERROR("gdb sent a packet with wrong register size");
1316 free(bin_buf);
1317 return ERROR_SERVER_REMOTE_CLOSED;
1320 gdb_target_to_reg(target, separator + 1, chars, bin_buf);
1322 reg_list[reg_num]->type->set(reg_list[reg_num], bin_buf);
1324 gdb_put_packet(connection, "OK", 2);
1326 free(bin_buf);
1327 free(reg_list);
1329 return ERROR_OK;
1332 /* No attempt is made to translate the "retval" to
1333 * GDB speak. This has to be done at the calling
1334 * site as no mapping really exists.
1336 static int gdb_error(struct connection *connection, int retval)
1338 LOG_DEBUG("Reporting %i to GDB as generic error", retval);
1339 gdb_send_error(connection, EFAULT);
1340 return ERROR_OK;
1343 /* We don't have to worry about the default 2 second timeout for GDB packets,
1344 * because GDB breaks up large memory reads into smaller reads.
1346 * 8191 bytes by the looks of it. Why 8191 bytes instead of 8192?????
1348 static int gdb_read_memory_packet(struct connection *connection,
1349 char const *packet, int packet_size)
1351 struct target *target = get_target_from_connection(connection);
1352 char *separator;
1353 uint32_t addr = 0;
1354 uint32_t len = 0;
1356 uint8_t *buffer;
1357 char *hex_buffer;
1359 int retval = ERROR_OK;
1361 /* skip command character */
1362 packet++;
1364 addr = strtoul(packet, &separator, 16);
1366 if (*separator != ',') {
1367 LOG_ERROR("incomplete read memory packet received, dropping connection");
1368 return ERROR_SERVER_REMOTE_CLOSED;
1371 len = strtoul(separator + 1, NULL, 16);
1373 if (!len) {
1374 LOG_WARNING("invalid read memory packet received (len == 0)");
1375 gdb_put_packet(connection, NULL, 0);
1376 return ERROR_OK;
1379 buffer = malloc(len);
1381 LOG_DEBUG("addr: 0x%8.8" PRIx32 ", len: 0x%8.8" PRIx32 "", addr, len);
1383 retval = target_read_buffer(target, addr, len, buffer);
1385 if ((retval != ERROR_OK) && !gdb_report_data_abort) {
1386 /* TODO : Here we have to lie and send back all zero's lest stack traces won't work.
1387 * At some point this might be fixed in GDB, in which case this code can be removed.
1389 * OpenOCD developers are acutely aware of this problem, but there is nothing
1390 * gained by involving the user in this problem that hopefully will get resolved
1391 * eventually
1393 * http://sourceware.org/cgi-bin/gnatsweb.pl? \
1394 * cmd = view%20audit-trail&database = gdb&pr = 2395
1396 * For now, the default is to fix up things to make current GDB versions work.
1397 * This can be overwritten using the gdb_report_data_abort <'enable'|'disable'> command.
1399 memset(buffer, 0, len);
1400 retval = ERROR_OK;
1403 if (retval == ERROR_OK) {
1404 hex_buffer = malloc(len * 2 + 1);
1406 int pkt_len = hexify(hex_buffer, (char *)buffer, len, len * 2 + 1);
1408 gdb_put_packet(connection, hex_buffer, pkt_len);
1410 free(hex_buffer);
1411 } else
1412 retval = gdb_error(connection, retval);
1414 free(buffer);
1416 return retval;
1419 static int gdb_write_memory_packet(struct connection *connection,
1420 char const *packet, int packet_size)
1422 struct target *target = get_target_from_connection(connection);
1423 char *separator;
1424 uint32_t addr = 0;
1425 uint32_t len = 0;
1427 uint8_t *buffer;
1428 int retval;
1430 /* skip command character */
1431 packet++;
1433 addr = strtoul(packet, &separator, 16);
1435 if (*separator != ',') {
1436 LOG_ERROR("incomplete write memory packet received, dropping connection");
1437 return ERROR_SERVER_REMOTE_CLOSED;
1440 len = strtoul(separator + 1, &separator, 16);
1442 if (*(separator++) != ':') {
1443 LOG_ERROR("incomplete write memory packet received, dropping connection");
1444 return ERROR_SERVER_REMOTE_CLOSED;
1447 buffer = malloc(len);
1449 LOG_DEBUG("addr: 0x%8.8" PRIx32 ", len: 0x%8.8" PRIx32 "", addr, len);
1451 if (unhexify((char *)buffer, separator, len) != (int)len)
1452 LOG_ERROR("unable to decode memory packet");
1454 retval = target_write_buffer(target, addr, len, buffer);
1456 if (retval == ERROR_OK)
1457 gdb_put_packet(connection, "OK", 2);
1458 else
1459 retval = gdb_error(connection, retval);
1461 free(buffer);
1463 return retval;
1466 static int gdb_write_memory_binary_packet(struct connection *connection,
1467 char const *packet, int packet_size)
1469 struct target *target = get_target_from_connection(connection);
1470 char *separator;
1471 uint32_t addr = 0;
1472 uint32_t len = 0;
1474 int retval = ERROR_OK;
1476 /* skip command character */
1477 packet++;
1479 addr = strtoul(packet, &separator, 16);
1481 if (*separator != ',') {
1482 LOG_ERROR("incomplete write memory binary packet received, dropping connection");
1483 return ERROR_SERVER_REMOTE_CLOSED;
1486 len = strtoul(separator + 1, &separator, 16);
1488 if (*(separator++) != ':') {
1489 LOG_ERROR("incomplete write memory binary packet received, dropping connection");
1490 return ERROR_SERVER_REMOTE_CLOSED;
1493 struct gdb_connection *gdb_connection = connection->priv;
1495 if (gdb_connection->mem_write_error) {
1496 retval = ERROR_FAIL;
1497 /* now that we have reported the memory write error, we can clear the condition */
1498 gdb_connection->mem_write_error = false;
1501 /* By replying the packet *immediately* GDB will send us a new packet
1502 * while we write the last one to the target.
1504 if (retval == ERROR_OK)
1505 gdb_put_packet(connection, "OK", 2);
1506 else {
1507 retval = gdb_error(connection, retval);
1508 if (retval != ERROR_OK)
1509 return retval;
1512 if (len) {
1513 LOG_DEBUG("addr: 0x%8.8" PRIx32 ", len: 0x%8.8" PRIx32 "", addr, len);
1515 retval = target_write_buffer(target, addr, len, (uint8_t *)separator);
1516 if (retval != ERROR_OK)
1517 gdb_connection->mem_write_error = true;
1520 return ERROR_OK;
1523 static int gdb_step_continue_packet(struct connection *connection,
1524 char const *packet, int packet_size)
1526 struct target *target = get_target_from_connection(connection);
1527 int current = 0;
1528 uint32_t address = 0x0;
1529 int retval = ERROR_OK;
1531 LOG_DEBUG("-");
1533 if (packet_size > 1)
1534 address = strtoul(packet + 1, NULL, 16);
1535 else
1536 current = 1;
1538 gdb_running_type = packet[0];
1539 if (packet[0] == 'c') {
1540 LOG_DEBUG("continue");
1541 /* resume at current address, don't handle breakpoints, not debugging */
1542 retval = target_resume(target, current, address, 0, 0);
1543 } else if (packet[0] == 's') {
1544 LOG_DEBUG("step");
1545 /* step at current or address, don't handle breakpoints */
1546 retval = target_step(target, current, address, 0);
1548 return retval;
1551 static int gdb_breakpoint_watchpoint_packet(struct connection *connection,
1552 char const *packet, int packet_size)
1554 struct target *target = get_target_from_connection(connection);
1555 int type;
1556 enum breakpoint_type bp_type = BKPT_SOFT /* dummy init to avoid warning */;
1557 enum watchpoint_rw wp_type = WPT_READ /* dummy init to avoid warning */;
1558 uint32_t address;
1559 uint32_t size;
1560 char *separator;
1561 int retval;
1563 LOG_DEBUG("-");
1565 type = strtoul(packet + 1, &separator, 16);
1567 if (type == 0) /* memory breakpoint */
1568 bp_type = BKPT_SOFT;
1569 else if (type == 1) /* hardware breakpoint */
1570 bp_type = BKPT_HARD;
1571 else if (type == 2) /* write watchpoint */
1572 wp_type = WPT_WRITE;
1573 else if (type == 3) /* read watchpoint */
1574 wp_type = WPT_READ;
1575 else if (type == 4) /* access watchpoint */
1576 wp_type = WPT_ACCESS;
1577 else {
1578 LOG_ERROR("invalid gdb watch/breakpoint type(%d), dropping connection", type);
1579 return ERROR_SERVER_REMOTE_CLOSED;
1582 if (gdb_breakpoint_override && ((bp_type == BKPT_SOFT) || (bp_type == BKPT_HARD)))
1583 bp_type = gdb_breakpoint_override_type;
1585 if (*separator != ',') {
1586 LOG_ERROR("incomplete breakpoint/watchpoint packet received, dropping connection");
1587 return ERROR_SERVER_REMOTE_CLOSED;
1590 address = strtoul(separator + 1, &separator, 16);
1592 if (*separator != ',') {
1593 LOG_ERROR("incomplete breakpoint/watchpoint packet received, dropping connection");
1594 return ERROR_SERVER_REMOTE_CLOSED;
1597 size = strtoul(separator + 1, &separator, 16);
1599 switch (type) {
1600 case 0:
1601 case 1:
1602 if (packet[0] == 'Z') {
1603 retval = breakpoint_add(target, address, size, bp_type);
1604 if (retval != ERROR_OK) {
1605 retval = gdb_error(connection, retval);
1606 if (retval != ERROR_OK)
1607 return retval;
1608 } else
1609 gdb_put_packet(connection, "OK", 2);
1610 } else {
1611 breakpoint_remove(target, address);
1612 gdb_put_packet(connection, "OK", 2);
1614 break;
1615 case 2:
1616 case 3:
1617 case 4:
1619 if (packet[0] == 'Z') {
1620 retval = watchpoint_add(target, address, size, wp_type, 0, 0xffffffffu);
1621 if (retval != ERROR_OK) {
1622 retval = gdb_error(connection, retval);
1623 if (retval != ERROR_OK)
1624 return retval;
1625 } else
1626 gdb_put_packet(connection, "OK", 2);
1627 } else {
1628 watchpoint_remove(target, address);
1629 gdb_put_packet(connection, "OK", 2);
1631 break;
1633 default:
1634 break;
1637 return ERROR_OK;
1640 /* print out a string and allocate more space as needed,
1641 * mainly used for XML at this point
1643 static void xml_printf(int *retval, char **xml, int *pos, int *size,
1644 const char *fmt, ...)
1646 if (*retval != ERROR_OK)
1647 return;
1648 int first = 1;
1650 for (;; ) {
1651 if ((*xml == NULL) || (!first)) {
1652 /* start by 0 to exercise all the code paths.
1653 * Need minimum 2 bytes to fit 1 char and 0 terminator. */
1655 *size = *size * 2 + 2;
1656 char *t = *xml;
1657 *xml = realloc(*xml, *size);
1658 if (*xml == NULL) {
1659 if (t)
1660 free(t);
1661 *retval = ERROR_SERVER_REMOTE_CLOSED;
1662 return;
1666 va_list ap;
1667 int ret;
1668 va_start(ap, fmt);
1669 ret = vsnprintf(*xml + *pos, *size - *pos, fmt, ap);
1670 va_end(ap);
1671 if ((ret > 0) && ((ret + 1) < *size - *pos)) {
1672 *pos += ret;
1673 return;
1675 /* there was just enough or not enough space, allocate more. */
1676 first = 0;
1680 static int decode_xfer_read(char const *buf, char **annex, int *ofs, unsigned int *len)
1682 /* Locate the annex. */
1683 const char *annex_end = strchr(buf, ':');
1684 if (annex_end == NULL)
1685 return ERROR_FAIL;
1687 /* After the read marker and annex, qXfer looks like a
1688 * traditional 'm' packet. */
1689 char *separator;
1690 *ofs = strtoul(annex_end + 1, &separator, 16);
1692 if (*separator != ',')
1693 return ERROR_FAIL;
1695 *len = strtoul(separator + 1, NULL, 16);
1697 /* Extract the annex if needed */
1698 if (annex != NULL) {
1699 *annex = strndup(buf, annex_end - buf);
1700 if (*annex == NULL)
1701 return ERROR_FAIL;
1704 return ERROR_OK;
1707 static int compare_bank(const void *a, const void *b)
1709 struct flash_bank *b1, *b2;
1710 b1 = *((struct flash_bank **)a);
1711 b2 = *((struct flash_bank **)b);
1713 if (b1->base == b2->base)
1714 return 0;
1715 else if (b1->base > b2->base)
1716 return 1;
1717 else
1718 return -1;
1721 static int gdb_memory_map(struct connection *connection,
1722 char const *packet, int packet_size)
1724 /* We get away with only specifying flash here. Regions that are not
1725 * specified are treated as if we provided no memory map(if not we
1726 * could detect the holes and mark them as RAM).
1727 * Normally we only execute this code once, but no big deal if we
1728 * have to regenerate it a couple of times.
1731 struct target *target = get_target_from_connection(connection);
1732 struct flash_bank *p;
1733 char *xml = NULL;
1734 int size = 0;
1735 int pos = 0;
1736 int retval = ERROR_OK;
1737 struct flash_bank **banks;
1738 int offset;
1739 int length;
1740 char *separator;
1741 uint32_t ram_start = 0;
1742 int i;
1743 int target_flash_banks = 0;
1745 /* skip command character */
1746 packet += 23;
1748 offset = strtoul(packet, &separator, 16);
1749 length = strtoul(separator + 1, &separator, 16);
1751 xml_printf(&retval, &xml, &pos, &size, "<memory-map>\n");
1753 /* Sort banks in ascending order. We need to report non-flash
1754 * memory as ram (or rather read/write) by default for GDB, since
1755 * it has no concept of non-cacheable read/write memory (i/o etc).
1757 * FIXME Most non-flash addresses are *NOT* RAM! Don't lie.
1758 * Current versions of GDB assume unlisted addresses are RAM...
1760 banks = malloc(sizeof(struct flash_bank *)*flash_get_bank_count());
1762 for (i = 0; i < flash_get_bank_count(); i++) {
1763 p = get_flash_bank_by_num_noprobe(i);
1764 if (p->target != target)
1765 continue;
1766 retval = get_flash_bank_by_num(i, &p);
1767 if (retval != ERROR_OK) {
1768 free(banks);
1769 gdb_error(connection, retval);
1770 return retval;
1772 banks[target_flash_banks++] = p;
1775 qsort(banks, target_flash_banks, sizeof(struct flash_bank *),
1776 compare_bank);
1778 for (i = 0; i < target_flash_banks; i++) {
1779 int j;
1780 unsigned sector_size = 0;
1781 uint32_t start;
1783 p = banks[i];
1784 start = p->base;
1786 if (ram_start < p->base)
1787 xml_printf(&retval, &xml, &pos, &size,
1788 "<memory type=\"ram\" start=\"0x%x\" "
1789 "length=\"0x%x\"/>\n",
1790 ram_start, p->base - ram_start);
1792 /* Report adjacent groups of same-size sectors. So for
1793 * example top boot CFI flash will list an initial region
1794 * with several large sectors (maybe 128KB) and several
1795 * smaller ones at the end (maybe 32KB). STR7 will have
1796 * regions with 8KB, 32KB, and 64KB sectors; etc.
1798 for (j = 0; j < p->num_sectors; j++) {
1799 unsigned group_len;
1801 /* Maybe start a new group of sectors. */
1802 if (sector_size == 0) {
1803 start = p->base + p->sectors[j].offset;
1804 xml_printf(&retval, &xml, &pos, &size,
1805 "<memory type=\"flash\" "
1806 "start=\"0x%x\" ",
1807 start);
1808 sector_size = p->sectors[j].size;
1811 /* Does this finish a group of sectors?
1812 * If not, continue an already-started group.
1814 if (j == p->num_sectors - 1)
1815 group_len = (p->base + p->size) - start;
1816 else if (p->sectors[j + 1].size != sector_size)
1817 group_len = p->base + p->sectors[j + 1].offset
1818 - start;
1819 else
1820 continue;
1822 xml_printf(&retval, &xml, &pos, &size,
1823 "length=\"0x%x\">\n"
1824 "<property name=\"blocksize\">"
1825 "0x%x</property>\n"
1826 "</memory>\n",
1827 group_len,
1828 sector_size);
1829 sector_size = 0;
1832 ram_start = p->base + p->size;
1835 if (ram_start != 0)
1836 xml_printf(&retval, &xml, &pos, &size,
1837 "<memory type=\"ram\" start=\"0x%x\" "
1838 "length=\"0x%x\"/>\n",
1839 ram_start, 0-ram_start);
1840 /* ELSE a flash chip could be at the very end of the 32 bit address
1841 * space, in which case ram_start will be precisely 0
1844 free(banks);
1845 banks = NULL;
1847 xml_printf(&retval, &xml, &pos, &size, "</memory-map>\n");
1849 if (retval != ERROR_OK) {
1850 gdb_error(connection, retval);
1851 return retval;
1854 if (offset + length > pos)
1855 length = pos - offset;
1857 char *t = malloc(length + 1);
1858 t[0] = 'l';
1859 memcpy(t + 1, xml + offset, length);
1860 gdb_put_packet(connection, t, length + 1);
1862 free(t);
1863 free(xml);
1864 return ERROR_OK;
1867 static const char *gdb_get_reg_type_name(enum reg_type type)
1869 switch (type) {
1870 case REG_TYPE_INT:
1871 return "int";
1872 case REG_TYPE_INT8:
1873 return "int8";
1874 case REG_TYPE_INT16:
1875 return "int16";
1876 case REG_TYPE_INT32:
1877 return "int32";
1878 case REG_TYPE_INT64:
1879 return "int64";
1880 case REG_TYPE_INT128:
1881 return "int128";
1882 case REG_TYPE_UINT8:
1883 return "uint8";
1884 case REG_TYPE_UINT16:
1885 return "uint16";
1886 case REG_TYPE_UINT32:
1887 return "uint32";
1888 case REG_TYPE_UINT64:
1889 return "uint64";
1890 case REG_TYPE_UINT128:
1891 return "uint128";
1892 case REG_TYPE_CODE_PTR:
1893 return "code_ptr";
1894 case REG_TYPE_DATA_PTR:
1895 return "data_ptr";
1896 case REG_TYPE_FLOAT:
1897 return "float";
1898 case REG_TYPE_IEEE_SINGLE:
1899 return "ieee_single";
1900 case REG_TYPE_IEEE_DOUBLE:
1901 return "ieee_double";
1902 case REG_TYPE_ARCH_DEFINED:
1903 return "int"; /* return arbitrary string to avoid compile warning. */
1906 return "int"; /* "int" as default value */
1909 static int gdb_generate_reg_type_description(struct target *target,
1910 char **tdesc, int *pos, int *size, struct reg_data_type *type)
1912 int retval = ERROR_OK;
1914 if (type->type_class == REG_TYPE_CLASS_VECTOR) {
1915 /* <vector id="id" type="type" count="count"/> */
1916 xml_printf(&retval, tdesc, pos, size,
1917 "<vector id=\"%s\" type=\"%s\" count=\"%d\"/>\n",
1918 type->id, type->reg_type_vector->type->id,
1919 type->reg_type_vector->count);
1921 } else if (type->type_class == REG_TYPE_CLASS_UNION) {
1922 /* <union id="id">
1923 * <field name="name" type="type"/> ...
1924 * </union> */
1925 xml_printf(&retval, tdesc, pos, size,
1926 "<union id=\"%s\">\n",
1927 type->id);
1929 struct reg_data_type_union_field *field;
1930 field = type->reg_type_union->fields;
1931 while (field != NULL) {
1932 xml_printf(&retval, tdesc, pos, size,
1933 "<field name=\"%s\" type=\"%s\"/>\n",
1934 field->name, field->type->id);
1936 field = field->next;
1939 xml_printf(&retval, tdesc, pos, size,
1940 "</union>\n");
1942 } else if (type->type_class == REG_TYPE_CLASS_STRUCT) {
1943 struct reg_data_type_struct_field *field;
1944 field = type->reg_type_struct->fields;
1946 if (field->use_bitfields) {
1947 /* <struct id="id" size="size">
1948 * <field name="name" start="start" end="end"/> ...
1949 * </struct> */
1950 xml_printf(&retval, tdesc, pos, size,
1951 "<struct id=\"%s\" size=\"%d\">\n",
1952 type->id, type->reg_type_struct->size);
1953 while (field != NULL) {
1954 xml_printf(&retval, tdesc, pos, size,
1955 "<field name=\"%s\" start=\"%d\" end=\"%d\"/>\n",
1956 field->name, field->bitfield->start,
1957 field->bitfield->end);
1959 field = field->next;
1961 } else {
1962 /* <struct id="id">
1963 * <field name="name" type="type"/> ...
1964 * </struct> */
1965 xml_printf(&retval, tdesc, pos, size,
1966 "<struct id=\"%s\">\n",
1967 type->id);
1968 while (field != NULL) {
1969 xml_printf(&retval, tdesc, pos, size,
1970 "<field name=\"%s\" type=\"%s\"/>\n",
1971 field->name, field->type->id);
1973 field = field->next;
1977 xml_printf(&retval, tdesc, pos, size,
1978 "</struct>\n");
1980 } else if (type->type_class == REG_TYPE_CLASS_FLAGS) {
1981 /* <flags id="id" size="size">
1982 * <field name="name" start="start" end="end"/> ...
1983 * </flags> */
1984 xml_printf(&retval, tdesc, pos, size,
1985 "<flags id=\"%s\" size=\"%d\">\n",
1986 type->id, type->reg_type_flags->size);
1988 struct reg_data_type_flags_field *field;
1989 field = type->reg_type_flags->fields;
1990 while (field != NULL) {
1991 xml_printf(&retval, tdesc, pos, size,
1992 "<field name=\"%s\" start=\"%d\" end=\"%d\"/>\n",
1993 field->name, field->bitfield->start, field->bitfield->end);
1995 field = field->next;
1998 xml_printf(&retval, tdesc, pos, size,
1999 "</flags>\n");
2003 return ERROR_OK;
2006 /* Get a list of available target registers features. feature_list must
2007 * be freed by caller.
2009 static int get_reg_features_list(struct target *target, char const **feature_list[], int *feature_list_size,
2010 struct reg **reg_list, int reg_list_size)
2012 int tbl_sz = 0;
2014 /* Start with only one element */
2015 *feature_list = calloc(1, sizeof(char *));
2017 for (int i = 0; i < reg_list_size; i++) {
2018 if (reg_list[i]->exist == false)
2019 continue;
2021 if (reg_list[i]->feature != NULL
2022 && reg_list[i]->feature->name != NULL
2023 && (strcmp(reg_list[i]->feature->name, ""))) {
2024 /* We found a feature, check if the feature is already in the
2025 * table. If not, allocate a new entry for the table and
2026 * put the new feature in it.
2028 for (int j = 0; j < (tbl_sz + 1); j++) {
2029 if (!((*feature_list)[j])) {
2030 (*feature_list)[tbl_sz++] = reg_list[i]->feature->name;
2031 *feature_list = realloc(*feature_list, sizeof(char *) * (tbl_sz + 1));
2032 (*feature_list)[tbl_sz] = NULL;
2033 break;
2034 } else {
2035 if (!strcmp((*feature_list)[j], reg_list[i]->feature->name))
2036 break;
2042 if (feature_list_size)
2043 *feature_list_size = tbl_sz;
2045 return ERROR_OK;
2048 static int gdb_generate_target_description(struct target *target, char **tdesc_out)
2050 int retval = ERROR_OK;
2051 struct reg **reg_list = NULL;
2052 int reg_list_size;
2053 char const **features = NULL;
2054 int feature_list_size = 0;
2055 char *tdesc = NULL;
2056 int pos = 0;
2057 int size = 0;
2059 retval = target_get_gdb_reg_list(target, &reg_list,
2060 &reg_list_size, REG_CLASS_ALL);
2062 if (retval != ERROR_OK) {
2063 LOG_ERROR("get register list failed");
2064 retval = ERROR_FAIL;
2065 goto error;
2068 if (reg_list_size <= 0) {
2069 LOG_ERROR("get register list failed");
2070 retval = ERROR_FAIL;
2071 goto error;
2074 /* Get a list of available target registers features */
2075 retval = get_reg_features_list(target, &features, &feature_list_size, reg_list, reg_list_size);
2076 if (retval != ERROR_OK) {
2077 LOG_ERROR("Can't get the registers feature list");
2078 retval = ERROR_FAIL;
2079 goto error;
2082 /* If we found some features associated with registers, create sections */
2083 int current_feature = 0;
2085 xml_printf(&retval, &tdesc, &pos, &size,
2086 "<?xml version=\"1.0\"?>\n"
2087 "<!DOCTYPE target SYSTEM \"gdb-target.dtd\">\n"
2088 "<target version=\"1.0\">\n");
2090 /* generate target description according to register list */
2091 if (features != NULL) {
2092 while (features[current_feature]) {
2094 xml_printf(&retval, &tdesc, &pos, &size,
2095 "<feature name=\"%s\">\n",
2096 features[current_feature]);
2098 int i;
2099 for (i = 0; i < reg_list_size; i++) {
2101 if (reg_list[i]->exist == false)
2102 continue;
2104 if (strcmp(reg_list[i]->feature->name, features[current_feature]))
2105 continue;
2107 const char *type_str;
2108 if (reg_list[i]->reg_data_type != NULL) {
2109 if (reg_list[i]->reg_data_type->type == REG_TYPE_ARCH_DEFINED) {
2110 /* generate <type... first, if there are architecture-defined types. */
2111 gdb_generate_reg_type_description(target, &tdesc, &pos, &size,
2112 reg_list[i]->reg_data_type);
2114 type_str = reg_list[i]->reg_data_type->id;
2115 } else {
2116 /* predefined type */
2117 type_str = gdb_get_reg_type_name(
2118 reg_list[i]->reg_data_type->type);
2120 } else {
2121 /* Default type is "int" */
2122 type_str = "int";
2125 xml_printf(&retval, &tdesc, &pos, &size,
2126 "<reg name=\"%s\"", reg_list[i]->name);
2127 xml_printf(&retval, &tdesc, &pos, &size,
2128 " bitsize=\"%d\"", reg_list[i]->size);
2129 xml_printf(&retval, &tdesc, &pos, &size,
2130 " regnum=\"%d\"", reg_list[i]->number);
2131 if (reg_list[i]->caller_save)
2132 xml_printf(&retval, &tdesc, &pos, &size,
2133 " save-restore=\"yes\"");
2134 else
2135 xml_printf(&retval, &tdesc, &pos, &size,
2136 " save-restore=\"no\"");
2138 xml_printf(&retval, &tdesc, &pos, &size,
2139 " type=\"%s\"", type_str);
2141 if (reg_list[i]->group != NULL)
2142 xml_printf(&retval, &tdesc, &pos, &size,
2143 " group=\"%s\"", reg_list[i]->group);
2145 xml_printf(&retval, &tdesc, &pos, &size,
2146 "/>\n");
2149 xml_printf(&retval, &tdesc, &pos, &size,
2150 "</feature>\n");
2152 current_feature++;
2156 xml_printf(&retval, &tdesc, &pos, &size,
2157 "</target>\n");
2159 error:
2160 free(features);
2161 free(reg_list);
2163 if (retval == ERROR_OK)
2164 *tdesc_out = tdesc;
2165 else
2166 free(tdesc);
2168 return retval;
2171 static int gdb_get_target_description_chunk(struct target *target, struct target_desc_format *target_desc,
2172 char **chunk, int32_t offset, uint32_t length)
2174 if (target_desc == NULL) {
2175 LOG_ERROR("Unable to Generate Target Description");
2176 return ERROR_FAIL;
2179 char *tdesc = target_desc->tdesc;
2180 uint32_t tdesc_length = target_desc->tdesc_length;
2182 if (tdesc == NULL) {
2183 int retval = gdb_generate_target_description(target, &tdesc);
2184 if (retval != ERROR_OK) {
2185 LOG_ERROR("Unable to Generate Target Description");
2186 return ERROR_FAIL;
2189 tdesc_length = strlen(tdesc);
2192 char transfer_type;
2194 if (length < (tdesc_length - offset))
2195 transfer_type = 'm';
2196 else
2197 transfer_type = 'l';
2199 *chunk = malloc(length + 2);
2200 if (*chunk == NULL) {
2201 LOG_ERROR("Unable to allocate memory");
2202 return ERROR_FAIL;
2205 (*chunk)[0] = transfer_type;
2206 if (transfer_type == 'm') {
2207 strncpy((*chunk) + 1, tdesc + offset, length);
2208 (*chunk)[1 + length] = '\0';
2209 } else {
2210 strncpy((*chunk) + 1, tdesc + offset, tdesc_length - offset);
2211 (*chunk)[1 + (tdesc_length - offset)] = '\0';
2213 /* After gdb-server sends out last chunk, invalidate tdesc. */
2214 free(tdesc);
2215 tdesc = NULL;
2216 tdesc_length = 0;
2219 target_desc->tdesc = tdesc;
2220 target_desc->tdesc_length = tdesc_length;
2222 return ERROR_OK;
2225 static int gdb_target_description_supported(struct target *target, int *supported)
2227 int retval = ERROR_OK;
2228 struct reg **reg_list = NULL;
2229 int reg_list_size = 0;
2230 char const **features = NULL;
2231 int feature_list_size = 0;
2233 retval = target_get_gdb_reg_list(target, &reg_list,
2234 &reg_list_size, REG_CLASS_ALL);
2235 if (retval != ERROR_OK) {
2236 LOG_ERROR("get register list failed");
2237 goto error;
2240 if (reg_list_size <= 0) {
2241 LOG_ERROR("get register list failed");
2242 retval = ERROR_FAIL;
2243 goto error;
2246 /* Get a list of available target registers features */
2247 retval = get_reg_features_list(target, &features, &feature_list_size, reg_list, reg_list_size);
2248 if (retval != ERROR_OK) {
2249 LOG_ERROR("Can't get the registers feature list");
2250 goto error;
2253 if (supported) {
2254 if (feature_list_size)
2255 *supported = 1;
2256 else
2257 *supported = 0;
2260 error:
2261 free(features);
2263 free(reg_list);
2265 return retval;
2268 static int gdb_query_packet(struct connection *connection,
2269 char const *packet, int packet_size)
2271 struct command_context *cmd_ctx = connection->cmd_ctx;
2272 struct gdb_connection *gdb_connection = connection->priv;
2273 struct target *target = get_target_from_connection(connection);
2275 if (strncmp(packet, "qRcmd,", 6) == 0) {
2276 if (packet_size > 6) {
2277 char *cmd;
2278 cmd = malloc((packet_size - 6) / 2 + 1);
2279 int len = unhexify(cmd, packet + 6, (packet_size - 6) / 2);
2280 cmd[len] = 0;
2282 /* We want to print all debug output to GDB connection */
2283 log_add_callback(gdb_log_callback, connection);
2284 target_call_timer_callbacks_now();
2285 /* some commands need to know the GDB connection, make note of current
2286 * GDB connection. */
2287 current_gdb_connection = gdb_connection;
2288 command_run_line(cmd_ctx, cmd);
2289 current_gdb_connection = NULL;
2290 target_call_timer_callbacks_now();
2291 log_remove_callback(gdb_log_callback, connection);
2292 free(cmd);
2294 gdb_put_packet(connection, "OK", 2);
2295 return ERROR_OK;
2296 } else if (strncmp(packet, "qCRC:", 5) == 0) {
2297 if (packet_size > 5) {
2298 int retval;
2299 char gdb_reply[10];
2300 char *separator;
2301 uint32_t checksum;
2302 uint32_t addr = 0;
2303 uint32_t len = 0;
2305 /* skip command character */
2306 packet += 5;
2308 addr = strtoul(packet, &separator, 16);
2310 if (*separator != ',') {
2311 LOG_ERROR("incomplete read memory packet received, dropping connection");
2312 return ERROR_SERVER_REMOTE_CLOSED;
2315 len = strtoul(separator + 1, NULL, 16);
2317 retval = target_checksum_memory(target, addr, len, &checksum);
2319 if (retval == ERROR_OK) {
2320 snprintf(gdb_reply, 10, "C%8.8" PRIx32 "", checksum);
2321 gdb_put_packet(connection, gdb_reply, 9);
2322 } else {
2323 retval = gdb_error(connection, retval);
2324 if (retval != ERROR_OK)
2325 return retval;
2328 return ERROR_OK;
2330 } else if (strncmp(packet, "qSupported", 10) == 0) {
2331 /* we currently support packet size and qXfer:memory-map:read (if enabled)
2332 * qXfer:features:read is supported for some targets */
2333 int retval = ERROR_OK;
2334 char *buffer = NULL;
2335 int pos = 0;
2336 int size = 0;
2337 int gdb_target_desc_supported = 0;
2339 /* we need to test that the target supports target descriptions */
2340 retval = gdb_target_description_supported(target, &gdb_target_desc_supported);
2341 if (retval != ERROR_OK) {
2342 LOG_INFO("Failed detecting Target Description Support, disabling");
2343 gdb_target_desc_supported = 0;
2346 /* support may be disabled globally */
2347 if (gdb_use_target_description == 0) {
2348 if (gdb_target_desc_supported)
2349 LOG_WARNING("Target Descriptions Supported, but disabled");
2350 gdb_target_desc_supported = 0;
2353 xml_printf(&retval,
2354 &buffer,
2355 &pos,
2356 &size,
2357 "PacketSize=%x;qXfer:memory-map:read%c;qXfer:features:read%c;QStartNoAckMode+",
2358 (GDB_BUFFER_SIZE - 1),
2359 ((gdb_use_memory_map == 1) && (flash_get_bank_count() > 0)) ? '+' : '-',
2360 (gdb_target_desc_supported == 1) ? '+' : '-');
2362 if (retval != ERROR_OK) {
2363 gdb_send_error(connection, 01);
2364 return ERROR_OK;
2367 gdb_put_packet(connection, buffer, strlen(buffer));
2368 free(buffer);
2370 return ERROR_OK;
2371 } else if ((strncmp(packet, "qXfer:memory-map:read::", 23) == 0)
2372 && (flash_get_bank_count() > 0))
2373 return gdb_memory_map(connection, packet, packet_size);
2374 else if (strncmp(packet, "qXfer:features:read:", 20) == 0) {
2375 char *xml = NULL;
2376 int retval = ERROR_OK;
2378 int offset;
2379 unsigned int length;
2381 /* skip command character */
2382 packet += 20;
2384 if (decode_xfer_read(packet, NULL, &offset, &length) < 0) {
2385 gdb_send_error(connection, 01);
2386 return ERROR_OK;
2389 /* Target should prepare correct target description for annex.
2390 * The first character of returned xml is 'm' or 'l'. 'm' for
2391 * there are *more* chunks to transfer. 'l' for it is the *last*
2392 * chunk of target description.
2394 retval = gdb_get_target_description_chunk(target, &gdb_connection->target_desc,
2395 &xml, offset, length);
2396 if (retval != ERROR_OK) {
2397 gdb_error(connection, retval);
2398 return retval;
2401 gdb_put_packet(connection, xml, strlen(xml));
2403 free(xml);
2404 return ERROR_OK;
2405 } else if (strncmp(packet, "QStartNoAckMode", 15) == 0) {
2406 gdb_connection->noack_mode = 1;
2407 gdb_put_packet(connection, "OK", 2);
2408 return ERROR_OK;
2411 gdb_put_packet(connection, "", 0);
2412 return ERROR_OK;
2415 static int gdb_v_packet(struct connection *connection,
2416 char const *packet, int packet_size)
2418 struct gdb_connection *gdb_connection = connection->priv;
2419 struct gdb_service *gdb_service = connection->service->priv;
2420 int result;
2422 /* if flash programming disabled - send a empty reply */
2424 if (gdb_flash_program == 0) {
2425 gdb_put_packet(connection, "", 0);
2426 return ERROR_OK;
2429 if (strncmp(packet, "vFlashErase:", 12) == 0) {
2430 unsigned long addr;
2431 unsigned long length;
2433 char const *parse = packet + 12;
2434 if (*parse == '\0') {
2435 LOG_ERROR("incomplete vFlashErase packet received, dropping connection");
2436 return ERROR_SERVER_REMOTE_CLOSED;
2439 addr = strtoul(parse, (char **)&parse, 16);
2441 if (*(parse++) != ',' || *parse == '\0') {
2442 LOG_ERROR("incomplete vFlashErase packet received, dropping connection");
2443 return ERROR_SERVER_REMOTE_CLOSED;
2446 length = strtoul(parse, (char **)&parse, 16);
2448 if (*parse != '\0') {
2449 LOG_ERROR("incomplete vFlashErase packet received, dropping connection");
2450 return ERROR_SERVER_REMOTE_CLOSED;
2453 /* assume all sectors need erasing - stops any problems
2454 * when flash_write is called multiple times */
2455 flash_set_dirty();
2457 /* perform any target specific operations before the erase */
2458 target_call_event_callbacks(gdb_service->target,
2459 TARGET_EVENT_GDB_FLASH_ERASE_START);
2461 /* vFlashErase:addr,length messages require region start and
2462 * end to be "block" aligned ... if padding is ever needed,
2463 * GDB will have become dangerously confused.
2465 result = flash_erase_address_range(gdb_service->target,
2466 false, addr, length);
2468 /* perform any target specific operations after the erase */
2469 target_call_event_callbacks(gdb_service->target,
2470 TARGET_EVENT_GDB_FLASH_ERASE_END);
2472 /* perform erase */
2473 if (result != ERROR_OK) {
2474 /* GDB doesn't evaluate the actual error number returned,
2475 * treat a failed erase as an I/O error
2477 gdb_send_error(connection, EIO);
2478 LOG_ERROR("flash_erase returned %i", result);
2479 } else
2480 gdb_put_packet(connection, "OK", 2);
2482 return ERROR_OK;
2485 if (strncmp(packet, "vFlashWrite:", 12) == 0) {
2486 int retval;
2487 unsigned long addr;
2488 unsigned long length;
2489 char const *parse = packet + 12;
2491 if (*parse == '\0') {
2492 LOG_ERROR("incomplete vFlashErase packet received, dropping connection");
2493 return ERROR_SERVER_REMOTE_CLOSED;
2495 addr = strtoul(parse, (char **)&parse, 16);
2496 if (*(parse++) != ':') {
2497 LOG_ERROR("incomplete vFlashErase packet received, dropping connection");
2498 return ERROR_SERVER_REMOTE_CLOSED;
2500 length = packet_size - (parse - packet);
2502 /* create a new image if there isn't already one */
2503 if (gdb_connection->vflash_image == NULL) {
2504 gdb_connection->vflash_image = malloc(sizeof(struct image));
2505 image_open(gdb_connection->vflash_image, "", "build");
2508 /* create new section with content from packet buffer */
2509 retval = image_add_section(gdb_connection->vflash_image,
2510 addr, length, 0x0, (uint8_t const *)parse);
2511 if (retval != ERROR_OK)
2512 return retval;
2514 gdb_put_packet(connection, "OK", 2);
2516 return ERROR_OK;
2519 if (strncmp(packet, "vFlashDone", 10) == 0) {
2520 uint32_t written;
2522 /* process the flashing buffer. No need to erase as GDB
2523 * always issues a vFlashErase first. */
2524 target_call_event_callbacks(gdb_service->target,
2525 TARGET_EVENT_GDB_FLASH_WRITE_START);
2526 result = flash_write(gdb_service->target, gdb_connection->vflash_image, &written, 0);
2527 target_call_event_callbacks(gdb_service->target, TARGET_EVENT_GDB_FLASH_WRITE_END);
2528 if (result != ERROR_OK) {
2529 if (result == ERROR_FLASH_DST_OUT_OF_BANK)
2530 gdb_put_packet(connection, "E.memtype", 9);
2531 else
2532 gdb_send_error(connection, EIO);
2533 } else {
2534 LOG_DEBUG("wrote %u bytes from vFlash image to flash", (unsigned)written);
2535 gdb_put_packet(connection, "OK", 2);
2538 image_close(gdb_connection->vflash_image);
2539 free(gdb_connection->vflash_image);
2540 gdb_connection->vflash_image = NULL;
2542 return ERROR_OK;
2545 gdb_put_packet(connection, "", 0);
2546 return ERROR_OK;
2549 static int gdb_detach(struct connection *connection)
2551 struct gdb_service *gdb_service = connection->service->priv;
2553 target_call_event_callbacks(gdb_service->target, TARGET_EVENT_GDB_DETACH);
2555 return gdb_put_packet(connection, "OK", 2);
2558 /* The format of 'F' response packet is
2559 * Fretcode,errno,Ctrl-C flag;call-specific attachment
2561 static int gdb_fileio_response_packet(struct connection *connection,
2562 char const *packet, int packet_size)
2564 struct target *target = get_target_from_connection(connection);
2565 char *separator;
2566 char *parsing_point;
2567 int fileio_retcode = strtoul(packet + 1, &separator, 16);
2568 int fileio_errno = 0;
2569 bool fileio_ctrl_c = false;
2570 int retval;
2572 LOG_DEBUG("-");
2574 if (*separator == ',') {
2575 parsing_point = separator + 1;
2576 fileio_errno = strtoul(parsing_point, &separator, 16);
2577 if (*separator == ',') {
2578 if (*(separator + 1) == 'C') {
2579 /* TODO: process ctrl-c */
2580 fileio_ctrl_c = true;
2585 LOG_DEBUG("File-I/O response, retcode: 0x%x, errno: 0x%x, ctrl-c: %s",
2586 fileio_retcode, fileio_errno, fileio_ctrl_c ? "true" : "false");
2588 retval = target_gdb_fileio_end(target, fileio_retcode, fileio_errno, fileio_ctrl_c);
2589 if (retval != ERROR_OK)
2590 return ERROR_FAIL;
2592 /* After File-I/O ends, keep continue or step */
2593 if (gdb_running_type == 'c')
2594 retval = target_resume(target, 1, 0x0, 0, 0);
2595 else if (gdb_running_type == 's')
2596 retval = target_step(target, 1, 0x0, 0);
2597 else
2598 retval = ERROR_FAIL;
2600 if (retval != ERROR_OK)
2601 return ERROR_FAIL;
2603 return ERROR_OK;
2606 static void gdb_log_callback(void *priv, const char *file, unsigned line,
2607 const char *function, const char *string)
2609 struct connection *connection = priv;
2610 struct gdb_connection *gdb_con = connection->priv;
2612 if (gdb_con->busy) {
2613 /* do not reply this using the O packet */
2614 return;
2617 gdb_output_con(connection, string);
2620 static void gdb_sig_halted(struct connection *connection)
2622 char sig_reply[4];
2623 snprintf(sig_reply, 4, "T%2.2x", 2);
2624 gdb_put_packet(connection, sig_reply, 3);
2627 static int gdb_input_inner(struct connection *connection)
2629 /* Do not allocate this on the stack */
2630 static char gdb_packet_buffer[GDB_BUFFER_SIZE];
2632 struct gdb_service *gdb_service = connection->service->priv;
2633 struct target *target = gdb_service->target;
2634 char const *packet = gdb_packet_buffer;
2635 int packet_size;
2636 int retval;
2637 struct gdb_connection *gdb_con = connection->priv;
2638 static int extended_protocol;
2640 /* drain input buffer. If one of the packets fail, then an error
2641 * packet is replied, if applicable.
2643 * This loop will terminate and the error code is returned.
2645 * The calling fn will check if this error is something that
2646 * can be recovered from, or if the connection must be closed.
2648 * If the error is recoverable, this fn is called again to
2649 * drain the rest of the buffer.
2651 do {
2652 packet_size = GDB_BUFFER_SIZE-1;
2653 retval = gdb_get_packet(connection, gdb_packet_buffer, &packet_size);
2654 if (retval != ERROR_OK)
2655 return retval;
2657 /* terminate with zero */
2658 gdb_packet_buffer[packet_size] = '\0';
2660 if (LOG_LEVEL_IS(LOG_LVL_DEBUG)) {
2661 if (packet[0] == 'X') {
2662 /* binary packets spew junk into the debug log stream */
2663 char buf[50];
2664 int x;
2665 for (x = 0; (x < 49) && (packet[x] != ':'); x++)
2666 buf[x] = packet[x];
2667 buf[x] = 0;
2668 LOG_DEBUG("received packet: '%s:<binary-data>'", buf);
2669 } else
2670 LOG_DEBUG("received packet: '%s'", packet);
2673 if (packet_size > 0) {
2674 retval = ERROR_OK;
2675 switch (packet[0]) {
2676 case 'T': /* Is thread alive? */
2677 gdb_thread_packet(connection, packet, packet_size);
2678 break;
2679 case 'H': /* Set current thread ( 'c' for step and continue,
2680 * 'g' for all other operations ) */
2681 gdb_thread_packet(connection, packet, packet_size);
2682 break;
2683 case 'q':
2684 case 'Q':
2685 retval = gdb_thread_packet(connection, packet, packet_size);
2686 if (retval == GDB_THREAD_PACKET_NOT_CONSUMED)
2687 retval = gdb_query_packet(connection, packet, packet_size);
2688 break;
2689 case 'g':
2690 retval = gdb_get_registers_packet(connection, packet, packet_size);
2691 break;
2692 case 'G':
2693 retval = gdb_set_registers_packet(connection, packet, packet_size);
2694 break;
2695 case 'p':
2696 retval = gdb_get_register_packet(connection, packet, packet_size);
2697 break;
2698 case 'P':
2699 retval = gdb_set_register_packet(connection, packet, packet_size);
2700 break;
2701 case 'm':
2702 retval = gdb_read_memory_packet(connection, packet, packet_size);
2703 break;
2704 case 'M':
2705 retval = gdb_write_memory_packet(connection, packet, packet_size);
2706 break;
2707 case 'z':
2708 case 'Z':
2709 retval = gdb_breakpoint_watchpoint_packet(connection, packet, packet_size);
2710 break;
2711 case '?':
2712 gdb_last_signal_packet(connection, packet, packet_size);
2713 break;
2714 case 'c':
2715 case 's':
2717 gdb_thread_packet(connection, packet, packet_size);
2718 log_add_callback(gdb_log_callback, connection);
2720 if (gdb_con->mem_write_error) {
2721 LOG_ERROR("Memory write failure!");
2723 /* now that we have reported the memory write error,
2724 * we can clear the condition */
2725 gdb_con->mem_write_error = false;
2728 bool nostep = false;
2729 bool already_running = false;
2730 if (target->state == TARGET_RUNNING) {
2731 LOG_WARNING("WARNING! The target is already running. "
2732 "All changes GDB did to registers will be discarded! "
2733 "Waiting for target to halt.");
2734 already_running = true;
2735 } else if (target->state != TARGET_HALTED) {
2736 LOG_WARNING("The target is not in the halted nor running stated, " \
2737 "stepi/continue ignored.");
2738 nostep = true;
2739 } else if ((packet[0] == 's') && gdb_con->sync) {
2740 /* Hmm..... when you issue a continue in GDB, then a "stepi" is
2741 * sent by GDB first to OpenOCD, thus defeating the check to
2742 * make only the single stepping have the sync feature...
2744 nostep = true;
2745 LOG_WARNING("stepi ignored. GDB will now fetch the register state " \
2746 "from the target.");
2748 gdb_con->sync = false;
2750 if (!already_running && nostep) {
2751 /* Either the target isn't in the halted state, then we can't
2752 * step/continue. This might be early setup, etc.
2754 * Or we want to allow GDB to pick up a fresh set of
2755 * register values without modifying the target state.
2758 gdb_sig_halted(connection);
2760 /* stop forwarding log packets! */
2761 log_remove_callback(gdb_log_callback, connection);
2762 } else {
2763 /* We're running/stepping, in which case we can
2764 * forward log output until the target is halted
2766 gdb_con->frontend_state = TARGET_RUNNING;
2767 target_call_event_callbacks(target, TARGET_EVENT_GDB_START);
2769 if (!already_running) {
2770 /* Here we don't want packet processing to stop even if this fails,
2771 * so we use a local variable instead of retval. */
2772 retval = gdb_step_continue_packet(connection, packet, packet_size);
2773 if (retval != ERROR_OK) {
2774 /* we'll never receive a halted
2775 * condition... issue a false one..
2777 gdb_frontend_halted(target, connection);
2782 break;
2783 case 'v':
2784 retval = gdb_v_packet(connection, packet, packet_size);
2785 break;
2786 case 'D':
2787 retval = gdb_detach(connection);
2788 extended_protocol = 0;
2789 break;
2790 case 'X':
2791 retval = gdb_write_memory_binary_packet(connection, packet, packet_size);
2792 if (retval != ERROR_OK)
2793 return retval;
2794 break;
2795 case 'k':
2796 if (extended_protocol != 0) {
2797 gdb_con->attached = false;
2798 break;
2800 gdb_put_packet(connection, "OK", 2);
2801 return ERROR_SERVER_REMOTE_CLOSED;
2802 case '!':
2803 /* handle extended remote protocol */
2804 extended_protocol = 1;
2805 gdb_put_packet(connection, "OK", 2);
2806 break;
2807 case 'R':
2808 /* handle extended restart packet */
2809 breakpoint_clear_target(gdb_service->target);
2810 watchpoint_clear_target(gdb_service->target);
2811 command_run_linef(connection->cmd_ctx, "ocd_gdb_restart %s",
2812 target_name(target));
2813 /* set connection as attached after reset */
2814 gdb_con->attached = true;
2815 /* info rtos parts */
2816 gdb_thread_packet(connection, packet, packet_size);
2817 break;
2819 case 'j':
2820 /* packet supported only by smp target i.e cortex_a.c*/
2821 /* handle smp packet replying coreid played to gbd */
2822 gdb_read_smp_packet(connection, packet, packet_size);
2823 break;
2825 case 'J':
2826 /* packet supported only by smp target i.e cortex_a.c */
2827 /* handle smp packet setting coreid to be played at next
2828 * resume to gdb */
2829 gdb_write_smp_packet(connection, packet, packet_size);
2830 break;
2832 case 'F':
2833 /* File-I/O extension */
2834 /* After gdb uses host-side syscall to complete target file
2835 * I/O, gdb sends host-side syscall return value to target
2836 * by 'F' packet.
2837 * The format of 'F' response packet is
2838 * Fretcode,errno,Ctrl-C flag;call-specific attachment
2840 gdb_con->frontend_state = TARGET_RUNNING;
2841 log_add_callback(gdb_log_callback, connection);
2842 gdb_fileio_response_packet(connection, packet, packet_size);
2843 break;
2845 default:
2846 /* ignore unknown packets */
2847 LOG_DEBUG("ignoring 0x%2.2x packet", packet[0]);
2848 gdb_put_packet(connection, NULL, 0);
2849 break;
2852 /* if a packet handler returned an error, exit input loop */
2853 if (retval != ERROR_OK)
2854 return retval;
2857 if (gdb_con->ctrl_c) {
2858 if (target->state == TARGET_RUNNING) {
2859 retval = target_halt(target);
2860 if (retval != ERROR_OK)
2861 target_call_event_callbacks(target, TARGET_EVENT_GDB_HALT);
2862 gdb_con->ctrl_c = 0;
2863 } else {
2864 LOG_INFO("The target is not running when halt was requested, stopping GDB.");
2865 target_call_event_callbacks(target, TARGET_EVENT_GDB_HALT);
2869 } while (gdb_con->buf_cnt > 0);
2871 return ERROR_OK;
2874 static int gdb_input(struct connection *connection)
2876 int retval = gdb_input_inner(connection);
2877 struct gdb_connection *gdb_con = connection->priv;
2878 if (retval == ERROR_SERVER_REMOTE_CLOSED)
2879 return retval;
2881 /* logging does not propagate the error, yet can set the gdb_con->closed flag */
2882 if (gdb_con->closed)
2883 return ERROR_SERVER_REMOTE_CLOSED;
2885 /* we'll recover from any other errors(e.g. temporary timeouts, etc.) */
2886 return ERROR_OK;
2889 static int gdb_target_start(struct target *target, const char *port)
2891 struct gdb_service *gdb_service;
2892 int ret;
2893 gdb_service = malloc(sizeof(struct gdb_service));
2895 if (NULL == gdb_service)
2896 return -ENOMEM;
2898 gdb_service->target = target;
2899 gdb_service->core[0] = -1;
2900 gdb_service->core[1] = -1;
2901 target->gdb_service = gdb_service;
2903 ret = add_service("gdb",
2904 port, 1, &gdb_new_connection, &gdb_input,
2905 &gdb_connection_closed, gdb_service);
2906 /* initialialize all targets gdb service with the same pointer */
2908 struct target_list *head;
2909 struct target *curr;
2910 head = target->head;
2911 while (head != (struct target_list *)NULL) {
2912 curr = head->target;
2913 if (curr != target)
2914 curr->gdb_service = gdb_service;
2915 head = head->next;
2918 return ret;
2921 static int gdb_target_add_one(struct target *target)
2923 /* one gdb instance per smp list */
2924 if ((target->smp) && (target->gdb_service))
2925 return ERROR_OK;
2926 int retval = gdb_target_start(target, gdb_port_next);
2927 if (retval == ERROR_OK) {
2928 long portnumber;
2929 /* If we can parse the port number
2930 * then we increment the port number for the next target.
2932 char *end;
2933 portnumber = strtol(gdb_port_next, &end, 0);
2934 if (!*end) {
2935 if (parse_long(gdb_port_next, &portnumber) == ERROR_OK) {
2936 free(gdb_port_next);
2937 gdb_port_next = alloc_printf("%d", portnumber+1);
2941 return retval;
2944 int gdb_target_add_all(struct target *target)
2946 if (NULL == target) {
2947 LOG_WARNING("gdb services need one or more targets defined");
2948 return ERROR_OK;
2951 while (NULL != target) {
2952 int retval = gdb_target_add_one(target);
2953 if (ERROR_OK != retval)
2954 return retval;
2956 target = target->next;
2959 return ERROR_OK;
2962 COMMAND_HANDLER(handle_gdb_sync_command)
2964 if (CMD_ARGC != 0)
2965 return ERROR_COMMAND_SYNTAX_ERROR;
2967 if (current_gdb_connection == NULL) {
2968 command_print(CMD_CTX,
2969 "gdb_sync command can only be run from within gdb using \"monitor gdb_sync\"");
2970 return ERROR_FAIL;
2973 current_gdb_connection->sync = true;
2975 return ERROR_OK;
2978 /* daemon configuration command gdb_port */
2979 COMMAND_HANDLER(handle_gdb_port_command)
2981 int retval = CALL_COMMAND_HANDLER(server_pipe_command, &gdb_port);
2982 if (ERROR_OK == retval) {
2983 free(gdb_port_next);
2984 gdb_port_next = strdup(gdb_port);
2986 return retval;
2989 COMMAND_HANDLER(handle_gdb_memory_map_command)
2991 if (CMD_ARGC != 1)
2992 return ERROR_COMMAND_SYNTAX_ERROR;
2994 COMMAND_PARSE_ENABLE(CMD_ARGV[0], gdb_use_memory_map);
2995 return ERROR_OK;
2998 COMMAND_HANDLER(handle_gdb_flash_program_command)
3000 if (CMD_ARGC != 1)
3001 return ERROR_COMMAND_SYNTAX_ERROR;
3003 COMMAND_PARSE_ENABLE(CMD_ARGV[0], gdb_flash_program);
3004 return ERROR_OK;
3007 COMMAND_HANDLER(handle_gdb_report_data_abort_command)
3009 if (CMD_ARGC != 1)
3010 return ERROR_COMMAND_SYNTAX_ERROR;
3012 COMMAND_PARSE_ENABLE(CMD_ARGV[0], gdb_report_data_abort);
3013 return ERROR_OK;
3016 /* gdb_breakpoint_override */
3017 COMMAND_HANDLER(handle_gdb_breakpoint_override_command)
3019 if (CMD_ARGC == 0) {
3020 /* nothing */
3021 } else if (CMD_ARGC == 1) {
3022 gdb_breakpoint_override = 1;
3023 if (strcmp(CMD_ARGV[0], "hard") == 0)
3024 gdb_breakpoint_override_type = BKPT_HARD;
3025 else if (strcmp(CMD_ARGV[0], "soft") == 0)
3026 gdb_breakpoint_override_type = BKPT_SOFT;
3027 else if (strcmp(CMD_ARGV[0], "disable") == 0)
3028 gdb_breakpoint_override = 0;
3029 } else
3030 return ERROR_COMMAND_SYNTAX_ERROR;
3031 if (gdb_breakpoint_override)
3032 LOG_USER("force %s breakpoints",
3033 (gdb_breakpoint_override_type == BKPT_HARD) ? "hard" : "soft");
3034 else
3035 LOG_USER("breakpoint type is not overridden");
3037 return ERROR_OK;
3040 COMMAND_HANDLER(handle_gdb_target_description_command)
3042 if (CMD_ARGC != 1)
3043 return ERROR_COMMAND_SYNTAX_ERROR;
3045 COMMAND_PARSE_ENABLE(CMD_ARGV[0], gdb_use_target_description);
3046 return ERROR_OK;
3049 COMMAND_HANDLER(handle_gdb_save_tdesc_command)
3051 char *tdesc;
3052 uint32_t tdesc_length;
3053 struct target *target = get_current_target(CMD_CTX);
3055 int retval = gdb_generate_target_description(target, &tdesc);
3056 if (retval != ERROR_OK) {
3057 LOG_ERROR("Unable to Generate Target Description");
3058 return ERROR_FAIL;
3061 tdesc_length = strlen(tdesc);
3063 struct fileio fileio;
3064 size_t size_written;
3066 char *tdesc_filename = alloc_printf("%s.xml", target_type_name(target));
3067 if (tdesc_filename == NULL) {
3068 retval = ERROR_FAIL;
3069 goto out;
3072 retval = fileio_open(&fileio, tdesc_filename, FILEIO_WRITE, FILEIO_TEXT);
3074 if (retval != ERROR_OK) {
3075 LOG_ERROR("Can't open %s for writing", tdesc_filename);
3076 goto out;
3079 retval = fileio_write(&fileio, tdesc_length, tdesc, &size_written);
3081 fileio_close(&fileio);
3083 if (retval != ERROR_OK)
3084 LOG_ERROR("Error while writing the tdesc file");
3086 out:
3087 free(tdesc_filename);
3088 free(tdesc);
3090 return retval;
3093 static const struct command_registration gdb_command_handlers[] = {
3095 .name = "gdb_sync",
3096 .handler = handle_gdb_sync_command,
3097 .mode = COMMAND_ANY,
3098 .help = "next stepi will return immediately allowing "
3099 "GDB to fetch register state without affecting "
3100 "target state",
3101 .usage = ""
3104 .name = "gdb_port",
3105 .handler = handle_gdb_port_command,
3106 .mode = COMMAND_ANY,
3107 .help = "Normally gdb listens to a TCP/IP port. Each subsequent GDB "
3108 "server listens for the next port number after the "
3109 "base port number specified. "
3110 "No arguments reports GDB port. \"pipe\" means listen to stdin "
3111 "output to stdout, an integer is base port number, \"disable\" disables "
3112 "port. Any other string is are interpreted as named pipe to listen to. "
3113 "Output pipe is the same name as input pipe, but with 'o' appended.",
3114 .usage = "[port_num]",
3117 .name = "gdb_memory_map",
3118 .handler = handle_gdb_memory_map_command,
3119 .mode = COMMAND_CONFIG,
3120 .help = "enable or disable memory map",
3121 .usage = "('enable'|'disable')"
3124 .name = "gdb_flash_program",
3125 .handler = handle_gdb_flash_program_command,
3126 .mode = COMMAND_CONFIG,
3127 .help = "enable or disable flash program",
3128 .usage = "('enable'|'disable')"
3131 .name = "gdb_report_data_abort",
3132 .handler = handle_gdb_report_data_abort_command,
3133 .mode = COMMAND_CONFIG,
3134 .help = "enable or disable reporting data aborts",
3135 .usage = "('enable'|'disable')"
3138 .name = "gdb_breakpoint_override",
3139 .handler = handle_gdb_breakpoint_override_command,
3140 .mode = COMMAND_ANY,
3141 .help = "Display or specify type of breakpoint "
3142 "to be used by gdb 'break' commands.",
3143 .usage = "('hard'|'soft'|'disable')"
3146 .name = "gdb_target_description",
3147 .handler = handle_gdb_target_description_command,
3148 .mode = COMMAND_CONFIG,
3149 .help = "enable or disable target description",
3150 .usage = "('enable'|'disable')"
3153 .name = "gdb_save_tdesc",
3154 .handler = handle_gdb_save_tdesc_command,
3155 .mode = COMMAND_EXEC,
3156 .help = "Save the target description file",
3158 COMMAND_REGISTRATION_DONE
3161 int gdb_register_commands(struct command_context *cmd_ctx)
3163 gdb_port = strdup("3333");
3164 gdb_port_next = strdup("3333");
3165 return register_commands(cmd_ctx, NULL, gdb_command_handlers);