gdb: fix occasional crash when flash probe failed
[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         /* remove the initial ACK from the incoming buffer */
837         if ((retval = gdb_get_char(connection, &initial_ack)) != ERROR_OK)
838                 return retval;
839
840         /* FIX!!!??? would we actually ever receive a + here???
841          * Not observed.
842          */
843         if (initial_ack != '+')
844                 gdb_putback_char(connection, initial_ack);
845         target_call_event_callbacks(gdb_service->target, TARGET_EVENT_GDB_ATTACH);
846
847         if (gdb_use_memory_map)
848         {
849                 /* Connect must fail if the memory map can't be set up correctly.
850                  *
851                  * This will cause an auto_probe to be invoked, which is either
852                  * a no-op or it will fail when the target isn't ready(e.g. not halted).
853                  */
854                 int i;
855                 for (i = 0; i < flash_get_bank_count(); i++)
856                 {
857                         struct flash_bank *p;
858                         retval = get_flash_bank_by_num(i, &p);
859                         if (retval != ERROR_OK)
860                         {
861                                 LOG_ERROR("Connect failed. Consider setting up a gdb-attach event for the target to prepare target for GDB connect, or use 'gdb_memory_map disable'.");
862                                 return retval;
863                         }
864                 }
865         }
866
867         gdb_actual_connections++;
868         LOG_DEBUG("New GDB Connection: %d, Target %s, state: %s",
869                   gdb_actual_connections,
870                   target_name(gdb_service->target),
871                   target_state_name(gdb_service->target));
872
873         /* DANGER! If we fail subsequently, we must remove this handler,
874          * otherwise we occasionally see crashes as the timer can invoke the
875          * callback fn.
876          *
877          * register callback to be informed about target events */
878         target_register_event_callback(gdb_target_callback_event_handler, connection);
879
880         return ERROR_OK;
881 }
882
883 static int gdb_connection_closed(struct connection *connection)
884 {
885         struct gdb_service *gdb_service = connection->service->priv;
886         struct gdb_connection *gdb_connection = connection->priv;
887
888         /* we're done forwarding messages. Tear down callback before
889          * cleaning up connection.
890          */
891         log_remove_callback(gdb_log_callback, connection);
892
893         gdb_actual_connections--;
894         LOG_DEBUG("GDB Close, Target: %s, state: %s, gdb_actual_connections=%d",
895                   target_name(gdb_service->target),
896                   target_state_name(gdb_service->target),
897                   gdb_actual_connections);
898
899         /* see if an image built with vFlash commands is left */
900         if (gdb_connection->vflash_image)
901         {
902                 image_close(gdb_connection->vflash_image);
903                 free(gdb_connection->vflash_image);
904                 gdb_connection->vflash_image = NULL;
905         }
906
907         /* if this connection registered a debug-message receiver delete it */
908         delete_debug_msg_receiver(connection->cmd_ctx, gdb_service->target);
909
910         if (connection->priv)
911         {
912                 free(connection->priv);
913                 connection->priv = NULL;
914         }
915         else
916         {
917                 LOG_ERROR("BUG: connection->priv == NULL");
918         }
919
920
921         target_unregister_event_callback(gdb_target_callback_event_handler, connection);
922
923         target_call_event_callbacks(gdb_service->target, TARGET_EVENT_GDB_END);
924
925         target_call_event_callbacks(gdb_service->target, TARGET_EVENT_GDB_DETACH);
926
927         return ERROR_OK;
928 }
929
930 static void gdb_send_error(struct connection *connection, uint8_t the_error)
931 {
932         char err[4];
933         snprintf(err, 4, "E%2.2X", the_error);
934         gdb_put_packet(connection, err, 3);
935 }
936
937 static int gdb_last_signal_packet(struct connection *connection,
938                 struct target *target, char* packet, int packet_size)
939 {
940         char sig_reply[4];
941         int signal_var;
942
943         signal_var = gdb_last_signal(target);
944
945         snprintf(sig_reply, 4, "S%2.2x", signal_var);
946         gdb_put_packet(connection, sig_reply, 3);
947
948         return ERROR_OK;
949 }
950
951 static int gdb_reg_pos(struct target *target, int pos, int len)
952 {
953         if (target->endianness == TARGET_LITTLE_ENDIAN)
954                 return pos;
955         else
956                 return len - 1 - pos;
957 }
958
959 /* Convert register to string of bytes. NB! The # of bits in the
960  * register might be non-divisible by 8(a byte), in which
961  * case an entire byte is shown.
962  *
963  * NB! the format on the wire is the target endianness
964  *
965  * The format of reg->value is little endian
966  *
967  */
968 static void gdb_str_to_target(struct target *target,
969                 char *tstr, struct reg *reg)
970 {
971         int i;
972
973         uint8_t *buf;
974         int buf_len;
975         buf = reg->value;
976         buf_len = DIV_ROUND_UP(reg->size, 8);
977
978         for (i = 0; i < buf_len; i++)
979         {
980                 int j = gdb_reg_pos(target, i, buf_len);
981                 tstr[i*2]   = DIGITS[(buf[j]>>4) & 0xf];
982                 tstr[i*2 + 1] = DIGITS[buf[j]&0xf];
983         }
984 }
985
986 static int hextoint(int c)
987 {
988         if (c>='0'&&c<='9')
989         {
990                 return c-'0';
991         }
992         c = toupper(c);
993         if (c>='A'&&c<='F')
994         {
995                 return c-'A'+10;
996         }
997         LOG_ERROR("BUG: invalid register value %08x", c);
998         return 0;
999 }
1000
1001 /* copy over in register buffer */
1002 static void gdb_target_to_reg(struct target *target,
1003                 char *tstr, int str_len, uint8_t *bin)
1004 {
1005         if (str_len % 2)
1006         {
1007                 LOG_ERROR("BUG: gdb value with uneven number of characters encountered");
1008                 exit(-1);
1009         }
1010
1011         int i;
1012         for (i = 0; i < str_len; i += 2)
1013         {
1014                 uint8_t t = hextoint(tstr[i]) << 4;
1015                 t |= hextoint(tstr[i + 1]);
1016
1017                 int j = gdb_reg_pos(target, i/2, str_len/2);
1018                 bin[j] = t;
1019         }
1020 }
1021
1022 static int gdb_get_registers_packet(struct connection *connection,
1023                 struct target *target, char* packet, int packet_size)
1024 {
1025         struct reg **reg_list;
1026         int reg_list_size;
1027         int retval;
1028         int reg_packet_size = 0;
1029         char *reg_packet;
1030         char *reg_packet_p;
1031         int i;
1032
1033 #ifdef _DEBUG_GDB_IO_
1034         LOG_DEBUG("-");
1035 #endif
1036
1037         if ((retval = target_get_gdb_reg_list(target, &reg_list, &reg_list_size)) != ERROR_OK)
1038         {
1039                 return gdb_error(connection, retval);
1040         }
1041
1042         for (i = 0; i < reg_list_size; i++)
1043         {
1044                 reg_packet_size += reg_list[i]->size;
1045         }
1046
1047         reg_packet = malloc(DIV_ROUND_UP(reg_packet_size, 8) * 2);
1048         reg_packet_p = reg_packet;
1049
1050         for (i = 0; i < reg_list_size; i++)
1051         {
1052                 gdb_str_to_target(target, reg_packet_p, reg_list[i]);
1053                 reg_packet_p += DIV_ROUND_UP(reg_list[i]->size, 8) * 2;
1054         }
1055
1056 #ifdef _DEBUG_GDB_IO_
1057         {
1058                 char *reg_packet_p;
1059                 reg_packet_p = strndup(reg_packet, DIV_ROUND_UP(reg_packet_size, 8) * 2);
1060                 LOG_DEBUG("reg_packet: %s", reg_packet_p);
1061                 free(reg_packet_p);
1062         }
1063 #endif
1064
1065         gdb_put_packet(connection, reg_packet, DIV_ROUND_UP(reg_packet_size, 8) * 2);
1066         free(reg_packet);
1067
1068         free(reg_list);
1069
1070         return ERROR_OK;
1071 }
1072
1073 static int gdb_set_registers_packet(struct connection *connection,
1074                 struct target *target, char *packet, int packet_size)
1075 {
1076         int i;
1077         struct reg **reg_list;
1078         int reg_list_size;
1079         int retval;
1080         char *packet_p;
1081
1082 #ifdef _DEBUG_GDB_IO_
1083         LOG_DEBUG("-");
1084 #endif
1085
1086         /* skip command character */
1087         packet++;
1088         packet_size--;
1089
1090         if (packet_size % 2)
1091         {
1092                 LOG_WARNING("GDB set_registers packet with uneven characters received, dropping connection");
1093                 return ERROR_SERVER_REMOTE_CLOSED;
1094         }
1095
1096         if ((retval = target_get_gdb_reg_list(target, &reg_list, &reg_list_size)) != ERROR_OK)
1097         {
1098                 return gdb_error(connection, retval);
1099         }
1100
1101         packet_p = packet;
1102         for (i = 0; i < reg_list_size; i++)
1103         {
1104                 uint8_t *bin_buf;
1105                 int chars = (DIV_ROUND_UP(reg_list[i]->size, 8) * 2);
1106
1107                 if (packet_p + chars > packet + packet_size)
1108                 {
1109                         LOG_ERROR("BUG: register packet is too small for registers");
1110                 }
1111
1112                 bin_buf = malloc(DIV_ROUND_UP(reg_list[i]->size, 8));
1113                 gdb_target_to_reg(target, packet_p, chars, bin_buf);
1114
1115                 reg_list[i]->type->set(reg_list[i], bin_buf);
1116
1117                 /* advance packet pointer */
1118                 packet_p += chars;
1119
1120
1121                 free(bin_buf);
1122         }
1123
1124         /* free struct reg *reg_list[] array allocated by get_gdb_reg_list */
1125         free(reg_list);
1126
1127         gdb_put_packet(connection, "OK", 2);
1128
1129         return ERROR_OK;
1130 }
1131
1132 static int gdb_get_register_packet(struct connection *connection,
1133                 struct target *target, char *packet, int packet_size)
1134 {
1135         char *reg_packet;
1136         int reg_num = strtoul(packet + 1, NULL, 16);
1137         struct reg **reg_list;
1138         int reg_list_size;
1139         int retval;
1140
1141 #ifdef _DEBUG_GDB_IO_
1142         LOG_DEBUG("-");
1143 #endif
1144
1145         if ((retval = target_get_gdb_reg_list(target, &reg_list, &reg_list_size)) != ERROR_OK)
1146         {
1147                 return gdb_error(connection, retval);
1148         }
1149
1150         if (reg_list_size <= reg_num)
1151         {
1152                 LOG_ERROR("gdb requested a non-existing register");
1153                 exit(-1);
1154         }
1155
1156         reg_packet = malloc(DIV_ROUND_UP(reg_list[reg_num]->size, 8) * 2);
1157
1158         gdb_str_to_target(target, reg_packet, reg_list[reg_num]);
1159
1160         gdb_put_packet(connection, reg_packet, DIV_ROUND_UP(reg_list[reg_num]->size, 8) * 2);
1161
1162         free(reg_list);
1163         free(reg_packet);
1164
1165         return ERROR_OK;
1166 }
1167
1168 static int gdb_set_register_packet(struct connection *connection,
1169                 struct target *target, char *packet, int packet_size)
1170 {
1171         char *separator;
1172         uint8_t *bin_buf;
1173         int reg_num = strtoul(packet + 1, &separator, 16);
1174         struct reg **reg_list;
1175         int reg_list_size;
1176         int retval;
1177
1178         LOG_DEBUG("-");
1179
1180         if ((retval = target_get_gdb_reg_list(target, &reg_list, &reg_list_size)) != ERROR_OK)
1181         {
1182                 return gdb_error(connection, retval);
1183         }
1184
1185         if (reg_list_size < reg_num)
1186         {
1187                 LOG_ERROR("gdb requested a non-existing register");
1188                 return ERROR_SERVER_REMOTE_CLOSED;
1189         }
1190
1191         if (*separator != '=')
1192         {
1193                 LOG_ERROR("GDB 'set register packet', but no '=' following the register number");
1194                 return ERROR_SERVER_REMOTE_CLOSED;
1195         }
1196
1197         /* convert from GDB-string (target-endian) to hex-string (big-endian) */
1198         bin_buf = malloc(DIV_ROUND_UP(reg_list[reg_num]->size, 8));
1199         int chars = (DIV_ROUND_UP(reg_list[reg_num]->size, 8) * 2);
1200
1201         /* fix!!! add some sanity checks on packet size here */
1202
1203         gdb_target_to_reg(target, separator + 1, chars, bin_buf);
1204
1205         reg_list[reg_num]->type->set(reg_list[reg_num], bin_buf);
1206
1207         gdb_put_packet(connection, "OK", 2);
1208
1209         free(bin_buf);
1210         free(reg_list);
1211
1212         return ERROR_OK;
1213 }
1214
1215 /* No attempt is made to translate the "retval" to
1216  * GDB speak. This has to be done at the calling
1217  * site as no mapping really exists.
1218  */
1219 static int gdb_error(struct connection *connection, int retval)
1220 {
1221         LOG_DEBUG("Reporting %i to GDB as generic error", retval);
1222         gdb_send_error(connection, EFAULT);
1223         return ERROR_OK;
1224 }
1225
1226 /* We don't have to worry about the default 2 second timeout for GDB packets,
1227  * because GDB breaks up large memory reads into smaller reads.
1228  *
1229  * 8191 bytes by the looks of it. Why 8191 bytes instead of 8192?????
1230  */
1231 static int gdb_read_memory_packet(struct connection *connection,
1232                 struct target *target, char *packet, int packet_size)
1233 {
1234         char *separator;
1235         uint32_t addr = 0;
1236         uint32_t len = 0;
1237
1238         uint8_t *buffer;
1239         char *hex_buffer;
1240
1241         int retval = ERROR_OK;
1242
1243         /* skip command character */
1244         packet++;
1245
1246         addr = strtoul(packet, &separator, 16);
1247
1248         if (*separator != ',')
1249         {
1250                 LOG_ERROR("incomplete read memory packet received, dropping connection");
1251                 return ERROR_SERVER_REMOTE_CLOSED;
1252         }
1253
1254         len = strtoul(separator + 1, NULL, 16);
1255
1256         buffer = malloc(len);
1257
1258         LOG_DEBUG("addr: 0x%8.8" PRIx32 ", len: 0x%8.8" PRIx32 "", addr, len);
1259
1260         retval = target_read_buffer(target, addr, len, buffer);
1261
1262         if ((retval != ERROR_OK)&&!gdb_report_data_abort)
1263         {
1264                 /* TODO : Here we have to lie and send back all zero's lest stack traces won't work.
1265                  * At some point this might be fixed in GDB, in which case this code can be removed.
1266                  *
1267                  * OpenOCD developers are acutely aware of this problem, but there is nothing
1268                  * gained by involving the user in this problem that hopefully will get resolved
1269                  * eventually
1270                  *
1271                  * http://sourceware.org/cgi-bin/gnatsweb.pl?cmd = view%20audit-trail&database = gdb&pr = 2395
1272                  *
1273                  * For now, the default is to fix up things to make current GDB versions work.
1274                  * This can be overwritten using the gdb_report_data_abort <'enable'|'disable'> command.
1275                  */
1276                 memset(buffer, 0, len);
1277                 retval = ERROR_OK;
1278         }
1279
1280         if (retval == ERROR_OK)
1281         {
1282                 hex_buffer = malloc(len * 2 + 1);
1283
1284                 uint32_t i;
1285                 for (i = 0; i < len; i++)
1286                 {
1287                         uint8_t t = buffer[i];
1288                         hex_buffer[2 * i] = DIGITS[(t >> 4) & 0xf];
1289                         hex_buffer[2 * i + 1] = DIGITS[t & 0xf];
1290                 }
1291
1292                 gdb_put_packet(connection, hex_buffer, len * 2);
1293
1294                 free(hex_buffer);
1295         }
1296         else
1297         {
1298                 retval = gdb_error(connection, retval);
1299         }
1300
1301         free(buffer);
1302
1303         return retval;
1304 }
1305
1306 static int gdb_write_memory_packet(struct connection *connection,
1307                 struct target *target, char *packet, int packet_size)
1308 {
1309         char *separator;
1310         uint32_t addr = 0;
1311         uint32_t len = 0;
1312
1313         uint8_t *buffer;
1314
1315         uint32_t i;
1316         int retval;
1317
1318         /* skip command character */
1319         packet++;
1320
1321         addr = strtoul(packet, &separator, 16);
1322
1323         if (*separator != ',')
1324         {
1325                 LOG_ERROR("incomplete write memory packet received, dropping connection");
1326                 return ERROR_SERVER_REMOTE_CLOSED;
1327         }
1328
1329         len = strtoul(separator + 1, &separator, 16);
1330
1331         if (*(separator++) != ':')
1332         {
1333                 LOG_ERROR("incomplete write memory packet received, dropping connection");
1334                 return ERROR_SERVER_REMOTE_CLOSED;
1335         }
1336
1337         buffer = malloc(len);
1338
1339         LOG_DEBUG("addr: 0x%8.8" PRIx32 ", len: 0x%8.8" PRIx32 "", addr, len);
1340
1341         for (i = 0; i < len; i++)
1342         {
1343                 uint32_t tmp;
1344                 sscanf(separator + 2*i, "%2" SCNx32 , &tmp);
1345                 buffer[i] = tmp;
1346         }
1347
1348         retval = target_write_buffer(target, addr, len, buffer);
1349
1350         if (retval == ERROR_OK)
1351         {
1352                 gdb_put_packet(connection, "OK", 2);
1353         }
1354         else
1355         {
1356                 retval = gdb_error(connection, retval);
1357         }
1358
1359         free(buffer);
1360
1361         return retval;
1362 }
1363
1364 static int gdb_write_memory_binary_packet(struct connection *connection,
1365                 struct target *target, char *packet, int packet_size)
1366 {
1367         char *separator;
1368         uint32_t addr = 0;
1369         uint32_t len = 0;
1370
1371         int retval = ERROR_OK;
1372
1373         /* skip command character */
1374         packet++;
1375
1376         addr = strtoul(packet, &separator, 16);
1377
1378         if (*separator != ',')
1379         {
1380                 LOG_ERROR("incomplete write memory binary packet received, dropping connection");
1381                 return ERROR_SERVER_REMOTE_CLOSED;
1382         }
1383
1384         len = strtoul(separator + 1, &separator, 16);
1385
1386         if (*(separator++) != ':')
1387         {
1388                 LOG_ERROR("incomplete write memory binary packet received, dropping connection");
1389                 return ERROR_SERVER_REMOTE_CLOSED;
1390         }
1391
1392         struct gdb_connection *gdb_connection = connection->priv;
1393
1394         if (gdb_connection->mem_write_error)
1395         {
1396                 retval = ERROR_FAIL;
1397                 /* now that we have reported the memory write error, we can clear the condition */
1398                 gdb_connection->mem_write_error = false;
1399         }
1400
1401         /* By replying the packet *immediately* GDB will send us a new packet
1402          * while we write the last one to the target.
1403          */
1404         if (retval == ERROR_OK)
1405         {
1406                 gdb_put_packet(connection, "OK", 2);
1407         }
1408         else
1409         {
1410                 if ((retval = gdb_error(connection, retval)) != ERROR_OK)
1411                         return retval;
1412         }
1413
1414         if (len)
1415         {
1416                 LOG_DEBUG("addr: 0x%8.8" PRIx32 ", len: 0x%8.8" PRIx32 "", addr, len);
1417
1418                 retval = target_write_buffer(target, addr, len, (uint8_t*)separator);
1419                 if (retval != ERROR_OK)
1420                 {
1421                         gdb_connection->mem_write_error = true;
1422                 }
1423         }
1424
1425         return ERROR_OK;
1426 }
1427
1428 static int gdb_step_continue_packet(struct connection *connection,
1429                 struct target *target, char *packet, int packet_size)
1430 {
1431         int current = 0;
1432         uint32_t address = 0x0;
1433         int retval = ERROR_OK;
1434
1435         LOG_DEBUG("-");
1436
1437         if (packet_size > 1)
1438         {
1439                 packet[packet_size] = 0;
1440                 address = strtoul(packet + 1, NULL, 16);
1441         }
1442         else
1443         {
1444                 current = 1;
1445         }
1446
1447         if (packet[0] == 'c')
1448         {
1449                 LOG_DEBUG("continue");
1450                 target_handle_event(target, TARGET_EVENT_OLD_pre_resume);
1451                 retval = target_resume(target, current, address, 0, 0); /* resume at current address, don't handle breakpoints, not debugging */
1452         }
1453         else if (packet[0] == 's')
1454         {
1455                 LOG_DEBUG("step");
1456                 /* step at current or address, don't handle breakpoints */
1457                 retval = target_step(target, current, address, 0);
1458         }
1459         return retval;
1460 }
1461
1462 static int gdb_breakpoint_watchpoint_packet(struct connection *connection,
1463                 struct target *target, char *packet, int packet_size)
1464 {
1465         int type;
1466         enum breakpoint_type bp_type = BKPT_SOFT /* dummy init to avoid warning */;
1467         enum watchpoint_rw wp_type = WPT_READ /* dummy init to avoid warning */;
1468         uint32_t address;
1469         uint32_t size;
1470         char *separator;
1471         int retval;
1472
1473         LOG_DEBUG("-");
1474
1475         type = strtoul(packet + 1, &separator, 16);
1476
1477         if (type == 0)  /* memory breakpoint */
1478                 bp_type = BKPT_SOFT;
1479         else if (type == 1) /* hardware breakpoint */
1480                 bp_type = BKPT_HARD;
1481         else if (type == 2) /* write watchpoint */
1482                 wp_type = WPT_WRITE;
1483         else if (type == 3) /* read watchpoint */
1484                 wp_type = WPT_READ;
1485         else if (type == 4) /* access watchpoint */
1486                 wp_type = WPT_ACCESS;
1487         else
1488         {
1489                 LOG_ERROR("invalid gdb watch/breakpoint type(%d), dropping connection", type);
1490                 return ERROR_SERVER_REMOTE_CLOSED;
1491         }
1492
1493
1494         if (gdb_breakpoint_override && ((bp_type == BKPT_SOFT)||(bp_type == BKPT_HARD)))
1495         {
1496                 bp_type = gdb_breakpoint_override_type;
1497         }
1498
1499         if (*separator != ',')
1500         {
1501                 LOG_ERROR("incomplete breakpoint/watchpoint packet received, dropping connection");
1502                 return ERROR_SERVER_REMOTE_CLOSED;
1503         }
1504
1505         address = strtoul(separator + 1, &separator, 16);
1506
1507         if (*separator != ',')
1508         {
1509                 LOG_ERROR("incomplete breakpoint/watchpoint packet received, dropping connection");
1510                 return ERROR_SERVER_REMOTE_CLOSED;
1511         }
1512
1513         size = strtoul(separator + 1, &separator, 16);
1514
1515         switch (type)
1516         {
1517                 case 0:
1518                 case 1:
1519                         if (packet[0] == 'Z')
1520                         {
1521                                 if ((retval = breakpoint_add(target, address, size, bp_type)) != ERROR_OK)
1522                                 {
1523                                         if ((retval = gdb_error(connection, retval)) != ERROR_OK)
1524                                                 return retval;
1525                                 }
1526                                 else
1527                                 {
1528                                         gdb_put_packet(connection, "OK", 2);
1529                                 }
1530                         }
1531                         else
1532                         {
1533                                 breakpoint_remove(target, address);
1534                                 gdb_put_packet(connection, "OK", 2);
1535                         }
1536                         break;
1537                 case 2:
1538                 case 3:
1539                 case 4:
1540                 {
1541                         if (packet[0] == 'Z')
1542                         {
1543                                 if ((retval = watchpoint_add(target, address, size, wp_type, 0, 0xffffffffu)) != ERROR_OK)
1544                                 {
1545                                         if ((retval = gdb_error(connection, retval)) != ERROR_OK)
1546                                                 return retval;
1547                                 }
1548                                 else
1549                                 {
1550                                         gdb_put_packet(connection, "OK", 2);
1551                                 }
1552                         }
1553                         else
1554                         {
1555                                 watchpoint_remove(target, address);
1556                                 gdb_put_packet(connection, "OK", 2);
1557                         }
1558                         break;
1559                 }
1560                 default:
1561                         break;
1562         }
1563
1564         return ERROR_OK;
1565 }
1566
1567 /* print out a string and allocate more space as needed,
1568  * mainly used for XML at this point
1569  */
1570 static void xml_printf(int *retval, char **xml, int *pos, int *size,
1571                 const char *fmt, ...)
1572 {
1573         if (*retval != ERROR_OK)
1574         {
1575                 return;
1576         }
1577         int first = 1;
1578
1579         for (;;)
1580         {
1581                 if ((*xml == NULL) || (!first))
1582                 {
1583                         /* start by 0 to exercise all the code paths.
1584                          * Need minimum 2 bytes to fit 1 char and 0 terminator. */
1585
1586                         *size = *size * 2 + 2;
1587                         char *t = *xml;
1588                         *xml = realloc(*xml, *size);
1589                         if (*xml == NULL)
1590                         {
1591                                 if (t)
1592                                         free(t);
1593                                 *retval = ERROR_SERVER_REMOTE_CLOSED;
1594                                 return;
1595                         }
1596                 }
1597
1598                 va_list ap;
1599                 int ret;
1600                 va_start(ap, fmt);
1601                 ret = vsnprintf(*xml + *pos, *size - *pos, fmt, ap);
1602                 va_end(ap);
1603                 if ((ret > 0) && ((ret + 1) < *size - *pos))
1604                 {
1605                         *pos += ret;
1606                         return;
1607                 }
1608                 /* there was just enough or not enough space, allocate more. */
1609                 first = 0;
1610         }
1611 }
1612
1613 static int decode_xfer_read(char *buf, char **annex, int *ofs, unsigned int *len)
1614 {
1615         char *separator;
1616
1617         /* Extract and NUL-terminate the annex. */
1618         *annex = buf;
1619         while (*buf && *buf != ':')
1620                 buf++;
1621         if (*buf == '\0')
1622                 return -1;
1623         *buf++ = 0;
1624
1625         /* After the read marker and annex, qXfer looks like a
1626          * traditional 'm' packet. */
1627
1628         *ofs = strtoul(buf, &separator, 16);
1629
1630         if (*separator != ',')
1631                 return -1;
1632
1633         *len = strtoul(separator + 1, NULL, 16);
1634
1635         return 0;
1636 }
1637
1638 static int compare_bank (const void * a, const void * b)
1639 {
1640         struct flash_bank *b1, *b2;
1641         b1=*((struct flash_bank **)a);
1642         b2=*((struct flash_bank **)b);
1643
1644         if (b1->base == b2->base)
1645         {
1646                 return 0;
1647         } else if (b1->base > b2->base)
1648         {
1649                 return 1;
1650         } else
1651         {
1652                 return -1;
1653         }
1654 }
1655
1656 static int gdb_memory_map(struct connection *connection,
1657                 struct target *target, char *packet, int packet_size)
1658 {
1659         /* We get away with only specifying flash here. Regions that are not
1660          * specified are treated as if we provided no memory map(if not we
1661          * could detect the holes and mark them as RAM).
1662          * Normally we only execute this code once, but no big deal if we
1663          * have to regenerate it a couple of times.
1664          */
1665
1666         struct flash_bank *p;
1667         char *xml = NULL;
1668         int size = 0;
1669         int pos = 0;
1670         int retval = ERROR_OK;
1671         struct flash_bank **banks;
1672         int offset;
1673         int length;
1674         char *separator;
1675         uint32_t ram_start = 0;
1676         int i;
1677         int target_flash_banks = 0;
1678
1679         /* skip command character */
1680         packet += 23;
1681
1682         offset = strtoul(packet, &separator, 16);
1683         length = strtoul(separator + 1, &separator, 16);
1684
1685         xml_printf(&retval, &xml, &pos, &size, "<memory-map>\n");
1686
1687         /* Sort banks in ascending order.  We need to report non-flash
1688          * memory as ram (or rather read/write) by default for GDB, since
1689          * it has no concept of non-cacheable read/write memory (i/o etc).
1690          *
1691          * FIXME Most non-flash addresses are *NOT* RAM!  Don't lie.
1692          * Current versions of GDB assume unlisted addresses are RAM...
1693          */
1694         banks = malloc(sizeof(struct flash_bank *)*flash_get_bank_count());
1695
1696         for (i = 0; i < flash_get_bank_count(); i++) {
1697                 retval = get_flash_bank_by_num(i, &p);
1698                 if (retval != ERROR_OK)
1699                 {
1700                         free(banks);
1701                         gdb_error(connection, retval);
1702                         return retval;
1703                 }
1704                 if(p->target == target)
1705                         banks[target_flash_banks++] = p;
1706         }
1707
1708         qsort(banks, target_flash_banks, sizeof(struct flash_bank *),
1709                         compare_bank);
1710
1711         for (i = 0; i < flash_get_bank_count(); i++) {
1712                 int j;
1713                 unsigned sector_size = 0;
1714                 uint32_t start, end;
1715
1716                 p = banks[i];
1717                 start = p->base;
1718                 end = p->base + p->size;
1719
1720                 if (ram_start < p->base)
1721                         xml_printf(&retval, &xml, &pos, &size,
1722                                 "<memory type=\"ram\" start=\"0x%x\" "
1723                                         "length=\"0x%x\"/>\n",
1724                                 ram_start, p->base - ram_start);
1725
1726                 /* Report adjacent groups of same-size sectors.  So for
1727                  * example top boot CFI flash will list an initial region
1728                  * with several large sectors (maybe 128KB) and several
1729                  * smaller ones at the end (maybe 32KB).  STR7 will have
1730                  * regions with 8KB, 32KB, and 64KB sectors; etc.
1731                  */
1732                 for (j = 0; j < p->num_sectors; j++) {
1733                         unsigned group_len;
1734
1735                         /* Maybe start a new group of sectors. */
1736                         if (sector_size == 0) {
1737                                 start = p->base + p->sectors[j].offset;
1738                                 xml_printf(&retval, &xml, &pos, &size,
1739                                         "<memory type=\"flash\" "
1740                                                 "start=\"0x%x\" ",
1741                                         start);
1742                                 sector_size = p->sectors[j].size;
1743                         }
1744
1745                         /* Does this finish a group of sectors?
1746                          * If not, continue an already-started group.
1747                          */
1748                         if (j == p->num_sectors -1)
1749                                 group_len = (p->base + p->size) - start;
1750                         else if (p->sectors[j + 1].size != sector_size)
1751                                 group_len = p->base + p->sectors[j + 1].offset
1752                                                 - start;
1753                         else
1754                                 continue;
1755
1756                         xml_printf(&retval, &xml, &pos, &size,
1757                                 "length=\"0x%x\">\n"
1758                                 "<property name=\"blocksize\">"
1759                                         "0x%x</property>\n"
1760                                 "</memory>\n",
1761                                 group_len,
1762                                 sector_size);
1763                         sector_size = 0;
1764                 }
1765
1766                 ram_start = p->base + p->size;
1767         }
1768
1769         if (ram_start != 0)
1770                 xml_printf(&retval, &xml, &pos, &size,
1771                         "<memory type=\"ram\" start=\"0x%x\" "
1772                                 "length=\"0x%x\"/>\n",
1773                         ram_start, 0-ram_start);
1774         /* ELSE a flash chip could be at the very end of the 32 bit address
1775          * space, in which case ram_start will be precisely 0
1776          */
1777
1778         free(banks);
1779         banks = NULL;
1780
1781         xml_printf(&retval, &xml, &pos, &size, "</memory-map>\n");
1782
1783         if (retval != ERROR_OK) {
1784                 gdb_error(connection, retval);
1785                 return retval;
1786         }
1787
1788         if (offset + length > pos)
1789                 length = pos - offset;
1790
1791         char *t = malloc(length + 1);
1792         t[0] = 'l';
1793         memcpy(t + 1, xml + offset, length);
1794         gdb_put_packet(connection, t, length + 1);
1795
1796         free(t);
1797         free(xml);
1798         return ERROR_OK;
1799 }
1800
1801 static int gdb_query_packet(struct connection *connection,
1802         struct target *target, char *packet, int packet_size)
1803 {
1804         struct command_context *cmd_ctx = connection->cmd_ctx;
1805         struct gdb_connection *gdb_connection = connection->priv;
1806
1807         if (strstr(packet, "qRcmd,"))
1808         {
1809                 if (packet_size > 6)
1810                 {
1811                         char *cmd;
1812                         int i;
1813                         cmd = malloc((packet_size - 6)/2 + 1);
1814                         for (i = 0; i < (packet_size - 6)/2; i++)
1815                         {
1816                                 uint32_t tmp;
1817                                 sscanf(packet + 6 + 2*i, "%2" SCNx32 , &tmp);
1818                                 cmd[i] = tmp;
1819                         }
1820                         cmd[(packet_size - 6)/2] = 0x0;
1821
1822                         /* We want to print all debug output to GDB connection */
1823                         log_add_callback(gdb_log_callback, connection);
1824                         target_call_timer_callbacks_now();
1825                         /* some commands need to know the GDB connection, make note of current
1826                          * GDB connection. */
1827                         current_gdb_connection = gdb_connection;
1828                         command_run_line(cmd_ctx, cmd);
1829                         current_gdb_connection = NULL;
1830                         target_call_timer_callbacks_now();
1831                         log_remove_callback(gdb_log_callback, connection);
1832                         free(cmd);
1833                 }
1834                 gdb_put_packet(connection, "OK", 2);
1835                 return ERROR_OK;
1836         }
1837         else if (strstr(packet, "qCRC:"))
1838         {
1839                 if (packet_size > 5)
1840                 {
1841                         int retval;
1842                         char gdb_reply[10];
1843                         char *separator;
1844                         uint32_t checksum;
1845                         uint32_t addr = 0;
1846                         uint32_t len = 0;
1847
1848                         /* skip command character */
1849                         packet += 5;
1850
1851                         addr = strtoul(packet, &separator, 16);
1852
1853                         if (*separator != ',')
1854                         {
1855                                 LOG_ERROR("incomplete read memory packet received, dropping connection");
1856                                 return ERROR_SERVER_REMOTE_CLOSED;
1857                         }
1858
1859                         len = strtoul(separator + 1, NULL, 16);
1860
1861                         retval = target_checksum_memory(target, addr, len, &checksum);
1862
1863                         if (retval == ERROR_OK)
1864                         {
1865                                 snprintf(gdb_reply, 10, "C%8.8" PRIx32 "", checksum);
1866                                 gdb_put_packet(connection, gdb_reply, 9);
1867                         }
1868                         else
1869                         {
1870                                 if ((retval = gdb_error(connection, retval)) != ERROR_OK)
1871                                         return retval;
1872                         }
1873
1874                         return ERROR_OK;
1875                 }
1876         }
1877         else if (strstr(packet, "qSupported"))
1878         {
1879                 /* we currently support packet size and qXfer:memory-map:read (if enabled)
1880                  * disable qXfer:features:read for the moment */
1881                 int retval = ERROR_OK;
1882                 char *buffer = NULL;
1883                 int pos = 0;
1884                 int size = 0;
1885
1886                 xml_printf(&retval, &buffer, &pos, &size,
1887                                 "PacketSize=%x;qXfer:memory-map:read%c;qXfer:features:read-;QStartNoAckMode+",
1888                                 (GDB_BUFFER_SIZE - 1), ((gdb_use_memory_map == 1) && (flash_get_bank_count() > 0)) ? '+' : '-');
1889
1890                 if (retval != ERROR_OK)
1891                 {
1892                         gdb_send_error(connection, 01);
1893                         return ERROR_OK;
1894                 }
1895
1896                 gdb_put_packet(connection, buffer, strlen(buffer));
1897                 free(buffer);
1898
1899                 return ERROR_OK;
1900         }
1901         else if (strstr(packet, "qXfer:memory-map:read::")
1902                         && (flash_get_bank_count() > 0))
1903                 return gdb_memory_map(connection, target, packet, packet_size);
1904         else if (strstr(packet, "qXfer:features:read:"))
1905         {
1906                 char *xml = NULL;
1907                 int size = 0;
1908                 int pos = 0;
1909                 int retval = ERROR_OK;
1910
1911                 int offset;
1912                 unsigned int length;
1913                 char *annex;
1914
1915                 /* skip command character */
1916                 packet += 20;
1917
1918                 if (decode_xfer_read(packet, &annex, &offset, &length) < 0)
1919                 {
1920                         gdb_send_error(connection, 01);
1921                         return ERROR_OK;
1922                 }
1923
1924                 if (strcmp(annex, "target.xml") != 0)
1925                 {
1926                         gdb_send_error(connection, 01);
1927                         return ERROR_OK;
1928                 }
1929
1930                 xml_printf(&retval, &xml, &pos, &size, \
1931                         "l < target version=\"1.0\">\n < architecture > arm</architecture>\n</target>\n");
1932
1933                 if (retval != ERROR_OK)
1934                 {
1935                         gdb_error(connection, retval);
1936                         return retval;
1937                 }
1938
1939                 gdb_put_packet(connection, xml, strlen(xml));
1940
1941                 free(xml);
1942                 return ERROR_OK;
1943         }
1944         else if (strstr(packet, "QStartNoAckMode"))
1945         {
1946                 gdb_connection->noack_mode = 1;
1947                 gdb_put_packet(connection, "OK", 2);
1948                 return ERROR_OK;
1949         }
1950
1951         gdb_put_packet(connection, "", 0);
1952         return ERROR_OK;
1953 }
1954
1955 static int gdb_v_packet(struct connection *connection,
1956                 struct target *target, char *packet, int packet_size)
1957 {
1958         struct gdb_connection *gdb_connection = connection->priv;
1959         struct gdb_service *gdb_service = connection->service->priv;
1960         int result;
1961
1962         /* if flash programming disabled - send a empty reply */
1963
1964         if (gdb_flash_program == 0)
1965         {
1966                 gdb_put_packet(connection, "", 0);
1967                 return ERROR_OK;
1968         }
1969
1970         if (strstr(packet, "vFlashErase:"))
1971         {
1972                 unsigned long addr;
1973                 unsigned long length;
1974
1975                 char *parse = packet + 12;
1976                 if (*parse == '\0')
1977                 {
1978                         LOG_ERROR("incomplete vFlashErase packet received, dropping connection");
1979                         return ERROR_SERVER_REMOTE_CLOSED;
1980                 }
1981
1982                 addr = strtoul(parse, &parse, 16);
1983
1984                 if (*(parse++) != ',' || *parse == '\0')
1985                 {
1986                         LOG_ERROR("incomplete vFlashErase packet received, dropping connection");
1987                         return ERROR_SERVER_REMOTE_CLOSED;
1988                 }
1989
1990                 length = strtoul(parse, &parse, 16);
1991
1992                 if (*parse != '\0')
1993                 {
1994                         LOG_ERROR("incomplete vFlashErase packet received, dropping connection");
1995                         return ERROR_SERVER_REMOTE_CLOSED;
1996                 }
1997
1998                 /* assume all sectors need erasing - stops any problems
1999                  * when flash_write is called multiple times */
2000                 flash_set_dirty();
2001
2002                 /* perform any target specific operations before the erase */
2003                 target_call_event_callbacks(gdb_service->target,
2004                                 TARGET_EVENT_GDB_FLASH_ERASE_START);
2005
2006                 /* vFlashErase:addr,length messages require region start and
2007                  * end to be "block" aligned ... if padding is ever needed,
2008                  * GDB will have become dangerously confused.
2009                  */
2010                 result = flash_erase_address_range(gdb_service->target,
2011                                 false, addr, length);
2012
2013                 /* perform any target specific operations after the erase */
2014                 target_call_event_callbacks(gdb_service->target,
2015                                 TARGET_EVENT_GDB_FLASH_ERASE_END);
2016
2017                 /* perform erase */
2018                 if (result != ERROR_OK)
2019                 {
2020                         /* GDB doesn't evaluate the actual error number returned,
2021                          * treat a failed erase as an I/O error
2022                          */
2023                         gdb_send_error(connection, EIO);
2024                         LOG_ERROR("flash_erase returned %i", result);
2025                 }
2026                 else
2027                         gdb_put_packet(connection, "OK", 2);
2028
2029                 return ERROR_OK;
2030         }
2031
2032         if (strstr(packet, "vFlashWrite:"))
2033         {
2034                 int retval;
2035                 unsigned long addr;
2036                 unsigned long length;
2037                 char *parse = packet + 12;
2038
2039                 if (*parse == '\0')
2040                 {
2041                         LOG_ERROR("incomplete vFlashErase packet received, dropping connection");
2042                         return ERROR_SERVER_REMOTE_CLOSED;
2043                 }
2044                 addr = strtoul(parse, &parse, 16);
2045                 if (*(parse++) != ':')
2046                 {
2047                         LOG_ERROR("incomplete vFlashErase packet received, dropping connection");
2048                         return ERROR_SERVER_REMOTE_CLOSED;
2049                 }
2050                 length = packet_size - (parse - packet);
2051
2052                 /* create a new image if there isn't already one */
2053                 if (gdb_connection->vflash_image == NULL)
2054                 {
2055                         gdb_connection->vflash_image = malloc(sizeof(struct image));
2056                         image_open(gdb_connection->vflash_image, "", "build");
2057                 }
2058
2059                 /* create new section with content from packet buffer */
2060                 if ((retval = image_add_section(gdb_connection->vflash_image, addr, length, 0x0, (uint8_t*)parse)) != ERROR_OK)
2061                 {
2062                         return retval;
2063                 }
2064
2065                 gdb_put_packet(connection, "OK", 2);
2066
2067                 return ERROR_OK;
2068         }
2069
2070         if (!strcmp(packet, "vFlashDone"))
2071         {
2072                 uint32_t written;
2073
2074                 /* process the flashing buffer. No need to erase as GDB
2075                  * always issues a vFlashErase first. */
2076                 target_call_event_callbacks(gdb_service->target, TARGET_EVENT_GDB_FLASH_WRITE_START);
2077                 result = flash_write(gdb_service->target, gdb_connection->vflash_image, &written, 0);
2078                 target_call_event_callbacks(gdb_service->target, TARGET_EVENT_GDB_FLASH_WRITE_END);
2079                 if (result != ERROR_OK)
2080                 {
2081                         if (result == ERROR_FLASH_DST_OUT_OF_BANK)
2082                                 gdb_put_packet(connection, "E.memtype", 9);
2083                         else
2084                                 gdb_send_error(connection, EIO);
2085                         }
2086                 else
2087                 {
2088                         LOG_DEBUG("wrote %u bytes from vFlash image to flash", (unsigned)written);
2089                         gdb_put_packet(connection, "OK", 2);
2090                 }
2091
2092                 image_close(gdb_connection->vflash_image);
2093                 free(gdb_connection->vflash_image);
2094                 gdb_connection->vflash_image = NULL;
2095
2096                 return ERROR_OK;
2097         }
2098
2099         gdb_put_packet(connection, "", 0);
2100         return ERROR_OK;
2101 }
2102
2103 static int gdb_detach(struct connection *connection, struct target *target)
2104 {
2105         struct gdb_service *gdb_service = connection->service->priv;
2106
2107         target_call_event_callbacks(gdb_service->target,
2108                         TARGET_EVENT_GDB_DETACH);
2109
2110         return gdb_put_packet(connection, "OK", 2);
2111 }
2112
2113 static void gdb_log_callback(void *priv, const char *file, unsigned line,
2114                 const char *function, const char *string)
2115 {
2116         struct connection *connection = priv;
2117         struct gdb_connection *gdb_con = connection->priv;
2118
2119         if (gdb_con->busy)
2120         {
2121                 /* do not reply this using the O packet */
2122                 return;
2123         }
2124
2125         gdb_output_con(connection, string);
2126 }
2127
2128 static void gdb_sig_halted(struct connection *connection)
2129 {
2130         char sig_reply[4];
2131         snprintf(sig_reply, 4, "T%2.2x", 2);
2132         gdb_put_packet(connection, sig_reply, 3);
2133
2134 }
2135
2136 static int gdb_input_inner(struct connection *connection)
2137 {
2138         /* Do not allocate this on the stack */
2139         static char gdb_packet_buffer[GDB_BUFFER_SIZE];
2140
2141         struct gdb_service *gdb_service = connection->service->priv;
2142         struct target *target = gdb_service->target;
2143         char *packet = gdb_packet_buffer;
2144         int packet_size;
2145         int retval;
2146         struct gdb_connection *gdb_con = connection->priv;
2147         static int extended_protocol = 0;
2148
2149         /* drain input buffer. If one of the packets fail, then an error
2150          * packet is replied, if applicable.
2151          *
2152          * This loop will terminate and the error code is returned.
2153          *
2154          * The calling fn will check if this error is something that
2155          * can be recovered from, or if the connection must be closed.
2156          *
2157          * If the error is recoverable, this fn is called again to
2158          * drain the rest of the buffer.
2159          */
2160         do
2161         {
2162                 packet_size = GDB_BUFFER_SIZE-1;
2163                 retval = gdb_get_packet(connection, packet, &packet_size);
2164                 if (retval != ERROR_OK)
2165                         return retval;
2166
2167                 /* terminate with zero */
2168                 packet[packet_size] = 0;
2169
2170                 if (LOG_LEVEL_IS(LOG_LVL_DEBUG)) {
2171                         if (packet[0] == 'X') {
2172                                 // binary packets spew junk into the debug log stream
2173                                 char buf[ 50 ];
2174                                 int x;
2175                                 for (x = 0 ; (x < 49) && (packet[x] != ':') ; x++) {
2176                                         buf[x] = packet[x];
2177                                 }
2178                                 buf[x] = 0;
2179                                 LOG_DEBUG("received packet: '%s:<binary-data>'", buf);
2180                         } else {
2181                                 LOG_DEBUG("received packet: '%s'", packet);
2182                         }
2183                 }
2184
2185                 if (packet_size > 0)
2186                 {
2187                         retval = ERROR_OK;
2188                         switch (packet[0])
2189                         {
2190                                 case 'H':
2191                                         /* Hct... -- set thread
2192                                          * we don't have threads, send empty reply */
2193                                         gdb_put_packet(connection, NULL, 0);
2194                                         break;
2195                                 case 'q':
2196                                 case 'Q':
2197                                         retval = gdb_query_packet(connection,
2198                                                         target, packet,
2199                                                         packet_size);
2200                                         break;
2201                                 case 'g':
2202                                         retval = gdb_get_registers_packet(
2203                                                         connection, target,
2204                                                         packet, packet_size);
2205                                         break;
2206                                 case 'G':
2207                                         retval = gdb_set_registers_packet(
2208                                                         connection, target,
2209                                                         packet, packet_size);
2210                                         break;
2211                                 case 'p':
2212                                         retval = gdb_get_register_packet(
2213                                                         connection, target,
2214                                                         packet, packet_size);
2215                                         break;
2216                                 case 'P':
2217                                         retval = gdb_set_register_packet(
2218                                                         connection, target,
2219                                                         packet, packet_size);
2220                                         break;
2221                                 case 'm':
2222                                         retval = gdb_read_memory_packet(
2223                                                         connection, target,
2224                                                         packet, packet_size);
2225                                         break;
2226                                 case 'M':
2227                                         retval = gdb_write_memory_packet(
2228                                                         connection, target,
2229                                                         packet, packet_size);
2230                                         break;
2231                                 case 'z':
2232                                 case 'Z':
2233                                         retval = gdb_breakpoint_watchpoint_packet(connection, target, packet, packet_size);
2234                                         break;
2235                                 case '?':
2236                                         gdb_last_signal_packet(
2237                                                         connection, target,
2238                                                         packet, packet_size);
2239                                         break;
2240                                 case 'c':
2241                                 case 's':
2242                                         {
2243                                                 log_add_callback(gdb_log_callback, connection);
2244
2245                                                 if (gdb_con->mem_write_error)
2246                                                 {
2247                                                         LOG_ERROR("Memory write failure!");
2248
2249                                                         /* now that we have reported the memory write error, we can clear the condition */
2250                                                         gdb_con->mem_write_error = false;
2251                                                 }
2252
2253                                                 bool nostep = false;
2254                                                 bool already_running = false;
2255                                                 if (target->state == TARGET_RUNNING)
2256                                                 {
2257                                                         LOG_WARNING("WARNING! The target is already running. "
2258                                                                         "All changes GDB did to registers will be discarded! "
2259                                                                         "Waiting for target to halt.");
2260                                                         already_running = true;
2261                                                 } else if (target->state != TARGET_HALTED)
2262                                                 {
2263                                                         LOG_WARNING("The target is not in the halted nor running stated, stepi/continue ignored.");
2264                                                         nostep = true;
2265                                                 } else if ((packet[0] == 's') && gdb_con->sync)
2266                                                 {
2267                                                         /* Hmm..... when you issue a continue in GDB, then a "stepi" is
2268                                                          * sent by GDB first to OpenOCD, thus defeating the check to
2269                                                          * make only the single stepping have the sync feature...
2270                                                          */
2271                                                         nostep = true;
2272                                                         LOG_WARNING("stepi ignored. GDB will now fetch the register state from the target.");
2273                                                 }
2274                                                 gdb_con->sync = false;
2275
2276                                                 if (!already_running && nostep)
2277                                                 {
2278                                                         /* Either the target isn't in the halted state, then we can't
2279                                                          * step/continue. This might be early setup, etc.
2280                                                          *
2281                                                          * Or we want to allow GDB to pick up a fresh set of
2282                                                          * register values without modifying the target state.
2283                                                          *
2284                                                          */
2285                                                         gdb_sig_halted(connection);
2286
2287                                                         /* stop forwarding log packets! */
2288                                                         log_remove_callback(gdb_log_callback, connection);
2289                                                 } else
2290                                                 {
2291                                                         /* We're running/stepping, in which case we can
2292                                                          * forward log output until the target is halted
2293                                                          */
2294                                                         gdb_con->frontend_state = TARGET_RUNNING;
2295                                                         target_call_event_callbacks(target, TARGET_EVENT_GDB_START);
2296
2297                                                         if (!already_running)
2298                                                         {
2299                                                                 /* Here we don't want packet processing to stop even if this fails,
2300                                                                  * so we use a local variable instead of retval. */
2301                                                                 retval = gdb_step_continue_packet(connection, target, packet, packet_size);
2302                                                                 if (retval != ERROR_OK)
2303                                                                 {
2304                                                                         /* we'll never receive a halted condition... issue a false one.. */
2305                                                                         gdb_frontend_halted(target, connection);
2306                                                                 }
2307                                                         }
2308                                                 }
2309                                         }
2310                                         break;
2311                                 case 'v':
2312                                         retval = gdb_v_packet(
2313                                                         connection, target,
2314                                                         packet, packet_size);
2315                                         break;
2316                                 case 'D':
2317                                         retval = gdb_detach(connection, target);
2318                                         extended_protocol = 0;
2319                                         break;
2320                                 case 'X':
2321                                         retval = gdb_write_memory_binary_packet(
2322                                                         connection, target,
2323                                                         packet, packet_size);
2324                                         if (retval != ERROR_OK)
2325                                                 return retval;
2326                                         break;
2327                                 case 'k':
2328                                         if (extended_protocol != 0)
2329                                                 break;
2330                                         gdb_put_packet(connection, "OK", 2);
2331                                         return ERROR_SERVER_REMOTE_CLOSED;
2332                                 case '!':
2333                                         /* handle extended remote protocol */
2334                                         extended_protocol = 1;
2335                                         gdb_put_packet(connection, "OK", 2);
2336                                         break;
2337                                 case 'R':
2338                                         /* handle extended restart packet */
2339                                         breakpoint_clear_target(gdb_service->target);
2340                                         watchpoint_clear_target(gdb_service->target);
2341                                         command_run_linef(connection->cmd_ctx,
2342                                                         "ocd_gdb_restart %s",
2343                                                         target_name(target));
2344                                         break;
2345                                 default:
2346                                         /* ignore unknown packets */
2347                                         LOG_DEBUG("ignoring 0x%2.2x packet", packet[0]);
2348                                         gdb_put_packet(connection, NULL, 0);
2349                                         break;
2350                         }
2351
2352                         /* if a packet handler returned an error, exit input loop */
2353                         if (retval != ERROR_OK)
2354                                 return retval;
2355                 }
2356
2357                 if (gdb_con->ctrl_c)
2358                 {
2359                         if (target->state == TARGET_RUNNING)
2360                         {
2361                                 retval = target_halt(target);
2362                                 if (retval != ERROR_OK)
2363                                 {
2364                                         target_call_event_callbacks(target, TARGET_EVENT_GDB_HALT);
2365                                 }
2366                                 gdb_con->ctrl_c = 0;
2367                         } else
2368                         {
2369                                 LOG_INFO("The target is not running when halt was requested, stopping GDB.");
2370                                 target_call_event_callbacks(target, TARGET_EVENT_GDB_HALT);
2371                         }
2372                 }
2373
2374         } while (gdb_con->buf_cnt > 0);
2375
2376         return ERROR_OK;
2377 }
2378
2379 static int gdb_input(struct connection *connection)
2380 {
2381         int retval = gdb_input_inner(connection);
2382         struct gdb_connection *gdb_con = connection->priv;
2383         if (retval == ERROR_SERVER_REMOTE_CLOSED)
2384                 return retval;
2385
2386         /* logging does not propagate the error, yet can set the gdb_con->closed flag */
2387         if (gdb_con->closed)
2388                 return ERROR_SERVER_REMOTE_CLOSED;
2389
2390         /* we'll recover from any other errors(e.g. temporary timeouts, etc.) */
2391         return ERROR_OK;
2392 }
2393
2394 static int gdb_target_start(struct target *target, const char *port)
2395 {
2396         struct gdb_service *gdb_service = malloc(sizeof(struct gdb_service));
2397         if (NULL == gdb_service)
2398                 return -ENOMEM;
2399
2400         gdb_service->target = target;
2401
2402         return add_service("gdb",
2403                         port, 1, &gdb_new_connection, &gdb_input,
2404                         &gdb_connection_closed, gdb_service);
2405 }
2406
2407 static int gdb_target_add_one(struct target *target)
2408 {
2409         int retval = gdb_target_start(target, gdb_port_next);
2410         if (retval == ERROR_OK)
2411         {
2412                 long portnumber;
2413                 /* If we can parse the port number
2414                  * then we increment the port number for the next target.
2415                  */
2416                 char *end;
2417                 portnumber = strtol(gdb_port_next, &end, 0);
2418                 if (!*end)
2419                 {
2420                         if (parse_long(gdb_port_next, &portnumber) == ERROR_OK)
2421                         {
2422                                 free((void *)gdb_port_next);
2423                                 gdb_port_next = alloc_printf("%d", portnumber+1);
2424                         }
2425                 }
2426         }
2427         return retval;
2428 }
2429
2430 int gdb_target_add_all(struct target *target)
2431 {
2432         if (NULL == target)
2433         {
2434                 LOG_WARNING("gdb services need one or more targets defined");
2435                 return ERROR_OK;
2436         }
2437
2438         while (NULL != target)
2439         {
2440                 int retval = gdb_target_add_one(target);
2441                 if (ERROR_OK != retval)
2442                         return retval;
2443
2444                 target = target->next;
2445         }
2446
2447         return ERROR_OK;
2448 }
2449
2450 COMMAND_HANDLER(handle_gdb_sync_command)
2451 {
2452         if (CMD_ARGC != 0)
2453         {
2454                 return ERROR_COMMAND_SYNTAX_ERROR;
2455         }
2456
2457         if (current_gdb_connection == NULL)
2458         {
2459                 command_print(CMD_CTX,
2460                                 "gdb_sync command can only be run from within gdb using \"monitor gdb_sync\"");
2461                 return ERROR_FAIL;
2462         }
2463
2464         current_gdb_connection->sync = true;
2465
2466         return ERROR_OK;
2467 }
2468
2469 /* daemon configuration command gdb_port */
2470 COMMAND_HANDLER(handle_gdb_port_command)
2471 {
2472         int retval = CALL_COMMAND_HANDLER(server_pipe_command, &gdb_port);
2473         if (ERROR_OK == retval) {
2474                 free((void*)gdb_port_next);
2475                 gdb_port_next = strdup(gdb_port);
2476         }
2477         return retval;
2478 }
2479
2480 COMMAND_HANDLER(handle_gdb_memory_map_command)
2481 {
2482         if (CMD_ARGC != 1)
2483                 return ERROR_COMMAND_SYNTAX_ERROR;
2484
2485         COMMAND_PARSE_ENABLE(CMD_ARGV[0], gdb_use_memory_map);
2486         return ERROR_OK;
2487 }
2488
2489 COMMAND_HANDLER(handle_gdb_flash_program_command)
2490 {
2491         if (CMD_ARGC != 1)
2492                 return ERROR_COMMAND_SYNTAX_ERROR;
2493
2494         COMMAND_PARSE_ENABLE(CMD_ARGV[0], gdb_flash_program);
2495         return ERROR_OK;
2496 }
2497
2498 COMMAND_HANDLER(handle_gdb_report_data_abort_command)
2499 {
2500         if (CMD_ARGC != 1)
2501                 return ERROR_COMMAND_SYNTAX_ERROR;
2502
2503         COMMAND_PARSE_ENABLE(CMD_ARGV[0], gdb_report_data_abort);
2504         return ERROR_OK;
2505 }
2506
2507 /* gdb_breakpoint_override */
2508 COMMAND_HANDLER(handle_gdb_breakpoint_override_command)
2509 {
2510         if (CMD_ARGC == 0)
2511         {
2512
2513         } else if (CMD_ARGC == 1)
2514         {
2515                 gdb_breakpoint_override = 1;
2516                 if (strcmp(CMD_ARGV[0], "hard") == 0)
2517                 {
2518                         gdb_breakpoint_override_type = BKPT_HARD;
2519                 } else if (strcmp(CMD_ARGV[0], "soft") == 0)
2520                 {
2521                         gdb_breakpoint_override_type = BKPT_SOFT;
2522                 } else if (strcmp(CMD_ARGV[0], "disable") == 0)
2523                 {
2524                         gdb_breakpoint_override = 0;
2525                 }
2526         } else
2527         {
2528                 return ERROR_COMMAND_SYNTAX_ERROR;
2529         }
2530         if (gdb_breakpoint_override)
2531         {
2532                 LOG_USER("force %s breakpoints", (gdb_breakpoint_override_type == BKPT_HARD)?"hard":"soft");
2533         } else
2534         {
2535                 LOG_USER("breakpoint type is not overridden");
2536         }
2537
2538         return ERROR_OK;
2539 }
2540
2541 static const struct command_registration gdb_command_handlers[] = {
2542         {
2543                 .name = "gdb_sync",
2544                 .handler = handle_gdb_sync_command,
2545                 .mode = COMMAND_ANY,
2546                 .help = "next stepi will return immediately allowing "
2547                         "GDB to fetch register state without affecting "
2548                         "target state",
2549         },
2550         {
2551                 .name = "gdb_port",
2552                 .handler = handle_gdb_port_command,
2553                 .mode = COMMAND_ANY,
2554                 .help = "Normally gdb listens to a TCP/IP port. Each subsequent GDB "
2555                                 "server listens for the next port number after the "
2556                                 "base port number specified. "
2557                                 "No arguments reports GDB port. \"pipe\" means listen to stdin "
2558                                 "output to stdout, an integer is base port number, \"disable\" disables "
2559                                 "port. Any other string is are interpreted as named pipe to listen to. "
2560                                 "Output pipe is the same name as input pipe, but with 'o' appended.",
2561                 .usage = "[port_num]",
2562         },
2563         {
2564                 .name = "gdb_memory_map",
2565                 .handler = handle_gdb_memory_map_command,
2566                 .mode = COMMAND_CONFIG,
2567                 .help = "enable or disable memory map",
2568                 .usage = "('enable'|'disable')"
2569         },
2570         {
2571                 .name = "gdb_flash_program",
2572                 .handler = handle_gdb_flash_program_command,
2573                 .mode = COMMAND_CONFIG,
2574                 .help = "enable or disable flash program",
2575                 .usage = "('enable'|'disable')"
2576         },
2577         {
2578                 .name = "gdb_report_data_abort",
2579                 .handler = handle_gdb_report_data_abort_command,
2580                 .mode = COMMAND_CONFIG,
2581                 .help = "enable or disable reporting data aborts",
2582                 .usage = "('enable'|'disable')"
2583         },
2584         {
2585                 .name = "gdb_breakpoint_override",
2586                 .handler = handle_gdb_breakpoint_override_command,
2587                 .mode = COMMAND_ANY,
2588                 .help = "Display or specify type of breakpoint "
2589                         "to be used by gdb 'break' commands.",
2590                 .usage = "('hard'|'soft'|'disable')"
2591         },
2592         COMMAND_REGISTRATION_DONE
2593 };
2594
2595 int gdb_register_commands(struct command_context *cmd_ctx)
2596 {
2597         gdb_port = strdup("3333");
2598         gdb_port_next = strdup("3333");
2599         return register_commands(cmd_ctx, NULL, gdb_command_handlers);
2600 }