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