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