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