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