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