jtag: clean up TAP state name handling
[openocd.git] / src / server / gdb_server.c
blobadf5c687d016c3a5ebd01451376708301beebc46
1 /***************************************************************************
2 * Copyright (C) 2005 by Dominic Rath *
3 * Dominic.Rath@gmx.de *
4 * *
5 * Copyright (C) 2007,2008 Ø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 "gdb_server.h"
31 #include "target_request.h"
32 #include "register.h"
33 #include "server.h"
34 #include "flash.h"
35 #include "image.h"
36 #include "jtag.h"
39 #if 0
40 #define _DEBUG_GDB_IO_
41 #endif
43 static gdb_connection_t *current_gdb_connection;
45 static int gdb_breakpoint_override;
46 static enum breakpoint_type gdb_breakpoint_override_type;
48 extern int gdb_error(connection_t *connection, int retval);
49 static unsigned short gdb_port = 3333;
50 static const char *DIGITS = "0123456789abcdef";
52 static void gdb_log_callback(void *priv, const char *file, int line,
53 const char *function, const char *string);
55 /* number of gdb connections, mainly to supress gdb related debugging spam
56 * in helper/log.c when no gdb connections are actually active */
57 int gdb_actual_connections;
59 /* set if we are sending a memory map to gdb
60 * via qXfer:memory-map:read packet */
61 /* enabled by default*/
62 int gdb_use_memory_map = 1;
63 /* enabled by default*/
64 int gdb_flash_program = 1;
66 /* if set, data aborts cause an error to be reported in memory read packets
67 * see the code in gdb_read_memory_packet() for further explanations */
68 int gdb_report_data_abort = 0;
70 int gdb_last_signal(target_t *target)
72 switch (target->debug_reason)
74 case DBG_REASON_DBGRQ:
75 return 0x2; /* SIGINT */
76 case DBG_REASON_BREAKPOINT:
77 case DBG_REASON_WATCHPOINT:
78 case DBG_REASON_WPTANDBKPT:
79 return 0x05; /* SIGTRAP */
80 case DBG_REASON_SINGLESTEP:
81 return 0x05; /* SIGTRAP */
82 case DBG_REASON_NOTHALTED:
83 return 0x0; /* no signal... shouldn't happen */
84 default:
85 LOG_USER("undefined debug reason %d - target needs reset", target->debug_reason);
86 return 0x0;
90 int check_pending(connection_t *connection, int timeout_s, int *got_data)
92 /* a non-blocking socket will block if there is 0 bytes available on the socket,
93 * but return with as many bytes as are available immediately
95 struct timeval tv;
96 fd_set read_fds;
97 gdb_connection_t *gdb_con = connection->priv;
98 int t;
99 if (got_data == NULL)
100 got_data=&t;
101 *got_data = 0;
103 if (gdb_con->buf_cnt > 0)
105 *got_data = 1;
106 return ERROR_OK;
109 FD_ZERO(&read_fds);
110 FD_SET(connection->fd, &read_fds);
112 tv.tv_sec = timeout_s;
113 tv.tv_usec = 0;
114 if (socket_select(connection->fd + 1, &read_fds, NULL, NULL, &tv) == 0)
116 /* This can typically be because a "monitor" command took too long
117 * before printing any progress messages
119 if (timeout_s > 0)
121 return ERROR_GDB_TIMEOUT;
122 } else
124 return ERROR_OK;
127 *got_data = FD_ISSET(connection->fd, &read_fds) != 0;
128 return ERROR_OK;
131 int gdb_get_char(connection_t *connection, int* next_char)
133 gdb_connection_t *gdb_con = connection->priv;
134 int retval = ERROR_OK;
136 #ifdef _DEBUG_GDB_IO_
137 char *debug_buffer;
138 #endif
140 if (gdb_con->buf_cnt-- > 0)
142 *next_char = *(gdb_con->buf_p++);
143 if (gdb_con->buf_cnt > 0)
144 connection->input_pending = 1;
145 else
146 connection->input_pending = 0;
148 #ifdef _DEBUG_GDB_IO_
149 LOG_DEBUG("returned char '%c' (0x%2.2x)", *next_char, *next_char);
150 #endif
152 return ERROR_OK;
155 for (;;)
157 if (connection->service->type == CONNECTION_PIPE)
159 gdb_con->buf_cnt = read(connection->fd, gdb_con->buffer, GDB_BUFFER_SIZE);
161 else
163 retval = check_pending(connection, 1, NULL);
164 if (retval != ERROR_OK)
165 return retval;
166 gdb_con->buf_cnt = read_socket(connection->fd, gdb_con->buffer, GDB_BUFFER_SIZE);
169 if (gdb_con->buf_cnt > 0)
171 break;
173 if (gdb_con->buf_cnt == 0)
175 gdb_con->closed = 1;
176 return ERROR_SERVER_REMOTE_CLOSED;
179 #ifdef _WIN32
180 errno = WSAGetLastError();
182 switch (errno)
184 case WSAEWOULDBLOCK:
185 usleep(1000);
186 break;
187 case WSAECONNABORTED:
188 gdb_con->closed = 1;
189 return ERROR_SERVER_REMOTE_CLOSED;
190 case WSAECONNRESET:
191 gdb_con->closed = 1;
192 return ERROR_SERVER_REMOTE_CLOSED;
193 default:
194 LOG_ERROR("read: %d", errno);
195 exit(-1);
197 #else
198 switch (errno)
200 case EAGAIN:
201 usleep(1000);
202 break;
203 case ECONNABORTED:
204 gdb_con->closed = 1;
205 return ERROR_SERVER_REMOTE_CLOSED;
206 case ECONNRESET:
207 gdb_con->closed = 1;
208 return ERROR_SERVER_REMOTE_CLOSED;
209 default:
210 LOG_ERROR("read: %s", strerror(errno));
211 gdb_con->closed = 1;
212 return ERROR_SERVER_REMOTE_CLOSED;
214 #endif
217 #ifdef _DEBUG_GDB_IO_
218 debug_buffer = malloc(gdb_con->buf_cnt + 1);
219 memcpy(debug_buffer, gdb_con->buffer, gdb_con->buf_cnt);
220 debug_buffer[gdb_con->buf_cnt] = 0;
221 LOG_DEBUG("received '%s'", debug_buffer);
222 free(debug_buffer);
223 #endif
225 gdb_con->buf_p = gdb_con->buffer;
226 gdb_con->buf_cnt--;
227 *next_char = *(gdb_con->buf_p++);
228 if (gdb_con->buf_cnt > 0)
229 connection->input_pending = 1;
230 else
231 connection->input_pending = 0;
232 #ifdef _DEBUG_GDB_IO_
233 LOG_DEBUG("returned char '%c' (0x%2.2x)", *next_char, *next_char);
234 #endif
236 return retval;
239 int gdb_putback_char(connection_t *connection, int last_char)
241 gdb_connection_t *gdb_con = connection->priv;
243 if (gdb_con->buf_p > gdb_con->buffer)
245 *(--gdb_con->buf_p) = last_char;
246 gdb_con->buf_cnt++;
248 else
250 LOG_ERROR("BUG: couldn't put character back");
253 return ERROR_OK;
256 /* The only way we can detect that the socket is closed is the first time
257 * we write to it, we will fail. Subsequent write operations will
258 * succeed. Shudder! */
259 int gdb_write(connection_t *connection, void *data, int len)
261 gdb_connection_t *gdb_con = connection->priv;
262 if (gdb_con->closed)
263 return ERROR_SERVER_REMOTE_CLOSED;
265 if (connection->service->type == CONNECTION_PIPE)
267 /* write to stdout */
268 if (write(STDOUT_FILENO, data, len) == len)
270 return ERROR_OK;
273 else
275 if (write_socket(connection->fd, data, len) == len)
277 return ERROR_OK;
280 gdb_con->closed = 1;
281 return ERROR_SERVER_REMOTE_CLOSED;
284 int gdb_put_packet_inner(connection_t *connection, char *buffer, int len)
286 int i;
287 unsigned char my_checksum = 0;
288 #ifdef _DEBUG_GDB_IO_
289 char *debug_buffer;
290 #endif
291 int reply;
292 int retval;
293 gdb_connection_t *gdb_con = connection->priv;
295 for (i = 0; i < len; i++)
296 my_checksum += buffer[i];
298 #ifdef _DEBUG_GDB_IO_
300 * At this point we should have nothing in the input queue from GDB,
301 * however sometimes '-' is sent even though we've already received
302 * an ACK (+) for everything we've sent off.
304 int gotdata;
305 for (;;)
307 if ((retval = check_pending(connection, 0, &gotdata)) != ERROR_OK)
308 return retval;
309 if (!gotdata)
310 break;
311 if ((retval = gdb_get_char(connection, &reply)) != ERROR_OK)
312 return retval;
313 if (reply == '$') {
314 /* fix a problem with some IAR tools */
315 gdb_putback_char(connection, reply);
316 LOG_DEBUG("Unexpected start of new packet");
317 break;
320 LOG_WARNING("Discard unexpected char %c", reply);
322 #endif
324 while (1)
326 #ifdef _DEBUG_GDB_IO_
327 debug_buffer = malloc(len + 1);
328 memcpy(debug_buffer, buffer, len);
329 debug_buffer[len] = 0;
330 LOG_DEBUG("sending packet '$%s#%2.2x'", debug_buffer, my_checksum);
331 free(debug_buffer);
332 #endif
334 char local_buffer[1024];
335 local_buffer[0] = '$';
336 if ((size_t)len + 4 <= sizeof(local_buffer))
338 /* performance gain on smaller packets by only a single call to gdb_write() */
339 memcpy(local_buffer + 1, buffer, len++);
340 local_buffer[len++] = '#';
341 local_buffer[len++] = DIGITS[(my_checksum >> 4) & 0xf];
342 local_buffer[len++] = DIGITS[my_checksum & 0xf];
343 if ((retval = gdb_write(connection, local_buffer, len)) != ERROR_OK)
345 return retval;
348 else
350 /* larger packets are transmitted directly from caller supplied buffer
351 by several calls to gdb_write() to avoid dynamic allocation */
352 local_buffer[1] = '#';
353 local_buffer[2] = DIGITS[(my_checksum >> 4) & 0xf];
354 local_buffer[3] = DIGITS[my_checksum & 0xf];
355 if ((retval = gdb_write(connection, local_buffer, 1)) != ERROR_OK)
357 return retval;
359 if ((retval = gdb_write(connection, buffer, len)) != ERROR_OK)
361 return retval;
363 if ((retval = gdb_write(connection, local_buffer + 1, 3)) != ERROR_OK)
365 return retval;
369 if (gdb_con->noack_mode)
370 break;
372 if ((retval = gdb_get_char(connection, &reply)) != ERROR_OK)
373 return retval;
375 if (reply == '+')
376 break;
377 else if (reply == '-')
379 /* Stop sending output packets for now */
380 log_remove_callback(gdb_log_callback, connection);
381 LOG_WARNING("negative reply, retrying");
383 else if (reply == 0x3)
385 gdb_con->ctrl_c = 1;
386 if ((retval = gdb_get_char(connection, &reply)) != ERROR_OK)
387 return retval;
388 if (reply == '+')
389 break;
390 else if (reply == '-')
392 /* Stop sending output packets for now */
393 log_remove_callback(gdb_log_callback, connection);
394 LOG_WARNING("negative reply, retrying");
396 else if (reply == '$') {
397 LOG_ERROR("GDB missing ack(1) - assumed good");
398 gdb_putback_char(connection, reply);
399 return ERROR_OK;
400 } else {
402 LOG_ERROR("unknown character(1) 0x%2.2x in reply, dropping connection", reply);
403 gdb_con->closed = 1;
404 return ERROR_SERVER_REMOTE_CLOSED;
407 else if (reply == '$') {
408 LOG_ERROR("GDB missing ack(2) - assumed good");
409 gdb_putback_char(connection, reply);
410 return ERROR_OK;
412 else
414 LOG_ERROR("unknown character(2) 0x%2.2x in reply, dropping connection", reply);
415 gdb_con->closed = 1;
416 return ERROR_SERVER_REMOTE_CLOSED;
419 if (gdb_con->closed)
420 return ERROR_SERVER_REMOTE_CLOSED;
422 return ERROR_OK;
425 int gdb_put_packet(connection_t *connection, char *buffer, int len)
427 gdb_connection_t *gdb_con = connection->priv;
428 gdb_con->busy = 1;
429 int retval = gdb_put_packet_inner(connection, buffer, len);
430 gdb_con->busy = 0;
432 /* we sent some data, reset timer for keep alive messages */
433 kept_alive();
435 return retval;
438 static __inline__ int fetch_packet(connection_t *connection, int *checksum_ok, int noack, int *len, char *buffer)
440 unsigned char my_checksum = 0;
441 char checksum[3];
442 int character;
443 int retval;
445 gdb_connection_t *gdb_con = connection->priv;
446 my_checksum = 0;
447 int count = 0;
448 count = 0;
449 for (;;)
451 /* The common case is that we have an entire packet with no escape chars.
452 * We need to leave at least 2 bytes in the buffer to have
453 * gdb_get_char() update various bits and bobs correctly.
455 if ((gdb_con->buf_cnt > 2) && ((gdb_con->buf_cnt + count) < *len))
457 /* The compiler will struggle a bit with constant propagation and
458 * aliasing, so we help it by showing that these values do not
459 * change inside the loop
461 int i;
462 char *buf = gdb_con->buf_p;
463 int run = gdb_con->buf_cnt - 2;
464 i = 0;
465 int done = 0;
466 while (i < run)
468 character = *buf++;
469 i++;
470 if (character == '#')
472 /* Danger! character can be '#' when esc is
473 * used so we need an explicit boolean for done here.
475 done = 1;
476 break;
479 if (character == '}')
481 /* data transmitted in binary mode (X packet)
482 * uses 0x7d as escape character */
483 my_checksum += character & 0xff;
484 character = *buf++;
485 i++;
486 my_checksum += character & 0xff;
487 buffer[count++] = (character ^ 0x20) & 0xff;
489 else
491 my_checksum += character & 0xff;
492 buffer[count++] = character & 0xff;
495 gdb_con->buf_p += i;
496 gdb_con->buf_cnt -= i;
497 if (done)
498 break;
500 if (count > *len)
502 LOG_ERROR("packet buffer too small");
503 return ERROR_GDB_BUFFER_TOO_SMALL;
506 if ((retval = gdb_get_char(connection, &character)) != ERROR_OK)
507 return retval;
509 if (character == '#')
510 break;
512 if (character == '}')
514 /* data transmitted in binary mode (X packet)
515 * uses 0x7d as escape character */
516 my_checksum += character & 0xff;
517 if ((retval = gdb_get_char(connection, &character)) != ERROR_OK)
518 return retval;
519 my_checksum += character & 0xff;
520 buffer[count++] = (character ^ 0x20) & 0xff;
522 else
524 my_checksum += character & 0xff;
525 buffer[count++] = character & 0xff;
529 *len = count;
531 if ((retval = gdb_get_char(connection, &character)) != ERROR_OK)
532 return retval;
533 checksum[0] = character;
534 if ((retval = gdb_get_char(connection, &character)) != ERROR_OK)
535 return retval;
536 checksum[1] = character;
537 checksum[2] = 0;
539 if (!noack)
541 *checksum_ok = (my_checksum == strtoul(checksum, NULL, 16));
544 return ERROR_OK;
547 int gdb_get_packet_inner(connection_t *connection, char *buffer, int *len)
549 int character;
550 int retval;
551 gdb_connection_t *gdb_con = connection->priv;
553 while (1)
557 if ((retval = gdb_get_char(connection, &character)) != ERROR_OK)
558 return retval;
560 #ifdef _DEBUG_GDB_IO_
561 LOG_DEBUG("character: '%c'", character);
562 #endif
564 switch (character)
566 case '$':
567 break;
568 case '+':
569 /* gdb sends a dummy ack '+' at every remote connect - see remote_start_remote (remote.c)
570 * incase anyone tries to debug why they receive this warning every time */
571 LOG_WARNING("acknowledgment received, but no packet pending");
572 break;
573 case '-':
574 LOG_WARNING("negative acknowledgment, but no packet pending");
575 break;
576 case 0x3:
577 gdb_con->ctrl_c = 1;
578 *len = 0;
579 return ERROR_OK;
580 default:
581 LOG_WARNING("ignoring character 0x%x", character);
582 break;
584 } while (character != '$');
588 int checksum_ok = 0;
589 /* explicit code expansion here to get faster inlined code in -O3 by not
590 * calculating checksum
592 if (gdb_con->noack_mode)
594 if ((retval = fetch_packet(connection, &checksum_ok, 1, len, buffer)) != ERROR_OK)
595 return retval;
596 } else
598 if ((retval = fetch_packet(connection, &checksum_ok, 0, len, buffer)) != ERROR_OK)
599 return retval;
602 if (gdb_con->noack_mode)
604 /* checksum is not checked in noack mode */
605 break;
607 if (checksum_ok)
609 if ((retval = gdb_write(connection, "+", 1)) != ERROR_OK)
611 return retval;
613 break;
616 if (gdb_con->closed)
617 return ERROR_SERVER_REMOTE_CLOSED;
619 return ERROR_OK;
622 int gdb_get_packet(connection_t *connection, char *buffer, int *len)
624 gdb_connection_t *gdb_con = connection->priv;
625 gdb_con->busy = 1;
626 int retval = gdb_get_packet_inner(connection, buffer, len);
627 gdb_con->busy = 0;
628 return retval;
631 int gdb_output_con(connection_t *connection, const char* line)
633 char *hex_buffer;
634 int i, bin_size;
636 bin_size = strlen(line);
638 hex_buffer = malloc(bin_size*2 + 2);
639 if (hex_buffer == NULL)
640 return ERROR_GDB_BUFFER_TOO_SMALL;
642 hex_buffer[0] = 'O';
643 for (i = 0; i < bin_size; i++)
644 snprintf(hex_buffer + 1 + i*2, 3, "%2.2x", line[i]);
645 hex_buffer[bin_size*2 + 1] = 0;
647 int retval = gdb_put_packet(connection, hex_buffer, bin_size*2 + 1);
649 free(hex_buffer);
650 return retval;
653 int gdb_output(struct command_context_s *context, const char* line)
655 /* this will be dumped to the log and also sent as an O packet if possible */
656 LOG_USER_N("%s", line);
657 return ERROR_OK;
661 static void gdb_frontend_halted(struct target_s *target, connection_t *connection)
663 gdb_connection_t *gdb_connection = connection->priv;
665 /* In the GDB protocol when we are stepping or continuing execution,
666 * we have a lingering reply. Upon receiving a halted event
667 * when we have that lingering packet, we reply to the original
668 * step or continue packet.
670 * Executing monitor commands can bring the target in and
671 * out of the running state so we'll see lots of TARGET_EVENT_XXX
672 * that are to be ignored.
674 if (gdb_connection->frontend_state == TARGET_RUNNING)
676 char sig_reply[4];
677 int signal;
679 /* stop forwarding log packets! */
680 log_remove_callback(gdb_log_callback, connection);
682 if (gdb_connection->ctrl_c)
684 signal = 0x2;
685 gdb_connection->ctrl_c = 0;
687 else
689 signal = gdb_last_signal(target);
692 snprintf(sig_reply, 4, "T%2.2x", signal);
693 gdb_put_packet(connection, sig_reply, 3);
694 gdb_connection->frontend_state = TARGET_HALTED;
698 int gdb_target_callback_event_handler(struct target_s *target, enum target_event event, void *priv)
700 int retval;
701 connection_t *connection = priv;
703 target_handle_event(target, event);
704 switch (event)
706 case TARGET_EVENT_GDB_HALT:
707 gdb_frontend_halted(target, connection);
708 break;
709 case TARGET_EVENT_HALTED:
710 target_call_event_callbacks(target, TARGET_EVENT_GDB_END);
711 break;
712 case TARGET_EVENT_GDB_FLASH_ERASE_START:
713 target_handle_event(target, TARGET_EVENT_OLD_gdb_program_config);
714 if ((retval = jtag_execute_queue()) != ERROR_OK)
716 return retval;
718 break;
719 default:
720 break;
723 return ERROR_OK;
726 int gdb_new_connection(connection_t *connection)
728 gdb_connection_t *gdb_connection = malloc(sizeof(gdb_connection_t));
729 gdb_service_t *gdb_service = connection->service->priv;
730 int retval;
731 int initial_ack;
733 connection->priv = gdb_connection;
735 /* initialize gdb connection information */
736 gdb_connection->buf_p = gdb_connection->buffer;
737 gdb_connection->buf_cnt = 0;
738 gdb_connection->ctrl_c = 0;
739 gdb_connection->frontend_state = TARGET_HALTED;
740 gdb_connection->vflash_image = NULL;
741 gdb_connection->closed = 0;
742 gdb_connection->busy = 0;
743 gdb_connection->noack_mode = 0;
744 gdb_connection->sync = true;
746 /* send ACK to GDB for debug request */
747 gdb_write(connection, "+", 1);
749 /* output goes through gdb connection */
750 command_set_output_handler(connection->cmd_ctx, gdb_output, connection);
752 /* we must remove all breakpoints registered to the target as a previous
753 * GDB session could leave dangling breakpoints if e.g. communication
754 * timed out.
756 breakpoint_clear_target(gdb_service->target);
757 watchpoint_clear_target(gdb_service->target);
759 /* register callback to be informed about target events */
760 target_register_event_callback(gdb_target_callback_event_handler, connection);
762 /* remove the initial ACK from the incoming buffer */
763 if ((retval = gdb_get_char(connection, &initial_ack)) != ERROR_OK)
764 return retval;
766 /* FIX!!!??? would we actually ever receive a + here???
767 * Not observed.
769 if (initial_ack != '+')
770 gdb_putback_char(connection, initial_ack);
771 target_call_event_callbacks(gdb_service->target, TARGET_EVENT_GDB_ATTACH);
773 gdb_actual_connections++;
774 LOG_DEBUG("New GDB Connection: %d, Target %s, state: %s",
775 gdb_actual_connections,
776 gdb_service->target->cmd_name,
777 target_state_name(gdb_service->target));
779 return ERROR_OK;
782 int gdb_connection_closed(connection_t *connection)
784 gdb_service_t *gdb_service = connection->service->priv;
785 gdb_connection_t *gdb_connection = connection->priv;
787 /* we're done forwarding messages. Tear down callback before
788 * cleaning up connection.
790 log_remove_callback(gdb_log_callback, connection);
792 gdb_actual_connections--;
793 LOG_DEBUG("GDB Close, Target: %s, state: %s, gdb_actual_connections=%d",
794 gdb_service->target->cmd_name,
795 target_state_name(gdb_service->target),
796 gdb_actual_connections);
798 /* see if an image built with vFlash commands is left */
799 if (gdb_connection->vflash_image)
801 image_close(gdb_connection->vflash_image);
802 free(gdb_connection->vflash_image);
803 gdb_connection->vflash_image = NULL;
806 /* if this connection registered a debug-message receiver delete it */
807 delete_debug_msg_receiver(connection->cmd_ctx, gdb_service->target);
809 if (connection->priv)
811 free(connection->priv);
812 connection->priv = NULL;
814 else
816 LOG_ERROR("BUG: connection->priv == NULL");
820 target_unregister_event_callback(gdb_target_callback_event_handler, connection);
822 target_call_event_callbacks(gdb_service->target, TARGET_EVENT_GDB_END);
824 target_call_event_callbacks(gdb_service->target, TARGET_EVENT_GDB_DETACH);
826 return ERROR_OK;
829 void gdb_send_error(connection_t *connection, uint8_t the_error)
831 char err[4];
832 snprintf(err, 4, "E%2.2X", the_error);
833 gdb_put_packet(connection, err, 3);
836 int gdb_last_signal_packet(connection_t *connection, target_t *target, char* packet, int packet_size)
838 char sig_reply[4];
839 int signal;
841 signal = gdb_last_signal(target);
843 snprintf(sig_reply, 4, "S%2.2x", signal);
844 gdb_put_packet(connection, sig_reply, 3);
846 return ERROR_OK;
849 static int gdb_reg_pos(target_t *target, int pos, int len)
851 if (target->endianness == TARGET_LITTLE_ENDIAN)
852 return pos;
853 else
854 return len - 1 - pos;
857 /* Convert register to string of bytes. NB! The # of bits in the
858 * register might be non-divisible by 8(a byte), in which
859 * case an entire byte is shown.
861 * NB! the format on the wire is the target endianess
863 * The format of reg->value is little endian
866 void gdb_str_to_target(target_t *target, char *tstr, reg_t *reg)
868 int i;
870 uint8_t *buf;
871 int buf_len;
872 buf = reg->value;
873 buf_len = CEIL(reg->size, 8);
875 for (i = 0; i < buf_len; i++)
877 int j = gdb_reg_pos(target, i, buf_len);
878 tstr[i*2] = DIGITS[(buf[j]>>4) & 0xf];
879 tstr[i*2 + 1] = DIGITS[buf[j]&0xf];
883 static int hextoint(char c)
885 if (c>='0'&&c<='9')
887 return c-'0';
889 c = toupper(c);
890 if (c>='A'&&c<='F')
892 return c-'A'+10;
894 LOG_ERROR("BUG: invalid register value %08x", c);
895 return 0;
898 /* copy over in register buffer */
899 void gdb_target_to_reg(target_t *target, char *tstr, int str_len, uint8_t *bin)
901 if (str_len % 2)
903 LOG_ERROR("BUG: gdb value with uneven number of characters encountered");
904 exit(-1);
907 int i;
908 for (i = 0; i < str_len; i += 2)
910 uint8_t t = hextoint(tstr[i]) << 4;
911 t |= hextoint(tstr[i + 1]);
913 int j = gdb_reg_pos(target, i/2, str_len/2);
914 bin[j] = t;
918 int gdb_get_registers_packet(connection_t *connection, target_t *target, char* packet, int packet_size)
920 reg_t **reg_list;
921 int reg_list_size;
922 int retval;
923 int reg_packet_size = 0;
924 char *reg_packet;
925 char *reg_packet_p;
926 int i;
928 #ifdef _DEBUG_GDB_IO_
929 LOG_DEBUG("-");
930 #endif
932 if ((retval = target_get_gdb_reg_list(target, &reg_list, &reg_list_size)) != ERROR_OK)
934 return gdb_error(connection, retval);
937 for (i = 0; i < reg_list_size; i++)
939 reg_packet_size += reg_list[i]->size;
942 reg_packet = malloc(CEIL(reg_packet_size, 8) * 2);
943 reg_packet_p = reg_packet;
945 for (i = 0; i < reg_list_size; i++)
947 gdb_str_to_target(target, reg_packet_p, reg_list[i]);
948 reg_packet_p += CEIL(reg_list[i]->size, 8) * 2;
951 #ifdef _DEBUG_GDB_IO_
953 char *reg_packet_p;
954 reg_packet_p = strndup(reg_packet, CEIL(reg_packet_size, 8) * 2);
955 LOG_DEBUG("reg_packet: %s", reg_packet_p);
956 free(reg_packet_p);
958 #endif
960 gdb_put_packet(connection, reg_packet, CEIL(reg_packet_size, 8) * 2);
961 free(reg_packet);
963 free(reg_list);
965 return ERROR_OK;
968 int gdb_set_registers_packet(connection_t *connection, target_t *target, char *packet, int packet_size)
970 int i;
971 reg_t **reg_list;
972 int reg_list_size;
973 int retval;
974 char *packet_p;
976 #ifdef _DEBUG_GDB_IO_
977 LOG_DEBUG("-");
978 #endif
980 /* skip command character */
981 packet++;
982 packet_size--;
984 if (packet_size % 2)
986 LOG_WARNING("GDB set_registers packet with uneven characters received, dropping connection");
987 return ERROR_SERVER_REMOTE_CLOSED;
990 if ((retval = target_get_gdb_reg_list(target, &reg_list, &reg_list_size)) != ERROR_OK)
992 return gdb_error(connection, retval);
995 packet_p = packet;
996 for (i = 0; i < reg_list_size; i++)
998 uint8_t *bin_buf;
999 int chars = (CEIL(reg_list[i]->size, 8) * 2);
1001 if (packet_p + chars > packet + packet_size)
1003 LOG_ERROR("BUG: register packet is too small for registers");
1006 reg_arch_type_t *arch_type;
1007 bin_buf = malloc(CEIL(reg_list[i]->size, 8));
1008 gdb_target_to_reg(target, packet_p, chars, bin_buf);
1010 /* get register arch_type, and call set method */
1011 arch_type = register_get_arch_type(reg_list[i]->arch_type);
1013 arch_type->set(reg_list[i], bin_buf);
1015 /* advance packet pointer */
1016 packet_p += chars;
1019 free(bin_buf);
1022 /* free reg_t *reg_list[] array allocated by get_gdb_reg_list */
1023 free(reg_list);
1025 gdb_put_packet(connection, "OK", 2);
1027 return ERROR_OK;
1030 int gdb_get_register_packet(connection_t *connection, target_t *target, char *packet, int packet_size)
1032 char *reg_packet;
1033 int reg_num = strtoul(packet + 1, NULL, 16);
1034 reg_t **reg_list;
1035 int reg_list_size;
1036 int retval;
1038 #ifdef _DEBUG_GDB_IO_
1039 LOG_DEBUG("-");
1040 #endif
1042 if ((retval = target_get_gdb_reg_list(target, &reg_list, &reg_list_size)) != ERROR_OK)
1044 return gdb_error(connection, retval);
1047 if (reg_list_size <= reg_num)
1049 LOG_ERROR("gdb requested a non-existing register");
1050 exit(-1);
1053 reg_packet = malloc(CEIL(reg_list[reg_num]->size, 8) * 2);
1055 gdb_str_to_target(target, reg_packet, reg_list[reg_num]);
1057 gdb_put_packet(connection, reg_packet, CEIL(reg_list[reg_num]->size, 8) * 2);
1059 free(reg_list);
1060 free(reg_packet);
1062 return ERROR_OK;
1065 int gdb_set_register_packet(connection_t *connection, target_t *target, char *packet, int packet_size)
1067 char *separator;
1068 uint8_t *bin_buf;
1069 int reg_num = strtoul(packet + 1, &separator, 16);
1070 reg_t **reg_list;
1071 int reg_list_size;
1072 int retval;
1073 reg_arch_type_t *arch_type;
1075 LOG_DEBUG("-");
1077 if ((retval = target_get_gdb_reg_list(target, &reg_list, &reg_list_size)) != ERROR_OK)
1079 return gdb_error(connection, retval);
1082 if (reg_list_size < reg_num)
1084 LOG_ERROR("gdb requested a non-existing register");
1085 return ERROR_SERVER_REMOTE_CLOSED;
1088 if (*separator != '=')
1090 LOG_ERROR("GDB 'set register packet', but no '=' following the register number");
1091 return ERROR_SERVER_REMOTE_CLOSED;
1094 /* convert from GDB-string (target-endian) to hex-string (big-endian) */
1095 bin_buf = malloc(CEIL(reg_list[reg_num]->size, 8));
1096 int chars = (CEIL(reg_list[reg_num]->size, 8) * 2);
1098 /* fix!!! add some sanity checks on packet size here */
1100 gdb_target_to_reg(target, separator + 1, chars, bin_buf);
1102 /* get register arch_type, and call set method */
1103 arch_type = register_get_arch_type(reg_list[reg_num]->arch_type);
1104 arch_type->set(reg_list[reg_num], bin_buf);
1106 gdb_put_packet(connection, "OK", 2);
1108 free(bin_buf);
1109 free(reg_list);
1111 return ERROR_OK;
1114 int gdb_error(connection_t *connection, int retval)
1116 switch (retval)
1118 case ERROR_TARGET_DATA_ABORT:
1119 gdb_send_error(connection, EIO);
1120 break;
1121 case ERROR_TARGET_TRANSLATION_FAULT:
1122 gdb_send_error(connection, EFAULT);
1123 break;
1124 case ERROR_TARGET_UNALIGNED_ACCESS:
1125 gdb_send_error(connection, EFAULT);
1126 break;
1127 case ERROR_TARGET_NOT_HALTED:
1128 gdb_send_error(connection, EFAULT);
1129 break;
1130 default:
1131 /* This could be that the target reset itself. */
1132 LOG_ERROR("unexpected error %i", retval);
1133 gdb_send_error(connection, EFAULT);
1134 break;
1137 return ERROR_OK;
1140 /* We don't have to worry about the default 2 second timeout for GDB packets,
1141 * because GDB breaks up large memory reads into smaller reads.
1143 * 8191 bytes by the looks of it. Why 8191 bytes instead of 8192?????
1145 int gdb_read_memory_packet(connection_t *connection, target_t *target, char *packet, int packet_size)
1147 char *separator;
1148 uint32_t addr = 0;
1149 uint32_t len = 0;
1151 uint8_t *buffer;
1152 char *hex_buffer;
1154 int retval = ERROR_OK;
1156 /* skip command character */
1157 packet++;
1159 addr = strtoul(packet, &separator, 16);
1161 if (*separator != ',')
1163 LOG_ERROR("incomplete read memory packet received, dropping connection");
1164 return ERROR_SERVER_REMOTE_CLOSED;
1167 len = strtoul(separator + 1, NULL, 16);
1169 buffer = malloc(len);
1171 LOG_DEBUG("addr: 0x%8.8" PRIx32 ", len: 0x%8.8" PRIx32 "", addr, len);
1173 retval = target_read_buffer(target, addr, len, buffer);
1175 if ((retval != ERROR_OK)&&!gdb_report_data_abort)
1177 /* TODO : Here we have to lie and send back all zero's lest stack traces won't work.
1178 * At some point this might be fixed in GDB, in which case this code can be removed.
1180 * OpenOCD developers are acutely aware of this problem, but there is nothing
1181 * gained by involving the user in this problem that hopefully will get resolved
1182 * eventually
1184 * http://sourceware.org/cgi-bin/gnatsweb.pl?cmd = view%20audit-trail&database = gdb&pr = 2395
1186 * For now, the default is to fix up things to make current GDB versions work.
1187 * This can be overwritten using the gdb_report_data_abort <'enable'|'disable'> command.
1189 memset(buffer, 0, len);
1190 retval = ERROR_OK;
1193 if (retval == ERROR_OK)
1195 hex_buffer = malloc(len * 2 + 1);
1197 uint32_t i;
1198 for (i = 0; i < len; i++)
1200 uint8_t t = buffer[i];
1201 hex_buffer[2 * i] = DIGITS[(t >> 4) & 0xf];
1202 hex_buffer[2 * i + 1] = DIGITS[t & 0xf];
1205 gdb_put_packet(connection, hex_buffer, len * 2);
1207 free(hex_buffer);
1209 else
1211 retval = gdb_error(connection, retval);
1214 free(buffer);
1216 return retval;
1219 int gdb_write_memory_packet(connection_t *connection, target_t *target, char *packet, int packet_size)
1221 char *separator;
1222 uint32_t addr = 0;
1223 uint32_t len = 0;
1225 uint8_t *buffer;
1227 uint32_t i;
1228 int retval;
1230 /* skip command character */
1231 packet++;
1233 addr = strtoul(packet, &separator, 16);
1235 if (*separator != ',')
1237 LOG_ERROR("incomplete write memory packet received, dropping connection");
1238 return ERROR_SERVER_REMOTE_CLOSED;
1241 len = strtoul(separator + 1, &separator, 16);
1243 if (*(separator++) != ':')
1245 LOG_ERROR("incomplete write memory packet received, dropping connection");
1246 return ERROR_SERVER_REMOTE_CLOSED;
1249 buffer = malloc(len);
1251 LOG_DEBUG("addr: 0x%8.8" PRIx32 ", len: 0x%8.8" PRIx32 "", addr, len);
1253 for (i = 0; i < len; i++)
1255 uint32_t tmp;
1256 sscanf(separator + 2*i, "%2" SCNx32 , &tmp);
1257 buffer[i] = tmp;
1260 retval = target_write_buffer(target, addr, len, buffer);
1262 if (retval == ERROR_OK)
1264 gdb_put_packet(connection, "OK", 2);
1266 else
1268 retval = gdb_error(connection, retval);
1271 free(buffer);
1273 return retval;
1276 int gdb_write_memory_binary_packet(connection_t *connection, target_t *target, char *packet, int packet_size)
1278 char *separator;
1279 uint32_t addr = 0;
1280 uint32_t len = 0;
1282 int retval;
1284 /* skip command character */
1285 packet++;
1287 addr = strtoul(packet, &separator, 16);
1289 if (*separator != ',')
1291 LOG_ERROR("incomplete write memory binary packet received, dropping connection");
1292 return ERROR_SERVER_REMOTE_CLOSED;
1295 len = strtoul(separator + 1, &separator, 16);
1297 if (*(separator++) != ':')
1299 LOG_ERROR("incomplete write memory binary packet received, dropping connection");
1300 return ERROR_SERVER_REMOTE_CLOSED;
1303 retval = ERROR_OK;
1304 if (len)
1306 LOG_DEBUG("addr: 0x%8.8" PRIx32 ", len: 0x%8.8" PRIx32 "", addr, len);
1308 retval = target_write_buffer(target, addr, len, (uint8_t*)separator);
1311 if (retval == ERROR_OK)
1313 gdb_put_packet(connection, "OK", 2);
1315 else
1317 if ((retval = gdb_error(connection, retval)) != ERROR_OK)
1318 return retval;
1321 return ERROR_OK;
1324 int gdb_step_continue_packet(connection_t *connection, target_t *target, char *packet, int packet_size)
1326 int current = 0;
1327 uint32_t address = 0x0;
1328 int retval = ERROR_OK;
1330 LOG_DEBUG("-");
1332 if (packet_size > 1)
1334 packet[packet_size] = 0;
1335 address = strtoul(packet + 1, NULL, 16);
1337 else
1339 current = 1;
1342 if (packet[0] == 'c')
1344 LOG_DEBUG("continue");
1345 target_handle_event(target, TARGET_EVENT_OLD_pre_resume);
1346 retval = target_resume(target, current, address, 0, 0); /* resume at current address, don't handle breakpoints, not debugging */
1348 else if (packet[0] == 's')
1350 LOG_DEBUG("step");
1351 /* step at current or address, don't handle breakpoints */
1352 retval = target_step(target, current, address, 0);
1354 return retval;
1357 int gdb_breakpoint_watchpoint_packet(connection_t *connection, target_t *target, char *packet, int packet_size)
1359 int type;
1360 enum breakpoint_type bp_type = BKPT_SOFT /* dummy init to avoid warning */;
1361 enum watchpoint_rw wp_type;
1362 uint32_t address;
1363 uint32_t size;
1364 char *separator;
1365 int retval;
1367 LOG_DEBUG("-");
1369 type = strtoul(packet + 1, &separator, 16);
1371 if (type == 0) /* memory breakpoint */
1372 bp_type = BKPT_SOFT;
1373 else if (type == 1) /* hardware breakpoint */
1374 bp_type = BKPT_HARD;
1375 else if (type == 2) /* write watchpoint */
1376 wp_type = WPT_WRITE;
1377 else if (type == 3) /* read watchpoint */
1378 wp_type = WPT_READ;
1379 else if (type == 4) /* access watchpoint */
1380 wp_type = WPT_ACCESS;
1382 if (gdb_breakpoint_override && ((bp_type == BKPT_SOFT)||(bp_type == BKPT_HARD)))
1384 bp_type = gdb_breakpoint_override_type;
1387 if (*separator != ',')
1389 LOG_ERROR("incomplete breakpoint/watchpoint packet received, dropping connection");
1390 return ERROR_SERVER_REMOTE_CLOSED;
1393 address = strtoul(separator + 1, &separator, 16);
1395 if (*separator != ',')
1397 LOG_ERROR("incomplete breakpoint/watchpoint packet received, dropping connection");
1398 return ERROR_SERVER_REMOTE_CLOSED;
1401 size = strtoul(separator + 1, &separator, 16);
1403 switch (type)
1405 case 0:
1406 case 1:
1407 if (packet[0] == 'Z')
1409 if ((retval = breakpoint_add(target, address, size, bp_type)) != ERROR_OK)
1411 if ((retval = gdb_error(connection, retval)) != ERROR_OK)
1412 return retval;
1414 else
1416 gdb_put_packet(connection, "OK", 2);
1419 else
1421 breakpoint_remove(target, address);
1422 gdb_put_packet(connection, "OK", 2);
1424 break;
1425 case 2:
1426 case 3:
1427 case 4:
1429 if (packet[0] == 'Z')
1431 if ((retval = watchpoint_add(target, address, size, type-2, 0, 0xffffffffu)) != ERROR_OK)
1433 if ((retval = gdb_error(connection, retval)) != ERROR_OK)
1434 return retval;
1436 else
1438 gdb_put_packet(connection, "OK", 2);
1441 else
1443 watchpoint_remove(target, address);
1444 gdb_put_packet(connection, "OK", 2);
1446 break;
1448 default:
1449 break;
1452 return ERROR_OK;
1455 /* print out a string and allocate more space as needed, mainly used for XML at this point */
1456 void xml_printf(int *retval, char **xml, int *pos, int *size, const char *fmt, ...)
1458 if (*retval != ERROR_OK)
1460 return;
1462 int first = 1;
1464 for (;;)
1466 if ((*xml == NULL) || (!first))
1468 /* start by 0 to exercise all the code paths.
1469 * Need minimum 2 bytes to fit 1 char and 0 terminator. */
1471 *size = *size * 2 + 2;
1472 char *t = *xml;
1473 *xml = realloc(*xml, *size);
1474 if (*xml == NULL)
1476 if (t)
1477 free(t);
1478 *retval = ERROR_SERVER_REMOTE_CLOSED;
1479 return;
1483 va_list ap;
1484 int ret;
1485 va_start(ap, fmt);
1486 ret = vsnprintf(*xml + *pos, *size - *pos, fmt, ap);
1487 va_end(ap);
1488 if ((ret > 0) && ((ret + 1) < *size - *pos))
1490 *pos += ret;
1491 return;
1493 /* there was just enough or not enough space, allocate more. */
1494 first = 0;
1498 static int decode_xfer_read(char *buf, char **annex, int *ofs, unsigned int *len)
1500 char *separator;
1502 /* Extract and NUL-terminate the annex. */
1503 *annex = buf;
1504 while (*buf && *buf != ':')
1505 buf++;
1506 if (*buf == '\0')
1507 return -1;
1508 *buf++ = 0;
1510 /* After the read marker and annex, qXfer looks like a
1511 * traditional 'm' packet. */
1513 *ofs = strtoul(buf, &separator, 16);
1515 if (*separator != ',')
1516 return -1;
1518 *len = strtoul(separator + 1, NULL, 16);
1520 return 0;
1523 int gdb_calc_blocksize(flash_bank_t *bank)
1525 uint32_t i;
1526 uint32_t block_size = 0xffffffff;
1528 /* loop through all sectors and return smallest sector size */
1530 for (i = 0; i < (uint32_t)bank->num_sectors; i++)
1532 if (bank->sectors[i].size < block_size)
1533 block_size = bank->sectors[i].size;
1536 return block_size;
1539 static int compare_bank (const void * a, const void * b)
1541 flash_bank_t *b1, *b2;
1542 b1=*((flash_bank_t **)a);
1543 b2=*((flash_bank_t **)b);
1545 if (b1->base == b2->base)
1547 return 0;
1548 } else if (b1->base > b2->base)
1550 return 1;
1551 } else
1553 return -1;
1557 int gdb_query_packet(connection_t *connection, target_t *target, char *packet, int packet_size)
1559 command_context_t *cmd_ctx = connection->cmd_ctx;
1560 gdb_connection_t *gdb_connection = connection->priv;
1562 if (strstr(packet, "qRcmd,"))
1564 if (packet_size > 6)
1566 char *cmd;
1567 int i;
1568 cmd = malloc((packet_size - 6)/2 + 1);
1569 for (i = 0; i < (packet_size - 6)/2; i++)
1571 uint32_t tmp;
1572 sscanf(packet + 6 + 2*i, "%2" SCNx32 , &tmp);
1573 cmd[i] = tmp;
1575 cmd[(packet_size - 6)/2] = 0x0;
1577 /* We want to print all debug output to GDB connection */
1578 log_add_callback(gdb_log_callback, connection);
1579 target_call_timer_callbacks_now();
1580 /* some commands need to know the GDB connection, make note of current
1581 * GDB connection. */
1582 current_gdb_connection = gdb_connection;
1583 command_run_line(cmd_ctx, cmd);
1584 current_gdb_connection = NULL;
1585 target_call_timer_callbacks_now();
1586 log_remove_callback(gdb_log_callback, connection);
1587 free(cmd);
1589 gdb_put_packet(connection, "OK", 2);
1590 return ERROR_OK;
1592 else if (strstr(packet, "qCRC:"))
1594 if (packet_size > 5)
1596 int retval;
1597 char gdb_reply[10];
1598 char *separator;
1599 uint32_t checksum;
1600 uint32_t addr = 0;
1601 uint32_t len = 0;
1603 /* skip command character */
1604 packet += 5;
1606 addr = strtoul(packet, &separator, 16);
1608 if (*separator != ',')
1610 LOG_ERROR("incomplete read memory packet received, dropping connection");
1611 return ERROR_SERVER_REMOTE_CLOSED;
1614 len = strtoul(separator + 1, NULL, 16);
1616 retval = target_checksum_memory(target, addr, len, &checksum);
1618 if (retval == ERROR_OK)
1620 snprintf(gdb_reply, 10, "C%8.8" PRIx32 "", checksum);
1621 gdb_put_packet(connection, gdb_reply, 9);
1623 else
1625 if ((retval = gdb_error(connection, retval)) != ERROR_OK)
1626 return retval;
1629 return ERROR_OK;
1632 else if (strstr(packet, "qSupported"))
1634 /* we currently support packet size and qXfer:memory-map:read (if enabled)
1635 * disable qXfer:features:read for the moment */
1636 int retval = ERROR_OK;
1637 char *buffer = NULL;
1638 int pos = 0;
1639 int size = 0;
1641 xml_printf(&retval, &buffer, &pos, &size,
1642 "PacketSize=%x;qXfer:memory-map:read%c;qXfer:features:read-;QStartNoAckMode+",
1643 (GDB_BUFFER_SIZE - 1), ((gdb_use_memory_map == 1) && (flash_get_bank_count() > 0)) ? '+' : '-');
1645 if (retval != ERROR_OK)
1647 gdb_send_error(connection, 01);
1648 return ERROR_OK;
1651 gdb_put_packet(connection, buffer, strlen(buffer));
1652 free(buffer);
1654 return ERROR_OK;
1656 else if (strstr(packet, "qXfer:memory-map:read::") && (flash_get_bank_count() > 0))
1658 /* We get away with only specifying flash here. Regions that are not
1659 * specified are treated as if we provided no memory map(if not we
1660 * could detect the holes and mark them as RAM).
1661 * Normally we only execute this code once, but no big deal if we
1662 * have to regenerate it a couple of times. */
1664 flash_bank_t *p;
1665 char *xml = NULL;
1666 int size = 0;
1667 int pos = 0;
1668 int retval = ERROR_OK;
1670 int offset;
1671 int length;
1672 char *separator;
1673 int blocksize;
1675 /* skip command character */
1676 packet += 23;
1678 offset = strtoul(packet, &separator, 16);
1679 length = strtoul(separator + 1, &separator, 16);
1681 xml_printf(&retval, &xml, &pos, &size, "<memory-map>\n");
1684 sort banks in ascending order, we need to make non-flash memory be ram(or rather
1685 read/write) by default for GDB.
1686 GDB does not have a concept of non-cacheable read/write memory.
1688 flash_bank_t **banks = malloc(sizeof(flash_bank_t *)*flash_get_bank_count());
1689 int i;
1691 for (i = 0; i < flash_get_bank_count(); i++)
1693 p = get_flash_bank_by_num(i);
1694 if (p == NULL)
1696 free(banks);
1697 retval = ERROR_FAIL;
1698 gdb_send_error(connection, retval);
1699 return retval;
1701 banks[i]=p;
1704 qsort(banks, flash_get_bank_count(), sizeof(flash_bank_t *), compare_bank);
1706 uint32_t ram_start = 0;
1707 for (i = 0; i < flash_get_bank_count(); i++)
1709 p = banks[i];
1711 if (ram_start < p->base)
1713 xml_printf(&retval, &xml, &pos, &size, "<memory type=\"ram\" start=\"0x%x\" length=\"0x%x\"/>\n",
1714 ram_start, p->base-ram_start);
1717 /* if device has uneven sector sizes, eg. str7, lpc
1718 * we pass the smallest sector size to gdb memory map */
1719 blocksize = gdb_calc_blocksize(p);
1721 xml_printf(&retval, &xml, &pos, &size, "<memory type=\"flash\" start=\"0x%x\" length=\"0x%x\">\n" \
1722 "<property name=\"blocksize\">0x%x</property>\n" \
1723 "</memory>\n", \
1724 p->base, p->size, blocksize);
1725 ram_start = p->base + p->size;
1727 if (ram_start != 0)
1729 xml_printf(&retval, &xml, &pos, &size, "<memory type=\"ram\" start=\"0x%x\" length=\"0x%x\"/>\n",
1730 ram_start, 0-ram_start);
1731 } else
1733 /* a flash chip could be at the very end of the 32 bit address space, in which case
1734 ram_start will be precisely 0 */
1737 free(banks);
1738 banks = NULL;
1740 xml_printf(&retval, &xml, &pos, &size, "</memory-map>\n");
1742 if (retval != ERROR_OK)
1744 gdb_send_error(connection, retval);
1745 return retval;
1748 if (offset + length > pos)
1750 length = pos - offset;
1753 char *t = malloc(length + 1);
1754 t[0] = 'l';
1755 memcpy(t + 1, xml + offset, length);
1756 gdb_put_packet(connection, t, length + 1);
1758 free(t);
1759 free(xml);
1760 return ERROR_OK;
1762 else if (strstr(packet, "qXfer:features:read:"))
1764 char *xml = NULL;
1765 int size = 0;
1766 int pos = 0;
1767 int retval = ERROR_OK;
1769 int offset;
1770 unsigned int length;
1771 char *annex;
1773 /* skip command character */
1774 packet += 20;
1776 if (decode_xfer_read(packet, &annex, &offset, &length) < 0)
1778 gdb_send_error(connection, 01);
1779 return ERROR_OK;
1782 if (strcmp(annex, "target.xml") != 0)
1784 gdb_send_error(connection, 01);
1785 return ERROR_OK;
1788 xml_printf(&retval, &xml, &pos, &size, \
1789 "l < target version=\"1.0\">\n < architecture > arm</architecture>\n</target>\n");
1791 if (retval != ERROR_OK)
1793 gdb_send_error(connection, retval);
1794 return retval;
1797 gdb_put_packet(connection, xml, strlen(xml));
1799 free(xml);
1800 return ERROR_OK;
1802 else if (strstr(packet, "QStartNoAckMode"))
1804 gdb_connection->noack_mode = 1;
1805 gdb_put_packet(connection, "OK", 2);
1806 return ERROR_OK;
1809 gdb_put_packet(connection, "", 0);
1810 return ERROR_OK;
1813 int gdb_v_packet(connection_t *connection, target_t *target, char *packet, int packet_size)
1815 gdb_connection_t *gdb_connection = connection->priv;
1816 gdb_service_t *gdb_service = connection->service->priv;
1817 int result;
1819 /* if flash programming disabled - send a empty reply */
1821 if (gdb_flash_program == 0)
1823 gdb_put_packet(connection, "", 0);
1824 return ERROR_OK;
1827 if (strstr(packet, "vFlashErase:"))
1829 unsigned long addr;
1830 unsigned long length;
1832 char *parse = packet + 12;
1833 if (*parse == '\0')
1835 LOG_ERROR("incomplete vFlashErase packet received, dropping connection");
1836 return ERROR_SERVER_REMOTE_CLOSED;
1839 addr = strtoul(parse, &parse, 16);
1841 if (*(parse++) != ',' || *parse == '\0')
1843 LOG_ERROR("incomplete vFlashErase packet received, dropping connection");
1844 return ERROR_SERVER_REMOTE_CLOSED;
1847 length = strtoul(parse, &parse, 16);
1849 if (*parse != '\0')
1851 LOG_ERROR("incomplete vFlashErase packet received, dropping connection");
1852 return ERROR_SERVER_REMOTE_CLOSED;
1855 /* assume all sectors need erasing - stops any problems
1856 * when flash_write is called multiple times */
1857 flash_set_dirty();
1859 /* perform any target specific operations before the erase */
1860 target_call_event_callbacks(gdb_service->target, TARGET_EVENT_GDB_FLASH_ERASE_START);
1861 result = flash_erase_address_range(gdb_service->target, addr, length);
1862 target_call_event_callbacks(gdb_service->target, TARGET_EVENT_GDB_FLASH_ERASE_END);
1864 /* perform erase */
1865 if (result != ERROR_OK)
1867 /* GDB doesn't evaluate the actual error number returned,
1868 * treat a failed erase as an I/O error
1870 gdb_send_error(connection, EIO);
1871 LOG_ERROR("flash_erase returned %i", result);
1873 else
1874 gdb_put_packet(connection, "OK", 2);
1876 return ERROR_OK;
1879 if (strstr(packet, "vFlashWrite:"))
1881 int retval;
1882 unsigned long addr;
1883 unsigned long length;
1884 char *parse = packet + 12;
1886 if (*parse == '\0')
1888 LOG_ERROR("incomplete vFlashErase packet received, dropping connection");
1889 return ERROR_SERVER_REMOTE_CLOSED;
1891 addr = strtoul(parse, &parse, 16);
1892 if (*(parse++) != ':')
1894 LOG_ERROR("incomplete vFlashErase packet received, dropping connection");
1895 return ERROR_SERVER_REMOTE_CLOSED;
1897 length = packet_size - (parse - packet);
1899 /* create a new image if there isn't already one */
1900 if (gdb_connection->vflash_image == NULL)
1902 gdb_connection->vflash_image = malloc(sizeof(image_t));
1903 image_open(gdb_connection->vflash_image, "", "build");
1906 /* create new section with content from packet buffer */
1907 if ((retval = image_add_section(gdb_connection->vflash_image, addr, length, 0x0, (uint8_t*)parse)) != ERROR_OK)
1909 return retval;
1912 gdb_put_packet(connection, "OK", 2);
1914 return ERROR_OK;
1917 if (!strcmp(packet, "vFlashDone"))
1919 uint32_t written;
1921 /* process the flashing buffer. No need to erase as GDB
1922 * always issues a vFlashErase first. */
1923 target_call_event_callbacks(gdb_service->target, TARGET_EVENT_GDB_FLASH_WRITE_START);
1924 result = flash_write(gdb_service->target, gdb_connection->vflash_image, &written, 0);
1925 target_call_event_callbacks(gdb_service->target, TARGET_EVENT_GDB_FLASH_WRITE_END);
1926 if (result != ERROR_OK)
1928 if (result == ERROR_FLASH_DST_OUT_OF_BANK)
1929 gdb_put_packet(connection, "E.memtype", 9);
1930 else
1931 gdb_send_error(connection, EIO);
1933 else
1935 LOG_DEBUG("wrote %u bytes from vFlash image to flash", (unsigned)written);
1936 gdb_put_packet(connection, "OK", 2);
1939 image_close(gdb_connection->vflash_image);
1940 free(gdb_connection->vflash_image);
1941 gdb_connection->vflash_image = NULL;
1943 return ERROR_OK;
1946 gdb_put_packet(connection, "", 0);
1947 return ERROR_OK;
1950 int gdb_detach(connection_t *connection, target_t *target)
1952 gdb_service_t *gdb_service = connection->service->priv;
1954 target_call_event_callbacks(gdb_service->target, TARGET_EVENT_GDB_DETACH);
1956 return gdb_put_packet(connection, "OK", 2);
1959 static void gdb_log_callback(void *priv, const char *file, int line,
1960 const char *function, const char *string)
1962 connection_t *connection = priv;
1963 gdb_connection_t *gdb_con = connection->priv;
1965 if (gdb_con->busy)
1967 /* do not reply this using the O packet */
1968 return;
1971 gdb_output_con(connection, string);
1974 /* Do not allocate this on the stack */
1975 char gdb_packet_buffer[GDB_BUFFER_SIZE];
1977 static void gdb_sig_halted(connection_t *connection)
1979 char sig_reply[4];
1980 snprintf(sig_reply, 4, "T%2.2x", 2);
1981 gdb_put_packet(connection, sig_reply, 3);
1985 int gdb_input_inner(connection_t *connection)
1987 gdb_service_t *gdb_service = connection->service->priv;
1988 target_t *target = gdb_service->target;
1989 char *packet = gdb_packet_buffer;
1990 int packet_size;
1991 int retval;
1992 gdb_connection_t *gdb_con = connection->priv;
1993 static int extended_protocol = 0;
1995 /* drain input buffer */
1998 packet_size = GDB_BUFFER_SIZE-1;
1999 if ((retval = gdb_get_packet(connection, packet, &packet_size)) != ERROR_OK)
2001 return retval;
2004 /* terminate with zero */
2005 packet[packet_size] = 0;
2007 if (LOG_LEVEL_IS(LOG_LVL_DEBUG)) {
2008 if (packet[0] == 'X') {
2009 // binary packets spew junk into the debug log stream
2010 char buf[ 50 ];
2011 int x;
2012 for (x = 0 ; (x < 49) && (packet[x] != ':') ; x++) {
2013 buf[x] = packet[x];
2015 buf[x] = 0;
2016 LOG_DEBUG("received packet: '%s:<binary-data>'", buf);
2017 } else {
2018 LOG_DEBUG("received packet: '%s'", packet);
2022 if (packet_size > 0)
2024 retval = ERROR_OK;
2025 switch (packet[0])
2027 case 'H':
2028 /* Hct... -- set thread
2029 * we don't have threads, send empty reply */
2030 gdb_put_packet(connection, NULL, 0);
2031 break;
2032 case 'q':
2033 case 'Q':
2034 retval = gdb_query_packet(connection, target, packet, packet_size);
2035 break;
2036 case 'g':
2037 retval = gdb_get_registers_packet(connection, target, packet, packet_size);
2038 break;
2039 case 'G':
2040 retval = gdb_set_registers_packet(connection, target, packet, packet_size);
2041 break;
2042 case 'p':
2043 retval = gdb_get_register_packet(connection, target, packet, packet_size);
2044 break;
2045 case 'P':
2046 retval = gdb_set_register_packet(connection, target, packet, packet_size);
2047 break;
2048 case 'm':
2049 retval = gdb_read_memory_packet(connection, target, packet, packet_size);
2050 break;
2051 case 'M':
2052 retval = gdb_write_memory_packet(connection, target, packet, packet_size);
2053 break;
2054 case 'z':
2055 case 'Z':
2056 retval = gdb_breakpoint_watchpoint_packet(connection, target, packet, packet_size);
2057 break;
2058 case '?':
2059 gdb_last_signal_packet(connection, target, packet, packet_size);
2060 break;
2061 case 'c':
2062 case 's':
2064 int retval = ERROR_OK;
2066 gdb_connection_t *gdb_con = connection->priv;
2067 log_add_callback(gdb_log_callback, connection);
2069 bool nostep = false;
2070 if (target->state == TARGET_RUNNING)
2072 LOG_WARNING("The target is already running. Halt target before stepi/continue.");
2073 retval = target_halt(target);
2074 if (retval == ERROR_OK)
2075 retval = target_wait_state(target, TARGET_HALTED, 100);
2076 } else if (target->state != TARGET_HALTED)
2078 LOG_WARNING("The target is not in the halted nor running stated, stepi/continue ignored.");
2079 nostep = true;
2080 } else if ((packet[0] == 's') && gdb_con->sync)
2082 /* Hmm..... when you issue a continue in GDB, then a "stepi" is
2083 * sent by GDB first to OpenOCD, thus defeating the check to
2084 * make only the single stepping have the sync feature...
2086 nostep = true;
2087 LOG_WARNING("stepi ignored. GDB will now fetch the register state from the target.");
2089 gdb_con->sync = false;
2091 if ((retval!=ERROR_OK) || nostep)
2093 /* Either the target isn't in the halted state, then we can't
2094 * step/continue. This might be early setup, etc.
2096 * Or we want to allow GDB to pick up a fresh set of
2097 * register values without modifying the target state.
2100 gdb_sig_halted(connection);
2102 /* stop forwarding log packets! */
2103 log_remove_callback(gdb_log_callback, connection);
2104 } else
2106 /* We're running/stepping, in which case we can
2107 * forward log output until the target is halted
2109 gdb_con->frontend_state = TARGET_RUNNING;
2110 target_call_event_callbacks(target, TARGET_EVENT_GDB_START);
2111 int retval = gdb_step_continue_packet(connection, target, packet, packet_size);
2112 if (retval != ERROR_OK)
2114 /* we'll never receive a halted condition... issue a false one.. */
2115 gdb_frontend_halted(target, connection);
2119 break;
2120 case 'v':
2121 retval = gdb_v_packet(connection, target, packet, packet_size);
2122 break;
2123 case 'D':
2124 retval = gdb_detach(connection, target);
2125 extended_protocol = 0;
2126 break;
2127 case 'X':
2128 if ((retval = gdb_write_memory_binary_packet(connection, target, packet, packet_size)) != ERROR_OK)
2129 return retval;
2130 break;
2131 case 'k':
2132 if (extended_protocol != 0)
2133 break;
2134 gdb_put_packet(connection, "OK", 2);
2135 return ERROR_SERVER_REMOTE_CLOSED;
2136 case '!':
2137 /* handle extended remote protocol */
2138 extended_protocol = 1;
2139 gdb_put_packet(connection, "OK", 2);
2140 break;
2141 case 'R':
2142 /* handle extended restart packet */
2143 breakpoint_clear_target(gdb_service->target);
2144 watchpoint_clear_target(gdb_service->target);
2145 command_run_linef(connection->cmd_ctx,
2146 "ocd_gdb_restart %s",
2147 target->cmd_name);
2148 break;
2149 default:
2150 /* ignore unkown packets */
2151 LOG_DEBUG("ignoring 0x%2.2x packet", packet[0]);
2152 gdb_put_packet(connection, NULL, 0);
2153 break;
2156 /* if a packet handler returned an error, exit input loop */
2157 if (retval != ERROR_OK)
2158 return retval;
2161 if (gdb_con->ctrl_c)
2163 if (target->state == TARGET_RUNNING)
2165 retval = target_halt(target);
2166 if (retval != ERROR_OK)
2168 target_call_event_callbacks(target, TARGET_EVENT_GDB_HALT);
2170 gdb_con->ctrl_c = 0;
2171 } else
2173 LOG_INFO("The target is not running when halt was requested, stopping GDB.");
2174 target_call_event_callbacks(target, TARGET_EVENT_GDB_HALT);
2178 } while (gdb_con->buf_cnt > 0);
2180 return ERROR_OK;
2183 int gdb_input(connection_t *connection)
2185 int retval = gdb_input_inner(connection);
2186 gdb_connection_t *gdb_con = connection->priv;
2187 if (retval == ERROR_SERVER_REMOTE_CLOSED)
2188 return retval;
2190 /* logging does not propagate the error, yet can set the gdb_con->closed flag */
2191 if (gdb_con->closed)
2192 return ERROR_SERVER_REMOTE_CLOSED;
2194 /* we'll recover from any other errors(e.g. temporary timeouts, etc.) */
2195 return ERROR_OK;
2198 int gdb_init(void)
2200 gdb_service_t *gdb_service;
2201 target_t *target = all_targets;
2203 if (!target)
2205 LOG_WARNING("no gdb ports allocated as no target has been specified");
2206 return ERROR_OK;
2209 if (gdb_port == 0 && server_use_pipes == 0)
2211 LOG_INFO("gdb port disabled");
2212 return ERROR_OK;
2215 if (server_use_pipes)
2217 /* only a single gdb connection when using a pipe */
2219 gdb_service = malloc(sizeof(gdb_service_t));
2220 gdb_service->target = target;
2222 add_service("gdb", CONNECTION_PIPE, 0, 1, gdb_new_connection, gdb_input, gdb_connection_closed, gdb_service);
2224 LOG_DEBUG("gdb service for target %s using pipes",
2225 target_get_name(target));
2227 else
2229 unsigned short port = gdb_port;
2231 while (target)
2233 gdb_service = malloc(sizeof(gdb_service_t));
2234 gdb_service->target = target;
2236 add_service("gdb", CONNECTION_TCP,
2237 port, 1,
2238 gdb_new_connection, gdb_input,
2239 gdb_connection_closed, gdb_service);
2241 LOG_DEBUG("gdb service for target %s at TCP port %i",
2242 target_get_name(target),
2243 port);
2244 target = target->next;
2245 port++;
2249 return ERROR_OK;
2252 int handle_gdb_sync_command(struct command_context_s *cmd_ctx, char *cmd, char **args, int argc)
2254 if (argc != 0)
2256 return ERROR_COMMAND_SYNTAX_ERROR;
2259 if (current_gdb_connection == NULL)
2261 command_print(cmd_ctx,
2262 "gdb_sync command can only be run from within gdb using \"monitor gdb_sync\"");
2263 return ERROR_FAIL;
2266 current_gdb_connection->sync = true;
2268 return ERROR_OK;
2271 /* daemon configuration command gdb_port */
2272 int handle_gdb_port_command(struct command_context_s *cmd_ctx, char *cmd, char **args, int argc)
2274 if (argc == 0)
2276 command_print(cmd_ctx, "%d", gdb_port);
2277 return ERROR_OK;
2280 gdb_port = strtoul(args[0], NULL, 0);
2282 return ERROR_OK;
2285 int handle_gdb_memory_map_command(struct command_context_s *cmd_ctx, char *cmd, char **args, int argc)
2287 if (argc == 1)
2289 if (strcmp(args[0], "enable") == 0)
2291 gdb_use_memory_map = 1;
2292 return ERROR_OK;
2294 else if (strcmp(args[0], "disable") == 0)
2296 gdb_use_memory_map = 0;
2297 return ERROR_OK;
2299 else
2300 LOG_WARNING("invalid gdb_memory_map configuration directive %s", args[0]);
2303 return ERROR_COMMAND_SYNTAX_ERROR;
2306 int handle_gdb_flash_program_command(struct command_context_s *cmd_ctx, char *cmd, char **args, int argc)
2308 if (argc == 1)
2310 if (strcmp(args[0], "enable") == 0)
2312 gdb_flash_program = 1;
2313 return ERROR_OK;
2315 else if (strcmp(args[0], "disable") == 0)
2317 gdb_flash_program = 0;
2318 return ERROR_OK;
2320 else
2321 LOG_WARNING("invalid gdb_flash_program configuration directive: %s", args[0]);
2324 return ERROR_COMMAND_SYNTAX_ERROR;
2327 int handle_gdb_report_data_abort_command(struct command_context_s *cmd_ctx, char *cmd, char **args, int argc)
2329 if (argc == 1)
2331 if (strcmp(args[0], "enable") == 0)
2333 gdb_report_data_abort = 1;
2334 return ERROR_OK;
2336 else if (strcmp(args[0], "disable") == 0)
2338 gdb_report_data_abort = 0;
2339 return ERROR_OK;
2341 else
2342 LOG_WARNING("invalid gdb_report_data_abort configuration directive: %s", args[0]);
2345 return ERROR_COMMAND_SYNTAX_ERROR;
2348 /* gdb_breakpoint_override */
2349 int handle_gdb_breakpoint_override_command(struct command_context_s *cmd_ctx, char *cmd, char **args, int argc)
2351 if (argc == 0)
2354 } else if (argc == 1)
2356 gdb_breakpoint_override = 1;
2357 if (strcmp(args[0], "hard") == 0)
2359 gdb_breakpoint_override_type = BKPT_HARD;
2360 } else if (strcmp(args[0], "soft") == 0)
2362 gdb_breakpoint_override_type = BKPT_SOFT;
2363 } else if (strcmp(args[0], "disable") == 0)
2365 gdb_breakpoint_override = 0;
2367 } else
2369 return ERROR_COMMAND_SYNTAX_ERROR;
2371 if (gdb_breakpoint_override)
2373 LOG_USER("force %s breakpoints", (gdb_breakpoint_override_type == BKPT_HARD)?"hard":"soft");
2374 } else
2376 LOG_USER("breakpoint type is not overriden");
2379 return ERROR_OK;
2382 int gdb_register_commands(command_context_t *command_context)
2384 register_command(command_context, NULL, "gdb_sync", handle_gdb_sync_command,
2385 COMMAND_ANY, "next stepi will return immediately allowing GDB fetch register state without affecting target state");
2386 register_command(command_context, NULL, "gdb_port", handle_gdb_port_command,
2387 COMMAND_ANY, "daemon configuration command gdb_port");
2388 register_command(command_context, NULL, "gdb_memory_map", handle_gdb_memory_map_command,
2389 COMMAND_CONFIG, "enable or disable memory map");
2390 register_command(command_context, NULL, "gdb_flash_program", handle_gdb_flash_program_command,
2391 COMMAND_CONFIG, "enable or disable flash program");
2392 register_command(command_context, NULL, "gdb_report_data_abort", handle_gdb_report_data_abort_command,
2393 COMMAND_CONFIG, "enable or disable reporting data aborts");
2394 register_command(command_context, NULL, "gdb_breakpoint_override", handle_gdb_breakpoint_override_command,
2395 COMMAND_EXEC, "hard/soft/disable - force breakpoint type for gdb 'break' commands.");
2396 return ERROR_OK;