Doxygen file comments
[openocd.git] / src / server / gdb_server.c
blobf4a99cae110e6bbda6ed4b8d47ddf073d0e96757
1 /***************************************************************************
2 * Copyright (C) 2005 by Dominic Rath *
3 * Dominic.Rath@gmx.de *
4 * *
5 * Copyright (C) 2007-2009 Øyvind Harboe *
6 * oyvind.harboe@zylin.com *
7 * *
8 * Copyright (C) 2008 by Spencer Oliver *
9 * spen@spen-soft.co.uk *
10 * *
11 * This program is free software; you can redistribute it and/or modify *
12 * it under the terms of the GNU General Public License as published by *
13 * the Free Software Foundation; either version 2 of the License, or *
14 * (at your option) any later version. *
15 * *
16 * This program is distributed in the hope that it will be useful, *
17 * but WITHOUT ANY WARRANTY; without even the implied warranty of *
18 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
19 * GNU General Public License for more details. *
20 * *
21 * You should have received a copy of the GNU General Public License *
22 * along with this program; if not, write to the *
23 * Free Software Foundation, Inc., *
24 * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. *
25 ***************************************************************************/
26 #ifdef HAVE_CONFIG_H
27 #include "config.h"
28 #endif
30 #include <target/breakpoints.h>
31 #include <target/target_request.h>
32 #include <target/register.h>
33 #include "server.h"
34 #include <flash/nor/core.h>
35 #include "gdb_server.h"
36 #include <target/image.h>
37 #include <jtag/jtag.h>
40 /**
41 * @file
42 * GDB server implementation.
44 * This implements the GDB Remote Serial Protocol, over TCP connections,
45 * giving GDB access to the JTAG or other hardware debugging facilities
46 * found in most modern embedded processors.
49 /* private connection data for GDB */
50 struct gdb_connection
52 char buffer[GDB_BUFFER_SIZE];
53 char *buf_p;
54 int buf_cnt;
55 int ctrl_c;
56 enum target_state frontend_state;
57 struct image *vflash_image;
58 int closed;
59 int busy;
60 int noack_mode;
61 bool sync; /* set flag to true if you want the next stepi to return immediately.
62 allowing GDB to pick up a fresh set of register values from the target
63 without modifying the target state. */
68 #if 0
69 #define _DEBUG_GDB_IO_
70 #endif
72 static struct gdb_connection *current_gdb_connection;
74 static int gdb_breakpoint_override;
75 static enum breakpoint_type gdb_breakpoint_override_type;
77 extern int gdb_error(struct connection *connection, int retval);
78 static unsigned short gdb_port = 3333;
79 static unsigned short gdb_port_next = 0;
80 static const char DIGITS[16] = "0123456789abcdef";
82 static void gdb_log_callback(void *priv, const char *file, unsigned line,
83 const char *function, const char *string);
85 /* number of gdb connections, mainly to suppress gdb related debugging spam
86 * in helper/log.c when no gdb connections are actually active */
87 int gdb_actual_connections;
89 /* set if we are sending a memory map to gdb
90 * via qXfer:memory-map:read packet */
91 /* enabled by default*/
92 int gdb_use_memory_map = 1;
93 /* enabled by default*/
94 int gdb_flash_program = 1;
96 /* if set, data aborts cause an error to be reported in memory read packets
97 * see the code in gdb_read_memory_packet() for further explanations */
98 int gdb_report_data_abort = 0;
100 int gdb_last_signal(struct target *target)
102 switch (target->debug_reason)
104 case DBG_REASON_DBGRQ:
105 return 0x2; /* SIGINT */
106 case DBG_REASON_BREAKPOINT:
107 case DBG_REASON_WATCHPOINT:
108 case DBG_REASON_WPTANDBKPT:
109 return 0x05; /* SIGTRAP */
110 case DBG_REASON_SINGLESTEP:
111 return 0x05; /* SIGTRAP */
112 case DBG_REASON_NOTHALTED:
113 return 0x0; /* no signal... shouldn't happen */
114 default:
115 LOG_USER("undefined debug reason %d - target needs reset", target->debug_reason);
116 return 0x0;
120 int check_pending(struct connection *connection, int timeout_s, int *got_data)
122 /* a non-blocking socket will block if there is 0 bytes available on the socket,
123 * but return with as many bytes as are available immediately
125 struct timeval tv;
126 fd_set read_fds;
127 struct gdb_connection *gdb_con = connection->priv;
128 int t;
129 if (got_data == NULL)
130 got_data=&t;
131 *got_data = 0;
133 if (gdb_con->buf_cnt > 0)
135 *got_data = 1;
136 return ERROR_OK;
139 FD_ZERO(&read_fds);
140 FD_SET(connection->fd, &read_fds);
142 tv.tv_sec = timeout_s;
143 tv.tv_usec = 0;
144 if (socket_select(connection->fd + 1, &read_fds, NULL, NULL, &tv) == 0)
146 /* This can typically be because a "monitor" command took too long
147 * before printing any progress messages
149 if (timeout_s > 0)
151 return ERROR_GDB_TIMEOUT;
152 } else
154 return ERROR_OK;
157 *got_data = FD_ISSET(connection->fd, &read_fds) != 0;
158 return ERROR_OK;
161 static int gdb_get_char_inner(struct connection *connection, int* next_char)
163 struct gdb_connection *gdb_con = connection->priv;
164 int retval = ERROR_OK;
166 for (;;)
168 if (connection->service->type == CONNECTION_PIPE)
170 gdb_con->buf_cnt = read(connection->fd, gdb_con->buffer, GDB_BUFFER_SIZE);
172 else
174 retval = check_pending(connection, 1, NULL);
175 if (retval != ERROR_OK)
176 return retval;
177 gdb_con->buf_cnt = read_socket(connection->fd, gdb_con->buffer, GDB_BUFFER_SIZE);
180 if (gdb_con->buf_cnt > 0)
182 break;
184 if (gdb_con->buf_cnt == 0)
186 gdb_con->closed = 1;
187 return ERROR_SERVER_REMOTE_CLOSED;
190 #ifdef _WIN32
191 errno = WSAGetLastError();
193 switch (errno)
195 case WSAEWOULDBLOCK:
196 usleep(1000);
197 break;
198 case WSAECONNABORTED:
199 gdb_con->closed = 1;
200 return ERROR_SERVER_REMOTE_CLOSED;
201 case WSAECONNRESET:
202 gdb_con->closed = 1;
203 return ERROR_SERVER_REMOTE_CLOSED;
204 default:
205 LOG_ERROR("read: %d", errno);
206 exit(-1);
208 #else
209 switch (errno)
211 case EAGAIN:
212 usleep(1000);
213 break;
214 case ECONNABORTED:
215 gdb_con->closed = 1;
216 return ERROR_SERVER_REMOTE_CLOSED;
217 case ECONNRESET:
218 gdb_con->closed = 1;
219 return ERROR_SERVER_REMOTE_CLOSED;
220 default:
221 LOG_ERROR("read: %s", strerror(errno));
222 gdb_con->closed = 1;
223 return ERROR_SERVER_REMOTE_CLOSED;
225 #endif
228 #ifdef _DEBUG_GDB_IO_
229 debug_buffer = malloc(gdb_con->buf_cnt + 1);
230 memcpy(debug_buffer, gdb_con->buffer, gdb_con->buf_cnt);
231 debug_buffer[gdb_con->buf_cnt] = 0;
232 LOG_DEBUG("received '%s'", debug_buffer);
233 free(debug_buffer);
234 #endif
236 gdb_con->buf_p = gdb_con->buffer;
237 gdb_con->buf_cnt--;
238 *next_char = *(gdb_con->buf_p++);
239 if (gdb_con->buf_cnt > 0)
240 connection->input_pending = 1;
241 else
242 connection->input_pending = 0;
243 #ifdef _DEBUG_GDB_IO_
244 LOG_DEBUG("returned char '%c' (0x%2.2x)", *next_char, *next_char);
245 #endif
247 return retval;
251 * The cool thing about this fn is that it allows buf_p and buf_cnt to be
252 * held in registers in the inner loop.
254 * For small caches and embedded systems this is important!
256 static inline int gdb_get_char_fast(struct connection *connection, int* next_char, char **buf_p, int *buf_cnt)
258 int retval = ERROR_OK;
260 if ((*buf_cnt)-- > 0)
262 *next_char = **buf_p;
263 (*buf_p)++;
264 if (*buf_cnt > 0)
265 connection->input_pending = 1;
266 else
267 connection->input_pending = 0;
269 #ifdef _DEBUG_GDB_IO_
270 LOG_DEBUG("returned char '%c' (0x%2.2x)", *next_char, *next_char);
271 #endif
273 return ERROR_OK;
276 struct gdb_connection *gdb_con = connection->priv;
277 gdb_con->buf_p = *buf_p;
278 gdb_con->buf_cnt = *buf_cnt;
279 retval = gdb_get_char_inner(connection, next_char);
280 *buf_p = gdb_con->buf_p;
281 *buf_cnt = gdb_con->buf_cnt;
283 return retval;
287 int gdb_get_char(struct connection *connection, int* next_char)
289 struct gdb_connection *gdb_con = connection->priv;
290 return gdb_get_char_fast(connection, next_char, &gdb_con->buf_p, &gdb_con->buf_cnt);
294 int gdb_putback_char(struct connection *connection, int last_char)
296 struct gdb_connection *gdb_con = connection->priv;
298 if (gdb_con->buf_p > gdb_con->buffer)
300 *(--gdb_con->buf_p) = last_char;
301 gdb_con->buf_cnt++;
303 else
305 LOG_ERROR("BUG: couldn't put character back");
308 return ERROR_OK;
311 /* The only way we can detect that the socket is closed is the first time
312 * we write to it, we will fail. Subsequent write operations will
313 * succeed. Shudder! */
314 int gdb_write(struct connection *connection, void *data, int len)
316 struct gdb_connection *gdb_con = connection->priv;
317 if (gdb_con->closed)
318 return ERROR_SERVER_REMOTE_CLOSED;
320 if (connection->service->type == CONNECTION_PIPE)
322 /* write to stdout */
323 if (write(STDOUT_FILENO, data, len) == len)
325 return ERROR_OK;
328 else
330 if (write_socket(connection->fd, data, len) == len)
332 return ERROR_OK;
335 gdb_con->closed = 1;
336 return ERROR_SERVER_REMOTE_CLOSED;
339 int gdb_put_packet_inner(struct connection *connection, char *buffer, int len)
341 int i;
342 unsigned char my_checksum = 0;
343 #ifdef _DEBUG_GDB_IO_
344 char *debug_buffer;
345 #endif
346 int reply;
347 int retval;
348 struct gdb_connection *gdb_con = connection->priv;
350 for (i = 0; i < len; i++)
351 my_checksum += buffer[i];
353 #ifdef _DEBUG_GDB_IO_
355 * At this point we should have nothing in the input queue from GDB,
356 * however sometimes '-' is sent even though we've already received
357 * an ACK (+) for everything we've sent off.
359 int gotdata;
360 for (;;)
362 if ((retval = check_pending(connection, 0, &gotdata)) != ERROR_OK)
363 return retval;
364 if (!gotdata)
365 break;
366 if ((retval = gdb_get_char(connection, &reply)) != ERROR_OK)
367 return retval;
368 if (reply == '$') {
369 /* fix a problem with some IAR tools */
370 gdb_putback_char(connection, reply);
371 LOG_DEBUG("Unexpected start of new packet");
372 break;
375 LOG_WARNING("Discard unexpected char %c", reply);
377 #endif
379 while (1)
381 #ifdef _DEBUG_GDB_IO_
382 debug_buffer = malloc(len + 1);
383 memcpy(debug_buffer, buffer, len);
384 debug_buffer[len] = 0;
385 LOG_DEBUG("sending packet '$%s#%2.2x'", debug_buffer, my_checksum);
386 free(debug_buffer);
387 #endif
389 char local_buffer[1024];
390 local_buffer[0] = '$';
391 if ((size_t)len + 4 <= sizeof(local_buffer))
393 /* performance gain on smaller packets by only a single call to gdb_write() */
394 memcpy(local_buffer + 1, buffer, len++);
395 local_buffer[len++] = '#';
396 local_buffer[len++] = DIGITS[(my_checksum >> 4) & 0xf];
397 local_buffer[len++] = DIGITS[my_checksum & 0xf];
398 if ((retval = gdb_write(connection, local_buffer, len)) != ERROR_OK)
400 return retval;
403 else
405 /* larger packets are transmitted directly from caller supplied buffer
406 by several calls to gdb_write() to avoid dynamic allocation */
407 local_buffer[1] = '#';
408 local_buffer[2] = DIGITS[(my_checksum >> 4) & 0xf];
409 local_buffer[3] = DIGITS[my_checksum & 0xf];
410 if ((retval = gdb_write(connection, local_buffer, 1)) != ERROR_OK)
412 return retval;
414 if ((retval = gdb_write(connection, buffer, len)) != ERROR_OK)
416 return retval;
418 if ((retval = gdb_write(connection, local_buffer + 1, 3)) != ERROR_OK)
420 return retval;
424 if (gdb_con->noack_mode)
425 break;
427 if ((retval = gdb_get_char(connection, &reply)) != ERROR_OK)
428 return retval;
430 if (reply == '+')
431 break;
432 else if (reply == '-')
434 /* Stop sending output packets for now */
435 log_remove_callback(gdb_log_callback, connection);
436 LOG_WARNING("negative reply, retrying");
438 else if (reply == 0x3)
440 gdb_con->ctrl_c = 1;
441 if ((retval = gdb_get_char(connection, &reply)) != ERROR_OK)
442 return retval;
443 if (reply == '+')
444 break;
445 else if (reply == '-')
447 /* Stop sending output packets for now */
448 log_remove_callback(gdb_log_callback, connection);
449 LOG_WARNING("negative reply, retrying");
451 else if (reply == '$') {
452 LOG_ERROR("GDB missing ack(1) - assumed good");
453 gdb_putback_char(connection, reply);
454 return ERROR_OK;
455 } else {
457 LOG_ERROR("unknown character(1) 0x%2.2x in reply, dropping connection", reply);
458 gdb_con->closed = 1;
459 return ERROR_SERVER_REMOTE_CLOSED;
462 else if (reply == '$') {
463 LOG_ERROR("GDB missing ack(2) - assumed good");
464 gdb_putback_char(connection, reply);
465 return ERROR_OK;
467 else
469 LOG_ERROR("unknown character(2) 0x%2.2x in reply, dropping connection", reply);
470 gdb_con->closed = 1;
471 return ERROR_SERVER_REMOTE_CLOSED;
474 if (gdb_con->closed)
475 return ERROR_SERVER_REMOTE_CLOSED;
477 return ERROR_OK;
480 int gdb_put_packet(struct connection *connection, char *buffer, int len)
482 struct gdb_connection *gdb_con = connection->priv;
483 gdb_con->busy = 1;
484 int retval = gdb_put_packet_inner(connection, buffer, len);
485 gdb_con->busy = 0;
487 /* we sent some data, reset timer for keep alive messages */
488 kept_alive();
490 return retval;
493 static __inline__ int fetch_packet(struct connection *connection, int *checksum_ok, int noack, int *len, char *buffer)
495 unsigned char my_checksum = 0;
496 char checksum[3];
497 int character;
498 int retval = ERROR_OK;
500 struct gdb_connection *gdb_con = connection->priv;
501 my_checksum = 0;
502 int count = 0;
503 count = 0;
505 /* move this over into local variables to use registers and give the
506 * more freedom to optimize */
507 char *buf_p = gdb_con->buf_p;
508 int buf_cnt = gdb_con->buf_cnt;
510 for (;;)
512 /* The common case is that we have an entire packet with no escape chars.
513 * We need to leave at least 2 bytes in the buffer to have
514 * gdb_get_char() update various bits and bobs correctly.
516 if ((buf_cnt > 2) && ((buf_cnt + count) < *len))
518 /* The compiler will struggle a bit with constant propagation and
519 * aliasing, so we help it by showing that these values do not
520 * change inside the loop
522 int i;
523 char *buf = buf_p;
524 int run = buf_cnt - 2;
525 i = 0;
526 int done = 0;
527 while (i < run)
529 character = *buf++;
530 i++;
531 if (character == '#')
533 /* Danger! character can be '#' when esc is
534 * used so we need an explicit boolean for done here.
536 done = 1;
537 break;
540 if (character == '}')
542 /* data transmitted in binary mode (X packet)
543 * uses 0x7d as escape character */
544 my_checksum += character & 0xff;
545 character = *buf++;
546 i++;
547 my_checksum += character & 0xff;
548 buffer[count++] = (character ^ 0x20) & 0xff;
550 else
552 my_checksum += character & 0xff;
553 buffer[count++] = character & 0xff;
556 buf_p += i;
557 buf_cnt -= i;
558 if (done)
559 break;
561 if (count > *len)
563 LOG_ERROR("packet buffer too small");
564 retval = ERROR_GDB_BUFFER_TOO_SMALL;
565 break;
568 retval = gdb_get_char_fast(connection, &character, &buf_p, &buf_cnt);
569 if (retval != ERROR_OK)
570 break;
572 if (character == '#')
573 break;
575 if (character == '}')
577 /* data transmitted in binary mode (X packet)
578 * uses 0x7d as escape character */
579 my_checksum += character & 0xff;
581 retval = gdb_get_char_fast(connection, &character, &buf_p, &buf_cnt);
582 if (retval != ERROR_OK)
583 break;
585 my_checksum += character & 0xff;
586 buffer[count++] = (character ^ 0x20) & 0xff;
588 else
590 my_checksum += character & 0xff;
591 buffer[count++] = character & 0xff;
595 gdb_con->buf_p = buf_p;
596 gdb_con->buf_cnt = buf_cnt;
598 if (retval != ERROR_OK)
599 return retval;
601 *len = count;
603 if ((retval = gdb_get_char(connection, &character)) != ERROR_OK)
604 return retval;
605 checksum[0] = character;
606 if ((retval = gdb_get_char(connection, &character)) != ERROR_OK)
607 return retval;
608 checksum[1] = character;
609 checksum[2] = 0;
611 if (!noack)
613 *checksum_ok = (my_checksum == strtoul(checksum, NULL, 16));
616 return ERROR_OK;
619 int gdb_get_packet_inner(struct connection *connection, char *buffer, int *len)
621 int character;
622 int retval;
623 struct gdb_connection *gdb_con = connection->priv;
625 while (1)
629 if ((retval = gdb_get_char(connection, &character)) != ERROR_OK)
630 return retval;
632 #ifdef _DEBUG_GDB_IO_
633 LOG_DEBUG("character: '%c'", character);
634 #endif
636 switch (character)
638 case '$':
639 break;
640 case '+':
641 /* gdb sends a dummy ack '+' at every remote connect - see remote_start_remote (remote.c)
642 * in case anyone tries to debug why they receive this warning every time */
643 LOG_WARNING("acknowledgment received, but no packet pending");
644 break;
645 case '-':
646 LOG_WARNING("negative acknowledgment, but no packet pending");
647 break;
648 case 0x3:
649 gdb_con->ctrl_c = 1;
650 *len = 0;
651 return ERROR_OK;
652 default:
653 LOG_WARNING("ignoring character 0x%x", character);
654 break;
656 } while (character != '$');
660 int checksum_ok = 0;
661 /* explicit code expansion here to get faster inlined code in -O3 by not
662 * calculating checksum
664 if (gdb_con->noack_mode)
666 if ((retval = fetch_packet(connection, &checksum_ok, 1, len, buffer)) != ERROR_OK)
667 return retval;
668 } else
670 if ((retval = fetch_packet(connection, &checksum_ok, 0, len, buffer)) != ERROR_OK)
671 return retval;
674 if (gdb_con->noack_mode)
676 /* checksum is not checked in noack mode */
677 break;
679 if (checksum_ok)
681 if ((retval = gdb_write(connection, "+", 1)) != ERROR_OK)
683 return retval;
685 break;
688 if (gdb_con->closed)
689 return ERROR_SERVER_REMOTE_CLOSED;
691 return ERROR_OK;
694 int gdb_get_packet(struct connection *connection, char *buffer, int *len)
696 struct gdb_connection *gdb_con = connection->priv;
697 gdb_con->busy = 1;
698 int retval = gdb_get_packet_inner(connection, buffer, len);
699 gdb_con->busy = 0;
700 return retval;
703 int gdb_output_con(struct connection *connection, const char* line)
705 char *hex_buffer;
706 int i, bin_size;
708 bin_size = strlen(line);
710 hex_buffer = malloc(bin_size*2 + 2);
711 if (hex_buffer == NULL)
712 return ERROR_GDB_BUFFER_TOO_SMALL;
714 hex_buffer[0] = 'O';
715 for (i = 0; i < bin_size; i++)
716 snprintf(hex_buffer + 1 + i*2, 3, "%2.2x", line[i]);
717 hex_buffer[bin_size*2 + 1] = 0;
719 int retval = gdb_put_packet(connection, hex_buffer, bin_size*2 + 1);
721 free(hex_buffer);
722 return retval;
725 int gdb_output(struct command_context *context, const char* line)
727 /* this will be dumped to the log and also sent as an O packet if possible */
728 LOG_USER_N("%s", line);
729 return ERROR_OK;
733 static void gdb_frontend_halted(struct target *target, struct connection *connection)
735 struct gdb_connection *gdb_connection = connection->priv;
737 /* In the GDB protocol when we are stepping or continuing execution,
738 * we have a lingering reply. Upon receiving a halted event
739 * when we have that lingering packet, we reply to the original
740 * step or continue packet.
742 * Executing monitor commands can bring the target in and
743 * out of the running state so we'll see lots of TARGET_EVENT_XXX
744 * that are to be ignored.
746 if (gdb_connection->frontend_state == TARGET_RUNNING)
748 char sig_reply[4];
749 int signal;
751 /* stop forwarding log packets! */
752 log_remove_callback(gdb_log_callback, connection);
754 if (gdb_connection->ctrl_c)
756 signal = 0x2;
757 gdb_connection->ctrl_c = 0;
759 else
761 signal = gdb_last_signal(target);
764 snprintf(sig_reply, 4, "T%2.2x", signal);
765 gdb_put_packet(connection, sig_reply, 3);
766 gdb_connection->frontend_state = TARGET_HALTED;
770 int gdb_target_callback_event_handler(struct target *target, enum target_event event, void *priv)
772 int retval;
773 struct connection *connection = priv;
775 target_handle_event(target, event);
776 switch (event)
778 case TARGET_EVENT_GDB_HALT:
779 gdb_frontend_halted(target, connection);
780 break;
781 case TARGET_EVENT_HALTED:
782 target_call_event_callbacks(target, TARGET_EVENT_GDB_END);
783 break;
784 case TARGET_EVENT_GDB_FLASH_ERASE_START:
785 target_handle_event(target, TARGET_EVENT_OLD_gdb_program_config);
786 if ((retval = jtag_execute_queue()) != ERROR_OK)
788 return retval;
790 break;
791 default:
792 break;
795 return ERROR_OK;
798 int gdb_new_connection(struct connection *connection)
800 struct gdb_connection *gdb_connection = malloc(sizeof(struct gdb_connection));
801 struct gdb_service *gdb_service = connection->service->priv;
802 int retval;
803 int initial_ack;
805 connection->priv = gdb_connection;
807 /* initialize gdb connection information */
808 gdb_connection->buf_p = gdb_connection->buffer;
809 gdb_connection->buf_cnt = 0;
810 gdb_connection->ctrl_c = 0;
811 gdb_connection->frontend_state = TARGET_HALTED;
812 gdb_connection->vflash_image = NULL;
813 gdb_connection->closed = 0;
814 gdb_connection->busy = 0;
815 gdb_connection->noack_mode = 0;
816 gdb_connection->sync = true;
818 /* send ACK to GDB for debug request */
819 gdb_write(connection, "+", 1);
821 /* output goes through gdb connection */
822 command_set_output_handler(connection->cmd_ctx, gdb_output, connection);
824 /* we must remove all breakpoints registered to the target as a previous
825 * GDB session could leave dangling breakpoints if e.g. communication
826 * timed out.
828 breakpoint_clear_target(gdb_service->target);
829 watchpoint_clear_target(gdb_service->target);
831 /* register callback to be informed about target events */
832 target_register_event_callback(gdb_target_callback_event_handler, connection);
834 /* remove the initial ACK from the incoming buffer */
835 if ((retval = gdb_get_char(connection, &initial_ack)) != ERROR_OK)
836 return retval;
838 /* FIX!!!??? would we actually ever receive a + here???
839 * Not observed.
841 if (initial_ack != '+')
842 gdb_putback_char(connection, initial_ack);
843 target_call_event_callbacks(gdb_service->target, TARGET_EVENT_GDB_ATTACH);
845 gdb_actual_connections++;
846 LOG_DEBUG("New GDB Connection: %d, Target %s, state: %s",
847 gdb_actual_connections,
848 target_name(gdb_service->target),
849 target_state_name(gdb_service->target));
851 return ERROR_OK;
854 int gdb_connection_closed(struct connection *connection)
856 struct gdb_service *gdb_service = connection->service->priv;
857 struct gdb_connection *gdb_connection = connection->priv;
859 /* we're done forwarding messages. Tear down callback before
860 * cleaning up connection.
862 log_remove_callback(gdb_log_callback, connection);
864 gdb_actual_connections--;
865 LOG_DEBUG("GDB Close, Target: %s, state: %s, gdb_actual_connections=%d",
866 target_name(gdb_service->target),
867 target_state_name(gdb_service->target),
868 gdb_actual_connections);
870 /* see if an image built with vFlash commands is left */
871 if (gdb_connection->vflash_image)
873 image_close(gdb_connection->vflash_image);
874 free(gdb_connection->vflash_image);
875 gdb_connection->vflash_image = NULL;
878 /* if this connection registered a debug-message receiver delete it */
879 delete_debug_msg_receiver(connection->cmd_ctx, gdb_service->target);
881 if (connection->priv)
883 free(connection->priv);
884 connection->priv = NULL;
886 else
888 LOG_ERROR("BUG: connection->priv == NULL");
892 target_unregister_event_callback(gdb_target_callback_event_handler, connection);
894 target_call_event_callbacks(gdb_service->target, TARGET_EVENT_GDB_END);
896 target_call_event_callbacks(gdb_service->target, TARGET_EVENT_GDB_DETACH);
898 return ERROR_OK;
901 void gdb_send_error(struct connection *connection, uint8_t the_error)
903 char err[4];
904 snprintf(err, 4, "E%2.2X", the_error);
905 gdb_put_packet(connection, err, 3);
908 int gdb_last_signal_packet(struct connection *connection, struct target *target, char* packet, int packet_size)
910 char sig_reply[4];
911 int signal;
913 signal = gdb_last_signal(target);
915 snprintf(sig_reply, 4, "S%2.2x", signal);
916 gdb_put_packet(connection, sig_reply, 3);
918 return ERROR_OK;
921 static int gdb_reg_pos(struct target *target, int pos, int len)
923 if (target->endianness == TARGET_LITTLE_ENDIAN)
924 return pos;
925 else
926 return len - 1 - pos;
929 /* Convert register to string of bytes. NB! The # of bits in the
930 * register might be non-divisible by 8(a byte), in which
931 * case an entire byte is shown.
933 * NB! the format on the wire is the target endianness
935 * The format of reg->value is little endian
938 void gdb_str_to_target(struct target *target, char *tstr, struct reg *reg)
940 int i;
942 uint8_t *buf;
943 int buf_len;
944 buf = reg->value;
945 buf_len = DIV_ROUND_UP(reg->size, 8);
947 for (i = 0; i < buf_len; i++)
949 int j = gdb_reg_pos(target, i, buf_len);
950 tstr[i*2] = DIGITS[(buf[j]>>4) & 0xf];
951 tstr[i*2 + 1] = DIGITS[buf[j]&0xf];
955 static int hextoint(int c)
957 if (c>='0'&&c<='9')
959 return c-'0';
961 c = toupper(c);
962 if (c>='A'&&c<='F')
964 return c-'A'+10;
966 LOG_ERROR("BUG: invalid register value %08x", c);
967 return 0;
970 /* copy over in register buffer */
971 void gdb_target_to_reg(struct target *target, char *tstr, int str_len, uint8_t *bin)
973 if (str_len % 2)
975 LOG_ERROR("BUG: gdb value with uneven number of characters encountered");
976 exit(-1);
979 int i;
980 for (i = 0; i < str_len; i += 2)
982 uint8_t t = hextoint(tstr[i]) << 4;
983 t |= hextoint(tstr[i + 1]);
985 int j = gdb_reg_pos(target, i/2, str_len/2);
986 bin[j] = t;
990 int gdb_get_registers_packet(struct connection *connection, struct target *target, char* packet, int packet_size)
992 struct reg **reg_list;
993 int reg_list_size;
994 int retval;
995 int reg_packet_size = 0;
996 char *reg_packet;
997 char *reg_packet_p;
998 int i;
1000 #ifdef _DEBUG_GDB_IO_
1001 LOG_DEBUG("-");
1002 #endif
1004 if ((retval = target_get_gdb_reg_list(target, &reg_list, &reg_list_size)) != ERROR_OK)
1006 return gdb_error(connection, retval);
1009 for (i = 0; i < reg_list_size; i++)
1011 reg_packet_size += reg_list[i]->size;
1014 reg_packet = malloc(DIV_ROUND_UP(reg_packet_size, 8) * 2);
1015 reg_packet_p = reg_packet;
1017 for (i = 0; i < reg_list_size; i++)
1019 gdb_str_to_target(target, reg_packet_p, reg_list[i]);
1020 reg_packet_p += DIV_ROUND_UP(reg_list[i]->size, 8) * 2;
1023 #ifdef _DEBUG_GDB_IO_
1025 char *reg_packet_p;
1026 reg_packet_p = strndup(reg_packet, DIV_ROUND_UP(reg_packet_size, 8) * 2);
1027 LOG_DEBUG("reg_packet: %s", reg_packet_p);
1028 free(reg_packet_p);
1030 #endif
1032 gdb_put_packet(connection, reg_packet, DIV_ROUND_UP(reg_packet_size, 8) * 2);
1033 free(reg_packet);
1035 free(reg_list);
1037 return ERROR_OK;
1040 int gdb_set_registers_packet(struct connection *connection, struct target *target, char *packet, int packet_size)
1042 int i;
1043 struct reg **reg_list;
1044 int reg_list_size;
1045 int retval;
1046 char *packet_p;
1048 #ifdef _DEBUG_GDB_IO_
1049 LOG_DEBUG("-");
1050 #endif
1052 /* skip command character */
1053 packet++;
1054 packet_size--;
1056 if (packet_size % 2)
1058 LOG_WARNING("GDB set_registers packet with uneven characters received, dropping connection");
1059 return ERROR_SERVER_REMOTE_CLOSED;
1062 if ((retval = target_get_gdb_reg_list(target, &reg_list, &reg_list_size)) != ERROR_OK)
1064 return gdb_error(connection, retval);
1067 packet_p = packet;
1068 for (i = 0; i < reg_list_size; i++)
1070 uint8_t *bin_buf;
1071 int chars = (DIV_ROUND_UP(reg_list[i]->size, 8) * 2);
1073 if (packet_p + chars > packet + packet_size)
1075 LOG_ERROR("BUG: register packet is too small for registers");
1078 bin_buf = malloc(DIV_ROUND_UP(reg_list[i]->size, 8));
1079 gdb_target_to_reg(target, packet_p, chars, bin_buf);
1081 reg_list[i]->type->set(reg_list[i], bin_buf);
1083 /* advance packet pointer */
1084 packet_p += chars;
1087 free(bin_buf);
1090 /* free struct reg *reg_list[] array allocated by get_gdb_reg_list */
1091 free(reg_list);
1093 gdb_put_packet(connection, "OK", 2);
1095 return ERROR_OK;
1098 int gdb_get_register_packet(struct connection *connection, struct target *target, char *packet, int packet_size)
1100 char *reg_packet;
1101 int reg_num = strtoul(packet + 1, NULL, 16);
1102 struct reg **reg_list;
1103 int reg_list_size;
1104 int retval;
1106 #ifdef _DEBUG_GDB_IO_
1107 LOG_DEBUG("-");
1108 #endif
1110 if ((retval = target_get_gdb_reg_list(target, &reg_list, &reg_list_size)) != ERROR_OK)
1112 return gdb_error(connection, retval);
1115 if (reg_list_size <= reg_num)
1117 LOG_ERROR("gdb requested a non-existing register");
1118 exit(-1);
1121 reg_packet = malloc(DIV_ROUND_UP(reg_list[reg_num]->size, 8) * 2);
1123 gdb_str_to_target(target, reg_packet, reg_list[reg_num]);
1125 gdb_put_packet(connection, reg_packet, DIV_ROUND_UP(reg_list[reg_num]->size, 8) * 2);
1127 free(reg_list);
1128 free(reg_packet);
1130 return ERROR_OK;
1133 int gdb_set_register_packet(struct connection *connection, struct target *target, char *packet, int packet_size)
1135 char *separator;
1136 uint8_t *bin_buf;
1137 int reg_num = strtoul(packet + 1, &separator, 16);
1138 struct reg **reg_list;
1139 int reg_list_size;
1140 int retval;
1142 LOG_DEBUG("-");
1144 if ((retval = target_get_gdb_reg_list(target, &reg_list, &reg_list_size)) != ERROR_OK)
1146 return gdb_error(connection, retval);
1149 if (reg_list_size < reg_num)
1151 LOG_ERROR("gdb requested a non-existing register");
1152 return ERROR_SERVER_REMOTE_CLOSED;
1155 if (*separator != '=')
1157 LOG_ERROR("GDB 'set register packet', but no '=' following the register number");
1158 return ERROR_SERVER_REMOTE_CLOSED;
1161 /* convert from GDB-string (target-endian) to hex-string (big-endian) */
1162 bin_buf = malloc(DIV_ROUND_UP(reg_list[reg_num]->size, 8));
1163 int chars = (DIV_ROUND_UP(reg_list[reg_num]->size, 8) * 2);
1165 /* fix!!! add some sanity checks on packet size here */
1167 gdb_target_to_reg(target, separator + 1, chars, bin_buf);
1169 reg_list[reg_num]->type->set(reg_list[reg_num], bin_buf);
1171 gdb_put_packet(connection, "OK", 2);
1173 free(bin_buf);
1174 free(reg_list);
1176 return ERROR_OK;
1179 int gdb_error(struct connection *connection, int retval)
1181 switch (retval)
1183 case ERROR_TARGET_DATA_ABORT:
1184 gdb_send_error(connection, EIO);
1185 break;
1186 case ERROR_TARGET_TRANSLATION_FAULT:
1187 gdb_send_error(connection, EFAULT);
1188 break;
1189 case ERROR_TARGET_UNALIGNED_ACCESS:
1190 gdb_send_error(connection, EFAULT);
1191 break;
1192 case ERROR_TARGET_NOT_HALTED:
1193 gdb_send_error(connection, EFAULT);
1194 break;
1195 default:
1196 /* This could be that the target reset itself. */
1197 LOG_ERROR("unexpected error %i", retval);
1198 gdb_send_error(connection, EFAULT);
1199 break;
1202 return ERROR_OK;
1205 /* We don't have to worry about the default 2 second timeout for GDB packets,
1206 * because GDB breaks up large memory reads into smaller reads.
1208 * 8191 bytes by the looks of it. Why 8191 bytes instead of 8192?????
1210 int gdb_read_memory_packet(struct connection *connection, struct target *target, char *packet, int packet_size)
1212 char *separator;
1213 uint32_t addr = 0;
1214 uint32_t len = 0;
1216 uint8_t *buffer;
1217 char *hex_buffer;
1219 int retval = ERROR_OK;
1221 /* skip command character */
1222 packet++;
1224 addr = strtoul(packet, &separator, 16);
1226 if (*separator != ',')
1228 LOG_ERROR("incomplete read memory packet received, dropping connection");
1229 return ERROR_SERVER_REMOTE_CLOSED;
1232 len = strtoul(separator + 1, NULL, 16);
1234 buffer = malloc(len);
1236 LOG_DEBUG("addr: 0x%8.8" PRIx32 ", len: 0x%8.8" PRIx32 "", addr, len);
1238 retval = target_read_buffer(target, addr, len, buffer);
1240 if ((retval != ERROR_OK)&&!gdb_report_data_abort)
1242 /* TODO : Here we have to lie and send back all zero's lest stack traces won't work.
1243 * At some point this might be fixed in GDB, in which case this code can be removed.
1245 * OpenOCD developers are acutely aware of this problem, but there is nothing
1246 * gained by involving the user in this problem that hopefully will get resolved
1247 * eventually
1249 * http://sourceware.org/cgi-bin/gnatsweb.pl?cmd = view%20audit-trail&database = gdb&pr = 2395
1251 * For now, the default is to fix up things to make current GDB versions work.
1252 * This can be overwritten using the gdb_report_data_abort <'enable'|'disable'> command.
1254 memset(buffer, 0, len);
1255 retval = ERROR_OK;
1258 if (retval == ERROR_OK)
1260 hex_buffer = malloc(len * 2 + 1);
1262 uint32_t i;
1263 for (i = 0; i < len; i++)
1265 uint8_t t = buffer[i];
1266 hex_buffer[2 * i] = DIGITS[(t >> 4) & 0xf];
1267 hex_buffer[2 * i + 1] = DIGITS[t & 0xf];
1270 gdb_put_packet(connection, hex_buffer, len * 2);
1272 free(hex_buffer);
1274 else
1276 retval = gdb_error(connection, retval);
1279 free(buffer);
1281 return retval;
1284 int gdb_write_memory_packet(struct connection *connection, struct target *target, char *packet, int packet_size)
1286 char *separator;
1287 uint32_t addr = 0;
1288 uint32_t len = 0;
1290 uint8_t *buffer;
1292 uint32_t i;
1293 int retval;
1295 /* skip command character */
1296 packet++;
1298 addr = strtoul(packet, &separator, 16);
1300 if (*separator != ',')
1302 LOG_ERROR("incomplete write memory packet received, dropping connection");
1303 return ERROR_SERVER_REMOTE_CLOSED;
1306 len = strtoul(separator + 1, &separator, 16);
1308 if (*(separator++) != ':')
1310 LOG_ERROR("incomplete write memory packet received, dropping connection");
1311 return ERROR_SERVER_REMOTE_CLOSED;
1314 buffer = malloc(len);
1316 LOG_DEBUG("addr: 0x%8.8" PRIx32 ", len: 0x%8.8" PRIx32 "", addr, len);
1318 for (i = 0; i < len; i++)
1320 uint32_t tmp;
1321 sscanf(separator + 2*i, "%2" SCNx32 , &tmp);
1322 buffer[i] = tmp;
1325 retval = target_write_buffer(target, addr, len, buffer);
1327 if (retval == ERROR_OK)
1329 gdb_put_packet(connection, "OK", 2);
1331 else
1333 retval = gdb_error(connection, retval);
1336 free(buffer);
1338 return retval;
1341 int gdb_write_memory_binary_packet(struct connection *connection, struct target *target, char *packet, int packet_size)
1343 char *separator;
1344 uint32_t addr = 0;
1345 uint32_t len = 0;
1347 int retval;
1349 /* skip command character */
1350 packet++;
1352 addr = strtoul(packet, &separator, 16);
1354 if (*separator != ',')
1356 LOG_ERROR("incomplete write memory binary packet received, dropping connection");
1357 return ERROR_SERVER_REMOTE_CLOSED;
1360 len = strtoul(separator + 1, &separator, 16);
1362 if (*(separator++) != ':')
1364 LOG_ERROR("incomplete write memory binary packet received, dropping connection");
1365 return ERROR_SERVER_REMOTE_CLOSED;
1368 retval = ERROR_OK;
1369 if (len)
1371 LOG_DEBUG("addr: 0x%8.8" PRIx32 ", len: 0x%8.8" PRIx32 "", addr, len);
1373 retval = target_write_buffer(target, addr, len, (uint8_t*)separator);
1376 if (retval == ERROR_OK)
1378 gdb_put_packet(connection, "OK", 2);
1380 else
1382 if ((retval = gdb_error(connection, retval)) != ERROR_OK)
1383 return retval;
1386 return ERROR_OK;
1389 int gdb_step_continue_packet(struct connection *connection, struct target *target, char *packet, int packet_size)
1391 int current = 0;
1392 uint32_t address = 0x0;
1393 int retval = ERROR_OK;
1395 LOG_DEBUG("-");
1397 if (packet_size > 1)
1399 packet[packet_size] = 0;
1400 address = strtoul(packet + 1, NULL, 16);
1402 else
1404 current = 1;
1407 if (packet[0] == 'c')
1409 LOG_DEBUG("continue");
1410 target_handle_event(target, TARGET_EVENT_OLD_pre_resume);
1411 retval = target_resume(target, current, address, 0, 0); /* resume at current address, don't handle breakpoints, not debugging */
1413 else if (packet[0] == 's')
1415 LOG_DEBUG("step");
1416 /* step at current or address, don't handle breakpoints */
1417 retval = target_step(target, current, address, 0);
1419 return retval;
1422 int gdb_breakpoint_watchpoint_packet(struct connection *connection, struct target *target, char *packet, int packet_size)
1424 int type;
1425 enum breakpoint_type bp_type = BKPT_SOFT /* dummy init to avoid warning */;
1426 enum watchpoint_rw wp_type;
1427 uint32_t address;
1428 uint32_t size;
1429 char *separator;
1430 int retval;
1432 LOG_DEBUG("-");
1434 type = strtoul(packet + 1, &separator, 16);
1436 if (type == 0) /* memory breakpoint */
1437 bp_type = BKPT_SOFT;
1438 else if (type == 1) /* hardware breakpoint */
1439 bp_type = BKPT_HARD;
1440 else if (type == 2) /* write watchpoint */
1441 wp_type = WPT_WRITE;
1442 else if (type == 3) /* read watchpoint */
1443 wp_type = WPT_READ;
1444 else if (type == 4) /* access watchpoint */
1445 wp_type = WPT_ACCESS;
1447 if (gdb_breakpoint_override && ((bp_type == BKPT_SOFT)||(bp_type == BKPT_HARD)))
1449 bp_type = gdb_breakpoint_override_type;
1452 if (*separator != ',')
1454 LOG_ERROR("incomplete breakpoint/watchpoint packet received, dropping connection");
1455 return ERROR_SERVER_REMOTE_CLOSED;
1458 address = strtoul(separator + 1, &separator, 16);
1460 if (*separator != ',')
1462 LOG_ERROR("incomplete breakpoint/watchpoint packet received, dropping connection");
1463 return ERROR_SERVER_REMOTE_CLOSED;
1466 size = strtoul(separator + 1, &separator, 16);
1468 switch (type)
1470 case 0:
1471 case 1:
1472 if (packet[0] == 'Z')
1474 if ((retval = breakpoint_add(target, address, size, bp_type)) != ERROR_OK)
1476 if ((retval = gdb_error(connection, retval)) != ERROR_OK)
1477 return retval;
1479 else
1481 gdb_put_packet(connection, "OK", 2);
1484 else
1486 breakpoint_remove(target, address);
1487 gdb_put_packet(connection, "OK", 2);
1489 break;
1490 case 2:
1491 case 3:
1492 case 4:
1494 if (packet[0] == 'Z')
1496 if ((retval = watchpoint_add(target, address, size, type-2, 0, 0xffffffffu)) != ERROR_OK)
1498 if ((retval = gdb_error(connection, retval)) != ERROR_OK)
1499 return retval;
1501 else
1503 gdb_put_packet(connection, "OK", 2);
1506 else
1508 watchpoint_remove(target, address);
1509 gdb_put_packet(connection, "OK", 2);
1511 break;
1513 default:
1514 break;
1517 return ERROR_OK;
1520 /* print out a string and allocate more space as needed, mainly used for XML at this point */
1521 void xml_printf(int *retval, char **xml, int *pos, int *size, const char *fmt, ...)
1523 if (*retval != ERROR_OK)
1525 return;
1527 int first = 1;
1529 for (;;)
1531 if ((*xml == NULL) || (!first))
1533 /* start by 0 to exercise all the code paths.
1534 * Need minimum 2 bytes to fit 1 char and 0 terminator. */
1536 *size = *size * 2 + 2;
1537 char *t = *xml;
1538 *xml = realloc(*xml, *size);
1539 if (*xml == NULL)
1541 if (t)
1542 free(t);
1543 *retval = ERROR_SERVER_REMOTE_CLOSED;
1544 return;
1548 va_list ap;
1549 int ret;
1550 va_start(ap, fmt);
1551 ret = vsnprintf(*xml + *pos, *size - *pos, fmt, ap);
1552 va_end(ap);
1553 if ((ret > 0) && ((ret + 1) < *size - *pos))
1555 *pos += ret;
1556 return;
1558 /* there was just enough or not enough space, allocate more. */
1559 first = 0;
1563 static int decode_xfer_read(char *buf, char **annex, int *ofs, unsigned int *len)
1565 char *separator;
1567 /* Extract and NUL-terminate the annex. */
1568 *annex = buf;
1569 while (*buf && *buf != ':')
1570 buf++;
1571 if (*buf == '\0')
1572 return -1;
1573 *buf++ = 0;
1575 /* After the read marker and annex, qXfer looks like a
1576 * traditional 'm' packet. */
1578 *ofs = strtoul(buf, &separator, 16);
1580 if (*separator != ',')
1581 return -1;
1583 *len = strtoul(separator + 1, NULL, 16);
1585 return 0;
1588 int gdb_calc_blocksize(struct flash_bank *bank)
1590 uint32_t i;
1591 uint32_t block_size = 0xffffffff;
1593 /* loop through all sectors and return smallest sector size */
1595 for (i = 0; i < (uint32_t)bank->num_sectors; i++)
1597 if (bank->sectors[i].size < block_size)
1598 block_size = bank->sectors[i].size;
1601 return block_size;
1604 static int compare_bank (const void * a, const void * b)
1606 struct flash_bank *b1, *b2;
1607 b1=*((struct flash_bank **)a);
1608 b2=*((struct flash_bank **)b);
1610 if (b1->base == b2->base)
1612 return 0;
1613 } else if (b1->base > b2->base)
1615 return 1;
1616 } else
1618 return -1;
1622 int gdb_query_packet(struct connection *connection, struct target *target, char *packet, int packet_size)
1624 struct command_context *cmd_ctx = connection->cmd_ctx;
1625 struct gdb_connection *gdb_connection = connection->priv;
1627 if (strstr(packet, "qRcmd,"))
1629 if (packet_size > 6)
1631 char *cmd;
1632 int i;
1633 cmd = malloc((packet_size - 6)/2 + 1);
1634 for (i = 0; i < (packet_size - 6)/2; i++)
1636 uint32_t tmp;
1637 sscanf(packet + 6 + 2*i, "%2" SCNx32 , &tmp);
1638 cmd[i] = tmp;
1640 cmd[(packet_size - 6)/2] = 0x0;
1642 /* We want to print all debug output to GDB connection */
1643 log_add_callback(gdb_log_callback, connection);
1644 target_call_timer_callbacks_now();
1645 /* some commands need to know the GDB connection, make note of current
1646 * GDB connection. */
1647 current_gdb_connection = gdb_connection;
1648 command_run_line(cmd_ctx, cmd);
1649 current_gdb_connection = NULL;
1650 target_call_timer_callbacks_now();
1651 log_remove_callback(gdb_log_callback, connection);
1652 free(cmd);
1654 gdb_put_packet(connection, "OK", 2);
1655 return ERROR_OK;
1657 else if (strstr(packet, "qCRC:"))
1659 if (packet_size > 5)
1661 int retval;
1662 char gdb_reply[10];
1663 char *separator;
1664 uint32_t checksum;
1665 uint32_t addr = 0;
1666 uint32_t len = 0;
1668 /* skip command character */
1669 packet += 5;
1671 addr = strtoul(packet, &separator, 16);
1673 if (*separator != ',')
1675 LOG_ERROR("incomplete read memory packet received, dropping connection");
1676 return ERROR_SERVER_REMOTE_CLOSED;
1679 len = strtoul(separator + 1, NULL, 16);
1681 retval = target_checksum_memory(target, addr, len, &checksum);
1683 if (retval == ERROR_OK)
1685 snprintf(gdb_reply, 10, "C%8.8" PRIx32 "", checksum);
1686 gdb_put_packet(connection, gdb_reply, 9);
1688 else
1690 if ((retval = gdb_error(connection, retval)) != ERROR_OK)
1691 return retval;
1694 return ERROR_OK;
1697 else if (strstr(packet, "qSupported"))
1699 /* we currently support packet size and qXfer:memory-map:read (if enabled)
1700 * disable qXfer:features:read for the moment */
1701 int retval = ERROR_OK;
1702 char *buffer = NULL;
1703 int pos = 0;
1704 int size = 0;
1706 xml_printf(&retval, &buffer, &pos, &size,
1707 "PacketSize=%x;qXfer:memory-map:read%c;qXfer:features:read-;QStartNoAckMode+",
1708 (GDB_BUFFER_SIZE - 1), ((gdb_use_memory_map == 1) && (flash_get_bank_count() > 0)) ? '+' : '-');
1710 if (retval != ERROR_OK)
1712 gdb_send_error(connection, 01);
1713 return ERROR_OK;
1716 gdb_put_packet(connection, buffer, strlen(buffer));
1717 free(buffer);
1719 return ERROR_OK;
1721 else if (strstr(packet, "qXfer:memory-map:read::") && (flash_get_bank_count() > 0))
1723 /* We get away with only specifying flash here. Regions that are not
1724 * specified are treated as if we provided no memory map(if not we
1725 * could detect the holes and mark them as RAM).
1726 * Normally we only execute this code once, but no big deal if we
1727 * have to regenerate it a couple of times. */
1729 struct flash_bank *p;
1730 char *xml = NULL;
1731 int size = 0;
1732 int pos = 0;
1733 int retval = ERROR_OK;
1735 int offset;
1736 int length;
1737 char *separator;
1738 int blocksize;
1740 /* skip command character */
1741 packet += 23;
1743 offset = strtoul(packet, &separator, 16);
1744 length = strtoul(separator + 1, &separator, 16);
1746 xml_printf(&retval, &xml, &pos, &size, "<memory-map>\n");
1749 sort banks in ascending order, we need to make non-flash memory be ram(or rather
1750 read/write) by default for GDB.
1751 GDB does not have a concept of non-cacheable read/write memory.
1753 struct flash_bank **banks = malloc(sizeof(struct flash_bank *)*flash_get_bank_count());
1754 int i;
1756 for (i = 0; i < flash_get_bank_count(); i++)
1758 p = get_flash_bank_by_num(i);
1759 if (p == NULL)
1761 free(banks);
1762 retval = ERROR_FAIL;
1763 gdb_send_error(connection, retval);
1764 return retval;
1766 banks[i]=p;
1769 qsort(banks, flash_get_bank_count(), sizeof(struct flash_bank *), compare_bank);
1771 uint32_t ram_start = 0;
1772 for (i = 0; i < flash_get_bank_count(); i++)
1774 p = banks[i];
1776 if (ram_start < p->base)
1778 xml_printf(&retval, &xml, &pos, &size, "<memory type=\"ram\" start=\"0x%x\" length=\"0x%x\"/>\n",
1779 ram_start, p->base-ram_start);
1782 /* if device has uneven sector sizes, eg. str7, lpc
1783 * we pass the smallest sector size to gdb memory map */
1784 blocksize = gdb_calc_blocksize(p);
1786 xml_printf(&retval, &xml, &pos, &size, "<memory type=\"flash\" start=\"0x%x\" length=\"0x%x\">\n" \
1787 "<property name=\"blocksize\">0x%x</property>\n" \
1788 "</memory>\n", \
1789 p->base, p->size, blocksize);
1790 ram_start = p->base + p->size;
1792 if (ram_start != 0)
1794 xml_printf(&retval, &xml, &pos, &size, "<memory type=\"ram\" start=\"0x%x\" length=\"0x%x\"/>\n",
1795 ram_start, 0-ram_start);
1796 } else
1798 /* a flash chip could be at the very end of the 32 bit address space, in which case
1799 ram_start will be precisely 0 */
1802 free(banks);
1803 banks = NULL;
1805 xml_printf(&retval, &xml, &pos, &size, "</memory-map>\n");
1807 if (retval != ERROR_OK)
1809 gdb_send_error(connection, retval);
1810 return retval;
1813 if (offset + length > pos)
1815 length = pos - offset;
1818 char *t = malloc(length + 1);
1819 t[0] = 'l';
1820 memcpy(t + 1, xml + offset, length);
1821 gdb_put_packet(connection, t, length + 1);
1823 free(t);
1824 free(xml);
1825 return ERROR_OK;
1827 else if (strstr(packet, "qXfer:features:read:"))
1829 char *xml = NULL;
1830 int size = 0;
1831 int pos = 0;
1832 int retval = ERROR_OK;
1834 int offset;
1835 unsigned int length;
1836 char *annex;
1838 /* skip command character */
1839 packet += 20;
1841 if (decode_xfer_read(packet, &annex, &offset, &length) < 0)
1843 gdb_send_error(connection, 01);
1844 return ERROR_OK;
1847 if (strcmp(annex, "target.xml") != 0)
1849 gdb_send_error(connection, 01);
1850 return ERROR_OK;
1853 xml_printf(&retval, &xml, &pos, &size, \
1854 "l < target version=\"1.0\">\n < architecture > arm</architecture>\n</target>\n");
1856 if (retval != ERROR_OK)
1858 gdb_send_error(connection, retval);
1859 return retval;
1862 gdb_put_packet(connection, xml, strlen(xml));
1864 free(xml);
1865 return ERROR_OK;
1867 else if (strstr(packet, "QStartNoAckMode"))
1869 gdb_connection->noack_mode = 1;
1870 gdb_put_packet(connection, "OK", 2);
1871 return ERROR_OK;
1874 gdb_put_packet(connection, "", 0);
1875 return ERROR_OK;
1878 int gdb_v_packet(struct connection *connection, struct target *target, char *packet, int packet_size)
1880 struct gdb_connection *gdb_connection = connection->priv;
1881 struct gdb_service *gdb_service = connection->service->priv;
1882 int result;
1884 /* if flash programming disabled - send a empty reply */
1886 if (gdb_flash_program == 0)
1888 gdb_put_packet(connection, "", 0);
1889 return ERROR_OK;
1892 if (strstr(packet, "vFlashErase:"))
1894 unsigned long addr;
1895 unsigned long length;
1897 char *parse = packet + 12;
1898 if (*parse == '\0')
1900 LOG_ERROR("incomplete vFlashErase packet received, dropping connection");
1901 return ERROR_SERVER_REMOTE_CLOSED;
1904 addr = strtoul(parse, &parse, 16);
1906 if (*(parse++) != ',' || *parse == '\0')
1908 LOG_ERROR("incomplete vFlashErase packet received, dropping connection");
1909 return ERROR_SERVER_REMOTE_CLOSED;
1912 length = strtoul(parse, &parse, 16);
1914 if (*parse != '\0')
1916 LOG_ERROR("incomplete vFlashErase packet received, dropping connection");
1917 return ERROR_SERVER_REMOTE_CLOSED;
1920 /* assume all sectors need erasing - stops any problems
1921 * when flash_write is called multiple times */
1922 flash_set_dirty();
1924 /* perform any target specific operations before the erase */
1925 target_call_event_callbacks(gdb_service->target, TARGET_EVENT_GDB_FLASH_ERASE_START);
1926 result = flash_erase_address_range(gdb_service->target, addr, length);
1927 target_call_event_callbacks(gdb_service->target, TARGET_EVENT_GDB_FLASH_ERASE_END);
1929 /* perform erase */
1930 if (result != ERROR_OK)
1932 /* GDB doesn't evaluate the actual error number returned,
1933 * treat a failed erase as an I/O error
1935 gdb_send_error(connection, EIO);
1936 LOG_ERROR("flash_erase returned %i", result);
1938 else
1939 gdb_put_packet(connection, "OK", 2);
1941 return ERROR_OK;
1944 if (strstr(packet, "vFlashWrite:"))
1946 int retval;
1947 unsigned long addr;
1948 unsigned long length;
1949 char *parse = packet + 12;
1951 if (*parse == '\0')
1953 LOG_ERROR("incomplete vFlashErase packet received, dropping connection");
1954 return ERROR_SERVER_REMOTE_CLOSED;
1956 addr = strtoul(parse, &parse, 16);
1957 if (*(parse++) != ':')
1959 LOG_ERROR("incomplete vFlashErase packet received, dropping connection");
1960 return ERROR_SERVER_REMOTE_CLOSED;
1962 length = packet_size - (parse - packet);
1964 /* create a new image if there isn't already one */
1965 if (gdb_connection->vflash_image == NULL)
1967 gdb_connection->vflash_image = malloc(sizeof(struct image));
1968 image_open(gdb_connection->vflash_image, "", "build");
1971 /* create new section with content from packet buffer */
1972 if ((retval = image_add_section(gdb_connection->vflash_image, addr, length, 0x0, (uint8_t*)parse)) != ERROR_OK)
1974 return retval;
1977 gdb_put_packet(connection, "OK", 2);
1979 return ERROR_OK;
1982 if (!strcmp(packet, "vFlashDone"))
1984 uint32_t written;
1986 /* process the flashing buffer. No need to erase as GDB
1987 * always issues a vFlashErase first. */
1988 target_call_event_callbacks(gdb_service->target, TARGET_EVENT_GDB_FLASH_WRITE_START);
1989 result = flash_write(gdb_service->target, gdb_connection->vflash_image, &written, 0);
1990 target_call_event_callbacks(gdb_service->target, TARGET_EVENT_GDB_FLASH_WRITE_END);
1991 if (result != ERROR_OK)
1993 if (result == ERROR_FLASH_DST_OUT_OF_BANK)
1994 gdb_put_packet(connection, "E.memtype", 9);
1995 else
1996 gdb_send_error(connection, EIO);
1998 else
2000 LOG_DEBUG("wrote %u bytes from vFlash image to flash", (unsigned)written);
2001 gdb_put_packet(connection, "OK", 2);
2004 image_close(gdb_connection->vflash_image);
2005 free(gdb_connection->vflash_image);
2006 gdb_connection->vflash_image = NULL;
2008 return ERROR_OK;
2011 gdb_put_packet(connection, "", 0);
2012 return ERROR_OK;
2015 int gdb_detach(struct connection *connection, struct target *target)
2017 struct gdb_service *gdb_service = connection->service->priv;
2019 target_call_event_callbacks(gdb_service->target, TARGET_EVENT_GDB_DETACH);
2021 return gdb_put_packet(connection, "OK", 2);
2024 static void gdb_log_callback(void *priv, const char *file, unsigned line,
2025 const char *function, const char *string)
2027 struct connection *connection = priv;
2028 struct gdb_connection *gdb_con = connection->priv;
2030 if (gdb_con->busy)
2032 /* do not reply this using the O packet */
2033 return;
2036 gdb_output_con(connection, string);
2039 /* Do not allocate this on the stack */
2040 char gdb_packet_buffer[GDB_BUFFER_SIZE];
2042 static void gdb_sig_halted(struct connection *connection)
2044 char sig_reply[4];
2045 snprintf(sig_reply, 4, "T%2.2x", 2);
2046 gdb_put_packet(connection, sig_reply, 3);
2050 int gdb_input_inner(struct connection *connection)
2052 struct gdb_service *gdb_service = connection->service->priv;
2053 struct target *target = gdb_service->target;
2054 char *packet = gdb_packet_buffer;
2055 int packet_size;
2056 int retval;
2057 struct gdb_connection *gdb_con = connection->priv;
2058 static int extended_protocol = 0;
2060 /* drain input buffer */
2063 packet_size = GDB_BUFFER_SIZE-1;
2064 if ((retval = gdb_get_packet(connection, packet, &packet_size)) != ERROR_OK)
2066 return retval;
2069 /* terminate with zero */
2070 packet[packet_size] = 0;
2072 if (LOG_LEVEL_IS(LOG_LVL_DEBUG)) {
2073 if (packet[0] == 'X') {
2074 // binary packets spew junk into the debug log stream
2075 char buf[ 50 ];
2076 int x;
2077 for (x = 0 ; (x < 49) && (packet[x] != ':') ; x++) {
2078 buf[x] = packet[x];
2080 buf[x] = 0;
2081 LOG_DEBUG("received packet: '%s:<binary-data>'", buf);
2082 } else {
2083 LOG_DEBUG("received packet: '%s'", packet);
2087 if (packet_size > 0)
2089 retval = ERROR_OK;
2090 switch (packet[0])
2092 case 'H':
2093 /* Hct... -- set thread
2094 * we don't have threads, send empty reply */
2095 gdb_put_packet(connection, NULL, 0);
2096 break;
2097 case 'q':
2098 case 'Q':
2099 retval = gdb_query_packet(connection, target, packet, packet_size);
2100 break;
2101 case 'g':
2102 retval = gdb_get_registers_packet(connection, target, packet, packet_size);
2103 break;
2104 case 'G':
2105 retval = gdb_set_registers_packet(connection, target, packet, packet_size);
2106 break;
2107 case 'p':
2108 retval = gdb_get_register_packet(connection, target, packet, packet_size);
2109 break;
2110 case 'P':
2111 retval = gdb_set_register_packet(connection, target, packet, packet_size);
2112 break;
2113 case 'm':
2114 retval = gdb_read_memory_packet(connection, target, packet, packet_size);
2115 break;
2116 case 'M':
2117 retval = gdb_write_memory_packet(connection, target, packet, packet_size);
2118 break;
2119 case 'z':
2120 case 'Z':
2121 retval = gdb_breakpoint_watchpoint_packet(connection, target, packet, packet_size);
2122 break;
2123 case '?':
2124 gdb_last_signal_packet(connection, target, packet, packet_size);
2125 break;
2126 case 'c':
2127 case 's':
2129 int retval = ERROR_OK;
2131 struct gdb_connection *gdb_con = connection->priv;
2132 log_add_callback(gdb_log_callback, connection);
2134 bool nostep = false;
2135 if (target->state == TARGET_RUNNING)
2137 LOG_WARNING("The target is already running. Halt target before stepi/continue.");
2138 retval = target_halt(target);
2139 if (retval == ERROR_OK)
2140 retval = target_wait_state(target, TARGET_HALTED, 100);
2141 } else if (target->state != TARGET_HALTED)
2143 LOG_WARNING("The target is not in the halted nor running stated, stepi/continue ignored.");
2144 nostep = true;
2145 } else if ((packet[0] == 's') && gdb_con->sync)
2147 /* Hmm..... when you issue a continue in GDB, then a "stepi" is
2148 * sent by GDB first to OpenOCD, thus defeating the check to
2149 * make only the single stepping have the sync feature...
2151 nostep = true;
2152 LOG_WARNING("stepi ignored. GDB will now fetch the register state from the target.");
2154 gdb_con->sync = false;
2156 if ((retval!=ERROR_OK) || nostep)
2158 /* Either the target isn't in the halted state, then we can't
2159 * step/continue. This might be early setup, etc.
2161 * Or we want to allow GDB to pick up a fresh set of
2162 * register values without modifying the target state.
2165 gdb_sig_halted(connection);
2167 /* stop forwarding log packets! */
2168 log_remove_callback(gdb_log_callback, connection);
2169 } else
2171 /* We're running/stepping, in which case we can
2172 * forward log output until the target is halted
2174 gdb_con->frontend_state = TARGET_RUNNING;
2175 target_call_event_callbacks(target, TARGET_EVENT_GDB_START);
2176 int retval = gdb_step_continue_packet(connection, target, packet, packet_size);
2177 if (retval != ERROR_OK)
2179 /* we'll never receive a halted condition... issue a false one.. */
2180 gdb_frontend_halted(target, connection);
2184 break;
2185 case 'v':
2186 retval = gdb_v_packet(connection, target, packet, packet_size);
2187 break;
2188 case 'D':
2189 retval = gdb_detach(connection, target);
2190 extended_protocol = 0;
2191 break;
2192 case 'X':
2193 if ((retval = gdb_write_memory_binary_packet(connection, target, packet, packet_size)) != ERROR_OK)
2194 return retval;
2195 break;
2196 case 'k':
2197 if (extended_protocol != 0)
2198 break;
2199 gdb_put_packet(connection, "OK", 2);
2200 return ERROR_SERVER_REMOTE_CLOSED;
2201 case '!':
2202 /* handle extended remote protocol */
2203 extended_protocol = 1;
2204 gdb_put_packet(connection, "OK", 2);
2205 break;
2206 case 'R':
2207 /* handle extended restart packet */
2208 breakpoint_clear_target(gdb_service->target);
2209 watchpoint_clear_target(gdb_service->target);
2210 command_run_linef(connection->cmd_ctx,
2211 "ocd_gdb_restart %s",
2212 target_name(target));
2213 break;
2214 default:
2215 /* ignore unknown packets */
2216 LOG_DEBUG("ignoring 0x%2.2x packet", packet[0]);
2217 gdb_put_packet(connection, NULL, 0);
2218 break;
2221 /* if a packet handler returned an error, exit input loop */
2222 if (retval != ERROR_OK)
2223 return retval;
2226 if (gdb_con->ctrl_c)
2228 if (target->state == TARGET_RUNNING)
2230 retval = target_halt(target);
2231 if (retval != ERROR_OK)
2233 target_call_event_callbacks(target, TARGET_EVENT_GDB_HALT);
2235 gdb_con->ctrl_c = 0;
2236 } else
2238 LOG_INFO("The target is not running when halt was requested, stopping GDB.");
2239 target_call_event_callbacks(target, TARGET_EVENT_GDB_HALT);
2243 } while (gdb_con->buf_cnt > 0);
2245 return ERROR_OK;
2248 int gdb_input(struct connection *connection)
2250 int retval = gdb_input_inner(connection);
2251 struct gdb_connection *gdb_con = connection->priv;
2252 if (retval == ERROR_SERVER_REMOTE_CLOSED)
2253 return retval;
2255 /* logging does not propagate the error, yet can set the gdb_con->closed flag */
2256 if (gdb_con->closed)
2257 return ERROR_SERVER_REMOTE_CLOSED;
2259 /* we'll recover from any other errors(e.g. temporary timeouts, etc.) */
2260 return ERROR_OK;
2263 static int gdb_target_start(struct target *target, uint16_t port)
2265 bool use_pipes = 0 == port;
2266 struct gdb_service *gdb_service = malloc(sizeof(struct gdb_service));
2267 if (NULL == gdb_service)
2268 return -ENOMEM;
2270 gdb_service->target = target;
2272 add_service("gdb", use_pipes ? CONNECTION_PIPE : CONNECTION_TCP,
2273 port, 1, &gdb_new_connection, &gdb_input,
2274 &gdb_connection_closed, gdb_service);
2276 const char *name = target_name(target);
2277 if (use_pipes)
2278 LOG_DEBUG("gdb service for target '%s' using pipes", name);
2279 else
2280 LOG_DEBUG("gdb service for target '%s' on TCP port %u", name, port);
2281 return ERROR_OK;
2284 /* FIXME static */
2285 int gdb_target_add_one(struct target *target)
2287 if (gdb_port == 0 && server_use_pipes == 0)
2289 LOG_INFO("gdb port disabled");
2290 return ERROR_OK;
2292 if (0 == gdb_port_next)
2293 gdb_port_next = gdb_port;
2295 bool use_pipes = server_use_pipes;
2296 static bool server_started_with_pipes = false;
2297 if (server_started_with_pipes)
2299 LOG_WARNING("gdb service permits one target when using pipes");
2300 if (0 == gdb_port)
2301 return ERROR_OK;
2303 use_pipes = false;
2306 int e = gdb_target_start(target, use_pipes ? 0 : gdb_port_next);
2307 if (ERROR_OK == e)
2309 server_started_with_pipes |= use_pipes;
2310 gdb_port_next++;
2312 return e;
2315 int gdb_target_add_all(struct target *target)
2317 if (NULL == target)
2319 LOG_WARNING("gdb services need one or more targets defined");
2320 return ERROR_OK;
2323 while (NULL != target)
2325 int retval = gdb_target_add_one(target);
2326 if (ERROR_OK != retval)
2327 return retval;
2329 target = target->next;
2332 return ERROR_OK;
2335 COMMAND_HANDLER(handle_gdb_sync_command)
2337 if (CMD_ARGC != 0)
2339 return ERROR_COMMAND_SYNTAX_ERROR;
2342 if (current_gdb_connection == NULL)
2344 command_print(CMD_CTX,
2345 "gdb_sync command can only be run from within gdb using \"monitor gdb_sync\"");
2346 return ERROR_FAIL;
2349 current_gdb_connection->sync = true;
2351 return ERROR_OK;
2354 /* daemon configuration command gdb_port */
2355 COMMAND_HANDLER(handle_gdb_port_command)
2357 int retval = CALL_COMMAND_HANDLER(server_port_command, &gdb_port);
2358 if (ERROR_OK == retval)
2359 gdb_port_next = gdb_port;
2360 return retval;
2363 COMMAND_HANDLER(handle_gdb_memory_map_command)
2365 if (CMD_ARGC == 1)
2366 COMMAND_PARSE_ENABLE(CMD_ARGV[0], gdb_use_memory_map);
2368 return ERROR_COMMAND_SYNTAX_ERROR;
2371 COMMAND_HANDLER(handle_gdb_flash_program_command)
2373 if (CMD_ARGC == 1)
2374 COMMAND_PARSE_ENABLE(CMD_ARGV[0], gdb_flash_program);
2376 return ERROR_COMMAND_SYNTAX_ERROR;
2379 COMMAND_HANDLER(handle_gdb_report_data_abort_command)
2381 if (CMD_ARGC == 1)
2382 COMMAND_PARSE_ENABLE(CMD_ARGV[0], gdb_report_data_abort);
2384 return ERROR_COMMAND_SYNTAX_ERROR;
2387 /* gdb_breakpoint_override */
2388 COMMAND_HANDLER(handle_gdb_breakpoint_override_command)
2390 if (CMD_ARGC == 0)
2393 } else if (CMD_ARGC == 1)
2395 gdb_breakpoint_override = 1;
2396 if (strcmp(CMD_ARGV[0], "hard") == 0)
2398 gdb_breakpoint_override_type = BKPT_HARD;
2399 } else if (strcmp(CMD_ARGV[0], "soft") == 0)
2401 gdb_breakpoint_override_type = BKPT_SOFT;
2402 } else if (strcmp(CMD_ARGV[0], "disable") == 0)
2404 gdb_breakpoint_override = 0;
2406 } else
2408 return ERROR_COMMAND_SYNTAX_ERROR;
2410 if (gdb_breakpoint_override)
2412 LOG_USER("force %s breakpoints", (gdb_breakpoint_override_type == BKPT_HARD)?"hard":"soft");
2413 } else
2415 LOG_USER("breakpoint type is not overridden");
2418 return ERROR_OK;
2421 static const struct command_registration gdb_command_handlers[] = {
2423 .name = "gdb_sync",
2424 .handler = handle_gdb_sync_command,
2425 .mode = COMMAND_ANY,
2426 .help = "next stepi will return immediately allowing "
2427 "GDB to fetch register state without affecting "
2428 "target state",
2431 .name = "gdb_port",
2432 .handler = handle_gdb_port_command,
2433 .mode = COMMAND_ANY,
2434 .help = "Display or specify base port on which to listen "
2435 "for incoming GDB connections. "
2436 "No arguments reports GDB port; zero disables.",
2437 .usage = "[port_num]",
2440 .name = "gdb_memory_map",
2441 .handler = handle_gdb_memory_map_command,
2442 .mode = COMMAND_CONFIG,
2443 .help = "enable or disable memory map",
2444 .usage = "('enable'|'disable')"
2447 .name = "gdb_flash_program",
2448 .handler = handle_gdb_flash_program_command,
2449 .mode = COMMAND_CONFIG,
2450 .help = "enable or disable flash program",
2451 .usage = "('enable'|'disable')"
2454 .name = "gdb_report_data_abort",
2455 .handler = handle_gdb_report_data_abort_command,
2456 .mode = COMMAND_CONFIG,
2457 .help = "enable or disable reporting data aborts",
2458 .usage = "('enable'|'disable')"
2461 .name = "gdb_breakpoint_override",
2462 .handler = handle_gdb_breakpoint_override_command,
2463 .mode = COMMAND_EXEC,
2464 .help = "Display or specify type of breakpoint "
2465 "to be used by gdb 'break' commands.",
2466 .usage = "('hard'|'soft'|'disable')"
2468 COMMAND_REGISTRATION_DONE
2471 int gdb_register_commands(struct command_context *cmd_ctx)
2473 return register_commands(cmd_ctx, NULL, gdb_command_handlers);