gdbserver: fix typo that broke read/write watchpoint
[fw/openocd] / src / server / gdb_server.c
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
29
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>
38
39
40 /**
41  * @file
42  * GDB server implementation.
43  *
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.
47  */
48
49 /* private connection data for GDB */
50 struct gdb_connection
51 {
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. */
64
65 };
66
67
68 #if 0
69 #define _DEBUG_GDB_IO_
70 #endif
71
72 static struct gdb_connection *current_gdb_connection;
73
74 static int gdb_breakpoint_override;
75 static enum breakpoint_type gdb_breakpoint_override_type;
76
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";
81
82 static void gdb_log_callback(void *priv, const char *file, unsigned line,
83                 const char *function, const char *string);
84
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;
88
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;
95
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;
99
100 int gdb_last_signal(struct target *target)
101 {
102         switch (target->debug_reason)
103         {
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;
117         }
118 }
119
120 int check_pending(struct connection *connection, int timeout_s, int *got_data)
121 {
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
124          */
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;
132
133         if (gdb_con->buf_cnt > 0)
134         {
135                 *got_data = 1;
136                 return ERROR_OK;
137         }
138
139         FD_ZERO(&read_fds);
140         FD_SET(connection->fd, &read_fds);
141
142         tv.tv_sec = timeout_s;
143         tv.tv_usec = 0;
144         if (socket_select(connection->fd + 1, &read_fds, NULL, NULL, &tv) == 0)
145         {
146                 /* This can typically be because a "monitor" command took too long
147                  * before printing any progress messages
148                  */
149                 if (timeout_s > 0)
150                 {
151                         return ERROR_GDB_TIMEOUT;
152                 } else
153                 {
154                         return ERROR_OK;
155                 }
156         }
157         *got_data = FD_ISSET(connection->fd, &read_fds) != 0;
158         return ERROR_OK;
159 }
160
161 static int gdb_get_char_inner(struct connection *connection, int* next_char)
162 {
163         struct gdb_connection *gdb_con = connection->priv;
164         int retval = ERROR_OK;
165
166         for (;;)
167         {
168                 if (connection->service->type == CONNECTION_PIPE)
169                 {
170                         gdb_con->buf_cnt = read(connection->fd, gdb_con->buffer, GDB_BUFFER_SIZE);
171                 }
172                 else
173                 {
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);
178                 }
179
180                 if (gdb_con->buf_cnt > 0)
181                 {
182                         break;
183                 }
184                 if (gdb_con->buf_cnt == 0)
185                 {
186                         gdb_con->closed = 1;
187                         return ERROR_SERVER_REMOTE_CLOSED;
188                 }
189
190 #ifdef _WIN32
191                 errno = WSAGetLastError();
192
193                 switch (errno)
194                 {
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);
207                 }
208 #else
209                 switch (errno)
210                 {
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;
224                 }
225 #endif
226         }
227
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
235
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
246
247         return retval;
248 }
249
250 /**
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.
253  *
254  * For small caches and embedded systems this is important!
255  */
256 static inline int gdb_get_char_fast(struct connection *connection, int* next_char, char **buf_p, int *buf_cnt)
257 {
258         int retval = ERROR_OK;
259
260         if ((*buf_cnt)-- > 0)
261         {
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;
268
269 #ifdef _DEBUG_GDB_IO_
270                 LOG_DEBUG("returned char '%c' (0x%2.2x)", *next_char, *next_char);
271 #endif
272
273                 return ERROR_OK;
274         }
275
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;
282
283         return retval;
284 }
285
286
287 int gdb_get_char(struct connection *connection, int* next_char)
288 {
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);
291 }
292
293
294 int gdb_putback_char(struct connection *connection, int last_char)
295 {
296         struct gdb_connection *gdb_con = connection->priv;
297
298         if (gdb_con->buf_p > gdb_con->buffer)
299         {
300                 *(--gdb_con->buf_p) = last_char;
301                 gdb_con->buf_cnt++;
302         }
303         else
304         {
305                 LOG_ERROR("BUG: couldn't put character back");
306         }
307
308         return ERROR_OK;
309 }
310
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)
315 {
316         struct gdb_connection *gdb_con = connection->priv;
317         if (gdb_con->closed)
318                 return ERROR_SERVER_REMOTE_CLOSED;
319
320         if (connection->service->type == CONNECTION_PIPE)
321         {
322                 /* write to stdout */
323                 if (write(STDOUT_FILENO, data, len) == len)
324                 {
325                         return ERROR_OK;
326                 }
327         }
328         else
329         {
330                 if (write_socket(connection->fd, data, len) == len)
331                 {
332                         return ERROR_OK;
333                 }
334         }
335         gdb_con->closed = 1;
336         return ERROR_SERVER_REMOTE_CLOSED;
337 }
338
339 int gdb_put_packet_inner(struct connection *connection, char *buffer, int len)
340 {
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;
349
350         for (i = 0; i < len; i++)
351                 my_checksum += buffer[i];
352
353 #ifdef _DEBUG_GDB_IO_
354         /*
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.
358          */
359         int gotdata;
360         for (;;)
361         {
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;
373                 }
374
375                 LOG_WARNING("Discard unexpected char %c", reply);
376         }
377 #endif
378
379         while (1)
380         {
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
388
389                 char local_buffer[1024];
390                 local_buffer[0] = '$';
391                 if ((size_t)len + 4 <= sizeof(local_buffer))
392                 {
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)
399                         {
400                                 return retval;
401                         }
402                 }
403                 else
404                 {
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)
411                         {
412                                 return retval;
413                         }
414                         if ((retval = gdb_write(connection, buffer, len)) != ERROR_OK)
415                         {
416                                 return retval;
417                         }
418                         if ((retval = gdb_write(connection, local_buffer + 1, 3)) != ERROR_OK)
419                         {
420                                 return retval;
421                         }
422                 }
423
424                 if (gdb_con->noack_mode)
425                         break;
426
427                 if ((retval = gdb_get_char(connection, &reply)) != ERROR_OK)
428                         return retval;
429
430                 if (reply == '+')
431                         break;
432                 else if (reply == '-')
433                 {
434                         /* Stop sending output packets for now */
435                         log_remove_callback(gdb_log_callback, connection);
436                         LOG_WARNING("negative reply, retrying");
437                 }
438                 else if (reply == 0x3)
439                 {
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 == '-')
446                         {
447                                 /* Stop sending output packets for now */
448                                 log_remove_callback(gdb_log_callback, connection);
449                                 LOG_WARNING("negative reply, retrying");
450                         }
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 {
456
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;
460                         }
461                 }
462                 else if (reply == '$') {
463                         LOG_ERROR("GDB missing ack(2) - assumed good");
464                         gdb_putback_char(connection, reply);
465                         return ERROR_OK;
466                 }
467                 else
468                 {
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;
472                 }
473         }
474         if (gdb_con->closed)
475                 return ERROR_SERVER_REMOTE_CLOSED;
476
477         return ERROR_OK;
478 }
479
480 int gdb_put_packet(struct connection *connection, char *buffer, int len)
481 {
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;
486
487         /* we sent some data, reset timer for keep alive messages */
488         kept_alive();
489
490         return retval;
491 }
492
493 static __inline__ int fetch_packet(struct connection *connection, int *checksum_ok, int noack, int *len, char *buffer)
494 {
495         unsigned char my_checksum = 0;
496         char checksum[3];
497         int character;
498         int retval = ERROR_OK;
499
500         struct gdb_connection *gdb_con = connection->priv;
501         my_checksum = 0;
502         int count = 0;
503         count = 0;
504
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;
509
510         for (;;)
511         {
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.
515                  */
516                 if ((buf_cnt > 2) && ((buf_cnt + count) < *len))
517                 {
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
521                          */
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)
528                         {
529                                 character = *buf++;
530                                 i++;
531                                 if (character == '#')
532                                 {
533                                         /* Danger! character can be '#' when esc is
534                                          * used so we need an explicit boolean for done here.
535                                          */
536                                         done = 1;
537                                         break;
538                                 }
539
540                                 if (character == '}')
541                                 {
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;
549                                 }
550                                 else
551                                 {
552                                         my_checksum += character & 0xff;
553                                         buffer[count++] = character & 0xff;
554                                 }
555                         }
556                         buf_p += i;
557                         buf_cnt -= i;
558                         if (done)
559                                 break;
560                 }
561                 if (count > *len)
562                 {
563                         LOG_ERROR("packet buffer too small");
564                         retval = ERROR_GDB_BUFFER_TOO_SMALL;
565                         break;
566                 }
567
568                 retval = gdb_get_char_fast(connection, &character, &buf_p, &buf_cnt);
569                 if (retval != ERROR_OK)
570                         break;
571
572                 if (character == '#')
573                         break;
574
575                 if (character == '}')
576                 {
577                         /* data transmitted in binary mode (X packet)
578                          * uses 0x7d as escape character */
579                         my_checksum += character & 0xff;
580
581                         retval = gdb_get_char_fast(connection, &character, &buf_p, &buf_cnt);
582                         if (retval != ERROR_OK)
583                                 break;
584
585                         my_checksum += character & 0xff;
586                         buffer[count++] = (character ^ 0x20) & 0xff;
587                 }
588                 else
589                 {
590                         my_checksum += character & 0xff;
591                         buffer[count++] = character & 0xff;
592                 }
593         }
594
595         gdb_con->buf_p = buf_p;
596         gdb_con->buf_cnt = buf_cnt;
597
598         if (retval != ERROR_OK)
599                 return retval;
600
601         *len = count;
602
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;
610
611         if (!noack)
612         {
613                 *checksum_ok = (my_checksum == strtoul(checksum, NULL, 16));
614         }
615
616         return ERROR_OK;
617 }
618
619 int gdb_get_packet_inner(struct connection *connection, char *buffer, int *len)
620 {
621         int character;
622         int retval;
623         struct gdb_connection *gdb_con = connection->priv;
624
625         while (1)
626         {
627                 do
628                 {
629                         if ((retval = gdb_get_char(connection, &character)) != ERROR_OK)
630                                 return retval;
631
632 #ifdef _DEBUG_GDB_IO_
633                         LOG_DEBUG("character: '%c'", character);
634 #endif
635
636                         switch (character)
637                         {
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;
655                         }
656                 } while (character != '$');
657
658
659
660                 int checksum_ok = 0;
661                 /* explicit code expansion here to get faster inlined code in -O3 by not
662                  * calculating checksum
663                  */
664                 if (gdb_con->noack_mode)
665                 {
666                         if ((retval = fetch_packet(connection, &checksum_ok, 1, len, buffer)) != ERROR_OK)
667                                 return retval;
668                 } else
669                 {
670                         if ((retval = fetch_packet(connection, &checksum_ok, 0, len, buffer)) != ERROR_OK)
671                                 return retval;
672                 }
673
674                 if (gdb_con->noack_mode)
675                 {
676                         /* checksum is not checked in noack mode */
677                         break;
678                 }
679                 if (checksum_ok)
680                 {
681                         if ((retval = gdb_write(connection, "+", 1)) != ERROR_OK)
682                         {
683                                 return retval;
684                         }
685                         break;
686                 }
687         }
688         if (gdb_con->closed)
689                 return ERROR_SERVER_REMOTE_CLOSED;
690
691         return ERROR_OK;
692 }
693
694 int gdb_get_packet(struct connection *connection, char *buffer, int *len)
695 {
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;
701 }
702
703 int gdb_output_con(struct connection *connection, const char* line)
704 {
705         char *hex_buffer;
706         int i, bin_size;
707
708         bin_size = strlen(line);
709
710         hex_buffer = malloc(bin_size*2 + 2);
711         if (hex_buffer == NULL)
712                 return ERROR_GDB_BUFFER_TOO_SMALL;
713
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;
718
719         int retval = gdb_put_packet(connection, hex_buffer, bin_size*2 + 1);
720
721         free(hex_buffer);
722         return retval;
723 }
724
725 int gdb_output(struct command_context *context, const char* line)
726 {
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;
730 }
731
732
733 static void gdb_frontend_halted(struct target *target, struct connection *connection)
734 {
735         struct gdb_connection *gdb_connection = connection->priv;
736
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.
741          *
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.
745          */
746         if (gdb_connection->frontend_state == TARGET_RUNNING)
747         {
748                 char sig_reply[4];
749                 int signal;
750
751                 /* stop forwarding log packets! */
752                 log_remove_callback(gdb_log_callback, connection);
753
754                 if (gdb_connection->ctrl_c)
755                 {
756                         signal = 0x2;
757                         gdb_connection->ctrl_c = 0;
758                 }
759                 else
760                 {
761                         signal = gdb_last_signal(target);
762                 }
763
764                 snprintf(sig_reply, 4, "T%2.2x", signal);
765                 gdb_put_packet(connection, sig_reply, 3);
766                 gdb_connection->frontend_state = TARGET_HALTED;
767         }
768 }
769
770 int gdb_target_callback_event_handler(struct target *target, enum target_event event, void *priv)
771 {
772         int retval;
773         struct connection *connection = priv;
774
775         target_handle_event(target, event);
776         switch (event)
777         {
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)
787                         {
788                                 return retval;
789                         }
790                         break;
791                 default:
792                         break;
793         }
794
795         return ERROR_OK;
796 }
797
798 int gdb_new_connection(struct connection *connection)
799 {
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;
804
805         connection->priv = gdb_connection;
806
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;
817
818         /* send ACK to GDB for debug request */
819         gdb_write(connection, "+", 1);
820
821         /* output goes through gdb connection */
822         command_set_output_handler(connection->cmd_ctx, gdb_output, connection);
823
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.
827          */
828         breakpoint_clear_target(gdb_service->target);
829         watchpoint_clear_target(gdb_service->target);
830
831         /* register callback to be informed about target events */
832         target_register_event_callback(gdb_target_callback_event_handler, connection);
833
834         /* remove the initial ACK from the incoming buffer */
835         if ((retval = gdb_get_char(connection, &initial_ack)) != ERROR_OK)
836                 return retval;
837
838         /* FIX!!!??? would we actually ever receive a + here???
839          * Not observed.
840          */
841         if (initial_ack != '+')
842                 gdb_putback_char(connection, initial_ack);
843         target_call_event_callbacks(gdb_service->target, TARGET_EVENT_GDB_ATTACH);
844
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));
850
851         return ERROR_OK;
852 }
853
854 int gdb_connection_closed(struct connection *connection)
855 {
856         struct gdb_service *gdb_service = connection->service->priv;
857         struct gdb_connection *gdb_connection = connection->priv;
858
859         /* we're done forwarding messages. Tear down callback before
860          * cleaning up connection.
861          */
862         log_remove_callback(gdb_log_callback, connection);
863
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);
869
870         /* see if an image built with vFlash commands is left */
871         if (gdb_connection->vflash_image)
872         {
873                 image_close(gdb_connection->vflash_image);
874                 free(gdb_connection->vflash_image);
875                 gdb_connection->vflash_image = NULL;
876         }
877
878         /* if this connection registered a debug-message receiver delete it */
879         delete_debug_msg_receiver(connection->cmd_ctx, gdb_service->target);
880
881         if (connection->priv)
882         {
883                 free(connection->priv);
884                 connection->priv = NULL;
885         }
886         else
887         {
888                 LOG_ERROR("BUG: connection->priv == NULL");
889         }
890
891
892         target_unregister_event_callback(gdb_target_callback_event_handler, connection);
893
894         target_call_event_callbacks(gdb_service->target, TARGET_EVENT_GDB_END);
895
896         target_call_event_callbacks(gdb_service->target, TARGET_EVENT_GDB_DETACH);
897
898         return ERROR_OK;
899 }
900
901 void gdb_send_error(struct connection *connection, uint8_t the_error)
902 {
903         char err[4];
904         snprintf(err, 4, "E%2.2X", the_error);
905         gdb_put_packet(connection, err, 3);
906 }
907
908 int gdb_last_signal_packet(struct connection *connection, struct target *target, char* packet, int packet_size)
909 {
910         char sig_reply[4];
911         int signal;
912
913         signal = gdb_last_signal(target);
914
915         snprintf(sig_reply, 4, "S%2.2x", signal);
916         gdb_put_packet(connection, sig_reply, 3);
917
918         return ERROR_OK;
919 }
920
921 static int gdb_reg_pos(struct target *target, int pos, int len)
922 {
923         if (target->endianness == TARGET_LITTLE_ENDIAN)
924                 return pos;
925         else
926                 return len - 1 - pos;
927 }
928
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.
932  *
933  * NB! the format on the wire is the target endianness
934  *
935  * The format of reg->value is little endian
936  *
937  */
938 void gdb_str_to_target(struct target *target, char *tstr, struct reg *reg)
939 {
940         int i;
941
942         uint8_t *buf;
943         int buf_len;
944         buf = reg->value;
945         buf_len = DIV_ROUND_UP(reg->size, 8);
946
947         for (i = 0; i < buf_len; i++)
948         {
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];
952         }
953 }
954
955 static int hextoint(int c)
956 {
957         if (c>='0'&&c<='9')
958         {
959                 return c-'0';
960         }
961         c = toupper(c);
962         if (c>='A'&&c<='F')
963         {
964                 return c-'A'+10;
965         }
966         LOG_ERROR("BUG: invalid register value %08x", c);
967         return 0;
968 }
969
970 /* copy over in register buffer */
971 void gdb_target_to_reg(struct target *target, char *tstr, int str_len, uint8_t *bin)
972 {
973         if (str_len % 2)
974         {
975                 LOG_ERROR("BUG: gdb value with uneven number of characters encountered");
976                 exit(-1);
977         }
978
979         int i;
980         for (i = 0; i < str_len; i += 2)
981         {
982                 uint8_t t = hextoint(tstr[i]) << 4;
983                 t |= hextoint(tstr[i + 1]);
984
985                 int j = gdb_reg_pos(target, i/2, str_len/2);
986                 bin[j] = t;
987         }
988 }
989
990 int gdb_get_registers_packet(struct connection *connection, struct target *target, char* packet, int packet_size)
991 {
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;
999
1000 #ifdef _DEBUG_GDB_IO_
1001         LOG_DEBUG("-");
1002 #endif
1003
1004         if ((retval = target_get_gdb_reg_list(target, &reg_list, &reg_list_size)) != ERROR_OK)
1005         {
1006                 return gdb_error(connection, retval);
1007         }
1008
1009         for (i = 0; i < reg_list_size; i++)
1010         {
1011                 reg_packet_size += reg_list[i]->size;
1012         }
1013
1014         reg_packet = malloc(DIV_ROUND_UP(reg_packet_size, 8) * 2);
1015         reg_packet_p = reg_packet;
1016
1017         for (i = 0; i < reg_list_size; i++)
1018         {
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;
1021         }
1022
1023 #ifdef _DEBUG_GDB_IO_
1024         {
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);
1029         }
1030 #endif
1031
1032         gdb_put_packet(connection, reg_packet, DIV_ROUND_UP(reg_packet_size, 8) * 2);
1033         free(reg_packet);
1034
1035         free(reg_list);
1036
1037         return ERROR_OK;
1038 }
1039
1040 int gdb_set_registers_packet(struct connection *connection, struct target *target, char *packet, int packet_size)
1041 {
1042         int i;
1043         struct reg **reg_list;
1044         int reg_list_size;
1045         int retval;
1046         char *packet_p;
1047
1048 #ifdef _DEBUG_GDB_IO_
1049         LOG_DEBUG("-");
1050 #endif
1051
1052         /* skip command character */
1053         packet++;
1054         packet_size--;
1055
1056         if (packet_size % 2)
1057         {
1058                 LOG_WARNING("GDB set_registers packet with uneven characters received, dropping connection");
1059                 return ERROR_SERVER_REMOTE_CLOSED;
1060         }
1061
1062         if ((retval = target_get_gdb_reg_list(target, &reg_list, &reg_list_size)) != ERROR_OK)
1063         {
1064                 return gdb_error(connection, retval);
1065         }
1066
1067         packet_p = packet;
1068         for (i = 0; i < reg_list_size; i++)
1069         {
1070                 uint8_t *bin_buf;
1071                 int chars = (DIV_ROUND_UP(reg_list[i]->size, 8) * 2);
1072
1073                 if (packet_p + chars > packet + packet_size)
1074                 {
1075                         LOG_ERROR("BUG: register packet is too small for registers");
1076                 }
1077
1078                 bin_buf = malloc(DIV_ROUND_UP(reg_list[i]->size, 8));
1079                 gdb_target_to_reg(target, packet_p, chars, bin_buf);
1080
1081                 reg_list[i]->type->set(reg_list[i], bin_buf);
1082
1083                 /* advance packet pointer */
1084                 packet_p += chars;
1085
1086
1087                 free(bin_buf);
1088         }
1089
1090         /* free struct reg *reg_list[] array allocated by get_gdb_reg_list */
1091         free(reg_list);
1092
1093         gdb_put_packet(connection, "OK", 2);
1094
1095         return ERROR_OK;
1096 }
1097
1098 int gdb_get_register_packet(struct connection *connection, struct target *target, char *packet, int packet_size)
1099 {
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;
1105
1106 #ifdef _DEBUG_GDB_IO_
1107         LOG_DEBUG("-");
1108 #endif
1109
1110         if ((retval = target_get_gdb_reg_list(target, &reg_list, &reg_list_size)) != ERROR_OK)
1111         {
1112                 return gdb_error(connection, retval);
1113         }
1114
1115         if (reg_list_size <= reg_num)
1116         {
1117                 LOG_ERROR("gdb requested a non-existing register");
1118                 exit(-1);
1119         }
1120
1121         reg_packet = malloc(DIV_ROUND_UP(reg_list[reg_num]->size, 8) * 2);
1122
1123         gdb_str_to_target(target, reg_packet, reg_list[reg_num]);
1124
1125         gdb_put_packet(connection, reg_packet, DIV_ROUND_UP(reg_list[reg_num]->size, 8) * 2);
1126
1127         free(reg_list);
1128         free(reg_packet);
1129
1130         return ERROR_OK;
1131 }
1132
1133 int gdb_set_register_packet(struct connection *connection, struct target *target, char *packet, int packet_size)
1134 {
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;
1141
1142         LOG_DEBUG("-");
1143
1144         if ((retval = target_get_gdb_reg_list(target, &reg_list, &reg_list_size)) != ERROR_OK)
1145         {
1146                 return gdb_error(connection, retval);
1147         }
1148
1149         if (reg_list_size < reg_num)
1150         {
1151                 LOG_ERROR("gdb requested a non-existing register");
1152                 return ERROR_SERVER_REMOTE_CLOSED;
1153         }
1154
1155         if (*separator != '=')
1156         {
1157                 LOG_ERROR("GDB 'set register packet', but no '=' following the register number");
1158                 return ERROR_SERVER_REMOTE_CLOSED;
1159         }
1160
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);
1164
1165         /* fix!!! add some sanity checks on packet size here */
1166
1167         gdb_target_to_reg(target, separator + 1, chars, bin_buf);
1168
1169         reg_list[reg_num]->type->set(reg_list[reg_num], bin_buf);
1170
1171         gdb_put_packet(connection, "OK", 2);
1172
1173         free(bin_buf);
1174         free(reg_list);
1175
1176         return ERROR_OK;
1177 }
1178
1179 int gdb_error(struct connection *connection, int retval)
1180 {
1181         switch (retval)
1182         {
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;
1200         }
1201
1202         return ERROR_OK;
1203 }
1204
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.
1207  *
1208  * 8191 bytes by the looks of it. Why 8191 bytes instead of 8192?????
1209  */
1210 int gdb_read_memory_packet(struct connection *connection, struct target *target, char *packet, int packet_size)
1211 {
1212         char *separator;
1213         uint32_t addr = 0;
1214         uint32_t len = 0;
1215
1216         uint8_t *buffer;
1217         char *hex_buffer;
1218
1219         int retval = ERROR_OK;
1220
1221         /* skip command character */
1222         packet++;
1223
1224         addr = strtoul(packet, &separator, 16);
1225
1226         if (*separator != ',')
1227         {
1228                 LOG_ERROR("incomplete read memory packet received, dropping connection");
1229                 return ERROR_SERVER_REMOTE_CLOSED;
1230         }
1231
1232         len = strtoul(separator + 1, NULL, 16);
1233
1234         buffer = malloc(len);
1235
1236         LOG_DEBUG("addr: 0x%8.8" PRIx32 ", len: 0x%8.8" PRIx32 "", addr, len);
1237
1238         retval = target_read_buffer(target, addr, len, buffer);
1239
1240         if ((retval != ERROR_OK)&&!gdb_report_data_abort)
1241         {
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.
1244                  *
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
1248                  *
1249                  * http://sourceware.org/cgi-bin/gnatsweb.pl?cmd = view%20audit-trail&database = gdb&pr = 2395
1250                  *
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.
1253                  */
1254                 memset(buffer, 0, len);
1255                 retval = ERROR_OK;
1256         }
1257
1258         if (retval == ERROR_OK)
1259         {
1260                 hex_buffer = malloc(len * 2 + 1);
1261
1262                 uint32_t i;
1263                 for (i = 0; i < len; i++)
1264                 {
1265                         uint8_t t = buffer[i];
1266                         hex_buffer[2 * i] = DIGITS[(t >> 4) & 0xf];
1267                         hex_buffer[2 * i + 1] = DIGITS[t & 0xf];
1268                 }
1269
1270                 gdb_put_packet(connection, hex_buffer, len * 2);
1271
1272                 free(hex_buffer);
1273         }
1274         else
1275         {
1276                 retval = gdb_error(connection, retval);
1277         }
1278
1279         free(buffer);
1280
1281         return retval;
1282 }
1283
1284 int gdb_write_memory_packet(struct connection *connection, struct target *target, char *packet, int packet_size)
1285 {
1286         char *separator;
1287         uint32_t addr = 0;
1288         uint32_t len = 0;
1289
1290         uint8_t *buffer;
1291
1292         uint32_t i;
1293         int retval;
1294
1295         /* skip command character */
1296         packet++;
1297
1298         addr = strtoul(packet, &separator, 16);
1299
1300         if (*separator != ',')
1301         {
1302                 LOG_ERROR("incomplete write memory packet received, dropping connection");
1303                 return ERROR_SERVER_REMOTE_CLOSED;
1304         }
1305
1306         len = strtoul(separator + 1, &separator, 16);
1307
1308         if (*(separator++) != ':')
1309         {
1310                 LOG_ERROR("incomplete write memory packet received, dropping connection");
1311                 return ERROR_SERVER_REMOTE_CLOSED;
1312         }
1313
1314         buffer = malloc(len);
1315
1316         LOG_DEBUG("addr: 0x%8.8" PRIx32 ", len: 0x%8.8" PRIx32 "", addr, len);
1317
1318         for (i = 0; i < len; i++)
1319         {
1320                 uint32_t tmp;
1321                 sscanf(separator + 2*i, "%2" SCNx32 , &tmp);
1322                 buffer[i] = tmp;
1323         }
1324
1325         retval = target_write_buffer(target, addr, len, buffer);
1326
1327         if (retval == ERROR_OK)
1328         {
1329                 gdb_put_packet(connection, "OK", 2);
1330         }
1331         else
1332         {
1333                 retval = gdb_error(connection, retval);
1334         }
1335
1336         free(buffer);
1337
1338         return retval;
1339 }
1340
1341 int gdb_write_memory_binary_packet(struct connection *connection, struct target *target, char *packet, int packet_size)
1342 {
1343         char *separator;
1344         uint32_t addr = 0;
1345         uint32_t len = 0;
1346
1347         int retval;
1348
1349         /* skip command character */
1350         packet++;
1351
1352         addr = strtoul(packet, &separator, 16);
1353
1354         if (*separator != ',')
1355         {
1356                 LOG_ERROR("incomplete write memory binary packet received, dropping connection");
1357                 return ERROR_SERVER_REMOTE_CLOSED;
1358         }
1359
1360         len = strtoul(separator + 1, &separator, 16);
1361
1362         if (*(separator++) != ':')
1363         {
1364                 LOG_ERROR("incomplete write memory binary packet received, dropping connection");
1365                 return ERROR_SERVER_REMOTE_CLOSED;
1366         }
1367
1368         retval = ERROR_OK;
1369         if (len)
1370         {
1371                 LOG_DEBUG("addr: 0x%8.8" PRIx32 ", len: 0x%8.8" PRIx32 "", addr, len);
1372
1373                 retval = target_write_buffer(target, addr, len, (uint8_t*)separator);
1374         }
1375
1376         if (retval == ERROR_OK)
1377         {
1378                 gdb_put_packet(connection, "OK", 2);
1379         }
1380         else
1381         {
1382                 if ((retval = gdb_error(connection, retval)) != ERROR_OK)
1383                         return retval;
1384         }
1385
1386         return ERROR_OK;
1387 }
1388
1389 int gdb_step_continue_packet(struct connection *connection, struct target *target, char *packet, int packet_size)
1390 {
1391         int current = 0;
1392         uint32_t address = 0x0;
1393         int retval = ERROR_OK;
1394
1395         LOG_DEBUG("-");
1396
1397         if (packet_size > 1)
1398         {
1399                 packet[packet_size] = 0;
1400                 address = strtoul(packet + 1, NULL, 16);
1401         }
1402         else
1403         {
1404                 current = 1;
1405         }
1406
1407         if (packet[0] == 'c')
1408         {
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 */
1412         }
1413         else if (packet[0] == 's')
1414         {
1415                 LOG_DEBUG("step");
1416                 /* step at current or address, don't handle breakpoints */
1417                 retval = target_step(target, current, address, 0);
1418         }
1419         return retval;
1420 }
1421
1422 int gdb_breakpoint_watchpoint_packet(struct connection *connection, struct target *target, char *packet, int packet_size)
1423 {
1424         int type;
1425         enum breakpoint_type bp_type = BKPT_SOFT /* dummy init to avoid warning */;
1426         enum watchpoint_rw wp_type = WPT_READ /* dummy init to avoid warning */;
1427         uint32_t address;
1428         uint32_t size;
1429         char *separator;
1430         int retval;
1431
1432         LOG_DEBUG("-");
1433
1434         type = strtoul(packet + 1, &separator, 16);
1435
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;
1446         else
1447         {
1448                 LOG_ERROR("invalid gdb watch/breakpoint type(%d), dropping connection", type);
1449                 return ERROR_SERVER_REMOTE_CLOSED;
1450         }
1451
1452
1453         if (gdb_breakpoint_override && ((bp_type == BKPT_SOFT)||(bp_type == BKPT_HARD)))
1454         {
1455                 bp_type = gdb_breakpoint_override_type;
1456         }
1457
1458         if (*separator != ',')
1459         {
1460                 LOG_ERROR("incomplete breakpoint/watchpoint packet received, dropping connection");
1461                 return ERROR_SERVER_REMOTE_CLOSED;
1462         }
1463
1464         address = strtoul(separator + 1, &separator, 16);
1465
1466         if (*separator != ',')
1467         {
1468                 LOG_ERROR("incomplete breakpoint/watchpoint packet received, dropping connection");
1469                 return ERROR_SERVER_REMOTE_CLOSED;
1470         }
1471
1472         size = strtoul(separator + 1, &separator, 16);
1473
1474         switch (type)
1475         {
1476                 case 0:
1477                 case 1:
1478                         if (packet[0] == 'Z')
1479                         {
1480                                 if ((retval = breakpoint_add(target, address, size, bp_type)) != ERROR_OK)
1481                                 {
1482                                         if ((retval = gdb_error(connection, retval)) != ERROR_OK)
1483                                                 return retval;
1484                                 }
1485                                 else
1486                                 {
1487                                         gdb_put_packet(connection, "OK", 2);
1488                                 }
1489                         }
1490                         else
1491                         {
1492                                 breakpoint_remove(target, address);
1493                                 gdb_put_packet(connection, "OK", 2);
1494                         }
1495                         break;
1496                 case 2:
1497                 case 3:
1498                 case 4:
1499                 {
1500                         if (packet[0] == 'Z')
1501                         {
1502                                 if ((retval = watchpoint_add(target, address, size, wp_type, 0, 0xffffffffu)) != ERROR_OK)
1503                                 {
1504                                         if ((retval = gdb_error(connection, retval)) != ERROR_OK)
1505                                                 return retval;
1506                                 }
1507                                 else
1508                                 {
1509                                         gdb_put_packet(connection, "OK", 2);
1510                                 }
1511                         }
1512                         else
1513                         {
1514                                 watchpoint_remove(target, address);
1515                                 gdb_put_packet(connection, "OK", 2);
1516                         }
1517                         break;
1518                 }
1519                 default:
1520                         break;
1521         }
1522
1523         return ERROR_OK;
1524 }
1525
1526 /* print out a string and allocate more space as needed, mainly used for XML at this point */
1527 void xml_printf(int *retval, char **xml, int *pos, int *size, const char *fmt, ...)
1528 {
1529         if (*retval != ERROR_OK)
1530         {
1531                 return;
1532         }
1533         int first = 1;
1534
1535         for (;;)
1536         {
1537                 if ((*xml == NULL) || (!first))
1538                 {
1539                         /* start by 0 to exercise all the code paths.
1540                          * Need minimum 2 bytes to fit 1 char and 0 terminator. */
1541
1542                         *size = *size * 2 + 2;
1543                         char *t = *xml;
1544                         *xml = realloc(*xml, *size);
1545                         if (*xml == NULL)
1546                         {
1547                                 if (t)
1548                                         free(t);
1549                                 *retval = ERROR_SERVER_REMOTE_CLOSED;
1550                                 return;
1551                         }
1552                 }
1553
1554                 va_list ap;
1555                 int ret;
1556                 va_start(ap, fmt);
1557                 ret = vsnprintf(*xml + *pos, *size - *pos, fmt, ap);
1558                 va_end(ap);
1559                 if ((ret > 0) && ((ret + 1) < *size - *pos))
1560                 {
1561                         *pos += ret;
1562                         return;
1563                 }
1564                 /* there was just enough or not enough space, allocate more. */
1565                 first = 0;
1566         }
1567 }
1568
1569 static int decode_xfer_read(char *buf, char **annex, int *ofs, unsigned int *len)
1570 {
1571         char *separator;
1572
1573         /* Extract and NUL-terminate the annex. */
1574         *annex = buf;
1575         while (*buf && *buf != ':')
1576                 buf++;
1577         if (*buf == '\0')
1578                 return -1;
1579         *buf++ = 0;
1580
1581         /* After the read marker and annex, qXfer looks like a
1582          * traditional 'm' packet. */
1583
1584         *ofs = strtoul(buf, &separator, 16);
1585
1586         if (*separator != ',')
1587                 return -1;
1588
1589         *len = strtoul(separator + 1, NULL, 16);
1590
1591         return 0;
1592 }
1593
1594 int gdb_calc_blocksize(struct flash_bank *bank)
1595 {
1596         uint32_t i;
1597         uint32_t block_size = 0xffffffff;
1598
1599         /* loop through all sectors and return smallest sector size */
1600
1601         for (i = 0; i < (uint32_t)bank->num_sectors; i++)
1602         {
1603                 if (bank->sectors[i].size < block_size)
1604                         block_size = bank->sectors[i].size;
1605         }
1606
1607         return block_size;
1608 }
1609
1610 static int compare_bank (const void * a, const void * b)
1611 {
1612         struct flash_bank *b1, *b2;
1613         b1=*((struct flash_bank **)a);
1614         b2=*((struct flash_bank **)b);
1615
1616         if (b1->base == b2->base)
1617         {
1618                 return 0;
1619         } else if (b1->base > b2->base)
1620         {
1621                 return 1;
1622         } else
1623         {
1624                 return -1;
1625         }
1626 }
1627
1628 int gdb_query_packet(struct connection *connection, struct target *target, char *packet, int packet_size)
1629 {
1630         struct command_context *cmd_ctx = connection->cmd_ctx;
1631         struct gdb_connection *gdb_connection = connection->priv;
1632
1633         if (strstr(packet, "qRcmd,"))
1634         {
1635                 if (packet_size > 6)
1636                 {
1637                         char *cmd;
1638                         int i;
1639                         cmd = malloc((packet_size - 6)/2 + 1);
1640                         for (i = 0; i < (packet_size - 6)/2; i++)
1641                         {
1642                                 uint32_t tmp;
1643                                 sscanf(packet + 6 + 2*i, "%2" SCNx32 , &tmp);
1644                                 cmd[i] = tmp;
1645                         }
1646                         cmd[(packet_size - 6)/2] = 0x0;
1647
1648                         /* We want to print all debug output to GDB connection */
1649                         log_add_callback(gdb_log_callback, connection);
1650                         target_call_timer_callbacks_now();
1651                         /* some commands need to know the GDB connection, make note of current
1652                          * GDB connection. */
1653                         current_gdb_connection = gdb_connection;
1654                         command_run_line(cmd_ctx, cmd);
1655                         current_gdb_connection = NULL;
1656                         target_call_timer_callbacks_now();
1657                         log_remove_callback(gdb_log_callback, connection);
1658                         free(cmd);
1659                 }
1660                 gdb_put_packet(connection, "OK", 2);
1661                 return ERROR_OK;
1662         }
1663         else if (strstr(packet, "qCRC:"))
1664         {
1665                 if (packet_size > 5)
1666                 {
1667                         int retval;
1668                         char gdb_reply[10];
1669                         char *separator;
1670                         uint32_t checksum;
1671                         uint32_t addr = 0;
1672                         uint32_t len = 0;
1673
1674                         /* skip command character */
1675                         packet += 5;
1676
1677                         addr = strtoul(packet, &separator, 16);
1678
1679                         if (*separator != ',')
1680                         {
1681                                 LOG_ERROR("incomplete read memory packet received, dropping connection");
1682                                 return ERROR_SERVER_REMOTE_CLOSED;
1683                         }
1684
1685                         len = strtoul(separator + 1, NULL, 16);
1686
1687                         retval = target_checksum_memory(target, addr, len, &checksum);
1688
1689                         if (retval == ERROR_OK)
1690                         {
1691                                 snprintf(gdb_reply, 10, "C%8.8" PRIx32 "", checksum);
1692                                 gdb_put_packet(connection, gdb_reply, 9);
1693                         }
1694                         else
1695                         {
1696                                 if ((retval = gdb_error(connection, retval)) != ERROR_OK)
1697                                         return retval;
1698                         }
1699
1700                         return ERROR_OK;
1701                 }
1702         }
1703         else if (strstr(packet, "qSupported"))
1704         {
1705                 /* we currently support packet size and qXfer:memory-map:read (if enabled)
1706                  * disable qXfer:features:read for the moment */
1707                 int retval = ERROR_OK;
1708                 char *buffer = NULL;
1709                 int pos = 0;
1710                 int size = 0;
1711
1712                 xml_printf(&retval, &buffer, &pos, &size,
1713                                 "PacketSize=%x;qXfer:memory-map:read%c;qXfer:features:read-;QStartNoAckMode+",
1714                                 (GDB_BUFFER_SIZE - 1), ((gdb_use_memory_map == 1) && (flash_get_bank_count() > 0)) ? '+' : '-');
1715
1716                 if (retval != ERROR_OK)
1717                 {
1718                         gdb_send_error(connection, 01);
1719                         return ERROR_OK;
1720                 }
1721
1722                 gdb_put_packet(connection, buffer, strlen(buffer));
1723                 free(buffer);
1724
1725                 return ERROR_OK;
1726         }
1727         else if (strstr(packet, "qXfer:memory-map:read::") && (flash_get_bank_count() > 0))
1728         {
1729                 /* We get away with only specifying flash here. Regions that are not
1730                  * specified are treated as if we provided no memory map(if not we
1731                  * could detect the holes and mark them as RAM).
1732                  * Normally we only execute this code once, but no big deal if we
1733                  * have to regenerate it a couple of times. */
1734
1735                 struct flash_bank *p;
1736                 char *xml = NULL;
1737                 int size = 0;
1738                 int pos = 0;
1739                 int retval = ERROR_OK;
1740
1741                 int offset;
1742                 int length;
1743                 char *separator;
1744                 int blocksize;
1745
1746                 /* skip command character */
1747                 packet += 23;
1748
1749                 offset = strtoul(packet, &separator, 16);
1750                 length = strtoul(separator + 1, &separator, 16);
1751
1752                 xml_printf(&retval, &xml, &pos, &size, "<memory-map>\n");
1753
1754                 /*
1755                 sort banks in ascending order, we need to make non-flash memory be ram(or rather
1756                 read/write) by default for GDB.
1757                 GDB does not have a concept of non-cacheable read/write memory.
1758                  */
1759                 struct flash_bank **banks = malloc(sizeof(struct flash_bank *)*flash_get_bank_count());
1760                 int i;
1761
1762                 for (i = 0; i < flash_get_bank_count(); i++)
1763                 {
1764                         p = get_flash_bank_by_num(i);
1765                         if (p == NULL)
1766                         {
1767                                 free(banks);
1768                                 retval = ERROR_FAIL;
1769                                 gdb_send_error(connection, retval);
1770                                 return retval;
1771                         }
1772                         banks[i]=p;
1773                 }
1774
1775                 qsort(banks, flash_get_bank_count(), sizeof(struct flash_bank *), compare_bank);
1776
1777                 uint32_t ram_start = 0;
1778                 for (i = 0; i < flash_get_bank_count(); i++)
1779                 {
1780                         p = banks[i];
1781
1782                         if (ram_start < p->base)
1783                         {
1784                                 xml_printf(&retval, &xml, &pos, &size, "<memory type=\"ram\" start=\"0x%x\" length=\"0x%x\"/>\n",
1785                                         ram_start, p->base-ram_start);
1786                         }
1787
1788                         /* if device has uneven sector sizes, eg. str7, lpc
1789                          * we pass the smallest sector size to gdb memory map */
1790                         blocksize = gdb_calc_blocksize(p);
1791
1792                         xml_printf(&retval, &xml, &pos, &size, "<memory type=\"flash\" start=\"0x%x\" length=\"0x%x\">\n" \
1793                                 "<property name=\"blocksize\">0x%x</property>\n" \
1794                                 "</memory>\n", \
1795                                 p->base, p->size, blocksize);
1796                         ram_start = p->base + p->size;
1797                 }
1798                 if (ram_start != 0)
1799                 {
1800                         xml_printf(&retval, &xml, &pos, &size, "<memory type=\"ram\" start=\"0x%x\" length=\"0x%x\"/>\n",
1801                                 ram_start, 0-ram_start);
1802                 } else
1803                 {
1804                         /* a flash chip could be at the very end of the 32 bit address space, in which case
1805                         ram_start will be precisely 0 */
1806                 }
1807
1808                 free(banks);
1809                 banks = NULL;
1810
1811                 xml_printf(&retval, &xml, &pos, &size, "</memory-map>\n");
1812
1813                 if (retval != ERROR_OK)
1814                 {
1815                         gdb_send_error(connection, retval);
1816                         return retval;
1817                 }
1818
1819                 if (offset + length > pos)
1820                 {
1821                         length = pos - offset;
1822                 }
1823
1824                 char *t = malloc(length + 1);
1825                 t[0] = 'l';
1826                 memcpy(t + 1, xml + offset, length);
1827                 gdb_put_packet(connection, t, length + 1);
1828
1829                 free(t);
1830                 free(xml);
1831                 return ERROR_OK;
1832         }
1833         else if (strstr(packet, "qXfer:features:read:"))
1834         {
1835                 char *xml = NULL;
1836                 int size = 0;
1837                 int pos = 0;
1838                 int retval = ERROR_OK;
1839
1840                 int offset;
1841                 unsigned int length;
1842                 char *annex;
1843
1844                 /* skip command character */
1845                 packet += 20;
1846
1847                 if (decode_xfer_read(packet, &annex, &offset, &length) < 0)
1848                 {
1849                         gdb_send_error(connection, 01);
1850                         return ERROR_OK;
1851                 }
1852
1853                 if (strcmp(annex, "target.xml") != 0)
1854                 {
1855                         gdb_send_error(connection, 01);
1856                         return ERROR_OK;
1857                 }
1858
1859                 xml_printf(&retval, &xml, &pos, &size, \
1860                         "l < target version=\"1.0\">\n < architecture > arm</architecture>\n</target>\n");
1861
1862                 if (retval != ERROR_OK)
1863                 {
1864                         gdb_send_error(connection, retval);
1865                         return retval;
1866                 }
1867
1868                 gdb_put_packet(connection, xml, strlen(xml));
1869
1870                 free(xml);
1871                 return ERROR_OK;
1872         }
1873         else if (strstr(packet, "QStartNoAckMode"))
1874         {
1875                 gdb_connection->noack_mode = 1;
1876                 gdb_put_packet(connection, "OK", 2);
1877                 return ERROR_OK;
1878         }
1879
1880         gdb_put_packet(connection, "", 0);
1881         return ERROR_OK;
1882 }
1883
1884 int gdb_v_packet(struct connection *connection, struct target *target, char *packet, int packet_size)
1885 {
1886         struct gdb_connection *gdb_connection = connection->priv;
1887         struct gdb_service *gdb_service = connection->service->priv;
1888         int result;
1889
1890         /* if flash programming disabled - send a empty reply */
1891
1892         if (gdb_flash_program == 0)
1893         {
1894                 gdb_put_packet(connection, "", 0);
1895                 return ERROR_OK;
1896         }
1897
1898         if (strstr(packet, "vFlashErase:"))
1899         {
1900                 unsigned long addr;
1901                 unsigned long length;
1902
1903                 char *parse = packet + 12;
1904                 if (*parse == '\0')
1905                 {
1906                         LOG_ERROR("incomplete vFlashErase packet received, dropping connection");
1907                         return ERROR_SERVER_REMOTE_CLOSED;
1908                 }
1909
1910                 addr = strtoul(parse, &parse, 16);
1911
1912                 if (*(parse++) != ',' || *parse == '\0')
1913                 {
1914                         LOG_ERROR("incomplete vFlashErase packet received, dropping connection");
1915                         return ERROR_SERVER_REMOTE_CLOSED;
1916                 }
1917
1918                 length = strtoul(parse, &parse, 16);
1919
1920                 if (*parse != '\0')
1921                 {
1922                         LOG_ERROR("incomplete vFlashErase packet received, dropping connection");
1923                         return ERROR_SERVER_REMOTE_CLOSED;
1924                 }
1925
1926                 /* assume all sectors need erasing - stops any problems
1927                  * when flash_write is called multiple times */
1928                 flash_set_dirty();
1929
1930                 /* perform any target specific operations before the erase */
1931                 target_call_event_callbacks(gdb_service->target, TARGET_EVENT_GDB_FLASH_ERASE_START);
1932                 result = flash_erase_address_range(gdb_service->target, addr, length);
1933                 target_call_event_callbacks(gdb_service->target, TARGET_EVENT_GDB_FLASH_ERASE_END);
1934
1935                 /* perform erase */
1936                 if (result != ERROR_OK)
1937                 {
1938                         /* GDB doesn't evaluate the actual error number returned,
1939                          * treat a failed erase as an I/O error
1940                          */
1941                         gdb_send_error(connection, EIO);
1942                         LOG_ERROR("flash_erase returned %i", result);
1943                 }
1944                 else
1945                         gdb_put_packet(connection, "OK", 2);
1946
1947                 return ERROR_OK;
1948         }
1949
1950         if (strstr(packet, "vFlashWrite:"))
1951         {
1952                 int retval;
1953                 unsigned long addr;
1954                 unsigned long length;
1955                 char *parse = packet + 12;
1956
1957                 if (*parse == '\0')
1958                 {
1959                         LOG_ERROR("incomplete vFlashErase packet received, dropping connection");
1960                         return ERROR_SERVER_REMOTE_CLOSED;
1961                 }
1962                 addr = strtoul(parse, &parse, 16);
1963                 if (*(parse++) != ':')
1964                 {
1965                         LOG_ERROR("incomplete vFlashErase packet received, dropping connection");
1966                         return ERROR_SERVER_REMOTE_CLOSED;
1967                 }
1968                 length = packet_size - (parse - packet);
1969
1970                 /* create a new image if there isn't already one */
1971                 if (gdb_connection->vflash_image == NULL)
1972                 {
1973                         gdb_connection->vflash_image = malloc(sizeof(struct image));
1974                         image_open(gdb_connection->vflash_image, "", "build");
1975                 }
1976
1977                 /* create new section with content from packet buffer */
1978                 if ((retval = image_add_section(gdb_connection->vflash_image, addr, length, 0x0, (uint8_t*)parse)) != ERROR_OK)
1979                 {
1980                         return retval;
1981                 }
1982
1983                 gdb_put_packet(connection, "OK", 2);
1984
1985                 return ERROR_OK;
1986         }
1987
1988         if (!strcmp(packet, "vFlashDone"))
1989         {
1990                 uint32_t written;
1991
1992                 /* process the flashing buffer. No need to erase as GDB
1993                  * always issues a vFlashErase first. */
1994                 target_call_event_callbacks(gdb_service->target, TARGET_EVENT_GDB_FLASH_WRITE_START);
1995                 result = flash_write(gdb_service->target, gdb_connection->vflash_image, &written, 0);
1996                 target_call_event_callbacks(gdb_service->target, TARGET_EVENT_GDB_FLASH_WRITE_END);
1997                 if (result != ERROR_OK)
1998                 {
1999                         if (result == ERROR_FLASH_DST_OUT_OF_BANK)
2000                                 gdb_put_packet(connection, "E.memtype", 9);
2001                         else
2002                                 gdb_send_error(connection, EIO);
2003                         }
2004                 else
2005                 {
2006                         LOG_DEBUG("wrote %u bytes from vFlash image to flash", (unsigned)written);
2007                         gdb_put_packet(connection, "OK", 2);
2008                 }
2009
2010                 image_close(gdb_connection->vflash_image);
2011                 free(gdb_connection->vflash_image);
2012                 gdb_connection->vflash_image = NULL;
2013
2014                 return ERROR_OK;
2015         }
2016
2017         gdb_put_packet(connection, "", 0);
2018         return ERROR_OK;
2019 }
2020
2021 int gdb_detach(struct connection *connection, struct target *target)
2022 {
2023         struct gdb_service *gdb_service = connection->service->priv;
2024
2025         target_call_event_callbacks(gdb_service->target, TARGET_EVENT_GDB_DETACH);
2026
2027         return gdb_put_packet(connection, "OK", 2);
2028 }
2029
2030 static void gdb_log_callback(void *priv, const char *file, unsigned line,
2031                 const char *function, const char *string)
2032 {
2033         struct connection *connection = priv;
2034         struct gdb_connection *gdb_con = connection->priv;
2035
2036         if (gdb_con->busy)
2037         {
2038                 /* do not reply this using the O packet */
2039                 return;
2040         }
2041
2042         gdb_output_con(connection, string);
2043 }
2044
2045 /* Do not allocate this on the stack */
2046 char gdb_packet_buffer[GDB_BUFFER_SIZE];
2047
2048 static void gdb_sig_halted(struct connection *connection)
2049 {
2050         char sig_reply[4];
2051         snprintf(sig_reply, 4, "T%2.2x", 2);
2052         gdb_put_packet(connection, sig_reply, 3);
2053
2054 }
2055
2056 int gdb_input_inner(struct connection *connection)
2057 {
2058         struct gdb_service *gdb_service = connection->service->priv;
2059         struct target *target = gdb_service->target;
2060         char *packet = gdb_packet_buffer;
2061         int packet_size;
2062         int retval;
2063         struct gdb_connection *gdb_con = connection->priv;
2064         static int extended_protocol = 0;
2065
2066         /* drain input buffer */
2067         do
2068         {
2069                 packet_size = GDB_BUFFER_SIZE-1;
2070                 if ((retval = gdb_get_packet(connection, packet, &packet_size)) != ERROR_OK)
2071                 {
2072                         return retval;
2073                 }
2074
2075                 /* terminate with zero */
2076                 packet[packet_size] = 0;
2077
2078                 if (LOG_LEVEL_IS(LOG_LVL_DEBUG)) {
2079                         if (packet[0] == 'X') {
2080                                 // binary packets spew junk into the debug log stream
2081                                 char buf[ 50 ];
2082                                 int x;
2083                                 for (x = 0 ; (x < 49) && (packet[x] != ':') ; x++) {
2084                                         buf[x] = packet[x];
2085                                 }
2086                                 buf[x] = 0;
2087                                 LOG_DEBUG("received packet: '%s:<binary-data>'", buf);
2088                         } else {
2089                                 LOG_DEBUG("received packet: '%s'", packet);
2090                         }
2091                 }
2092
2093                 if (packet_size > 0)
2094                 {
2095                         retval = ERROR_OK;
2096                         switch (packet[0])
2097                         {
2098                                 case 'H':
2099                                         /* Hct... -- set thread
2100                                          * we don't have threads, send empty reply */
2101                                         gdb_put_packet(connection, NULL, 0);
2102                                         break;
2103                                 case 'q':
2104                                 case 'Q':
2105                                         retval = gdb_query_packet(connection, target, packet, packet_size);
2106                                         break;
2107                                 case 'g':
2108                                         retval = gdb_get_registers_packet(connection, target, packet, packet_size);
2109                                         break;
2110                                 case 'G':
2111                                         retval = gdb_set_registers_packet(connection, target, packet, packet_size);
2112                                         break;
2113                                 case 'p':
2114                                         retval = gdb_get_register_packet(connection, target, packet, packet_size);
2115                                         break;
2116                                 case 'P':
2117                                         retval = gdb_set_register_packet(connection, target, packet, packet_size);
2118                                         break;
2119                                 case 'm':
2120                                         retval = gdb_read_memory_packet(connection, target, packet, packet_size);
2121                                         break;
2122                                 case 'M':
2123                                         retval = gdb_write_memory_packet(connection, target, packet, packet_size);
2124                                         break;
2125                                 case 'z':
2126                                 case 'Z':
2127                                         retval = gdb_breakpoint_watchpoint_packet(connection, target, packet, packet_size);
2128                                         break;
2129                                 case '?':
2130                                         gdb_last_signal_packet(connection, target, packet, packet_size);
2131                                         break;
2132                                 case 'c':
2133                                 case 's':
2134                                         {
2135                                                 int retval = ERROR_OK;
2136
2137                                                 struct gdb_connection *gdb_con = connection->priv;
2138                                                 log_add_callback(gdb_log_callback, connection);
2139
2140                                                 bool nostep = false;
2141                                                 if (target->state == TARGET_RUNNING)
2142                                                 {
2143                                                         LOG_WARNING("The target is already running. Halt target before stepi/continue.");
2144                                                         retval = target_halt(target);
2145                                                         if (retval == ERROR_OK)
2146                                                                 retval = target_wait_state(target, TARGET_HALTED, 100);
2147                                                 } else if (target->state != TARGET_HALTED)
2148                                                 {
2149                                                         LOG_WARNING("The target is not in the halted nor running stated, stepi/continue ignored.");
2150                                                         nostep = true;
2151                                                 } else if ((packet[0] == 's') && gdb_con->sync)
2152                                                 {
2153                                                         /* Hmm..... when you issue a continue in GDB, then a "stepi" is
2154                                                          * sent by GDB first to OpenOCD, thus defeating the check to
2155                                                          * make only the single stepping have the sync feature...
2156                                                          */
2157                                                         nostep = true;
2158                                                         LOG_WARNING("stepi ignored. GDB will now fetch the register state from the target.");
2159                                                 }
2160                                                 gdb_con->sync = false;
2161
2162                                                 if ((retval!=ERROR_OK) || nostep)
2163                                                 {
2164                                                         /* Either the target isn't in the halted state, then we can't
2165                                                          * step/continue. This might be early setup, etc.
2166                                                          *
2167                                                          * Or we want to allow GDB to pick up a fresh set of
2168                                                          * register values without modifying the target state.
2169                                                          *
2170                                                          */
2171                                                         gdb_sig_halted(connection);
2172
2173                                                         /* stop forwarding log packets! */
2174                                                         log_remove_callback(gdb_log_callback, connection);
2175                                                 } else
2176                                                 {
2177                                                         /* We're running/stepping, in which case we can
2178                                                          * forward log output until the target is halted
2179                                                          */
2180                                                         gdb_con->frontend_state = TARGET_RUNNING;
2181                                                         target_call_event_callbacks(target, TARGET_EVENT_GDB_START);
2182                                                         int retval = gdb_step_continue_packet(connection, target, packet, packet_size);
2183                                                         if (retval != ERROR_OK)
2184                                                         {
2185                                                                 /* we'll never receive a halted condition... issue a false one.. */
2186                                                                 gdb_frontend_halted(target, connection);
2187                                                         }
2188                                                 }
2189                                         }
2190                                         break;
2191                                 case 'v':
2192                                         retval = gdb_v_packet(connection, target, packet, packet_size);
2193                                         break;
2194                                 case 'D':
2195                                         retval = gdb_detach(connection, target);
2196                                         extended_protocol = 0;
2197                                         break;
2198                                 case 'X':
2199                                         if ((retval = gdb_write_memory_binary_packet(connection, target, packet, packet_size)) != ERROR_OK)
2200                                                 return retval;
2201                                         break;
2202                                 case 'k':
2203                                         if (extended_protocol != 0)
2204                                                 break;
2205                                         gdb_put_packet(connection, "OK", 2);
2206                                         return ERROR_SERVER_REMOTE_CLOSED;
2207                                 case '!':
2208                                         /* handle extended remote protocol */
2209                                         extended_protocol = 1;
2210                                         gdb_put_packet(connection, "OK", 2);
2211                                         break;
2212                                 case 'R':
2213                                         /* handle extended restart packet */
2214                                         breakpoint_clear_target(gdb_service->target);
2215                                         watchpoint_clear_target(gdb_service->target);
2216                                         command_run_linef(connection->cmd_ctx,
2217                                                         "ocd_gdb_restart %s",
2218                                                         target_name(target));
2219                                         break;
2220                                 default:
2221                                         /* ignore unknown packets */
2222                                         LOG_DEBUG("ignoring 0x%2.2x packet", packet[0]);
2223                                         gdb_put_packet(connection, NULL, 0);
2224                                         break;
2225                         }
2226
2227                         /* if a packet handler returned an error, exit input loop */
2228                         if (retval != ERROR_OK)
2229                                 return retval;
2230                 }
2231
2232                 if (gdb_con->ctrl_c)
2233                 {
2234                         if (target->state == TARGET_RUNNING)
2235                         {
2236                                 retval = target_halt(target);
2237                                 if (retval != ERROR_OK)
2238                                 {
2239                                         target_call_event_callbacks(target, TARGET_EVENT_GDB_HALT);
2240                                 }
2241                                 gdb_con->ctrl_c = 0;
2242                         } else
2243                         {
2244                                 LOG_INFO("The target is not running when halt was requested, stopping GDB.");
2245                                 target_call_event_callbacks(target, TARGET_EVENT_GDB_HALT);
2246                         }
2247                 }
2248
2249         } while (gdb_con->buf_cnt > 0);
2250
2251         return ERROR_OK;
2252 }
2253
2254 int gdb_input(struct connection *connection)
2255 {
2256         int retval = gdb_input_inner(connection);
2257         struct gdb_connection *gdb_con = connection->priv;
2258         if (retval == ERROR_SERVER_REMOTE_CLOSED)
2259                 return retval;
2260
2261         /* logging does not propagate the error, yet can set the gdb_con->closed flag */
2262         if (gdb_con->closed)
2263                 return ERROR_SERVER_REMOTE_CLOSED;
2264
2265         /* we'll recover from any other errors(e.g. temporary timeouts, etc.) */
2266         return ERROR_OK;
2267 }
2268
2269 static int gdb_target_start(struct target *target, uint16_t port)
2270 {
2271         bool use_pipes = 0 == port;
2272         struct gdb_service *gdb_service = malloc(sizeof(struct gdb_service));
2273         if (NULL == gdb_service)
2274                 return -ENOMEM;
2275
2276         gdb_service->target = target;
2277
2278         add_service("gdb", use_pipes ? CONNECTION_PIPE : CONNECTION_TCP,
2279                         port, 1, &gdb_new_connection, &gdb_input,
2280                         &gdb_connection_closed, gdb_service);
2281
2282         const char *name = target_name(target);
2283         if (use_pipes)
2284                 LOG_DEBUG("gdb service for target '%s' using pipes", name);
2285         else
2286                 LOG_DEBUG("gdb service for target '%s' on TCP port %u", name, port);
2287         return ERROR_OK;
2288 }
2289
2290 /* FIXME static */
2291 int gdb_target_add_one(struct target *target)
2292 {
2293         if (gdb_port == 0 && server_use_pipes == 0)
2294         {
2295                 LOG_INFO("gdb port disabled");
2296                 return ERROR_OK;
2297         }
2298         if (0 == gdb_port_next)
2299                 gdb_port_next = gdb_port;
2300
2301         bool use_pipes = server_use_pipes;
2302         static bool server_started_with_pipes = false;
2303         if (server_started_with_pipes)
2304         {
2305                 LOG_WARNING("gdb service permits one target when using pipes");
2306                 if (0 == gdb_port)
2307                         return ERROR_OK;
2308
2309                 use_pipes = false;
2310         }
2311
2312         int e = gdb_target_start(target, use_pipes ? 0 : gdb_port_next);
2313         if (ERROR_OK == e)
2314         {
2315                 server_started_with_pipes |= use_pipes;
2316                 gdb_port_next++;
2317         }
2318         return e;
2319 }
2320
2321 int gdb_target_add_all(struct target *target)
2322 {
2323         if (NULL == target)
2324         {
2325                 LOG_WARNING("gdb services need one or more targets defined");
2326                 return ERROR_OK;
2327         }
2328
2329         while (NULL != target)
2330         {
2331                 int retval = gdb_target_add_one(target);
2332                 if (ERROR_OK != retval)
2333                         return retval;
2334
2335                 target = target->next;
2336         }
2337
2338         return ERROR_OK;
2339 }
2340
2341 COMMAND_HANDLER(handle_gdb_sync_command)
2342 {
2343         if (CMD_ARGC != 0)
2344         {
2345                 return ERROR_COMMAND_SYNTAX_ERROR;
2346         }
2347
2348         if (current_gdb_connection == NULL)
2349         {
2350                 command_print(CMD_CTX,
2351                                 "gdb_sync command can only be run from within gdb using \"monitor gdb_sync\"");
2352                 return ERROR_FAIL;
2353         }
2354
2355         current_gdb_connection->sync = true;
2356
2357         return ERROR_OK;
2358 }
2359
2360 /* daemon configuration command gdb_port */
2361 COMMAND_HANDLER(handle_gdb_port_command)
2362 {
2363         int retval = CALL_COMMAND_HANDLER(server_port_command, &gdb_port);
2364         if (ERROR_OK == retval)
2365                 gdb_port_next = gdb_port;
2366         return retval;
2367 }
2368
2369 COMMAND_HANDLER(handle_gdb_memory_map_command)
2370 {
2371         if (CMD_ARGC == 1)
2372                 COMMAND_PARSE_ENABLE(CMD_ARGV[0], gdb_use_memory_map);
2373
2374         return ERROR_COMMAND_SYNTAX_ERROR;
2375 }
2376
2377 COMMAND_HANDLER(handle_gdb_flash_program_command)
2378 {
2379         if (CMD_ARGC == 1)
2380                 COMMAND_PARSE_ENABLE(CMD_ARGV[0], gdb_flash_program);
2381
2382         return ERROR_COMMAND_SYNTAX_ERROR;
2383 }
2384
2385 COMMAND_HANDLER(handle_gdb_report_data_abort_command)
2386 {
2387         if (CMD_ARGC == 1)
2388                 COMMAND_PARSE_ENABLE(CMD_ARGV[0], gdb_report_data_abort);
2389
2390         return ERROR_COMMAND_SYNTAX_ERROR;
2391 }
2392
2393 /* gdb_breakpoint_override */
2394 COMMAND_HANDLER(handle_gdb_breakpoint_override_command)
2395 {
2396         if (CMD_ARGC == 0)
2397         {
2398
2399         } else if (CMD_ARGC == 1)
2400         {
2401                 gdb_breakpoint_override = 1;
2402                 if (strcmp(CMD_ARGV[0], "hard") == 0)
2403                 {
2404                         gdb_breakpoint_override_type = BKPT_HARD;
2405                 } else if (strcmp(CMD_ARGV[0], "soft") == 0)
2406                 {
2407                         gdb_breakpoint_override_type = BKPT_SOFT;
2408                 } else if (strcmp(CMD_ARGV[0], "disable") == 0)
2409                 {
2410                         gdb_breakpoint_override = 0;
2411                 }
2412         } else
2413         {
2414                 return ERROR_COMMAND_SYNTAX_ERROR;
2415         }
2416         if (gdb_breakpoint_override)
2417         {
2418                 LOG_USER("force %s breakpoints", (gdb_breakpoint_override_type == BKPT_HARD)?"hard":"soft");
2419         } else
2420         {
2421                 LOG_USER("breakpoint type is not overridden");
2422         }
2423
2424         return ERROR_OK;
2425 }
2426
2427 static const struct command_registration gdb_command_handlers[] = {
2428         {
2429                 .name = "gdb_sync",
2430                 .handler = handle_gdb_sync_command,
2431                 .mode = COMMAND_ANY,
2432                 .help = "next stepi will return immediately allowing "
2433                         "GDB to fetch register state without affecting "
2434                         "target state",
2435         },
2436         {
2437                 .name = "gdb_port",
2438                 .handler = handle_gdb_port_command,
2439                 .mode = COMMAND_ANY,
2440                 .help = "Display or specify base port on which to listen "
2441                         "for incoming GDB connections.  "
2442                         "No arguments reports GDB port; zero disables.",
2443                 .usage = "[port_num]",
2444         },
2445         {
2446                 .name = "gdb_memory_map",
2447                 .handler = handle_gdb_memory_map_command,
2448                 .mode = COMMAND_CONFIG,
2449                 .help = "enable or disable memory map",
2450                 .usage = "('enable'|'disable')"
2451         },
2452         {
2453                 .name = "gdb_flash_program",
2454                 .handler = handle_gdb_flash_program_command,
2455                 .mode = COMMAND_CONFIG,
2456                 .help = "enable or disable flash program",
2457                 .usage = "('enable'|'disable')"
2458         },
2459         {
2460                 .name = "gdb_report_data_abort",
2461                 .handler = handle_gdb_report_data_abort_command,
2462                 .mode = COMMAND_CONFIG,
2463                 .help = "enable or disable reporting data aborts",
2464                 .usage = "('enable'|'disable')"
2465         },
2466         {
2467                 .name = "gdb_breakpoint_override",
2468                 .handler = handle_gdb_breakpoint_override_command,
2469                 .mode = COMMAND_EXEC,
2470                 .help = "Display or specify type of breakpoint "
2471                         "to be used by gdb 'break' commands.",
2472                 .usage = "('hard'|'soft'|'disable')"
2473         },
2474         COMMAND_REGISTRATION_DONE
2475 };
2476
2477 int gdb_register_commands(struct command_context *cmd_ctx)
2478 {
2479         return register_commands(cmd_ctx, NULL, gdb_command_handlers);
2480 }