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