gdb_server: improved gdb load performance
[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-2010 Ã˜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         /* We delay reporting memory write errors until next step/continue or memory
65          * write. This improves performance of gdb load significantly as the GDB packet
66          * can be replied immediately and a new GDB packet will be ready without delay
67          * (ca. 10% or so...).
68          */
69         bool mem_write_error;
70 };
71
72
73 #if 0
74 #define _DEBUG_GDB_IO_
75 #endif
76
77 static struct gdb_connection *current_gdb_connection;
78
79 static int gdb_breakpoint_override;
80 static enum breakpoint_type gdb_breakpoint_override_type;
81
82 static int gdb_error(struct connection *connection, int retval);
83 static unsigned short gdb_port = 3333;
84 static unsigned short gdb_port_next = 0;
85 static const char DIGITS[16] = "0123456789abcdef";
86
87 static void gdb_log_callback(void *priv, const char *file, unsigned line,
88                 const char *function, const char *string);
89
90 /* number of gdb connections, mainly to suppress gdb related debugging spam
91  * in helper/log.c when no gdb connections are actually active */
92 int gdb_actual_connections;
93
94 /* set if we are sending a memory map to gdb
95  * via qXfer:memory-map:read packet */
96 /* enabled by default*/
97 static int gdb_use_memory_map = 1;
98 /* enabled by default*/
99 static int gdb_flash_program = 1;
100
101 /* if set, data aborts cause an error to be reported in memory read packets
102  * see the code in gdb_read_memory_packet() for further explanations.
103  * Disabled by default.
104  */
105 static int gdb_report_data_abort;
106
107 static int gdb_last_signal(struct target *target)
108 {
109         switch (target->debug_reason)
110         {
111                 case DBG_REASON_DBGRQ:
112                         return 0x2; /* SIGINT */
113                 case DBG_REASON_BREAKPOINT:
114                 case DBG_REASON_WATCHPOINT:
115                 case DBG_REASON_WPTANDBKPT:
116                         return 0x05; /* SIGTRAP */
117                 case DBG_REASON_SINGLESTEP:
118                         return 0x05; /* SIGTRAP */
119                 case DBG_REASON_NOTHALTED:
120                         return 0x0; /* no signal... shouldn't happen */
121                 default:
122                         LOG_USER("undefined debug reason %d - target needs reset", target->debug_reason);
123                         return 0x0;
124         }
125 }
126
127 static int check_pending(struct connection *connection,
128                 int timeout_s, int *got_data)
129 {
130         /* a non-blocking socket will block if there is 0 bytes available on the socket,
131          * but return with as many bytes as are available immediately
132          */
133         struct timeval tv;
134         fd_set read_fds;
135         struct gdb_connection *gdb_con = connection->priv;
136         int t;
137         if (got_data == NULL)
138                 got_data=&t;
139         *got_data = 0;
140
141         if (gdb_con->buf_cnt > 0)
142         {
143                 *got_data = 1;
144                 return ERROR_OK;
145         }
146
147         FD_ZERO(&read_fds);
148         FD_SET(connection->fd, &read_fds);
149
150         tv.tv_sec = timeout_s;
151         tv.tv_usec = 0;
152         if (socket_select(connection->fd + 1, &read_fds, NULL, NULL, &tv) == 0)
153         {
154                 /* This can typically be because a "monitor" command took too long
155                  * before printing any progress messages
156                  */
157                 if (timeout_s > 0)
158                 {
159                         return ERROR_GDB_TIMEOUT;
160                 } else
161                 {
162                         return ERROR_OK;
163                 }
164         }
165         *got_data = FD_ISSET(connection->fd, &read_fds) != 0;
166         return ERROR_OK;
167 }
168
169 static int gdb_get_char_inner(struct connection *connection, int* next_char)
170 {
171         struct gdb_connection *gdb_con = connection->priv;
172         int retval = ERROR_OK;
173
174         for (;;)
175         {
176                 if (connection->service->type == CONNECTION_PIPE)
177                 {
178                         gdb_con->buf_cnt = read(connection->fd, gdb_con->buffer, GDB_BUFFER_SIZE);
179                 }
180                 else
181                 {
182                         retval = check_pending(connection, 1, NULL);
183                         if (retval != ERROR_OK)
184                                 return retval;
185                         gdb_con->buf_cnt = read_socket(connection->fd, gdb_con->buffer, GDB_BUFFER_SIZE);
186                 }
187
188                 if (gdb_con->buf_cnt > 0)
189                 {
190                         break;
191                 }
192                 if (gdb_con->buf_cnt == 0)
193                 {
194                         gdb_con->closed = 1;
195                         return ERROR_SERVER_REMOTE_CLOSED;
196                 }
197
198 #ifdef _WIN32
199                 errno = WSAGetLastError();
200
201                 switch (errno)
202                 {
203                         case WSAEWOULDBLOCK:
204                                 usleep(1000);
205                                 break;
206                         case WSAECONNABORTED:
207                                 gdb_con->closed = 1;
208                                 return ERROR_SERVER_REMOTE_CLOSED;
209                         case WSAECONNRESET:
210                                 gdb_con->closed = 1;
211                                 return ERROR_SERVER_REMOTE_CLOSED;
212                         default:
213                                 LOG_ERROR("read: %d", errno);
214                                 exit(-1);
215                 }
216 #else
217                 switch (errno)
218                 {
219                         case EAGAIN:
220                                 usleep(1000);
221                                 break;
222                         case ECONNABORTED:
223                                 gdb_con->closed = 1;
224                                 return ERROR_SERVER_REMOTE_CLOSED;
225                         case ECONNRESET:
226                                 gdb_con->closed = 1;
227                                 return ERROR_SERVER_REMOTE_CLOSED;
228                         default:
229                                 LOG_ERROR("read: %s", strerror(errno));
230                                 gdb_con->closed = 1;
231                                 return ERROR_SERVER_REMOTE_CLOSED;
232                 }
233 #endif
234         }
235
236 #ifdef _DEBUG_GDB_IO_
237         debug_buffer = malloc(gdb_con->buf_cnt + 1);
238         memcpy(debug_buffer, gdb_con->buffer, gdb_con->buf_cnt);
239         debug_buffer[gdb_con->buf_cnt] = 0;
240         LOG_DEBUG("received '%s'", debug_buffer);
241         free(debug_buffer);
242 #endif
243
244         gdb_con->buf_p = gdb_con->buffer;
245         gdb_con->buf_cnt--;
246         *next_char = *(gdb_con->buf_p++);
247         if (gdb_con->buf_cnt > 0)
248                 connection->input_pending = 1;
249         else
250                 connection->input_pending = 0;
251 #ifdef _DEBUG_GDB_IO_
252         LOG_DEBUG("returned char '%c' (0x%2.2x)", *next_char, *next_char);
253 #endif
254
255         return retval;
256 }
257
258 /**
259  * The cool thing about this fn is that it allows buf_p and buf_cnt to be
260  * held in registers in the inner loop.
261  *
262  * For small caches and embedded systems this is important!
263  */
264 static inline int gdb_get_char_fast(struct connection *connection, int* next_char, char **buf_p, int *buf_cnt)
265 {
266         int retval = ERROR_OK;
267
268         if ((*buf_cnt)-- > 0)
269         {
270                 *next_char = **buf_p;
271                 (*buf_p)++;
272                 if (*buf_cnt > 0)
273                         connection->input_pending = 1;
274                 else
275                         connection->input_pending = 0;
276
277 #ifdef _DEBUG_GDB_IO_
278                 LOG_DEBUG("returned char '%c' (0x%2.2x)", *next_char, *next_char);
279 #endif
280
281                 return ERROR_OK;
282         }
283
284         struct gdb_connection *gdb_con = connection->priv;
285         gdb_con->buf_p = *buf_p;
286         gdb_con->buf_cnt = *buf_cnt;
287         retval = gdb_get_char_inner(connection, next_char);
288         *buf_p = gdb_con->buf_p;
289         *buf_cnt = gdb_con->buf_cnt;
290
291         return retval;
292 }
293
294
295 static int gdb_get_char(struct connection *connection, int* next_char)
296 {
297         struct gdb_connection *gdb_con = connection->priv;
298         return gdb_get_char_fast(connection, next_char, &gdb_con->buf_p, &gdb_con->buf_cnt);
299 }
300
301
302 static int gdb_putback_char(struct connection *connection, int last_char)
303 {
304         struct gdb_connection *gdb_con = connection->priv;
305
306         if (gdb_con->buf_p > gdb_con->buffer)
307         {
308                 *(--gdb_con->buf_p) = last_char;
309                 gdb_con->buf_cnt++;
310         }
311         else
312         {
313                 LOG_ERROR("BUG: couldn't put character back");
314         }
315
316         return ERROR_OK;
317 }
318
319 /* The only way we can detect that the socket is closed is the first time
320  * we write to it, we will fail. Subsequent write operations will
321  * succeed. Shudder! */
322 static int gdb_write(struct connection *connection, void *data, int len)
323 {
324         struct gdb_connection *gdb_con = connection->priv;
325         if (gdb_con->closed)
326                 return ERROR_SERVER_REMOTE_CLOSED;
327
328         if (connection->service->type == CONNECTION_PIPE)
329         {
330                 /* write to stdout */
331                 if (write(STDOUT_FILENO, data, len) == len)
332                 {
333                         return ERROR_OK;
334                 }
335         }
336         else
337         {
338                 if (write_socket(connection->fd, data, len) == len)
339                 {
340                         return ERROR_OK;
341                 }
342         }
343         gdb_con->closed = 1;
344         return ERROR_SERVER_REMOTE_CLOSED;
345 }
346
347 static int gdb_put_packet_inner(struct connection *connection,
348                 char *buffer, int len)
349 {
350         int i;
351         unsigned char my_checksum = 0;
352 #ifdef _DEBUG_GDB_IO_
353         char *debug_buffer;
354 #endif
355         int reply;
356         int retval;
357         struct gdb_connection *gdb_con = connection->priv;
358
359         for (i = 0; i < len; i++)
360                 my_checksum += buffer[i];
361
362 #ifdef _DEBUG_GDB_IO_
363         /*
364          * At this point we should have nothing in the input queue from GDB,
365          * however sometimes '-' is sent even though we've already received
366          * an ACK (+) for everything we've sent off.
367          */
368         int gotdata;
369         for (;;)
370         {
371                 retval = check_pending(connection, 0, &gotdata);
372                 if (retval != ERROR_OK)
373                         return retval;
374                 if (!gotdata)
375                         break;
376                 if ((retval = gdb_get_char(connection, &reply)) != ERROR_OK)
377                         return retval;
378                 if (reply == '$') {
379                         /* fix a problem with some IAR tools */
380                         gdb_putback_char(connection, reply);
381                         LOG_DEBUG("Unexpected start of new packet");
382                         break;
383                 }
384
385                 LOG_WARNING("Discard unexpected char %c", reply);
386         }
387 #endif
388
389         while (1)
390         {
391 #ifdef _DEBUG_GDB_IO_
392                 debug_buffer = malloc(len + 1);
393                 memcpy(debug_buffer, buffer, len);
394                 debug_buffer[len] = 0;
395                 LOG_DEBUG("sending packet '$%s#%2.2x'", debug_buffer, my_checksum);
396                 free(debug_buffer);
397 #endif
398
399                 char local_buffer[1024];
400                 local_buffer[0] = '$';
401                 if ((size_t)len + 4 <= sizeof(local_buffer))
402                 {
403                         /* performance gain on smaller packets by only a single call to gdb_write() */
404                         memcpy(local_buffer + 1, buffer, len++);
405                         local_buffer[len++] = '#';
406                         local_buffer[len++] = DIGITS[(my_checksum >> 4) & 0xf];
407                         local_buffer[len++] = DIGITS[my_checksum & 0xf];
408                         if ((retval = gdb_write(connection, local_buffer, len)) != ERROR_OK)
409                         {
410                                 return retval;
411                         }
412                 }
413                 else
414                 {
415                         /* larger packets are transmitted directly from caller supplied buffer
416                            by several calls to gdb_write() to avoid dynamic allocation */
417                         local_buffer[1] = '#';
418                         local_buffer[2] = DIGITS[(my_checksum >> 4) & 0xf];
419                         local_buffer[3] = DIGITS[my_checksum & 0xf];
420                         if ((retval = gdb_write(connection, local_buffer, 1)) != ERROR_OK)
421                         {
422                                 return retval;
423                         }
424                         if ((retval = gdb_write(connection, buffer, len)) != ERROR_OK)
425                         {
426                                 return retval;
427                         }
428                         if ((retval = gdb_write(connection, local_buffer + 1, 3)) != ERROR_OK)
429                         {
430                                 return retval;
431                         }
432                 }
433
434                 if (gdb_con->noack_mode)
435                         break;
436
437                 if ((retval = gdb_get_char(connection, &reply)) != ERROR_OK)
438                         return retval;
439
440                 if (reply == '+')
441                         break;
442                 else if (reply == '-')
443                 {
444                         /* Stop sending output packets for now */
445                         log_remove_callback(gdb_log_callback, connection);
446                         LOG_WARNING("negative reply, retrying");
447                 }
448                 else if (reply == 0x3)
449                 {
450                         gdb_con->ctrl_c = 1;
451                         if ((retval = gdb_get_char(connection, &reply)) != ERROR_OK)
452                                 return retval;
453                         if (reply == '+')
454                                 break;
455                         else if (reply == '-')
456                         {
457                                 /* Stop sending output packets for now */
458                                 log_remove_callback(gdb_log_callback, connection);
459                                 LOG_WARNING("negative reply, retrying");
460                         }
461                         else if (reply == '$') {
462                                 LOG_ERROR("GDB missing ack(1) - assumed good");
463                                 gdb_putback_char(connection, reply);
464                                 return ERROR_OK;
465                         } else {
466
467                                 LOG_ERROR("unknown character(1) 0x%2.2x in reply, dropping connection", reply);
468                                 gdb_con->closed = 1;
469                                 return ERROR_SERVER_REMOTE_CLOSED;
470                         }
471                 }
472                 else if (reply == '$') {
473                         LOG_ERROR("GDB missing ack(2) - assumed good");
474                         gdb_putback_char(connection, reply);
475                         return ERROR_OK;
476                 }
477                 else
478                 {
479                         LOG_ERROR("unknown character(2) 0x%2.2x in reply, dropping connection", reply);
480                         gdb_con->closed = 1;
481                         return ERROR_SERVER_REMOTE_CLOSED;
482                 }
483         }
484         if (gdb_con->closed)
485                 return ERROR_SERVER_REMOTE_CLOSED;
486
487         return ERROR_OK;
488 }
489
490 static int gdb_put_packet(struct connection *connection, char *buffer, int len)
491 {
492         struct gdb_connection *gdb_con = connection->priv;
493         gdb_con->busy = 1;
494         int retval = gdb_put_packet_inner(connection, buffer, len);
495         gdb_con->busy = 0;
496
497         /* we sent some data, reset timer for keep alive messages */
498         kept_alive();
499
500         return retval;
501 }
502
503 static __inline__ int fetch_packet(struct connection *connection, int *checksum_ok, int noack, int *len, char *buffer)
504 {
505         unsigned char my_checksum = 0;
506         char checksum[3];
507         int character;
508         int retval = ERROR_OK;
509
510         struct gdb_connection *gdb_con = connection->priv;
511         my_checksum = 0;
512         int count = 0;
513         count = 0;
514
515         /* move this over into local variables to use registers and give the
516          * more freedom to optimize */
517         char *buf_p = gdb_con->buf_p;
518         int buf_cnt = gdb_con->buf_cnt;
519
520         for (;;)
521         {
522                 /* The common case is that we have an entire packet with no escape chars.
523                  * We need to leave at least 2 bytes in the buffer to have
524                  * gdb_get_char() update various bits and bobs correctly.
525                  */
526                 if ((buf_cnt > 2) && ((buf_cnt + count) < *len))
527                 {
528                         /* The compiler will struggle a bit with constant propagation and
529                          * aliasing, so we help it by showing that these values do not
530                          * change inside the loop
531                          */
532                         int i;
533                         char *buf = buf_p;
534                         int run = buf_cnt - 2;
535                         i = 0;
536                         int done = 0;
537                         while (i < run)
538                         {
539                                 character = *buf++;
540                                 i++;
541                                 if (character == '#')
542                                 {
543                                         /* Danger! character can be '#' when esc is
544                                          * used so we need an explicit boolean for done here.
545                                          */
546                                         done = 1;
547                                         break;
548                                 }
549
550                                 if (character == '}')
551                                 {
552                                         /* data transmitted in binary mode (X packet)
553                                          * uses 0x7d as escape character */
554                                         my_checksum += character & 0xff;
555                                         character = *buf++;
556                                         i++;
557                                         my_checksum += character & 0xff;
558                                         buffer[count++] = (character ^ 0x20) & 0xff;
559                                 }
560                                 else
561                                 {
562                                         my_checksum += character & 0xff;
563                                         buffer[count++] = character & 0xff;
564                                 }
565                         }
566                         buf_p += i;
567                         buf_cnt -= i;
568                         if (done)
569                                 break;
570                 }
571                 if (count > *len)
572                 {
573                         LOG_ERROR("packet buffer too small");
574                         retval = ERROR_GDB_BUFFER_TOO_SMALL;
575                         break;
576                 }
577
578                 retval = gdb_get_char_fast(connection, &character, &buf_p, &buf_cnt);
579                 if (retval != ERROR_OK)
580                         break;
581
582                 if (character == '#')
583                         break;
584
585                 if (character == '}')
586                 {
587                         /* data transmitted in binary mode (X packet)
588                          * uses 0x7d as escape character */
589                         my_checksum += character & 0xff;
590
591                         retval = gdb_get_char_fast(connection, &character, &buf_p, &buf_cnt);
592                         if (retval != ERROR_OK)
593                                 break;
594
595                         my_checksum += character & 0xff;
596                         buffer[count++] = (character ^ 0x20) & 0xff;
597                 }
598                 else
599                 {
600                         my_checksum += character & 0xff;
601                         buffer[count++] = character & 0xff;
602                 }
603         }
604
605         gdb_con->buf_p = buf_p;
606         gdb_con->buf_cnt = buf_cnt;
607
608         if (retval != ERROR_OK)
609                 return retval;
610
611         *len = count;
612
613         if ((retval = gdb_get_char(connection, &character)) != ERROR_OK)
614                 return retval;
615         checksum[0] = character;
616         if ((retval = gdb_get_char(connection, &character)) != ERROR_OK)
617                 return retval;
618         checksum[1] = character;
619         checksum[2] = 0;
620
621         if (!noack)
622         {
623                 *checksum_ok = (my_checksum == strtoul(checksum, NULL, 16));
624         }
625
626         return ERROR_OK;
627 }
628
629 static int gdb_get_packet_inner(struct connection *connection,
630                 char *buffer, int *len)
631 {
632         int character;
633         int retval;
634         struct gdb_connection *gdb_con = connection->priv;
635
636         while (1)
637         {
638                 do
639                 {
640                         if ((retval = gdb_get_char(connection, &character)) != ERROR_OK)
641                                 return retval;
642
643 #ifdef _DEBUG_GDB_IO_
644                         LOG_DEBUG("character: '%c'", character);
645 #endif
646
647                         switch (character)
648                         {
649                                 case '$':
650                                         break;
651                                 case '+':
652                                         /* gdb sends a dummy ack '+' at every remote connect - see remote_start_remote (remote.c)
653                                          * in case anyone tries to debug why they receive this warning every time */
654                                         LOG_WARNING("acknowledgment received, but no packet pending");
655                                         break;
656                                 case '-':
657                                         LOG_WARNING("negative acknowledgment, but no packet pending");
658                                         break;
659                                 case 0x3:
660                                         gdb_con->ctrl_c = 1;
661                                         *len = 0;
662                                         return ERROR_OK;
663                                 default:
664                                         LOG_WARNING("ignoring character 0x%x", character);
665                                         break;
666                         }
667                 } while (character != '$');
668
669
670
671                 int checksum_ok = 0;
672                 /* explicit code expansion here to get faster inlined code in -O3 by not
673                  * calculating checksum
674                  */
675                 if (gdb_con->noack_mode)
676                 {
677                         if ((retval = fetch_packet(connection, &checksum_ok, 1, len, buffer)) != ERROR_OK)
678                                 return retval;
679                 } else
680                 {
681                         if ((retval = fetch_packet(connection, &checksum_ok, 0, len, buffer)) != ERROR_OK)
682                                 return retval;
683                 }
684
685                 if (gdb_con->noack_mode)
686                 {
687                         /* checksum is not checked in noack mode */
688                         break;
689                 }
690                 if (checksum_ok)
691                 {
692                         if ((retval = gdb_write(connection, "+", 1)) != ERROR_OK)
693                         {
694                                 return retval;
695                         }
696                         break;
697                 }
698         }
699         if (gdb_con->closed)
700                 return ERROR_SERVER_REMOTE_CLOSED;
701
702         return ERROR_OK;
703 }
704
705 static int gdb_get_packet(struct connection *connection, char *buffer, int *len)
706 {
707         struct gdb_connection *gdb_con = connection->priv;
708         gdb_con->busy = 1;
709         int retval = gdb_get_packet_inner(connection, buffer, len);
710         gdb_con->busy = 0;
711         return retval;
712 }
713
714 static int gdb_output_con(struct connection *connection, const char* line)
715 {
716         char *hex_buffer;
717         int i, bin_size;
718
719         bin_size = strlen(line);
720
721         hex_buffer = malloc(bin_size*2 + 2);
722         if (hex_buffer == NULL)
723                 return ERROR_GDB_BUFFER_TOO_SMALL;
724
725         hex_buffer[0] = 'O';
726         for (i = 0; i < bin_size; i++)
727                 snprintf(hex_buffer + 1 + i*2, 3, "%2.2x", line[i]);
728         hex_buffer[bin_size*2 + 1] = 0;
729
730         int retval = gdb_put_packet(connection, hex_buffer, bin_size*2 + 1);
731
732         free(hex_buffer);
733         return retval;
734 }
735
736 static int gdb_output(struct command_context *context, const char* line)
737 {
738         /* this will be dumped to the log and also sent as an O packet if possible */
739         LOG_USER_N("%s", line);
740         return ERROR_OK;
741 }
742
743
744 static void gdb_frontend_halted(struct target *target, struct connection *connection)
745 {
746         struct gdb_connection *gdb_connection = connection->priv;
747
748         /* In the GDB protocol when we are stepping or continuing execution,
749          * we have a lingering reply. Upon receiving a halted event
750          * when we have that lingering packet, we reply to the original
751          * step or continue packet.
752          *
753          * Executing monitor commands can bring the target in and
754          * out of the running state so we'll see lots of TARGET_EVENT_XXX
755          * that are to be ignored.
756          */
757         if (gdb_connection->frontend_state == TARGET_RUNNING)
758         {
759                 char sig_reply[4];
760                 int signal;
761
762                 /* stop forwarding log packets! */
763                 log_remove_callback(gdb_log_callback, connection);
764
765                 if (gdb_connection->ctrl_c)
766                 {
767                         signal = 0x2;
768                         gdb_connection->ctrl_c = 0;
769                 }
770                 else
771                 {
772                         signal = gdb_last_signal(target);
773                 }
774
775                 snprintf(sig_reply, 4, "T%2.2x", signal);
776                 gdb_put_packet(connection, sig_reply, 3);
777                 gdb_connection->frontend_state = TARGET_HALTED;
778         }
779 }
780
781 static int gdb_target_callback_event_handler(struct target *target,
782                 enum target_event event, void *priv)
783 {
784         int retval;
785         struct connection *connection = priv;
786
787         target_handle_event(target, event);
788         switch (event)
789         {
790                 case TARGET_EVENT_GDB_HALT:
791                         gdb_frontend_halted(target, connection);
792                         break;
793                 case TARGET_EVENT_HALTED:
794                         target_call_event_callbacks(target, TARGET_EVENT_GDB_END);
795                         break;
796                 case TARGET_EVENT_GDB_FLASH_ERASE_START:
797                         target_handle_event(target, TARGET_EVENT_OLD_gdb_program_config);
798                         if ((retval = jtag_execute_queue()) != ERROR_OK)
799                         {
800                                 return retval;
801                         }
802                         break;
803                 default:
804                         break;
805         }
806
807         return ERROR_OK;
808 }
809
810 static int gdb_new_connection(struct connection *connection)
811 {
812         struct gdb_connection *gdb_connection = malloc(sizeof(struct gdb_connection));
813         struct gdb_service *gdb_service = connection->service->priv;
814         int retval;
815         int initial_ack;
816
817         connection->priv = gdb_connection;
818
819         /* initialize gdb connection information */
820         gdb_connection->buf_p = gdb_connection->buffer;
821         gdb_connection->buf_cnt = 0;
822         gdb_connection->ctrl_c = 0;
823         gdb_connection->frontend_state = TARGET_HALTED;
824         gdb_connection->vflash_image = NULL;
825         gdb_connection->closed = 0;
826         gdb_connection->busy = 0;
827         gdb_connection->noack_mode = 0;
828         gdb_connection->sync = true;
829         gdb_connection->mem_write_error = false;
830
831         /* send ACK to GDB for debug request */
832         gdb_write(connection, "+", 1);
833
834         /* output goes through gdb connection */
835         command_set_output_handler(connection->cmd_ctx, gdb_output, connection);
836
837         /* we must remove all breakpoints registered to the target as a previous
838          * GDB session could leave dangling breakpoints if e.g. communication
839          * timed out.
840          */
841         breakpoint_clear_target(gdb_service->target);
842         watchpoint_clear_target(gdb_service->target);
843
844         /* register callback to be informed about target events */
845         target_register_event_callback(gdb_target_callback_event_handler, connection);
846
847         /* remove the initial ACK from the incoming buffer */
848         if ((retval = gdb_get_char(connection, &initial_ack)) != ERROR_OK)
849                 return retval;
850
851         /* FIX!!!??? would we actually ever receive a + here???
852          * Not observed.
853          */
854         if (initial_ack != '+')
855                 gdb_putback_char(connection, initial_ack);
856         target_call_event_callbacks(gdb_service->target, TARGET_EVENT_GDB_ATTACH);
857
858         gdb_actual_connections++;
859         LOG_DEBUG("New GDB Connection: %d, Target %s, state: %s",
860                   gdb_actual_connections,
861                   target_name(gdb_service->target),
862                   target_state_name(gdb_service->target));
863
864         return ERROR_OK;
865 }
866
867 static int gdb_connection_closed(struct connection *connection)
868 {
869         struct gdb_service *gdb_service = connection->service->priv;
870         struct gdb_connection *gdb_connection = connection->priv;
871
872         /* we're done forwarding messages. Tear down callback before
873          * cleaning up connection.
874          */
875         log_remove_callback(gdb_log_callback, connection);
876
877         gdb_actual_connections--;
878         LOG_DEBUG("GDB Close, Target: %s, state: %s, gdb_actual_connections=%d",
879                   target_name(gdb_service->target),
880                   target_state_name(gdb_service->target),
881                   gdb_actual_connections);
882
883         /* see if an image built with vFlash commands is left */
884         if (gdb_connection->vflash_image)
885         {
886                 image_close(gdb_connection->vflash_image);
887                 free(gdb_connection->vflash_image);
888                 gdb_connection->vflash_image = NULL;
889         }
890
891         /* if this connection registered a debug-message receiver delete it */
892         delete_debug_msg_receiver(connection->cmd_ctx, gdb_service->target);
893
894         if (connection->priv)
895         {
896                 free(connection->priv);
897                 connection->priv = NULL;
898         }
899         else
900         {
901                 LOG_ERROR("BUG: connection->priv == NULL");
902         }
903
904
905         target_unregister_event_callback(gdb_target_callback_event_handler, connection);
906
907         target_call_event_callbacks(gdb_service->target, TARGET_EVENT_GDB_END);
908
909         target_call_event_callbacks(gdb_service->target, TARGET_EVENT_GDB_DETACH);
910
911         return ERROR_OK;
912 }
913
914 static void gdb_send_error(struct connection *connection, uint8_t the_error)
915 {
916         char err[4];
917         snprintf(err, 4, "E%2.2X", the_error);
918         gdb_put_packet(connection, err, 3);
919 }
920
921 static int gdb_last_signal_packet(struct connection *connection,
922                 struct target *target, char* packet, int packet_size)
923 {
924         char sig_reply[4];
925         int signal;
926
927         signal = gdb_last_signal(target);
928
929         snprintf(sig_reply, 4, "S%2.2x", signal);
930         gdb_put_packet(connection, sig_reply, 3);
931
932         return ERROR_OK;
933 }
934
935 static int gdb_reg_pos(struct target *target, int pos, int len)
936 {
937         if (target->endianness == TARGET_LITTLE_ENDIAN)
938                 return pos;
939         else
940                 return len - 1 - pos;
941 }
942
943 /* Convert register to string of bytes. NB! The # of bits in the
944  * register might be non-divisible by 8(a byte), in which
945  * case an entire byte is shown.
946  *
947  * NB! the format on the wire is the target endianness
948  *
949  * The format of reg->value is little endian
950  *
951  */
952 static void gdb_str_to_target(struct target *target,
953                 char *tstr, struct reg *reg)
954 {
955         int i;
956
957         uint8_t *buf;
958         int buf_len;
959         buf = reg->value;
960         buf_len = DIV_ROUND_UP(reg->size, 8);
961
962         for (i = 0; i < buf_len; i++)
963         {
964                 int j = gdb_reg_pos(target, i, buf_len);
965                 tstr[i*2]   = DIGITS[(buf[j]>>4) & 0xf];
966                 tstr[i*2 + 1] = DIGITS[buf[j]&0xf];
967         }
968 }
969
970 static int hextoint(int c)
971 {
972         if (c>='0'&&c<='9')
973         {
974                 return c-'0';
975         }
976         c = toupper(c);
977         if (c>='A'&&c<='F')
978         {
979                 return c-'A'+10;
980         }
981         LOG_ERROR("BUG: invalid register value %08x", c);
982         return 0;
983 }
984
985 /* copy over in register buffer */
986 static void gdb_target_to_reg(struct target *target,
987                 char *tstr, int str_len, uint8_t *bin)
988 {
989         if (str_len % 2)
990         {
991                 LOG_ERROR("BUG: gdb value with uneven number of characters encountered");
992                 exit(-1);
993         }
994
995         int i;
996         for (i = 0; i < str_len; i += 2)
997         {
998                 uint8_t t = hextoint(tstr[i]) << 4;
999                 t |= hextoint(tstr[i + 1]);
1000
1001                 int j = gdb_reg_pos(target, i/2, str_len/2);
1002                 bin[j] = t;
1003         }
1004 }
1005
1006 static int gdb_get_registers_packet(struct connection *connection,
1007                 struct target *target, char* packet, int packet_size)
1008 {
1009         struct reg **reg_list;
1010         int reg_list_size;
1011         int retval;
1012         int reg_packet_size = 0;
1013         char *reg_packet;
1014         char *reg_packet_p;
1015         int i;
1016
1017 #ifdef _DEBUG_GDB_IO_
1018         LOG_DEBUG("-");
1019 #endif
1020
1021         if ((retval = target_get_gdb_reg_list(target, &reg_list, &reg_list_size)) != ERROR_OK)
1022         {
1023                 return gdb_error(connection, retval);
1024         }
1025
1026         for (i = 0; i < reg_list_size; i++)
1027         {
1028                 reg_packet_size += reg_list[i]->size;
1029         }
1030
1031         reg_packet = malloc(DIV_ROUND_UP(reg_packet_size, 8) * 2);
1032         reg_packet_p = reg_packet;
1033
1034         for (i = 0; i < reg_list_size; i++)
1035         {
1036                 gdb_str_to_target(target, reg_packet_p, reg_list[i]);
1037                 reg_packet_p += DIV_ROUND_UP(reg_list[i]->size, 8) * 2;
1038         }
1039
1040 #ifdef _DEBUG_GDB_IO_
1041         {
1042                 char *reg_packet_p;
1043                 reg_packet_p = strndup(reg_packet, DIV_ROUND_UP(reg_packet_size, 8) * 2);
1044                 LOG_DEBUG("reg_packet: %s", reg_packet_p);
1045                 free(reg_packet_p);
1046         }
1047 #endif
1048
1049         gdb_put_packet(connection, reg_packet, DIV_ROUND_UP(reg_packet_size, 8) * 2);
1050         free(reg_packet);
1051
1052         free(reg_list);
1053
1054         return ERROR_OK;
1055 }
1056
1057 static int gdb_set_registers_packet(struct connection *connection,
1058                 struct target *target, char *packet, int packet_size)
1059 {
1060         int i;
1061         struct reg **reg_list;
1062         int reg_list_size;
1063         int retval;
1064         char *packet_p;
1065
1066 #ifdef _DEBUG_GDB_IO_
1067         LOG_DEBUG("-");
1068 #endif
1069
1070         /* skip command character */
1071         packet++;
1072         packet_size--;
1073
1074         if (packet_size % 2)
1075         {
1076                 LOG_WARNING("GDB set_registers packet with uneven characters received, dropping connection");
1077                 return ERROR_SERVER_REMOTE_CLOSED;
1078         }
1079
1080         if ((retval = target_get_gdb_reg_list(target, &reg_list, &reg_list_size)) != ERROR_OK)
1081         {
1082                 return gdb_error(connection, retval);
1083         }
1084
1085         packet_p = packet;
1086         for (i = 0; i < reg_list_size; i++)
1087         {
1088                 uint8_t *bin_buf;
1089                 int chars = (DIV_ROUND_UP(reg_list[i]->size, 8) * 2);
1090
1091                 if (packet_p + chars > packet + packet_size)
1092                 {
1093                         LOG_ERROR("BUG: register packet is too small for registers");
1094                 }
1095
1096                 bin_buf = malloc(DIV_ROUND_UP(reg_list[i]->size, 8));
1097                 gdb_target_to_reg(target, packet_p, chars, bin_buf);
1098
1099                 reg_list[i]->type->set(reg_list[i], bin_buf);
1100
1101                 /* advance packet pointer */
1102                 packet_p += chars;
1103
1104
1105                 free(bin_buf);
1106         }
1107
1108         /* free struct reg *reg_list[] array allocated by get_gdb_reg_list */
1109         free(reg_list);
1110
1111         gdb_put_packet(connection, "OK", 2);
1112
1113         return ERROR_OK;
1114 }
1115
1116 static int gdb_get_register_packet(struct connection *connection,
1117                 struct target *target, char *packet, int packet_size)
1118 {
1119         char *reg_packet;
1120         int reg_num = strtoul(packet + 1, NULL, 16);
1121         struct reg **reg_list;
1122         int reg_list_size;
1123         int retval;
1124
1125 #ifdef _DEBUG_GDB_IO_
1126         LOG_DEBUG("-");
1127 #endif
1128
1129         if ((retval = target_get_gdb_reg_list(target, &reg_list, &reg_list_size)) != ERROR_OK)
1130         {
1131                 return gdb_error(connection, retval);
1132         }
1133
1134         if (reg_list_size <= reg_num)
1135         {
1136                 LOG_ERROR("gdb requested a non-existing register");
1137                 exit(-1);
1138         }
1139
1140         reg_packet = malloc(DIV_ROUND_UP(reg_list[reg_num]->size, 8) * 2);
1141
1142         gdb_str_to_target(target, reg_packet, reg_list[reg_num]);
1143
1144         gdb_put_packet(connection, reg_packet, DIV_ROUND_UP(reg_list[reg_num]->size, 8) * 2);
1145
1146         free(reg_list);
1147         free(reg_packet);
1148
1149         return ERROR_OK;
1150 }
1151
1152 static int gdb_set_register_packet(struct connection *connection,
1153                 struct target *target, char *packet, int packet_size)
1154 {
1155         char *separator;
1156         uint8_t *bin_buf;
1157         int reg_num = strtoul(packet + 1, &separator, 16);
1158         struct reg **reg_list;
1159         int reg_list_size;
1160         int retval;
1161
1162         LOG_DEBUG("-");
1163
1164         if ((retval = target_get_gdb_reg_list(target, &reg_list, &reg_list_size)) != ERROR_OK)
1165         {
1166                 return gdb_error(connection, retval);
1167         }
1168
1169         if (reg_list_size < reg_num)
1170         {
1171                 LOG_ERROR("gdb requested a non-existing register");
1172                 return ERROR_SERVER_REMOTE_CLOSED;
1173         }
1174
1175         if (*separator != '=')
1176         {
1177                 LOG_ERROR("GDB 'set register packet', but no '=' following the register number");
1178                 return ERROR_SERVER_REMOTE_CLOSED;
1179         }
1180
1181         /* convert from GDB-string (target-endian) to hex-string (big-endian) */
1182         bin_buf = malloc(DIV_ROUND_UP(reg_list[reg_num]->size, 8));
1183         int chars = (DIV_ROUND_UP(reg_list[reg_num]->size, 8) * 2);
1184
1185         /* fix!!! add some sanity checks on packet size here */
1186
1187         gdb_target_to_reg(target, separator + 1, chars, bin_buf);
1188
1189         reg_list[reg_num]->type->set(reg_list[reg_num], bin_buf);
1190
1191         gdb_put_packet(connection, "OK", 2);
1192
1193         free(bin_buf);
1194         free(reg_list);
1195
1196         return ERROR_OK;
1197 }
1198
1199 static int gdb_error(struct connection *connection, int retval)
1200 {
1201         switch (retval)
1202         {
1203                 case ERROR_TARGET_DATA_ABORT:
1204                         gdb_send_error(connection, EIO);
1205                         break;
1206                 case ERROR_TARGET_TRANSLATION_FAULT:
1207                         gdb_send_error(connection, EFAULT);
1208                         break;
1209                 case ERROR_TARGET_UNALIGNED_ACCESS:
1210                         gdb_send_error(connection, EFAULT);
1211                         break;
1212                 case ERROR_TARGET_NOT_HALTED:
1213                         gdb_send_error(connection, EFAULT);
1214                         break;
1215                 default:
1216                         /* This could be that the target reset itself. */
1217                         LOG_ERROR("unexpected error %i", retval);
1218                         gdb_send_error(connection, EFAULT);
1219                         break;
1220         }
1221
1222         return ERROR_OK;
1223 }
1224
1225 /* We don't have to worry about the default 2 second timeout for GDB packets,
1226  * because GDB breaks up large memory reads into smaller reads.
1227  *
1228  * 8191 bytes by the looks of it. Why 8191 bytes instead of 8192?????
1229  */
1230 static int gdb_read_memory_packet(struct connection *connection,
1231                 struct target *target, char *packet, int packet_size)
1232 {
1233         char *separator;
1234         uint32_t addr = 0;
1235         uint32_t len = 0;
1236
1237         uint8_t *buffer;
1238         char *hex_buffer;
1239
1240         int retval = ERROR_OK;
1241
1242         /* skip command character */
1243         packet++;
1244
1245         addr = strtoul(packet, &separator, 16);
1246
1247         if (*separator != ',')
1248         {
1249                 LOG_ERROR("incomplete read memory packet received, dropping connection");
1250                 return ERROR_SERVER_REMOTE_CLOSED;
1251         }
1252
1253         len = strtoul(separator + 1, NULL, 16);
1254
1255         buffer = malloc(len);
1256
1257         LOG_DEBUG("addr: 0x%8.8" PRIx32 ", len: 0x%8.8" PRIx32 "", addr, len);
1258
1259         retval = target_read_buffer(target, addr, len, buffer);
1260
1261         if ((retval != ERROR_OK)&&!gdb_report_data_abort)
1262         {
1263                 /* TODO : Here we have to lie and send back all zero's lest stack traces won't work.
1264                  * At some point this might be fixed in GDB, in which case this code can be removed.
1265                  *
1266                  * OpenOCD developers are acutely aware of this problem, but there is nothing
1267                  * gained by involving the user in this problem that hopefully will get resolved
1268                  * eventually
1269                  *
1270                  * http://sourceware.org/cgi-bin/gnatsweb.pl?cmd = view%20audit-trail&database = gdb&pr = 2395
1271                  *
1272                  * For now, the default is to fix up things to make current GDB versions work.
1273                  * This can be overwritten using the gdb_report_data_abort <'enable'|'disable'> command.
1274                  */
1275                 memset(buffer, 0, len);
1276                 retval = ERROR_OK;
1277         }
1278
1279         if (retval == ERROR_OK)
1280         {
1281                 hex_buffer = malloc(len * 2 + 1);
1282
1283                 uint32_t i;
1284                 for (i = 0; i < len; i++)
1285                 {
1286                         uint8_t t = buffer[i];
1287                         hex_buffer[2 * i] = DIGITS[(t >> 4) & 0xf];
1288                         hex_buffer[2 * i + 1] = DIGITS[t & 0xf];
1289                 }
1290
1291                 gdb_put_packet(connection, hex_buffer, len * 2);
1292
1293                 free(hex_buffer);
1294         }
1295         else
1296         {
1297                 retval = gdb_error(connection, retval);
1298         }
1299
1300         free(buffer);
1301
1302         return retval;
1303 }
1304
1305 static int gdb_write_memory_packet(struct connection *connection,
1306                 struct target *target, char *packet, int packet_size)
1307 {
1308         char *separator;
1309         uint32_t addr = 0;
1310         uint32_t len = 0;
1311
1312         uint8_t *buffer;
1313
1314         uint32_t i;
1315         int retval;
1316
1317         /* skip command character */
1318         packet++;
1319
1320         addr = strtoul(packet, &separator, 16);
1321
1322         if (*separator != ',')
1323         {
1324                 LOG_ERROR("incomplete write memory packet received, dropping connection");
1325                 return ERROR_SERVER_REMOTE_CLOSED;
1326         }
1327
1328         len = strtoul(separator + 1, &separator, 16);
1329
1330         if (*(separator++) != ':')
1331         {
1332                 LOG_ERROR("incomplete write memory packet received, dropping connection");
1333                 return ERROR_SERVER_REMOTE_CLOSED;
1334         }
1335
1336         buffer = malloc(len);
1337
1338         LOG_DEBUG("addr: 0x%8.8" PRIx32 ", len: 0x%8.8" PRIx32 "", addr, len);
1339
1340         for (i = 0; i < len; i++)
1341         {
1342                 uint32_t tmp;
1343                 sscanf(separator + 2*i, "%2" SCNx32 , &tmp);
1344                 buffer[i] = tmp;
1345         }
1346
1347         retval = target_write_buffer(target, addr, len, buffer);
1348
1349         if (retval == ERROR_OK)
1350         {
1351                 gdb_put_packet(connection, "OK", 2);
1352         }
1353         else
1354         {
1355                 retval = gdb_error(connection, retval);
1356         }
1357
1358         free(buffer);
1359
1360         return retval;
1361 }
1362
1363 static int gdb_write_memory_binary_packet(struct connection *connection,
1364                 struct target *target, char *packet, int packet_size)
1365 {
1366         char *separator;
1367         uint32_t addr = 0;
1368         uint32_t len = 0;
1369
1370         int retval = ERROR_OK;
1371
1372         /* skip command character */
1373         packet++;
1374
1375         addr = strtoul(packet, &separator, 16);
1376
1377         if (*separator != ',')
1378         {
1379                 LOG_ERROR("incomplete write memory binary packet received, dropping connection");
1380                 return ERROR_SERVER_REMOTE_CLOSED;
1381         }
1382
1383         len = strtoul(separator + 1, &separator, 16);
1384
1385         if (*(separator++) != ':')
1386         {
1387                 LOG_ERROR("incomplete write memory binary packet received, dropping connection");
1388                 return ERROR_SERVER_REMOTE_CLOSED;
1389         }
1390
1391         struct gdb_connection *gdb_connection = connection->priv;
1392
1393         if (gdb_connection->mem_write_error)
1394         {
1395                 retval = ERROR_FAIL;
1396                 /* now that we have reported the memory write error, we can clear the condition */
1397                 gdb_connection->mem_write_error = false;
1398         }
1399
1400         /* By replying the packet *immediately* GDB will send us a new packet
1401          * while we write the last one to the target.
1402          */
1403         if (retval == ERROR_OK)
1404         {
1405                 gdb_put_packet(connection, "OK", 2);
1406         }
1407         else
1408         {
1409                 if ((retval = gdb_error(connection, retval)) != ERROR_OK)
1410                         return retval;
1411         }
1412
1413         if (len)
1414         {
1415                 LOG_DEBUG("addr: 0x%8.8" PRIx32 ", len: 0x%8.8" PRIx32 "", addr, len);
1416
1417                 retval = target_write_buffer(target, addr, len, (uint8_t*)separator);
1418                 if (retval != ERROR_OK)
1419                 {
1420                         gdb_connection->mem_write_error = true;
1421                 }
1422         }
1423
1424         return ERROR_OK;
1425 }
1426
1427 static int gdb_step_continue_packet(struct connection *connection,
1428                 struct target *target, char *packet, int packet_size)
1429 {
1430         int current = 0;
1431         uint32_t address = 0x0;
1432         int retval = ERROR_OK;
1433
1434         LOG_DEBUG("-");
1435
1436         if (packet_size > 1)
1437         {
1438                 packet[packet_size] = 0;
1439                 address = strtoul(packet + 1, NULL, 16);
1440         }
1441         else
1442         {
1443                 current = 1;
1444         }
1445
1446         if (packet[0] == 'c')
1447         {
1448                 LOG_DEBUG("continue");
1449                 target_handle_event(target, TARGET_EVENT_OLD_pre_resume);
1450                 retval = target_resume(target, current, address, 0, 0); /* resume at current address, don't handle breakpoints, not debugging */
1451         }
1452         else if (packet[0] == 's')
1453         {
1454                 LOG_DEBUG("step");
1455                 /* step at current or address, don't handle breakpoints */
1456                 retval = target_step(target, current, address, 0);
1457         }
1458         return retval;
1459 }
1460
1461 static int gdb_breakpoint_watchpoint_packet(struct connection *connection,
1462                 struct target *target, char *packet, int packet_size)
1463 {
1464         int type;
1465         enum breakpoint_type bp_type = BKPT_SOFT /* dummy init to avoid warning */;
1466         enum watchpoint_rw wp_type = WPT_READ /* dummy init to avoid warning */;
1467         uint32_t address;
1468         uint32_t size;
1469         char *separator;
1470         int retval;
1471
1472         LOG_DEBUG("-");
1473
1474         type = strtoul(packet + 1, &separator, 16);
1475
1476         if (type == 0)  /* memory breakpoint */
1477                 bp_type = BKPT_SOFT;
1478         else if (type == 1) /* hardware breakpoint */
1479                 bp_type = BKPT_HARD;
1480         else if (type == 2) /* write watchpoint */
1481                 wp_type = WPT_WRITE;
1482         else if (type == 3) /* read watchpoint */
1483                 wp_type = WPT_READ;
1484         else if (type == 4) /* access watchpoint */
1485                 wp_type = WPT_ACCESS;
1486         else
1487         {
1488                 LOG_ERROR("invalid gdb watch/breakpoint type(%d), dropping connection", type);
1489                 return ERROR_SERVER_REMOTE_CLOSED;
1490         }
1491
1492
1493         if (gdb_breakpoint_override && ((bp_type == BKPT_SOFT)||(bp_type == BKPT_HARD)))
1494         {
1495                 bp_type = gdb_breakpoint_override_type;
1496         }
1497
1498         if (*separator != ',')
1499         {
1500                 LOG_ERROR("incomplete breakpoint/watchpoint packet received, dropping connection");
1501                 return ERROR_SERVER_REMOTE_CLOSED;
1502         }
1503
1504         address = strtoul(separator + 1, &separator, 16);
1505
1506         if (*separator != ',')
1507         {
1508                 LOG_ERROR("incomplete breakpoint/watchpoint packet received, dropping connection");
1509                 return ERROR_SERVER_REMOTE_CLOSED;
1510         }
1511
1512         size = strtoul(separator + 1, &separator, 16);
1513
1514         switch (type)
1515         {
1516                 case 0:
1517                 case 1:
1518                         if (packet[0] == 'Z')
1519                         {
1520                                 if ((retval = breakpoint_add(target, address, size, bp_type)) != ERROR_OK)
1521                                 {
1522                                         if ((retval = gdb_error(connection, retval)) != ERROR_OK)
1523                                                 return retval;
1524                                 }
1525                                 else
1526                                 {
1527                                         gdb_put_packet(connection, "OK", 2);
1528                                 }
1529                         }
1530                         else
1531                         {
1532                                 breakpoint_remove(target, address);
1533                                 gdb_put_packet(connection, "OK", 2);
1534                         }
1535                         break;
1536                 case 2:
1537                 case 3:
1538                 case 4:
1539                 {
1540                         if (packet[0] == 'Z')
1541                         {
1542                                 if ((retval = watchpoint_add(target, address, size, wp_type, 0, 0xffffffffu)) != ERROR_OK)
1543                                 {
1544                                         if ((retval = gdb_error(connection, retval)) != ERROR_OK)
1545                                                 return retval;
1546                                 }
1547                                 else
1548                                 {
1549                                         gdb_put_packet(connection, "OK", 2);
1550                                 }
1551                         }
1552                         else
1553                         {
1554                                 watchpoint_remove(target, address);
1555                                 gdb_put_packet(connection, "OK", 2);
1556                         }
1557                         break;
1558                 }
1559                 default:
1560                         break;
1561         }
1562
1563         return ERROR_OK;
1564 }
1565
1566 /* print out a string and allocate more space as needed,
1567  * mainly used for XML at this point
1568  */
1569 static void xml_printf(int *retval, char **xml, int *pos, int *size,
1570                 const char *fmt, ...)
1571 {
1572         if (*retval != ERROR_OK)
1573         {
1574                 return;
1575         }
1576         int first = 1;
1577
1578         for (;;)
1579         {
1580                 if ((*xml == NULL) || (!first))
1581                 {
1582                         /* start by 0 to exercise all the code paths.
1583                          * Need minimum 2 bytes to fit 1 char and 0 terminator. */
1584
1585                         *size = *size * 2 + 2;
1586                         char *t = *xml;
1587                         *xml = realloc(*xml, *size);
1588                         if (*xml == NULL)
1589                         {
1590                                 if (t)
1591                                         free(t);
1592                                 *retval = ERROR_SERVER_REMOTE_CLOSED;
1593                                 return;
1594                         }
1595                 }
1596
1597                 va_list ap;
1598                 int ret;
1599                 va_start(ap, fmt);
1600                 ret = vsnprintf(*xml + *pos, *size - *pos, fmt, ap);
1601                 va_end(ap);
1602                 if ((ret > 0) && ((ret + 1) < *size - *pos))
1603                 {
1604                         *pos += ret;
1605                         return;
1606                 }
1607                 /* there was just enough or not enough space, allocate more. */
1608                 first = 0;
1609         }
1610 }
1611
1612 static int decode_xfer_read(char *buf, char **annex, int *ofs, unsigned int *len)
1613 {
1614         char *separator;
1615
1616         /* Extract and NUL-terminate the annex. */
1617         *annex = buf;
1618         while (*buf && *buf != ':')
1619                 buf++;
1620         if (*buf == '\0')
1621                 return -1;
1622         *buf++ = 0;
1623
1624         /* After the read marker and annex, qXfer looks like a
1625          * traditional 'm' packet. */
1626
1627         *ofs = strtoul(buf, &separator, 16);
1628
1629         if (*separator != ',')
1630                 return -1;
1631
1632         *len = strtoul(separator + 1, NULL, 16);
1633
1634         return 0;
1635 }
1636
1637 static int compare_bank (const void * a, const void * b)
1638 {
1639         struct flash_bank *b1, *b2;
1640         b1=*((struct flash_bank **)a);
1641         b2=*((struct flash_bank **)b);
1642
1643         if (b1->base == b2->base)
1644         {
1645                 return 0;
1646         } else if (b1->base > b2->base)
1647         {
1648                 return 1;
1649         } else
1650         {
1651                 return -1;
1652         }
1653 }
1654
1655 static int gdb_memory_map(struct connection *connection,
1656                 struct target *target, char *packet, int packet_size)
1657 {
1658         /* We get away with only specifying flash here. Regions that are not
1659          * specified are treated as if we provided no memory map(if not we
1660          * could detect the holes and mark them as RAM).
1661          * Normally we only execute this code once, but no big deal if we
1662          * have to regenerate it a couple of times.
1663          */
1664
1665         struct flash_bank *p;
1666         char *xml = NULL;
1667         int size = 0;
1668         int pos = 0;
1669         int retval = ERROR_OK;
1670         struct flash_bank **banks;
1671         int offset;
1672         int length;
1673         char *separator;
1674         uint32_t ram_start = 0;
1675         int i;
1676
1677         /* skip command character */
1678         packet += 23;
1679
1680         offset = strtoul(packet, &separator, 16);
1681         length = strtoul(separator + 1, &separator, 16);
1682
1683         xml_printf(&retval, &xml, &pos, &size, "<memory-map>\n");
1684
1685         /* Sort banks in ascending order.  We need to report non-flash
1686          * memory as ram (or rather read/write) by default for GDB, since
1687          * it has no concept of non-cacheable read/write memory (i/o etc).
1688          *
1689          * FIXME Most non-flash addresses are *NOT* RAM!  Don't lie.
1690          * Current versions of GDB assume unlisted addresses are RAM...
1691          */
1692         banks = malloc(sizeof(struct flash_bank *)*flash_get_bank_count());
1693
1694         for (i = 0; i < flash_get_bank_count(); i++) {
1695                 p = get_flash_bank_by_num(i);
1696                 if (p == NULL) {
1697                         free(banks);
1698                         retval = ERROR_FAIL;
1699                         gdb_send_error(connection, retval);
1700                         return retval;
1701                 }
1702                 banks[i] = p;
1703         }
1704
1705         qsort(banks, flash_get_bank_count(), sizeof(struct flash_bank *),
1706                         compare_bank);
1707
1708         for (i = 0; i < flash_get_bank_count(); i++) {
1709                 int j;
1710                 unsigned sector_size = 0;
1711                 uint32_t start, end;
1712
1713                 p = banks[i];
1714                 start = p->base;
1715                 end = p->base + p->size;
1716
1717                 if (ram_start < p->base)
1718                         xml_printf(&retval, &xml, &pos, &size,
1719                                 "<memory type=\"ram\" start=\"0x%x\" "
1720                                         "length=\"0x%x\"/>\n",
1721                                 ram_start, p->base - ram_start);
1722
1723                 /* Report adjacent groups of same-size sectors.  So for
1724                  * example top boot CFI flash will list an initial region
1725                  * with several large sectors (maybe 128KB) and several
1726                  * smaller ones at the end (maybe 32KB).  STR7 will have
1727                  * regions with 8KB, 32KB, and 64KB sectors; etc.
1728                  */
1729                 for (j = 0; j < p->num_sectors; j++) {
1730                         unsigned group_len;
1731
1732                         /* Maybe start a new group of sectors. */
1733                         if (sector_size == 0) {
1734                                 start = p->base + p->sectors[j].offset;
1735                                 xml_printf(&retval, &xml, &pos, &size,
1736                                         "<memory type=\"flash\" "
1737                                                 "start=\"0x%x\" ",
1738                                         start);
1739                                 sector_size = p->sectors[j].size;
1740                         }
1741
1742                         /* Does this finish a group of sectors?
1743                          * If not, continue an already-started group.
1744                          */
1745                         if (j == p->num_sectors -1)
1746                                 group_len = (p->base + p->size) - start;
1747                         else if (p->sectors[j + 1].size != sector_size)
1748                                 group_len = p->base + p->sectors[j + 1].offset
1749                                                 - start;
1750                         else
1751                                 continue;
1752
1753                         xml_printf(&retval, &xml, &pos, &size,
1754                                 "length=\"0x%x\">\n"
1755                                 "<property name=\"blocksize\">"
1756                                         "0x%x</property>\n"
1757                                 "</memory>\n",
1758                                 group_len,
1759                                 sector_size);
1760                         sector_size = 0;
1761                 }
1762
1763                 ram_start = p->base + p->size;
1764         }
1765
1766         if (ram_start != 0)
1767                 xml_printf(&retval, &xml, &pos, &size,
1768                         "<memory type=\"ram\" start=\"0x%x\" "
1769                                 "length=\"0x%x\"/>\n",
1770                         ram_start, 0-ram_start);
1771         /* ELSE a flash chip could be at the very end of the 32 bit address
1772          * space, in which case ram_start will be precisely 0
1773          */
1774
1775         free(banks);
1776         banks = NULL;
1777
1778         xml_printf(&retval, &xml, &pos, &size, "</memory-map>\n");
1779
1780         if (retval != ERROR_OK) {
1781                 gdb_send_error(connection, retval);
1782                 return retval;
1783         }
1784
1785         if (offset + length > pos)
1786                 length = pos - offset;
1787
1788         char *t = malloc(length + 1);
1789         t[0] = 'l';
1790         memcpy(t + 1, xml + offset, length);
1791         gdb_put_packet(connection, t, length + 1);
1792
1793         free(t);
1794         free(xml);
1795         return ERROR_OK;
1796 }
1797
1798 static int gdb_query_packet(struct connection *connection,
1799         struct target *target, char *packet, int packet_size)
1800 {
1801         struct command_context *cmd_ctx = connection->cmd_ctx;
1802         struct gdb_connection *gdb_connection = connection->priv;
1803
1804         if (strstr(packet, "qRcmd,"))
1805         {
1806                 if (packet_size > 6)
1807                 {
1808                         char *cmd;
1809                         int i;
1810                         cmd = malloc((packet_size - 6)/2 + 1);
1811                         for (i = 0; i < (packet_size - 6)/2; i++)
1812                         {
1813                                 uint32_t tmp;
1814                                 sscanf(packet + 6 + 2*i, "%2" SCNx32 , &tmp);
1815                                 cmd[i] = tmp;
1816                         }
1817                         cmd[(packet_size - 6)/2] = 0x0;
1818
1819                         /* We want to print all debug output to GDB connection */
1820                         log_add_callback(gdb_log_callback, connection);
1821                         target_call_timer_callbacks_now();
1822                         /* some commands need to know the GDB connection, make note of current
1823                          * GDB connection. */
1824                         current_gdb_connection = gdb_connection;
1825                         command_run_line(cmd_ctx, cmd);
1826                         current_gdb_connection = NULL;
1827                         target_call_timer_callbacks_now();
1828                         log_remove_callback(gdb_log_callback, connection);
1829                         free(cmd);
1830                 }
1831                 gdb_put_packet(connection, "OK", 2);
1832                 return ERROR_OK;
1833         }
1834         else if (strstr(packet, "qCRC:"))
1835         {
1836                 if (packet_size > 5)
1837                 {
1838                         int retval;
1839                         char gdb_reply[10];
1840                         char *separator;
1841                         uint32_t checksum;
1842                         uint32_t addr = 0;
1843                         uint32_t len = 0;
1844
1845                         /* skip command character */
1846                         packet += 5;
1847
1848                         addr = strtoul(packet, &separator, 16);
1849
1850                         if (*separator != ',')
1851                         {
1852                                 LOG_ERROR("incomplete read memory packet received, dropping connection");
1853                                 return ERROR_SERVER_REMOTE_CLOSED;
1854                         }
1855
1856                         len = strtoul(separator + 1, NULL, 16);
1857
1858                         retval = target_checksum_memory(target, addr, len, &checksum);
1859
1860                         if (retval == ERROR_OK)
1861                         {
1862                                 snprintf(gdb_reply, 10, "C%8.8" PRIx32 "", checksum);
1863                                 gdb_put_packet(connection, gdb_reply, 9);
1864                         }
1865                         else
1866                         {
1867                                 if ((retval = gdb_error(connection, retval)) != ERROR_OK)
1868                                         return retval;
1869                         }
1870
1871                         return ERROR_OK;
1872                 }
1873         }
1874         else if (strstr(packet, "qSupported"))
1875         {
1876                 /* we currently support packet size and qXfer:memory-map:read (if enabled)
1877                  * disable qXfer:features:read for the moment */
1878                 int retval = ERROR_OK;
1879                 char *buffer = NULL;
1880                 int pos = 0;
1881                 int size = 0;
1882
1883                 xml_printf(&retval, &buffer, &pos, &size,
1884                                 "PacketSize=%x;qXfer:memory-map:read%c;qXfer:features:read-;QStartNoAckMode+",
1885                                 (GDB_BUFFER_SIZE - 1), ((gdb_use_memory_map == 1) && (flash_get_bank_count() > 0)) ? '+' : '-');
1886
1887                 if (retval != ERROR_OK)
1888                 {
1889                         gdb_send_error(connection, 01);
1890                         return ERROR_OK;
1891                 }
1892
1893                 gdb_put_packet(connection, buffer, strlen(buffer));
1894                 free(buffer);
1895
1896                 return ERROR_OK;
1897         }
1898         else if (strstr(packet, "qXfer:memory-map:read::")
1899                         && (flash_get_bank_count() > 0))
1900                 return gdb_memory_map(connection, target, packet, packet_size);
1901         else if (strstr(packet, "qXfer:features:read:"))
1902         {
1903                 char *xml = NULL;
1904                 int size = 0;
1905                 int pos = 0;
1906                 int retval = ERROR_OK;
1907
1908                 int offset;
1909                 unsigned int length;
1910                 char *annex;
1911
1912                 /* skip command character */
1913                 packet += 20;
1914
1915                 if (decode_xfer_read(packet, &annex, &offset, &length) < 0)
1916                 {
1917                         gdb_send_error(connection, 01);
1918                         return ERROR_OK;
1919                 }
1920
1921                 if (strcmp(annex, "target.xml") != 0)
1922                 {
1923                         gdb_send_error(connection, 01);
1924                         return ERROR_OK;
1925                 }
1926
1927                 xml_printf(&retval, &xml, &pos, &size, \
1928                         "l < target version=\"1.0\">\n < architecture > arm</architecture>\n</target>\n");
1929
1930                 if (retval != ERROR_OK)
1931                 {
1932                         gdb_send_error(connection, retval);
1933                         return retval;
1934                 }
1935
1936                 gdb_put_packet(connection, xml, strlen(xml));
1937
1938                 free(xml);
1939                 return ERROR_OK;
1940         }
1941         else if (strstr(packet, "QStartNoAckMode"))
1942         {
1943                 gdb_connection->noack_mode = 1;
1944                 gdb_put_packet(connection, "OK", 2);
1945                 return ERROR_OK;
1946         }
1947
1948         gdb_put_packet(connection, "", 0);
1949         return ERROR_OK;
1950 }
1951
1952 static int gdb_v_packet(struct connection *connection,
1953                 struct target *target, char *packet, int packet_size)
1954 {
1955         struct gdb_connection *gdb_connection = connection->priv;
1956         struct gdb_service *gdb_service = connection->service->priv;
1957         int result;
1958
1959         /* if flash programming disabled - send a empty reply */
1960
1961         if (gdb_flash_program == 0)
1962         {
1963                 gdb_put_packet(connection, "", 0);
1964                 return ERROR_OK;
1965         }
1966
1967         if (strstr(packet, "vFlashErase:"))
1968         {
1969                 unsigned long addr;
1970                 unsigned long length;
1971
1972                 char *parse = packet + 12;
1973                 if (*parse == '\0')
1974                 {
1975                         LOG_ERROR("incomplete vFlashErase packet received, dropping connection");
1976                         return ERROR_SERVER_REMOTE_CLOSED;
1977                 }
1978
1979                 addr = strtoul(parse, &parse, 16);
1980
1981                 if (*(parse++) != ',' || *parse == '\0')
1982                 {
1983                         LOG_ERROR("incomplete vFlashErase packet received, dropping connection");
1984                         return ERROR_SERVER_REMOTE_CLOSED;
1985                 }
1986
1987                 length = strtoul(parse, &parse, 16);
1988
1989                 if (*parse != '\0')
1990                 {
1991                         LOG_ERROR("incomplete vFlashErase packet received, dropping connection");
1992                         return ERROR_SERVER_REMOTE_CLOSED;
1993                 }
1994
1995                 /* assume all sectors need erasing - stops any problems
1996                  * when flash_write is called multiple times */
1997                 flash_set_dirty();
1998
1999                 /* perform any target specific operations before the erase */
2000                 target_call_event_callbacks(gdb_service->target,
2001                                 TARGET_EVENT_GDB_FLASH_ERASE_START);
2002
2003                 /* vFlashErase:addr,length messages require region start and
2004                  * end to be "block" aligned ... if padding is ever needed,
2005                  * GDB will have become dangerously confused.
2006                  */
2007                 result = flash_erase_address_range(gdb_service->target,
2008                                 false, addr, length);
2009
2010                 /* perform any target specific operations after the erase */
2011                 target_call_event_callbacks(gdb_service->target,
2012                                 TARGET_EVENT_GDB_FLASH_ERASE_END);
2013
2014                 /* perform erase */
2015                 if (result != ERROR_OK)
2016                 {
2017                         /* GDB doesn't evaluate the actual error number returned,
2018                          * treat a failed erase as an I/O error
2019                          */
2020                         gdb_send_error(connection, EIO);
2021                         LOG_ERROR("flash_erase returned %i", result);
2022                 }
2023                 else
2024                         gdb_put_packet(connection, "OK", 2);
2025
2026                 return ERROR_OK;
2027         }
2028
2029         if (strstr(packet, "vFlashWrite:"))
2030         {
2031                 int retval;
2032                 unsigned long addr;
2033                 unsigned long length;
2034                 char *parse = packet + 12;
2035
2036                 if (*parse == '\0')
2037                 {
2038                         LOG_ERROR("incomplete vFlashErase packet received, dropping connection");
2039                         return ERROR_SERVER_REMOTE_CLOSED;
2040                 }
2041                 addr = strtoul(parse, &parse, 16);
2042                 if (*(parse++) != ':')
2043                 {
2044                         LOG_ERROR("incomplete vFlashErase packet received, dropping connection");
2045                         return ERROR_SERVER_REMOTE_CLOSED;
2046                 }
2047                 length = packet_size - (parse - packet);
2048
2049                 /* create a new image if there isn't already one */
2050                 if (gdb_connection->vflash_image == NULL)
2051                 {
2052                         gdb_connection->vflash_image = malloc(sizeof(struct image));
2053                         image_open(gdb_connection->vflash_image, "", "build");
2054                 }
2055
2056                 /* create new section with content from packet buffer */
2057                 if ((retval = image_add_section(gdb_connection->vflash_image, addr, length, 0x0, (uint8_t*)parse)) != ERROR_OK)
2058                 {
2059                         return retval;
2060                 }
2061
2062                 gdb_put_packet(connection, "OK", 2);
2063
2064                 return ERROR_OK;
2065         }
2066
2067         if (!strcmp(packet, "vFlashDone"))
2068         {
2069                 uint32_t written;
2070
2071                 /* process the flashing buffer. No need to erase as GDB
2072                  * always issues a vFlashErase first. */
2073                 target_call_event_callbacks(gdb_service->target, TARGET_EVENT_GDB_FLASH_WRITE_START);
2074                 result = flash_write(gdb_service->target, gdb_connection->vflash_image, &written, 0);
2075                 target_call_event_callbacks(gdb_service->target, TARGET_EVENT_GDB_FLASH_WRITE_END);
2076                 if (result != ERROR_OK)
2077                 {
2078                         if (result == ERROR_FLASH_DST_OUT_OF_BANK)
2079                                 gdb_put_packet(connection, "E.memtype", 9);
2080                         else
2081                                 gdb_send_error(connection, EIO);
2082                         }
2083                 else
2084                 {
2085                         LOG_DEBUG("wrote %u bytes from vFlash image to flash", (unsigned)written);
2086                         gdb_put_packet(connection, "OK", 2);
2087                 }
2088
2089                 image_close(gdb_connection->vflash_image);
2090                 free(gdb_connection->vflash_image);
2091                 gdb_connection->vflash_image = NULL;
2092
2093                 return ERROR_OK;
2094         }
2095
2096         gdb_put_packet(connection, "", 0);
2097         return ERROR_OK;
2098 }
2099
2100 static int gdb_detach(struct connection *connection, struct target *target)
2101 {
2102         struct gdb_service *gdb_service = connection->service->priv;
2103
2104         target_call_event_callbacks(gdb_service->target,
2105                         TARGET_EVENT_GDB_DETACH);
2106
2107         return gdb_put_packet(connection, "OK", 2);
2108 }
2109
2110 static void gdb_log_callback(void *priv, const char *file, unsigned line,
2111                 const char *function, const char *string)
2112 {
2113         struct connection *connection = priv;
2114         struct gdb_connection *gdb_con = connection->priv;
2115
2116         if (gdb_con->busy)
2117         {
2118                 /* do not reply this using the O packet */
2119                 return;
2120         }
2121
2122         gdb_output_con(connection, string);
2123 }
2124
2125 static void gdb_sig_halted(struct connection *connection)
2126 {
2127         char sig_reply[4];
2128         snprintf(sig_reply, 4, "T%2.2x", 2);
2129         gdb_put_packet(connection, sig_reply, 3);
2130
2131 }
2132
2133 static int gdb_input_inner(struct connection *connection)
2134 {
2135         /* Do not allocate this on the stack */
2136         static char gdb_packet_buffer[GDB_BUFFER_SIZE];
2137
2138         struct gdb_service *gdb_service = connection->service->priv;
2139         struct target *target = gdb_service->target;
2140         char *packet = gdb_packet_buffer;
2141         int packet_size;
2142         int retval;
2143         struct gdb_connection *gdb_con = connection->priv;
2144         static int extended_protocol = 0;
2145
2146         /* drain input buffer */
2147         do
2148         {
2149                 packet_size = GDB_BUFFER_SIZE-1;
2150                 retval = gdb_get_packet(connection, packet, &packet_size);
2151                 if (retval != ERROR_OK)
2152                         return retval;
2153
2154                 /* terminate with zero */
2155                 packet[packet_size] = 0;
2156
2157                 if (LOG_LEVEL_IS(LOG_LVL_DEBUG)) {
2158                         if (packet[0] == 'X') {
2159                                 // binary packets spew junk into the debug log stream
2160                                 char buf[ 50 ];
2161                                 int x;
2162                                 for (x = 0 ; (x < 49) && (packet[x] != ':') ; x++) {
2163                                         buf[x] = packet[x];
2164                                 }
2165                                 buf[x] = 0;
2166                                 LOG_DEBUG("received packet: '%s:<binary-data>'", buf);
2167                         } else {
2168                                 LOG_DEBUG("received packet: '%s'", packet);
2169                         }
2170                 }
2171
2172                 if (packet_size > 0)
2173                 {
2174                         retval = ERROR_OK;
2175                         switch (packet[0])
2176                         {
2177                                 case 'H':
2178                                         /* Hct... -- set thread
2179                                          * we don't have threads, send empty reply */
2180                                         gdb_put_packet(connection, NULL, 0);
2181                                         break;
2182                                 case 'q':
2183                                 case 'Q':
2184                                         retval = gdb_query_packet(connection,
2185                                                         target, packet,
2186                                                         packet_size);
2187                                         break;
2188                                 case 'g':
2189                                         retval = gdb_get_registers_packet(
2190                                                         connection, target,
2191                                                         packet, packet_size);
2192                                         break;
2193                                 case 'G':
2194                                         retval = gdb_set_registers_packet(
2195                                                         connection, target,
2196                                                         packet, packet_size);
2197                                         break;
2198                                 case 'p':
2199                                         retval = gdb_get_register_packet(
2200                                                         connection, target,
2201                                                         packet, packet_size);
2202                                         break;
2203                                 case 'P':
2204                                         retval = gdb_set_register_packet(
2205                                                         connection, target,
2206                                                         packet, packet_size);
2207                                         break;
2208                                 case 'm':
2209                                         retval = gdb_read_memory_packet(
2210                                                         connection, target,
2211                                                         packet, packet_size);
2212                                         break;
2213                                 case 'M':
2214                                         retval = gdb_write_memory_packet(
2215                                                         connection, target,
2216                                                         packet, packet_size);
2217                                         break;
2218                                 case 'z':
2219                                 case 'Z':
2220                                         retval = gdb_breakpoint_watchpoint_packet(connection, target, packet, packet_size);
2221                                         break;
2222                                 case '?':
2223                                         gdb_last_signal_packet(
2224                                                         connection, target,
2225                                                         packet, packet_size);
2226                                         break;
2227                                 case 'c':
2228                                 case 's':
2229                                         {
2230                                                 int retval = ERROR_OK;
2231
2232                                                 struct gdb_connection *gdb_con = connection->priv;
2233                                                 log_add_callback(gdb_log_callback, connection);
2234
2235                                                 if (gdb_con->mem_write_error)
2236                                                 {
2237                                                         LOG_ERROR("Memory write failure!");
2238
2239                                                         /* now that we have reported the memory write error, we can clear the condition */
2240                                                         gdb_con->mem_write_error = false;
2241                                                 }
2242
2243                                                 bool nostep = false;
2244                                                 bool already_running = false;
2245                                                 if (target->state == TARGET_RUNNING)
2246                                                 {
2247                                                         LOG_WARNING("WARNING! The target is already running. "
2248                                                                         "All changes GDB did to registers will be discarded! "
2249                                                                         "Waiting for target to halt.");
2250                                                         already_running = true;
2251                                                 } else if (target->state != TARGET_HALTED)
2252                                                 {
2253                                                         LOG_WARNING("The target is not in the halted nor running stated, stepi/continue ignored.");
2254                                                         nostep = true;
2255                                                 } else if ((packet[0] == 's') && gdb_con->sync)
2256                                                 {
2257                                                         /* Hmm..... when you issue a continue in GDB, then a "stepi" is
2258                                                          * sent by GDB first to OpenOCD, thus defeating the check to
2259                                                          * make only the single stepping have the sync feature...
2260                                                          */
2261                                                         nostep = true;
2262                                                         LOG_WARNING("stepi ignored. GDB will now fetch the register state from the target.");
2263                                                 }
2264                                                 gdb_con->sync = false;
2265
2266                                                 if ((retval!=ERROR_OK) || (!already_running && nostep))
2267                                                 {
2268                                                         /* Either the target isn't in the halted state, then we can't
2269                                                          * step/continue. This might be early setup, etc.
2270                                                          *
2271                                                          * Or we want to allow GDB to pick up a fresh set of
2272                                                          * register values without modifying the target state.
2273                                                          *
2274                                                          */
2275                                                         gdb_sig_halted(connection);
2276
2277                                                         /* stop forwarding log packets! */
2278                                                         log_remove_callback(gdb_log_callback, connection);
2279                                                 } else
2280                                                 {
2281                                                         /* We're running/stepping, in which case we can
2282                                                          * forward log output until the target is halted
2283                                                          */
2284                                                         gdb_con->frontend_state = TARGET_RUNNING;
2285                                                         target_call_event_callbacks(target, TARGET_EVENT_GDB_START);
2286
2287                                                         if (!already_running)
2288                                                         {
2289                                                                 int retval = gdb_step_continue_packet(connection, target, packet, packet_size);
2290                                                                 if (retval != ERROR_OK)
2291                                                                 {
2292                                                                         /* we'll never receive a halted condition... issue a false one.. */
2293                                                                         gdb_frontend_halted(target, connection);
2294                                                                 }
2295                                                         }
2296                                                 }
2297                                         }
2298                                         break;
2299                                 case 'v':
2300                                         retval = gdb_v_packet(
2301                                                         connection, target,
2302                                                         packet, packet_size);
2303                                         break;
2304                                 case 'D':
2305                                         retval = gdb_detach(connection, target);
2306                                         extended_protocol = 0;
2307                                         break;
2308                                 case 'X':
2309                                         retval = gdb_write_memory_binary_packet(
2310                                                         connection, target,
2311                                                         packet, packet_size);
2312                                         if (retval != ERROR_OK)
2313                                                 return retval;
2314                                         break;
2315                                 case 'k':
2316                                         if (extended_protocol != 0)
2317                                                 break;
2318                                         gdb_put_packet(connection, "OK", 2);
2319                                         return ERROR_SERVER_REMOTE_CLOSED;
2320                                 case '!':
2321                                         /* handle extended remote protocol */
2322                                         extended_protocol = 1;
2323                                         gdb_put_packet(connection, "OK", 2);
2324                                         break;
2325                                 case 'R':
2326                                         /* handle extended restart packet */
2327                                         breakpoint_clear_target(gdb_service->target);
2328                                         watchpoint_clear_target(gdb_service->target);
2329                                         command_run_linef(connection->cmd_ctx,
2330                                                         "ocd_gdb_restart %s",
2331                                                         target_name(target));
2332                                         break;
2333                                 default:
2334                                         /* ignore unknown packets */
2335                                         LOG_DEBUG("ignoring 0x%2.2x packet", packet[0]);
2336                                         gdb_put_packet(connection, NULL, 0);
2337                                         break;
2338                         }
2339
2340                         /* if a packet handler returned an error, exit input loop */
2341                         if (retval != ERROR_OK)
2342                                 return retval;
2343                 }
2344
2345                 if (gdb_con->ctrl_c)
2346                 {
2347                         if (target->state == TARGET_RUNNING)
2348                         {
2349                                 retval = target_halt(target);
2350                                 if (retval != ERROR_OK)
2351                                 {
2352                                         target_call_event_callbacks(target, TARGET_EVENT_GDB_HALT);
2353                                 }
2354                                 gdb_con->ctrl_c = 0;
2355                         } else
2356                         {
2357                                 LOG_INFO("The target is not running when halt was requested, stopping GDB.");
2358                                 target_call_event_callbacks(target, TARGET_EVENT_GDB_HALT);
2359                         }
2360                 }
2361
2362         } while (gdb_con->buf_cnt > 0);
2363
2364         return ERROR_OK;
2365 }
2366
2367 static int gdb_input(struct connection *connection)
2368 {
2369         int retval = gdb_input_inner(connection);
2370         struct gdb_connection *gdb_con = connection->priv;
2371         if (retval == ERROR_SERVER_REMOTE_CLOSED)
2372                 return retval;
2373
2374         /* logging does not propagate the error, yet can set the gdb_con->closed flag */
2375         if (gdb_con->closed)
2376                 return ERROR_SERVER_REMOTE_CLOSED;
2377
2378         /* we'll recover from any other errors(e.g. temporary timeouts, etc.) */
2379         return ERROR_OK;
2380 }
2381
2382 static int gdb_target_start(struct target *target, uint16_t port)
2383 {
2384         bool use_pipes = 0 == port;
2385         struct gdb_service *gdb_service = malloc(sizeof(struct gdb_service));
2386         if (NULL == gdb_service)
2387                 return -ENOMEM;
2388
2389         gdb_service->target = target;
2390
2391         add_service("gdb", use_pipes ? CONNECTION_PIPE : CONNECTION_TCP,
2392                         port, 1, &gdb_new_connection, &gdb_input,
2393                         &gdb_connection_closed, gdb_service);
2394
2395         const char *name = target_name(target);
2396         if (use_pipes)
2397                 LOG_DEBUG("gdb service for target '%s' using pipes", name);
2398         else
2399                 LOG_DEBUG("gdb service for target '%s' on TCP port %u", name, port);
2400         return ERROR_OK;
2401 }
2402
2403 static int gdb_target_add_one(struct target *target)
2404 {
2405         if (gdb_port == 0 && server_use_pipes == 0)
2406         {
2407                 LOG_INFO("gdb port disabled");
2408                 return ERROR_OK;
2409         }
2410         if (0 == gdb_port_next)
2411                 gdb_port_next = gdb_port;
2412
2413         bool use_pipes = server_use_pipes;
2414         static bool server_started_with_pipes = false;
2415         if (server_started_with_pipes)
2416         {
2417                 LOG_WARNING("gdb service permits one target when using pipes");
2418                 if (0 == gdb_port)
2419                         return ERROR_OK;
2420
2421                 use_pipes = false;
2422         }
2423
2424         int e = gdb_target_start(target, use_pipes ? 0 : gdb_port_next);
2425         if (ERROR_OK == e)
2426         {
2427                 server_started_with_pipes |= use_pipes;
2428                 gdb_port_next++;
2429         }
2430         return e;
2431 }
2432
2433 int gdb_target_add_all(struct target *target)
2434 {
2435         if (NULL == target)
2436         {
2437                 LOG_WARNING("gdb services need one or more targets defined");
2438                 return ERROR_OK;
2439         }
2440
2441         while (NULL != target)
2442         {
2443                 int retval = gdb_target_add_one(target);
2444                 if (ERROR_OK != retval)
2445                         return retval;
2446
2447                 target = target->next;
2448         }
2449
2450         return ERROR_OK;
2451 }
2452
2453 COMMAND_HANDLER(handle_gdb_sync_command)
2454 {
2455         if (CMD_ARGC != 0)
2456         {
2457                 return ERROR_COMMAND_SYNTAX_ERROR;
2458         }
2459
2460         if (current_gdb_connection == NULL)
2461         {
2462                 command_print(CMD_CTX,
2463                                 "gdb_sync command can only be run from within gdb using \"monitor gdb_sync\"");
2464                 return ERROR_FAIL;
2465         }
2466
2467         current_gdb_connection->sync = true;
2468
2469         return ERROR_OK;
2470 }
2471
2472 /* daemon configuration command gdb_port */
2473 COMMAND_HANDLER(handle_gdb_port_command)
2474 {
2475         int retval = CALL_COMMAND_HANDLER(server_port_command, &gdb_port);
2476         if (ERROR_OK == retval)
2477                 gdb_port_next = gdb_port;
2478         return retval;
2479 }
2480
2481 COMMAND_HANDLER(handle_gdb_memory_map_command)
2482 {
2483         if (CMD_ARGC == 1)
2484                 COMMAND_PARSE_ENABLE(CMD_ARGV[0], gdb_use_memory_map);
2485
2486         return ERROR_COMMAND_SYNTAX_ERROR;
2487 }
2488
2489 COMMAND_HANDLER(handle_gdb_flash_program_command)
2490 {
2491         if (CMD_ARGC == 1)
2492                 COMMAND_PARSE_ENABLE(CMD_ARGV[0], gdb_flash_program);
2493
2494         return ERROR_COMMAND_SYNTAX_ERROR;
2495 }
2496
2497 COMMAND_HANDLER(handle_gdb_report_data_abort_command)
2498 {
2499         if (CMD_ARGC == 1)
2500                 COMMAND_PARSE_ENABLE(CMD_ARGV[0], gdb_report_data_abort);
2501
2502         return ERROR_COMMAND_SYNTAX_ERROR;
2503 }
2504
2505 /* gdb_breakpoint_override */
2506 COMMAND_HANDLER(handle_gdb_breakpoint_override_command)
2507 {
2508         if (CMD_ARGC == 0)
2509         {
2510
2511         } else if (CMD_ARGC == 1)
2512         {
2513                 gdb_breakpoint_override = 1;
2514                 if (strcmp(CMD_ARGV[0], "hard") == 0)
2515                 {
2516                         gdb_breakpoint_override_type = BKPT_HARD;
2517                 } else if (strcmp(CMD_ARGV[0], "soft") == 0)
2518                 {
2519                         gdb_breakpoint_override_type = BKPT_SOFT;
2520                 } else if (strcmp(CMD_ARGV[0], "disable") == 0)
2521                 {
2522                         gdb_breakpoint_override = 0;
2523                 }
2524         } else
2525         {
2526                 return ERROR_COMMAND_SYNTAX_ERROR;
2527         }
2528         if (gdb_breakpoint_override)
2529         {
2530                 LOG_USER("force %s breakpoints", (gdb_breakpoint_override_type == BKPT_HARD)?"hard":"soft");
2531         } else
2532         {
2533                 LOG_USER("breakpoint type is not overridden");
2534         }
2535
2536         return ERROR_OK;
2537 }
2538
2539 static const struct command_registration gdb_command_handlers[] = {
2540         {
2541                 .name = "gdb_sync",
2542                 .handler = handle_gdb_sync_command,
2543                 .mode = COMMAND_ANY,
2544                 .help = "next stepi will return immediately allowing "
2545                         "GDB to fetch register state without affecting "
2546                         "target state",
2547         },
2548         {
2549                 .name = "gdb_port",
2550                 .handler = handle_gdb_port_command,
2551                 .mode = COMMAND_ANY,
2552                 .help = "Display or specify base port on which to listen "
2553                         "for incoming GDB connections.  "
2554                         "No arguments reports GDB port; zero disables.",
2555                 .usage = "[port_num]",
2556         },
2557         {
2558                 .name = "gdb_memory_map",
2559                 .handler = handle_gdb_memory_map_command,
2560                 .mode = COMMAND_CONFIG,
2561                 .help = "enable or disable memory map",
2562                 .usage = "('enable'|'disable')"
2563         },
2564         {
2565                 .name = "gdb_flash_program",
2566                 .handler = handle_gdb_flash_program_command,
2567                 .mode = COMMAND_CONFIG,
2568                 .help = "enable or disable flash program",
2569                 .usage = "('enable'|'disable')"
2570         },
2571         {
2572                 .name = "gdb_report_data_abort",
2573                 .handler = handle_gdb_report_data_abort_command,
2574                 .mode = COMMAND_CONFIG,
2575                 .help = "enable or disable reporting data aborts",
2576                 .usage = "('enable'|'disable')"
2577         },
2578         {
2579                 .name = "gdb_breakpoint_override",
2580                 .handler = handle_gdb_breakpoint_override_command,
2581                 .mode = COMMAND_ANY,
2582                 .help = "Display or specify type of breakpoint "
2583                         "to be used by gdb 'break' commands.",
2584                 .usage = "('hard'|'soft'|'disable')"
2585         },
2586         COMMAND_REGISTRATION_DONE
2587 };
2588
2589 int gdb_register_commands(struct command_context *cmd_ctx)
2590 {
2591         return register_commands(cmd_ctx, NULL, gdb_command_handlers);
2592 }