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