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