gdb_server: fix extended_protocol for multi-target
[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  *   Copyright (C) 2013 Andes Technology                                   *
18  *   Hsiangkai Wang <hkwang@andestech.com>                                 *
19  *                                                                         *
20  *   Copyright (C) 2013 Franck Jullien                                     *
21  *   elec4fun@gmail.com                                                    *
22  *                                                                         *
23  *   This program is free software; you can redistribute it and/or modify  *
24  *   it under the terms of the GNU General Public License as published by  *
25  *   the Free Software Foundation; either version 2 of the License, or     *
26  *   (at your option) any later version.                                   *
27  *                                                                         *
28  *   This program is distributed in the hope that it will be useful,       *
29  *   but WITHOUT ANY WARRANTY; without even the implied warranty of        *
30  *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the         *
31  *   GNU General Public License for more details.                          *
32  *                                                                         *
33  *   You should have received a copy of the GNU General Public License     *
34  *   along with this program.  If not, see <http://www.gnu.org/licenses/>. *
35  ***************************************************************************/
36
37 #ifdef HAVE_CONFIG_H
38 #include "config.h"
39 #endif
40
41 #include <target/breakpoints.h>
42 #include <target/target_request.h>
43 #include <target/register.h>
44 #include <target/target.h>
45 #include <target/target_type.h>
46 #include <target/semihosting_common.h>
47 #include "server.h"
48 #include <flash/nor/core.h>
49 #include "gdb_server.h"
50 #include <target/image.h>
51 #include <jtag/jtag.h>
52 #include "rtos/rtos.h"
53 #include "target/smp.h"
54
55 /**
56  * @file
57  * GDB server implementation.
58  *
59  * This implements the GDB Remote Serial Protocol, over TCP connections,
60  * giving GDB access to the JTAG or other hardware debugging facilities
61  * found in most modern embedded processors.
62  */
63
64 struct target_desc_format {
65         char *tdesc;
66         uint32_t tdesc_length;
67 };
68
69 /* private connection data for GDB */
70 struct gdb_connection {
71         char buffer[GDB_BUFFER_SIZE + 1]; /* Extra byte for nul-termination */
72         char *buf_p;
73         int buf_cnt;
74         int ctrl_c;
75         enum target_state frontend_state;
76         struct image *vflash_image;
77         bool closed;
78         bool busy;
79         int noack_mode;
80         /* set flag to true if you want the next stepi to return immediately.
81          * allowing GDB to pick up a fresh set of register values from the target
82          * without modifying the target state. */
83         bool sync;
84         /* We delay reporting memory write errors until next step/continue or memory
85          * write. This improves performance of gdb load significantly as the GDB packet
86          * can be replied immediately and a new GDB packet will be ready without delay
87          * (ca. 10% or so...). */
88         bool mem_write_error;
89         /* with extended-remote it seems we need to better emulate attach/detach.
90          * what this means is we reply with a W stop reply after a kill packet,
91          * normally we reply with a S reply via gdb_last_signal_packet.
92          * as a side note this behaviour only effects gdb > 6.8 */
93         bool attached;
94         /* set when extended protocol is used */
95         bool extended_protocol;
96         /* temporarily used for target description support */
97         struct target_desc_format target_desc;
98         /* temporarily used for thread list support */
99         char *thread_list;
100 };
101
102 #if 0
103 #define _DEBUG_GDB_IO_
104 #endif
105
106 static struct gdb_connection *current_gdb_connection;
107
108 static int gdb_breakpoint_override;
109 static enum breakpoint_type gdb_breakpoint_override_type;
110
111 static int gdb_error(struct connection *connection, int retval);
112 static char *gdb_port;
113 static char *gdb_port_next;
114
115 static void gdb_log_callback(void *priv, const char *file, unsigned line,
116                 const char *function, const char *string);
117
118 static void gdb_sig_halted(struct connection *connection);
119
120 /* number of gdb connections, mainly to suppress gdb related debugging spam
121  * in helper/log.c when no gdb connections are actually active */
122 int gdb_actual_connections;
123
124 /* set if we are sending a memory map to gdb
125  * via qXfer:memory-map:read packet */
126 /* enabled by default*/
127 static int gdb_use_memory_map = 1;
128 /* enabled by default*/
129 static int gdb_flash_program = 1;
130
131 /* if set, data aborts cause an error to be reported in memory read packets
132  * see the code in gdb_read_memory_packet() for further explanations.
133  * Disabled by default.
134  */
135 static int gdb_report_data_abort;
136 /* If set, errors when accessing registers are reported to gdb. Disabled by
137  * default. */
138 static int gdb_report_register_access_error;
139
140 /* set if we are sending target descriptions to gdb
141  * via qXfer:features:read packet */
142 /* enabled by default */
143 static int gdb_use_target_description = 1;
144
145 /* current processing free-run type, used by file-I/O */
146 static char gdb_running_type;
147
148 static int gdb_last_signal(struct target *target)
149 {
150         switch (target->debug_reason) {
151                 case DBG_REASON_DBGRQ:
152                         return 0x2;             /* SIGINT */
153                 case DBG_REASON_BREAKPOINT:
154                 case DBG_REASON_WATCHPOINT:
155                 case DBG_REASON_WPTANDBKPT:
156                         return 0x05;    /* SIGTRAP */
157                 case DBG_REASON_SINGLESTEP:
158                         return 0x05;    /* SIGTRAP */
159                 case DBG_REASON_EXC_CATCH:
160                         return 0x05;
161                 case DBG_REASON_NOTHALTED:
162                         return 0x0;             /* no signal... shouldn't happen */
163                 default:
164                         LOG_USER("undefined debug reason %d - target needs reset",
165                                         target->debug_reason);
166                         return 0x0;
167         }
168 }
169
170 static int check_pending(struct connection *connection,
171                 int timeout_s, int *got_data)
172 {
173         /* a non-blocking socket will block if there is 0 bytes available on the socket,
174          * but return with as many bytes as are available immediately
175          */
176         struct timeval tv;
177         fd_set read_fds;
178         struct gdb_connection *gdb_con = connection->priv;
179         int t;
180         if (got_data == NULL)
181                 got_data = &t;
182         *got_data = 0;
183
184         if (gdb_con->buf_cnt > 0) {
185                 *got_data = 1;
186                 return ERROR_OK;
187         }
188
189         FD_ZERO(&read_fds);
190         FD_SET(connection->fd, &read_fds);
191
192         tv.tv_sec = timeout_s;
193         tv.tv_usec = 0;
194         if (socket_select(connection->fd + 1, &read_fds, NULL, NULL, &tv) == 0) {
195                 /* This can typically be because a "monitor" command took too long
196                  * before printing any progress messages
197                  */
198                 if (timeout_s > 0)
199                         return ERROR_GDB_TIMEOUT;
200                 else
201                         return ERROR_OK;
202         }
203         *got_data = FD_ISSET(connection->fd, &read_fds) != 0;
204         return ERROR_OK;
205 }
206
207 static int gdb_get_char_inner(struct connection *connection, int *next_char)
208 {
209         struct gdb_connection *gdb_con = connection->priv;
210         int retval = ERROR_OK;
211
212 #ifdef _DEBUG_GDB_IO_
213         char *debug_buffer;
214 #endif
215         for (;; ) {
216                 if (connection->service->type != CONNECTION_TCP)
217                         gdb_con->buf_cnt = read(connection->fd, gdb_con->buffer, GDB_BUFFER_SIZE);
218                 else {
219                         retval = check_pending(connection, 1, NULL);
220                         if (retval != ERROR_OK)
221                                 return retval;
222                         gdb_con->buf_cnt = read_socket(connection->fd,
223                                         gdb_con->buffer,
224                                         GDB_BUFFER_SIZE);
225                 }
226
227                 if (gdb_con->buf_cnt > 0)
228                         break;
229                 if (gdb_con->buf_cnt == 0) {
230                         gdb_con->closed = true;
231                         return ERROR_SERVER_REMOTE_CLOSED;
232                 }
233
234 #ifdef _WIN32
235                 errno = WSAGetLastError();
236
237                 switch (errno) {
238                         case WSAEWOULDBLOCK:
239                                 usleep(1000);
240                                 break;
241                         case WSAECONNABORTED:
242                                 gdb_con->closed = true;
243                                 return ERROR_SERVER_REMOTE_CLOSED;
244                         case WSAECONNRESET:
245                                 gdb_con->closed = true;
246                                 return ERROR_SERVER_REMOTE_CLOSED;
247                         default:
248                                 LOG_ERROR("read: %d", errno);
249                                 exit(-1);
250                 }
251 #else
252                 switch (errno) {
253                         case EAGAIN:
254                                 usleep(1000);
255                                 break;
256                         case ECONNABORTED:
257                                 gdb_con->closed = true;
258                                 return ERROR_SERVER_REMOTE_CLOSED;
259                         case ECONNRESET:
260                                 gdb_con->closed = true;
261                                 return ERROR_SERVER_REMOTE_CLOSED;
262                         default:
263                                 LOG_ERROR("read: %s", strerror(errno));
264                                 gdb_con->closed = true;
265                                 return ERROR_SERVER_REMOTE_CLOSED;
266                 }
267 #endif
268         }
269
270 #ifdef _DEBUG_GDB_IO_
271         debug_buffer = strndup(gdb_con->buffer, gdb_con->buf_cnt);
272         LOG_DEBUG("received '%s'", debug_buffer);
273         free(debug_buffer);
274 #endif
275
276         gdb_con->buf_p = gdb_con->buffer;
277         gdb_con->buf_cnt--;
278         *next_char = *(gdb_con->buf_p++);
279         if (gdb_con->buf_cnt > 0)
280                 connection->input_pending = 1;
281         else
282                 connection->input_pending = 0;
283 #ifdef _DEBUG_GDB_IO_
284         LOG_DEBUG("returned char '%c' (0x%2.2x)", *next_char, *next_char);
285 #endif
286
287         return retval;
288 }
289
290 /**
291  * The cool thing about this fn is that it allows buf_p and buf_cnt to be
292  * held in registers in the inner loop.
293  *
294  * For small caches and embedded systems this is important!
295  */
296 static inline int gdb_get_char_fast(struct connection *connection,
297                 int *next_char, char **buf_p, int *buf_cnt)
298 {
299         int retval = ERROR_OK;
300
301         if ((*buf_cnt)-- > 0) {
302                 *next_char = **buf_p;
303                 (*buf_p)++;
304                 if (*buf_cnt > 0)
305                         connection->input_pending = 1;
306                 else
307                         connection->input_pending = 0;
308
309 #ifdef _DEBUG_GDB_IO_
310                 LOG_DEBUG("returned char '%c' (0x%2.2x)", *next_char, *next_char);
311 #endif
312
313                 return ERROR_OK;
314         }
315
316         struct gdb_connection *gdb_con = connection->priv;
317         gdb_con->buf_p = *buf_p;
318         gdb_con->buf_cnt = *buf_cnt;
319         retval = gdb_get_char_inner(connection, next_char);
320         *buf_p = gdb_con->buf_p;
321         *buf_cnt = gdb_con->buf_cnt;
322
323         return retval;
324 }
325
326 static int gdb_get_char(struct connection *connection, int *next_char)
327 {
328         struct gdb_connection *gdb_con = connection->priv;
329         return gdb_get_char_fast(connection, next_char, &gdb_con->buf_p, &gdb_con->buf_cnt);
330 }
331
332 static int gdb_putback_char(struct connection *connection, int last_char)
333 {
334         struct gdb_connection *gdb_con = connection->priv;
335
336         if (gdb_con->buf_p > gdb_con->buffer) {
337                 *(--gdb_con->buf_p) = last_char;
338                 gdb_con->buf_cnt++;
339         } else
340                 LOG_ERROR("BUG: couldn't put character back");
341
342         return ERROR_OK;
343 }
344
345 /* The only way we can detect that the socket is closed is the first time
346  * we write to it, we will fail. Subsequent write operations will
347  * succeed. Shudder! */
348 static int gdb_write(struct connection *connection, void *data, int len)
349 {
350         struct gdb_connection *gdb_con = connection->priv;
351         if (gdb_con->closed)
352                 return ERROR_SERVER_REMOTE_CLOSED;
353
354         if (connection_write(connection, data, len) == len)
355                 return ERROR_OK;
356         gdb_con->closed = true;
357         return ERROR_SERVER_REMOTE_CLOSED;
358 }
359
360 static int gdb_put_packet_inner(struct connection *connection,
361                 char *buffer, int len)
362 {
363         int i;
364         unsigned char my_checksum = 0;
365 #ifdef _DEBUG_GDB_IO_
366         char *debug_buffer;
367 #endif
368         int reply;
369         int retval;
370         struct gdb_connection *gdb_con = connection->priv;
371
372         for (i = 0; i < len; i++)
373                 my_checksum += buffer[i];
374
375 #ifdef _DEBUG_GDB_IO_
376         /*
377          * At this point we should have nothing in the input queue from GDB,
378          * however sometimes '-' is sent even though we've already received
379          * an ACK (+) for everything we've sent off.
380          */
381         int gotdata;
382         for (;; ) {
383                 retval = check_pending(connection, 0, &gotdata);
384                 if (retval != ERROR_OK)
385                         return retval;
386                 if (!gotdata)
387                         break;
388                 retval = gdb_get_char(connection, &reply);
389                 if (retval != ERROR_OK)
390                         return retval;
391                 if (reply == '$') {
392                         /* fix a problem with some IAR tools */
393                         gdb_putback_char(connection, reply);
394                         LOG_DEBUG("Unexpected start of new packet");
395                         break;
396                 }
397
398                 LOG_WARNING("Discard unexpected char %c", reply);
399         }
400 #endif
401
402         while (1) {
403 #ifdef _DEBUG_GDB_IO_
404                 debug_buffer = strndup(buffer, len);
405                 LOG_DEBUG("sending packet '$%s#%2.2x'", debug_buffer, my_checksum);
406                 free(debug_buffer);
407 #endif
408
409                 char local_buffer[1024];
410                 local_buffer[0] = '$';
411                 if ((size_t)len + 4 <= sizeof(local_buffer)) {
412                         /* performance gain on smaller packets by only a single call to gdb_write() */
413                         memcpy(local_buffer + 1, buffer, len++);
414                         len += snprintf(local_buffer + len, sizeof(local_buffer) - len, "#%02x", my_checksum);
415                         retval = gdb_write(connection, local_buffer, len);
416                         if (retval != ERROR_OK)
417                                 return retval;
418                 } else {
419                         /* larger packets are transmitted directly from caller supplied buffer
420                          * by several calls to gdb_write() to avoid dynamic allocation */
421                         snprintf(local_buffer + 1, sizeof(local_buffer) - 1, "#%02x", my_checksum);
422                         retval = gdb_write(connection, local_buffer, 1);
423                         if (retval != ERROR_OK)
424                                 return retval;
425                         retval = gdb_write(connection, buffer, len);
426                         if (retval != ERROR_OK)
427                                 return retval;
428                         retval = gdb_write(connection, local_buffer + 1, 3);
429                         if (retval != ERROR_OK)
430                                 return retval;
431                 }
432
433                 if (gdb_con->noack_mode)
434                         break;
435
436                 retval = gdb_get_char(connection, &reply);
437                 if (retval != ERROR_OK)
438                         return retval;
439
440                 if (reply == '+')
441                         break;
442                 else if (reply == '-') {
443                         /* Stop sending output packets for now */
444                         log_remove_callback(gdb_log_callback, connection);
445                         LOG_WARNING("negative reply, retrying");
446                 } else if (reply == 0x3) {
447                         gdb_con->ctrl_c = 1;
448                         retval = gdb_get_char(connection, &reply);
449                         if (retval != ERROR_OK)
450                                 return retval;
451                         if (reply == '+')
452                                 break;
453                         else if (reply == '-') {
454                                 /* Stop sending output packets for now */
455                                 log_remove_callback(gdb_log_callback, connection);
456                                 LOG_WARNING("negative reply, retrying");
457                         } else if (reply == '$') {
458                                 LOG_ERROR("GDB missing ack(1) - assumed good");
459                                 gdb_putback_char(connection, reply);
460                                 return ERROR_OK;
461                         } else {
462                                 LOG_ERROR("unknown character(1) 0x%2.2x in reply, dropping connection", reply);
463                                 gdb_con->closed = true;
464                                 return ERROR_SERVER_REMOTE_CLOSED;
465                         }
466                 } else if (reply == '$') {
467                         LOG_ERROR("GDB missing ack(2) - assumed good");
468                         gdb_putback_char(connection, reply);
469                         return ERROR_OK;
470                 } else {
471                         LOG_ERROR("unknown character(2) 0x%2.2x in reply, dropping connection",
472                                 reply);
473                         gdb_con->closed = true;
474                         return ERROR_SERVER_REMOTE_CLOSED;
475                 }
476         }
477         if (gdb_con->closed)
478                 return ERROR_SERVER_REMOTE_CLOSED;
479
480         return ERROR_OK;
481 }
482
483 int gdb_put_packet(struct connection *connection, char *buffer, int len)
484 {
485         struct gdb_connection *gdb_con = connection->priv;
486         gdb_con->busy = true;
487         int retval = gdb_put_packet_inner(connection, buffer, len);
488         gdb_con->busy = false;
489
490         /* we sent some data, reset timer for keep alive messages */
491         kept_alive();
492
493         return retval;
494 }
495
496 static inline int fetch_packet(struct connection *connection,
497                 int *checksum_ok, int noack, int *len, char *buffer)
498 {
499         unsigned char my_checksum = 0;
500         char checksum[3];
501         int character;
502         int retval = ERROR_OK;
503
504         struct gdb_connection *gdb_con = connection->priv;
505         my_checksum = 0;
506         int count = 0;
507         count = 0;
508
509         /* move this over into local variables to use registers and give the
510          * more freedom to optimize */
511         char *buf_p = gdb_con->buf_p;
512         int buf_cnt = gdb_con->buf_cnt;
513
514         for (;; ) {
515                 /* The common case is that we have an entire packet with no escape chars.
516                  * We need to leave at least 2 bytes in the buffer to have
517                  * gdb_get_char() update various bits and bobs correctly.
518                  */
519                 if ((buf_cnt > 2) && ((buf_cnt + count) < *len)) {
520                         /* The compiler will struggle a bit with constant propagation and
521                          * aliasing, so we help it by showing that these values do not
522                          * change inside the loop
523                          */
524                         int i;
525                         char *buf = buf_p;
526                         int run = buf_cnt - 2;
527                         i = 0;
528                         int done = 0;
529                         while (i < run) {
530                                 character = *buf++;
531                                 i++;
532                                 if (character == '#') {
533                                         /* Danger! character can be '#' when esc is
534                                          * used so we need an explicit boolean for done here. */
535                                         done = 1;
536                                         break;
537                                 }
538
539                                 if (character == '}') {
540                                         /* data transmitted in binary mode (X packet)
541                                          * uses 0x7d as escape character */
542                                         my_checksum += character & 0xff;
543                                         character = *buf++;
544                                         i++;
545                                         my_checksum += character & 0xff;
546                                         buffer[count++] = (character ^ 0x20) & 0xff;
547                                 } else {
548                                         my_checksum += character & 0xff;
549                                         buffer[count++] = character & 0xff;
550                                 }
551                         }
552                         buf_p += i;
553                         buf_cnt -= i;
554                         if (done)
555                                 break;
556                 }
557                 if (count > *len) {
558                         LOG_ERROR("packet buffer too small");
559                         retval = ERROR_GDB_BUFFER_TOO_SMALL;
560                         break;
561                 }
562
563                 retval = gdb_get_char_fast(connection, &character, &buf_p, &buf_cnt);
564                 if (retval != ERROR_OK)
565                         break;
566
567                 if (character == '#')
568                         break;
569
570                 if (character == '}') {
571                         /* data transmitted in binary mode (X packet)
572                          * uses 0x7d as escape character */
573                         my_checksum += character & 0xff;
574
575                         retval = gdb_get_char_fast(connection, &character, &buf_p, &buf_cnt);
576                         if (retval != ERROR_OK)
577                                 break;
578
579                         my_checksum += character & 0xff;
580                         buffer[count++] = (character ^ 0x20) & 0xff;
581                 } else {
582                         my_checksum += character & 0xff;
583                         buffer[count++] = character & 0xff;
584                 }
585         }
586
587         gdb_con->buf_p = buf_p;
588         gdb_con->buf_cnt = buf_cnt;
589
590         if (retval != ERROR_OK)
591                 return retval;
592
593         *len = count;
594
595         retval = gdb_get_char(connection, &character);
596         if (retval != ERROR_OK)
597                 return retval;
598         checksum[0] = character;
599         retval = gdb_get_char(connection, &character);
600         if (retval != ERROR_OK)
601                 return retval;
602         checksum[1] = character;
603         checksum[2] = 0;
604
605         if (!noack)
606                 *checksum_ok = (my_checksum == strtoul(checksum, NULL, 16));
607
608         return ERROR_OK;
609 }
610
611 static int gdb_get_packet_inner(struct connection *connection,
612                 char *buffer, int *len)
613 {
614         int character;
615         int retval;
616         struct gdb_connection *gdb_con = connection->priv;
617
618         while (1) {
619                 do {
620                         retval = gdb_get_char(connection, &character);
621                         if (retval != ERROR_OK)
622                                 return retval;
623
624 #ifdef _DEBUG_GDB_IO_
625                         LOG_DEBUG("character: '%c'", character);
626 #endif
627
628                         switch (character) {
629                                 case '$':
630                                         break;
631                                 case '+':
632                                         /* According to the GDB documentation
633                                          * (https://sourceware.org/gdb/onlinedocs/gdb/Packet-Acknowledgment.html):
634                                          * "gdb sends a final `+` acknowledgment of the stub's `OK`
635                                          * response, which can be safely ignored by the stub."
636                                          * However OpenOCD server already is in noack mode at this
637                                          * point and instead of ignoring this it was emitting a
638                                          * warning. This code makes server ignore the first ACK
639                                          * that will be received after going into noack mode,
640                                          * warning only about subsequent ACK's. */
641                                         if (gdb_con->noack_mode > 1) {
642                                                 LOG_WARNING("acknowledgment received, but no packet pending");
643                                         } else if (gdb_con->noack_mode) {
644                                                 LOG_DEBUG("Received first acknowledgment after entering noack mode. Ignoring it.");
645                                                 gdb_con->noack_mode = 2;
646                                         }
647                                         break;
648                                 case '-':
649                                         LOG_WARNING("negative acknowledgment, but no packet pending");
650                                         break;
651                                 case 0x3:
652                                         gdb_con->ctrl_c = 1;
653                                         *len = 0;
654                                         return ERROR_OK;
655                                 default:
656                                         LOG_WARNING("ignoring character 0x%x", character);
657                                         break;
658                         }
659                 } while (character != '$');
660
661                 int checksum_ok = 0;
662                 /* explicit code expansion here to get faster inlined code in -O3 by not
663                  * calculating checksum */
664                 if (gdb_con->noack_mode) {
665                         retval = fetch_packet(connection, &checksum_ok, 1, len, buffer);
666                         if (retval != ERROR_OK)
667                                 return retval;
668                 } else {
669                         retval = fetch_packet(connection, &checksum_ok, 0, len, buffer);
670                         if (retval != ERROR_OK)
671                                 return retval;
672                 }
673
674                 if (gdb_con->noack_mode) {
675                         /* checksum is not checked in noack mode */
676                         break;
677                 }
678                 if (checksum_ok) {
679                         retval = gdb_write(connection, "+", 1);
680                         if (retval != ERROR_OK)
681                                 return retval;
682                         break;
683                 }
684         }
685         if (gdb_con->closed)
686                 return ERROR_SERVER_REMOTE_CLOSED;
687
688         return ERROR_OK;
689 }
690
691 static int gdb_get_packet(struct connection *connection, char *buffer, int *len)
692 {
693         struct gdb_connection *gdb_con = connection->priv;
694         gdb_con->busy = true;
695         int retval = gdb_get_packet_inner(connection, buffer, len);
696         gdb_con->busy = false;
697         return retval;
698 }
699
700 static int gdb_output_con(struct connection *connection, const char *line)
701 {
702         char *hex_buffer;
703         int bin_size;
704
705         bin_size = strlen(line);
706
707         hex_buffer = malloc(bin_size * 2 + 2);
708         if (hex_buffer == NULL)
709                 return ERROR_GDB_BUFFER_TOO_SMALL;
710
711         hex_buffer[0] = 'O';
712         size_t pkt_len = hexify(hex_buffer + 1, (const uint8_t *)line, bin_size,
713                 bin_size * 2 + 1);
714         int retval = gdb_put_packet(connection, hex_buffer, pkt_len + 1);
715
716         free(hex_buffer);
717         return retval;
718 }
719
720 static int gdb_output(struct command_context *context, const char *line)
721 {
722         /* this will be dumped to the log and also sent as an O packet if possible */
723         LOG_USER_N("%s", line);
724         return ERROR_OK;
725 }
726
727 static void gdb_signal_reply(struct target *target, struct connection *connection)
728 {
729         struct gdb_connection *gdb_connection = connection->priv;
730         char sig_reply[65];
731         char stop_reason[20];
732         char current_thread[25];
733         int sig_reply_len;
734         int signal_var;
735
736         rtos_update_threads(target);
737
738         if (target->debug_reason == DBG_REASON_EXIT) {
739                 sig_reply_len = snprintf(sig_reply, sizeof(sig_reply), "W00");
740         } else {
741                 struct target *ct;
742                 if (target->rtos != NULL) {
743                         target->rtos->current_threadid = target->rtos->current_thread;
744                         target->rtos->gdb_target_for_threadid(connection, target->rtos->current_threadid, &ct);
745                 } else {
746                         ct = target;
747                 }
748
749                 if (gdb_connection->ctrl_c) {
750                         signal_var = 0x2;
751                 } else
752                         signal_var = gdb_last_signal(ct);
753
754                 stop_reason[0] = '\0';
755                 if (ct->debug_reason == DBG_REASON_WATCHPOINT) {
756                         enum watchpoint_rw hit_wp_type;
757                         target_addr_t hit_wp_address;
758
759                         if (watchpoint_hit(ct, &hit_wp_type, &hit_wp_address) == ERROR_OK) {
760
761                                 switch (hit_wp_type) {
762                                         case WPT_WRITE:
763                                                 snprintf(stop_reason, sizeof(stop_reason),
764                                                                 "watch:%08" TARGET_PRIxADDR ";", hit_wp_address);
765                                                 break;
766                                         case WPT_READ:
767                                                 snprintf(stop_reason, sizeof(stop_reason),
768                                                                 "rwatch:%08" TARGET_PRIxADDR ";", hit_wp_address);
769                                                 break;
770                                         case WPT_ACCESS:
771                                                 snprintf(stop_reason, sizeof(stop_reason),
772                                                                 "awatch:%08" TARGET_PRIxADDR ";", hit_wp_address);
773                                                 break;
774                                         default:
775                                                 break;
776                                 }
777                         }
778                 }
779
780                 current_thread[0] = '\0';
781                 if (target->rtos != NULL)
782                         snprintf(current_thread, sizeof(current_thread), "thread:%" PRIx64 ";",
783                                         target->rtos->current_thread);
784
785                 sig_reply_len = snprintf(sig_reply, sizeof(sig_reply), "T%2.2x%s%s",
786                                 signal_var, stop_reason, current_thread);
787
788                 gdb_connection->ctrl_c = 0;
789         }
790
791         gdb_put_packet(connection, sig_reply, sig_reply_len);
792         gdb_connection->frontend_state = TARGET_HALTED;
793 }
794
795 static void gdb_fileio_reply(struct target *target, struct connection *connection)
796 {
797         struct gdb_connection *gdb_connection = connection->priv;
798         char fileio_command[256];
799         int command_len;
800         bool program_exited = false;
801
802         if (strcmp(target->fileio_info->identifier, "open") == 0)
803                 sprintf(fileio_command, "F%s,%" PRIx64 "/%" PRIx64 ",%" PRIx64 ",%" PRIx64, target->fileio_info->identifier,
804                                 target->fileio_info->param_1,
805                                 target->fileio_info->param_2 + 1,       /* len + trailing zero */
806                                 target->fileio_info->param_3,
807                                 target->fileio_info->param_4);
808         else if (strcmp(target->fileio_info->identifier, "close") == 0)
809                 sprintf(fileio_command, "F%s,%" PRIx64, target->fileio_info->identifier,
810                                 target->fileio_info->param_1);
811         else if (strcmp(target->fileio_info->identifier, "read") == 0)
812                 sprintf(fileio_command, "F%s,%" PRIx64 ",%" PRIx64 ",%" PRIx64, target->fileio_info->identifier,
813                                 target->fileio_info->param_1,
814                                 target->fileio_info->param_2,
815                                 target->fileio_info->param_3);
816         else if (strcmp(target->fileio_info->identifier, "write") == 0)
817                 sprintf(fileio_command, "F%s,%" PRIx64 ",%" PRIx64 ",%" PRIx64, target->fileio_info->identifier,
818                                 target->fileio_info->param_1,
819                                 target->fileio_info->param_2,
820                                 target->fileio_info->param_3);
821         else if (strcmp(target->fileio_info->identifier, "lseek") == 0)
822                 sprintf(fileio_command, "F%s,%" PRIx64 ",%" PRIx64 ",%" PRIx64, target->fileio_info->identifier,
823                                 target->fileio_info->param_1,
824                                 target->fileio_info->param_2,
825                                 target->fileio_info->param_3);
826         else if (strcmp(target->fileio_info->identifier, "rename") == 0)
827                 sprintf(fileio_command, "F%s,%" PRIx64 "/%" PRIx64 ",%" PRIx64 "/%" PRIx64, target->fileio_info->identifier,
828                                 target->fileio_info->param_1,
829                                 target->fileio_info->param_2 + 1,       /* len + trailing zero */
830                                 target->fileio_info->param_3,
831                                 target->fileio_info->param_4 + 1);      /* len + trailing zero */
832         else if (strcmp(target->fileio_info->identifier, "unlink") == 0)
833                 sprintf(fileio_command, "F%s,%" PRIx64 "/%" PRIx64, target->fileio_info->identifier,
834                                 target->fileio_info->param_1,
835                                 target->fileio_info->param_2 + 1);      /* len + trailing zero */
836         else if (strcmp(target->fileio_info->identifier, "stat") == 0)
837                 sprintf(fileio_command, "F%s,%" PRIx64 "/%" PRIx64 ",%" PRIx64, target->fileio_info->identifier,
838                                 target->fileio_info->param_1,
839                                 target->fileio_info->param_2,
840                                 target->fileio_info->param_3);
841         else if (strcmp(target->fileio_info->identifier, "fstat") == 0)
842                 sprintf(fileio_command, "F%s,%" PRIx64 ",%" PRIx64, target->fileio_info->identifier,
843                                 target->fileio_info->param_1,
844                                 target->fileio_info->param_2);
845         else if (strcmp(target->fileio_info->identifier, "gettimeofday") == 0)
846                 sprintf(fileio_command, "F%s,%" PRIx64 ",%" PRIx64, target->fileio_info->identifier,
847                                 target->fileio_info->param_1,
848                                 target->fileio_info->param_2);
849         else if (strcmp(target->fileio_info->identifier, "isatty") == 0)
850                 sprintf(fileio_command, "F%s,%" PRIx64, target->fileio_info->identifier,
851                                 target->fileio_info->param_1);
852         else if (strcmp(target->fileio_info->identifier, "system") == 0)
853                 sprintf(fileio_command, "F%s,%" PRIx64 "/%" PRIx64, target->fileio_info->identifier,
854                                 target->fileio_info->param_1,
855                                 target->fileio_info->param_2 + 1);      /* len + trailing zero */
856         else if (strcmp(target->fileio_info->identifier, "exit") == 0) {
857                 /* If target hits exit syscall, report to GDB the program is terminated.
858                  * In addition, let target run its own exit syscall handler. */
859                 program_exited = true;
860                 sprintf(fileio_command, "W%02" PRIx64, target->fileio_info->param_1);
861         } else {
862                 LOG_DEBUG("Unknown syscall: %s", target->fileio_info->identifier);
863
864                 /* encounter unknown syscall, continue */
865                 gdb_connection->frontend_state = TARGET_RUNNING;
866                 target_resume(target, 1, 0x0, 0, 0);
867                 return;
868         }
869
870         command_len = strlen(fileio_command);
871         gdb_put_packet(connection, fileio_command, command_len);
872
873         if (program_exited) {
874                 /* Use target_resume() to let target run its own exit syscall handler. */
875                 gdb_connection->frontend_state = TARGET_RUNNING;
876                 target_resume(target, 1, 0x0, 0, 0);
877         } else {
878                 gdb_connection->frontend_state = TARGET_HALTED;
879                 rtos_update_threads(target);
880         }
881 }
882
883 static void gdb_frontend_halted(struct target *target, struct connection *connection)
884 {
885         struct gdb_connection *gdb_connection = connection->priv;
886
887         /* In the GDB protocol when we are stepping or continuing execution,
888          * we have a lingering reply. Upon receiving a halted event
889          * when we have that lingering packet, we reply to the original
890          * step or continue packet.
891          *
892          * Executing monitor commands can bring the target in and
893          * out of the running state so we'll see lots of TARGET_EVENT_XXX
894          * that are to be ignored.
895          */
896         if (gdb_connection->frontend_state == TARGET_RUNNING) {
897                 /* stop forwarding log packets! */
898                 log_remove_callback(gdb_log_callback, connection);
899
900                 /* check fileio first */
901                 if (target_get_gdb_fileio_info(target, target->fileio_info) == ERROR_OK)
902                         gdb_fileio_reply(target, connection);
903                 else
904                         gdb_signal_reply(target, connection);
905         }
906 }
907
908 static int gdb_target_callback_event_handler(struct target *target,
909                 enum target_event event, void *priv)
910 {
911         struct connection *connection = priv;
912         struct gdb_service *gdb_service = connection->service->priv;
913
914         if (gdb_service->target != target)
915                 return ERROR_OK;
916
917         switch (event) {
918                 case TARGET_EVENT_GDB_HALT:
919                         gdb_frontend_halted(target, connection);
920                         break;
921                 case TARGET_EVENT_HALTED:
922                         target_call_event_callbacks(target, TARGET_EVENT_GDB_END);
923                         break;
924                 default:
925                         break;
926         }
927
928         return ERROR_OK;
929 }
930
931 static int gdb_new_connection(struct connection *connection)
932 {
933         struct gdb_connection *gdb_connection = malloc(sizeof(struct gdb_connection));
934         struct target *target;
935         int retval;
936         int initial_ack;
937
938         target = get_target_from_connection(connection);
939         connection->priv = gdb_connection;
940         connection->cmd_ctx->current_target = target;
941
942         /* initialize gdb connection information */
943         gdb_connection->buf_p = gdb_connection->buffer;
944         gdb_connection->buf_cnt = 0;
945         gdb_connection->ctrl_c = 0;
946         gdb_connection->frontend_state = TARGET_HALTED;
947         gdb_connection->vflash_image = NULL;
948         gdb_connection->closed = false;
949         gdb_connection->busy = false;
950         gdb_connection->noack_mode = 0;
951         gdb_connection->sync = false;
952         gdb_connection->mem_write_error = false;
953         gdb_connection->attached = true;
954         gdb_connection->extended_protocol = false;
955         gdb_connection->target_desc.tdesc = NULL;
956         gdb_connection->target_desc.tdesc_length = 0;
957         gdb_connection->thread_list = NULL;
958
959         /* send ACK to GDB for debug request */
960         gdb_write(connection, "+", 1);
961
962         /* output goes through gdb connection */
963         command_set_output_handler(connection->cmd_ctx, gdb_output, connection);
964
965         /* we must remove all breakpoints registered to the target as a previous
966          * GDB session could leave dangling breakpoints if e.g. communication
967          * timed out.
968          */
969         breakpoint_clear_target(target);
970         watchpoint_clear_target(target);
971
972         if (target->rtos) {
973                 /* clean previous rtos session if supported*/
974                 if (target->rtos->type->clean)
975                         target->rtos->type->clean(target);
976
977                 /* update threads */
978                 rtos_update_threads(target);
979         }
980
981         /* remove the initial ACK from the incoming buffer */
982         retval = gdb_get_char(connection, &initial_ack);
983         if (retval != ERROR_OK)
984                 return retval;
985
986         /* FIX!!!??? would we actually ever receive a + here???
987          * Not observed.
988          */
989         if (initial_ack != '+')
990                 gdb_putback_char(connection, initial_ack);
991         target_call_event_callbacks(target, TARGET_EVENT_GDB_ATTACH);
992
993         if (gdb_use_memory_map) {
994                 /* Connect must fail if the memory map can't be set up correctly.
995                  *
996                  * This will cause an auto_probe to be invoked, which is either
997                  * a no-op or it will fail when the target isn't ready(e.g. not halted).
998                  */
999                 int i;
1000                 for (i = 0; i < flash_get_bank_count(); i++) {
1001                         struct flash_bank *p;
1002                         p = get_flash_bank_by_num_noprobe(i);
1003                         if (p->target != target)
1004                                 continue;
1005                         retval = get_flash_bank_by_num(i, &p);
1006                         if (retval != ERROR_OK) {
1007                                 LOG_ERROR("Connect failed. Consider setting up a gdb-attach event for the target " \
1008                                                 "to prepare target for GDB connect, or use 'gdb_memory_map disable'.");
1009                                 return retval;
1010                         }
1011                 }
1012         }
1013
1014         gdb_actual_connections++;
1015         log_printf_lf(all_targets->next != NULL ? LOG_LVL_INFO : LOG_LVL_DEBUG,
1016                         __FILE__, __LINE__, __func__,
1017                         "New GDB Connection: %d, Target %s, state: %s",
1018                         gdb_actual_connections,
1019                         target_name(target),
1020                         target_state_name(target));
1021
1022         /* DANGER! If we fail subsequently, we must remove this handler,
1023          * otherwise we occasionally see crashes as the timer can invoke the
1024          * callback fn.
1025          *
1026          * register callback to be informed about target events */
1027         target_register_event_callback(gdb_target_callback_event_handler, connection);
1028
1029         return ERROR_OK;
1030 }
1031
1032 static int gdb_connection_closed(struct connection *connection)
1033 {
1034         struct target *target;
1035         struct gdb_connection *gdb_connection = connection->priv;
1036
1037         target = get_target_from_connection(connection);
1038
1039         /* we're done forwarding messages. Tear down callback before
1040          * cleaning up connection.
1041          */
1042         log_remove_callback(gdb_log_callback, connection);
1043
1044         gdb_actual_connections--;
1045         LOG_DEBUG("GDB Close, Target: %s, state: %s, gdb_actual_connections=%d",
1046                 target_name(target),
1047                 target_state_name(target),
1048                 gdb_actual_connections);
1049
1050         /* see if an image built with vFlash commands is left */
1051         if (gdb_connection->vflash_image) {
1052                 image_close(gdb_connection->vflash_image);
1053                 free(gdb_connection->vflash_image);
1054                 gdb_connection->vflash_image = NULL;
1055         }
1056
1057         /* if this connection registered a debug-message receiver delete it */
1058         delete_debug_msg_receiver(connection->cmd_ctx, target);
1059
1060         if (connection->priv) {
1061                 free(connection->priv);
1062                 connection->priv = NULL;
1063         } else
1064                 LOG_ERROR("BUG: connection->priv == NULL");
1065
1066         target_unregister_event_callback(gdb_target_callback_event_handler, connection);
1067
1068         target_call_event_callbacks(target, TARGET_EVENT_GDB_END);
1069
1070         target_call_event_callbacks(target, TARGET_EVENT_GDB_DETACH);
1071
1072         return ERROR_OK;
1073 }
1074
1075 static void gdb_send_error(struct connection *connection, uint8_t the_error)
1076 {
1077         char err[4];
1078         snprintf(err, 4, "E%2.2X", the_error);
1079         gdb_put_packet(connection, err, 3);
1080 }
1081
1082 static int gdb_last_signal_packet(struct connection *connection,
1083                 char const *packet, int packet_size)
1084 {
1085         struct target *target = get_target_from_connection(connection);
1086         struct gdb_connection *gdb_con = connection->priv;
1087         char sig_reply[4];
1088         int signal_var;
1089
1090         if (!gdb_con->attached) {
1091                 /* if we are here we have received a kill packet
1092                  * reply W stop reply otherwise gdb gets very unhappy */
1093                 gdb_put_packet(connection, "W00", 3);
1094                 return ERROR_OK;
1095         }
1096
1097         signal_var = gdb_last_signal(target);
1098
1099         snprintf(sig_reply, 4, "S%2.2x", signal_var);
1100         gdb_put_packet(connection, sig_reply, 3);
1101
1102         return ERROR_OK;
1103 }
1104
1105 static inline int gdb_reg_pos(struct target *target, int pos, int len)
1106 {
1107         if (target->endianness == TARGET_LITTLE_ENDIAN)
1108                 return pos;
1109         else
1110                 return len - 1 - pos;
1111 }
1112
1113 /* Convert register to string of bytes. NB! The # of bits in the
1114  * register might be non-divisible by 8(a byte), in which
1115  * case an entire byte is shown.
1116  *
1117  * NB! the format on the wire is the target endianness
1118  *
1119  * The format of reg->value is little endian
1120  *
1121  */
1122 static void gdb_str_to_target(struct target *target,
1123                 char *tstr, struct reg *reg)
1124 {
1125         int i;
1126
1127         uint8_t *buf;
1128         int buf_len;
1129         buf = reg->value;
1130         buf_len = DIV_ROUND_UP(reg->size, 8);
1131
1132         for (i = 0; i < buf_len; i++) {
1133                 int j = gdb_reg_pos(target, i, buf_len);
1134                 tstr += sprintf(tstr, "%02x", buf[j]);
1135         }
1136 }
1137
1138 /* copy over in register buffer */
1139 static void gdb_target_to_reg(struct target *target,
1140                 char const *tstr, int str_len, uint8_t *bin)
1141 {
1142         if (str_len % 2) {
1143                 LOG_ERROR("BUG: gdb value with uneven number of characters encountered");
1144                 exit(-1);
1145         }
1146
1147         int i;
1148         for (i = 0; i < str_len; i += 2) {
1149                 unsigned t;
1150                 if (sscanf(tstr + i, "%02x", &t) != 1) {
1151                         LOG_ERROR("BUG: unable to convert register value");
1152                         exit(-1);
1153                 }
1154
1155                 int j = gdb_reg_pos(target, i/2, str_len/2);
1156                 bin[j] = t;
1157         }
1158 }
1159
1160 static int gdb_get_registers_packet(struct connection *connection,
1161                 char const *packet, int packet_size)
1162 {
1163         struct target *target = get_target_from_connection(connection);
1164         struct reg **reg_list;
1165         int reg_list_size;
1166         int retval;
1167         int reg_packet_size = 0;
1168         char *reg_packet;
1169         char *reg_packet_p;
1170         int i;
1171
1172 #ifdef _DEBUG_GDB_IO_
1173         LOG_DEBUG("-");
1174 #endif
1175
1176         if ((target->rtos != NULL) && (ERROR_OK == rtos_get_gdb_reg_list(connection)))
1177                 return ERROR_OK;
1178
1179         retval = target_get_gdb_reg_list(target, &reg_list, &reg_list_size,
1180                         REG_CLASS_GENERAL);
1181         if (retval != ERROR_OK)
1182                 return gdb_error(connection, retval);
1183
1184         for (i = 0; i < reg_list_size; i++) {
1185                 if (reg_list[i] == NULL || reg_list[i]->exist == false)
1186                         continue;
1187                 reg_packet_size += DIV_ROUND_UP(reg_list[i]->size, 8) * 2;
1188         }
1189
1190         assert(reg_packet_size > 0);
1191
1192         reg_packet = malloc(reg_packet_size + 1); /* plus one for string termination null */
1193         if (reg_packet == NULL)
1194                 return ERROR_FAIL;
1195
1196         reg_packet_p = reg_packet;
1197
1198         for (i = 0; i < reg_list_size; i++) {
1199                 if (reg_list[i] == NULL || reg_list[i]->exist == false)
1200                         continue;
1201                 if (!reg_list[i]->valid) {
1202                         retval = reg_list[i]->type->get(reg_list[i]);
1203                         if (retval != ERROR_OK && gdb_report_register_access_error) {
1204                                 LOG_DEBUG("Couldn't get register %s.", reg_list[i]->name);
1205                                 free(reg_packet);
1206                                 free(reg_list);
1207                                 return gdb_error(connection, retval);
1208                         }
1209                 }
1210                 gdb_str_to_target(target, reg_packet_p, reg_list[i]);
1211                 reg_packet_p += DIV_ROUND_UP(reg_list[i]->size, 8) * 2;
1212         }
1213
1214 #ifdef _DEBUG_GDB_IO_
1215         {
1216                 char *reg_packet_p_debug;
1217                 reg_packet_p_debug = strndup(reg_packet, reg_packet_size);
1218                 LOG_DEBUG("reg_packet: %s", reg_packet_p_debug);
1219                 free(reg_packet_p_debug);
1220         }
1221 #endif
1222
1223         gdb_put_packet(connection, reg_packet, reg_packet_size);
1224         free(reg_packet);
1225
1226         free(reg_list);
1227
1228         return ERROR_OK;
1229 }
1230
1231 static int gdb_set_registers_packet(struct connection *connection,
1232                 char const *packet, int packet_size)
1233 {
1234         struct target *target = get_target_from_connection(connection);
1235         int i;
1236         struct reg **reg_list;
1237         int reg_list_size;
1238         int retval;
1239         char const *packet_p;
1240
1241 #ifdef _DEBUG_GDB_IO_
1242         LOG_DEBUG("-");
1243 #endif
1244
1245         /* skip command character */
1246         packet++;
1247         packet_size--;
1248
1249         if (packet_size % 2) {
1250                 LOG_WARNING("GDB set_registers packet with uneven characters received, dropping connection");
1251                 return ERROR_SERVER_REMOTE_CLOSED;
1252         }
1253
1254         retval = target_get_gdb_reg_list(target, &reg_list, &reg_list_size,
1255                         REG_CLASS_GENERAL);
1256         if (retval != ERROR_OK)
1257                 return gdb_error(connection, retval);
1258
1259         packet_p = packet;
1260         for (i = 0; i < reg_list_size; i++) {
1261                 uint8_t *bin_buf;
1262                 int chars = (DIV_ROUND_UP(reg_list[i]->size, 8) * 2);
1263
1264                 if (packet_p + chars > packet + packet_size)
1265                         LOG_ERROR("BUG: register packet is too small for registers");
1266
1267                 bin_buf = malloc(DIV_ROUND_UP(reg_list[i]->size, 8));
1268                 gdb_target_to_reg(target, packet_p, chars, bin_buf);
1269
1270                 retval = reg_list[i]->type->set(reg_list[i], bin_buf);
1271                 if (retval != ERROR_OK && gdb_report_register_access_error) {
1272                         LOG_DEBUG("Couldn't set register %s.", reg_list[i]->name);
1273                         free(reg_list);
1274                         free(bin_buf);
1275                         return gdb_error(connection, retval);
1276                 }
1277
1278                 /* advance packet pointer */
1279                 packet_p += chars;
1280
1281                 free(bin_buf);
1282         }
1283
1284         /* free struct reg *reg_list[] array allocated by get_gdb_reg_list */
1285         free(reg_list);
1286
1287         gdb_put_packet(connection, "OK", 2);
1288
1289         return ERROR_OK;
1290 }
1291
1292 static int gdb_get_register_packet(struct connection *connection,
1293         char const *packet, int packet_size)
1294 {
1295         struct target *target = get_target_from_connection(connection);
1296         char *reg_packet;
1297         int reg_num = strtoul(packet + 1, NULL, 16);
1298         struct reg **reg_list;
1299         int reg_list_size;
1300         int retval;
1301
1302 #ifdef _DEBUG_GDB_IO_
1303         LOG_DEBUG("-");
1304 #endif
1305
1306         if ((target->rtos != NULL) && (ERROR_OK == rtos_get_gdb_reg(connection, reg_num)))
1307                 return ERROR_OK;
1308
1309         retval = target_get_gdb_reg_list_noread(target, &reg_list, &reg_list_size,
1310                         REG_CLASS_ALL);
1311         if (retval != ERROR_OK)
1312                 return gdb_error(connection, retval);
1313
1314         if (reg_list_size <= reg_num) {
1315                 LOG_ERROR("gdb requested a non-existing register");
1316                 return ERROR_SERVER_REMOTE_CLOSED;
1317         }
1318
1319         if (!reg_list[reg_num]->valid) {
1320                 retval = reg_list[reg_num]->type->get(reg_list[reg_num]);
1321                 if (retval != ERROR_OK && gdb_report_register_access_error) {
1322                         LOG_DEBUG("Couldn't get register %s.", reg_list[reg_num]->name);
1323                         free(reg_list);
1324                         return gdb_error(connection, retval);
1325                 }
1326         }
1327
1328         reg_packet = malloc(DIV_ROUND_UP(reg_list[reg_num]->size, 8) * 2 + 1); /* plus one for string termination null */
1329
1330         gdb_str_to_target(target, reg_packet, reg_list[reg_num]);
1331
1332         gdb_put_packet(connection, reg_packet, DIV_ROUND_UP(reg_list[reg_num]->size, 8) * 2);
1333
1334         free(reg_list);
1335         free(reg_packet);
1336
1337         return ERROR_OK;
1338 }
1339
1340 static int gdb_set_register_packet(struct connection *connection,
1341         char const *packet, int packet_size)
1342 {
1343         struct target *target = get_target_from_connection(connection);
1344         char *separator;
1345         int reg_num = strtoul(packet + 1, &separator, 16);
1346         struct reg **reg_list;
1347         int reg_list_size;
1348         int retval;
1349
1350 #ifdef _DEBUG_GDB_IO_
1351         LOG_DEBUG("-");
1352 #endif
1353
1354         if (*separator != '=') {
1355                 LOG_ERROR("GDB 'set register packet', but no '=' following the register number");
1356                 return ERROR_SERVER_REMOTE_CLOSED;
1357         }
1358         size_t chars = strlen(separator + 1);
1359         uint8_t *bin_buf = malloc(chars / 2);
1360         gdb_target_to_reg(target, separator + 1, chars, bin_buf);
1361
1362         if ((target->rtos != NULL) &&
1363                         (ERROR_OK == rtos_set_reg(connection, reg_num, bin_buf))) {
1364                 free(bin_buf);
1365                 gdb_put_packet(connection, "OK", 2);
1366                 return ERROR_OK;
1367         }
1368
1369         retval = target_get_gdb_reg_list_noread(target, &reg_list, &reg_list_size,
1370                         REG_CLASS_ALL);
1371         if (retval != ERROR_OK) {
1372                 free(bin_buf);
1373                 return gdb_error(connection, retval);
1374         }
1375
1376         if (reg_list_size <= reg_num) {
1377                 LOG_ERROR("gdb requested a non-existing register");
1378                 free(bin_buf);
1379                 free(reg_list);
1380                 return ERROR_SERVER_REMOTE_CLOSED;
1381         }
1382
1383         if (chars != (DIV_ROUND_UP(reg_list[reg_num]->size, 8) * 2)) {
1384                 LOG_ERROR("gdb sent %d bits for a %d-bit register (%s)",
1385                                 (int) chars * 4, reg_list[reg_num]->size, reg_list[reg_num]->name);
1386                 free(bin_buf);
1387                 free(reg_list);
1388                 return ERROR_SERVER_REMOTE_CLOSED;
1389         }
1390
1391         gdb_target_to_reg(target, separator + 1, chars, bin_buf);
1392
1393         retval = reg_list[reg_num]->type->set(reg_list[reg_num], bin_buf);
1394         if (retval != ERROR_OK && gdb_report_register_access_error) {
1395                 LOG_DEBUG("Couldn't set register %s.", reg_list[reg_num]->name);
1396                 free(bin_buf);
1397                 free(reg_list);
1398                 return gdb_error(connection, retval);
1399         }
1400
1401         gdb_put_packet(connection, "OK", 2);
1402
1403         free(bin_buf);
1404         free(reg_list);
1405
1406         return ERROR_OK;
1407 }
1408
1409 /* No attempt is made to translate the "retval" to
1410  * GDB speak. This has to be done at the calling
1411  * site as no mapping really exists.
1412  */
1413 static int gdb_error(struct connection *connection, int retval)
1414 {
1415         LOG_DEBUG("Reporting %i to GDB as generic error", retval);
1416         gdb_send_error(connection, EFAULT);
1417         return ERROR_OK;
1418 }
1419
1420 /* We don't have to worry about the default 2 second timeout for GDB packets,
1421  * because GDB breaks up large memory reads into smaller reads.
1422  */
1423 static int gdb_read_memory_packet(struct connection *connection,
1424                 char const *packet, int packet_size)
1425 {
1426         struct target *target = get_target_from_connection(connection);
1427         char *separator;
1428         uint64_t addr = 0;
1429         uint32_t len = 0;
1430
1431         uint8_t *buffer;
1432         char *hex_buffer;
1433
1434         int retval = ERROR_OK;
1435
1436         /* skip command character */
1437         packet++;
1438
1439         addr = strtoull(packet, &separator, 16);
1440
1441         if (*separator != ',') {
1442                 LOG_ERROR("incomplete read memory packet received, dropping connection");
1443                 return ERROR_SERVER_REMOTE_CLOSED;
1444         }
1445
1446         len = strtoul(separator + 1, NULL, 16);
1447
1448         if (!len) {
1449                 LOG_WARNING("invalid read memory packet received (len == 0)");
1450                 gdb_put_packet(connection, "", 0);
1451                 return ERROR_OK;
1452         }
1453
1454         buffer = malloc(len);
1455
1456         LOG_DEBUG("addr: 0x%16.16" PRIx64 ", len: 0x%8.8" PRIx32 "", addr, len);
1457
1458         retval = target_read_buffer(target, addr, len, buffer);
1459
1460         if ((retval != ERROR_OK) && !gdb_report_data_abort) {
1461                 /* TODO : Here we have to lie and send back all zero's lest stack traces won't work.
1462                  * At some point this might be fixed in GDB, in which case this code can be removed.
1463                  *
1464                  * OpenOCD developers are acutely aware of this problem, but there is nothing
1465                  * gained by involving the user in this problem that hopefully will get resolved
1466                  * eventually
1467                  *
1468                  * http://sourceware.org/cgi-bin/gnatsweb.pl? \
1469                  * cmd = view%20audit-trail&database = gdb&pr = 2395
1470                  *
1471                  * For now, the default is to fix up things to make current GDB versions work.
1472                  * This can be overwritten using the gdb_report_data_abort <'enable'|'disable'> command.
1473                  */
1474                 memset(buffer, 0, len);
1475                 retval = ERROR_OK;
1476         }
1477
1478         if (retval == ERROR_OK) {
1479                 hex_buffer = malloc(len * 2 + 1);
1480
1481                 size_t pkt_len = hexify(hex_buffer, buffer, len, len * 2 + 1);
1482
1483                 gdb_put_packet(connection, hex_buffer, pkt_len);
1484
1485                 free(hex_buffer);
1486         } else
1487                 retval = gdb_error(connection, retval);
1488
1489         free(buffer);
1490
1491         return retval;
1492 }
1493
1494 static int gdb_write_memory_packet(struct connection *connection,
1495                 char const *packet, int packet_size)
1496 {
1497         struct target *target = get_target_from_connection(connection);
1498         char *separator;
1499         uint64_t addr = 0;
1500         uint32_t len = 0;
1501
1502         uint8_t *buffer;
1503         int retval;
1504
1505         /* skip command character */
1506         packet++;
1507
1508         addr = strtoull(packet, &separator, 16);
1509
1510         if (*separator != ',') {
1511                 LOG_ERROR("incomplete write memory packet received, dropping connection");
1512                 return ERROR_SERVER_REMOTE_CLOSED;
1513         }
1514
1515         len = strtoul(separator + 1, &separator, 16);
1516
1517         if (*(separator++) != ':') {
1518                 LOG_ERROR("incomplete write memory packet received, dropping connection");
1519                 return ERROR_SERVER_REMOTE_CLOSED;
1520         }
1521
1522         buffer = malloc(len);
1523
1524         LOG_DEBUG("addr: 0x%" PRIx64 ", len: 0x%8.8" PRIx32 "", addr, len);
1525
1526         if (unhexify(buffer, separator, len) != len)
1527                 LOG_ERROR("unable to decode memory packet");
1528
1529         retval = target_write_buffer(target, addr, len, buffer);
1530
1531         if (retval == ERROR_OK)
1532                 gdb_put_packet(connection, "OK", 2);
1533         else
1534                 retval = gdb_error(connection, retval);
1535
1536         free(buffer);
1537
1538         return retval;
1539 }
1540
1541 static int gdb_write_memory_binary_packet(struct connection *connection,
1542                 char const *packet, int packet_size)
1543 {
1544         struct target *target = get_target_from_connection(connection);
1545         char *separator;
1546         uint64_t addr = 0;
1547         uint32_t len = 0;
1548
1549         int retval = ERROR_OK;
1550         /* Packets larger than fast_limit bytes will be acknowledged instantly on
1551          * the assumption that we're in a download and it's important to go as fast
1552          * as possible. */
1553         uint32_t fast_limit = 8;
1554
1555         /* skip command character */
1556         packet++;
1557
1558         addr = strtoull(packet, &separator, 16);
1559
1560         if (*separator != ',') {
1561                 LOG_ERROR("incomplete write memory binary packet received, dropping connection");
1562                 return ERROR_SERVER_REMOTE_CLOSED;
1563         }
1564
1565         len = strtoul(separator + 1, &separator, 16);
1566
1567         if (*(separator++) != ':') {
1568                 LOG_ERROR("incomplete write memory binary packet received, dropping connection");
1569                 return ERROR_SERVER_REMOTE_CLOSED;
1570         }
1571
1572         struct gdb_connection *gdb_connection = connection->priv;
1573
1574         if (gdb_connection->mem_write_error)
1575                 retval = ERROR_FAIL;
1576
1577         if (retval == ERROR_OK) {
1578                 if (len >= fast_limit) {
1579                         /* By replying the packet *immediately* GDB will send us a new packet
1580                          * while we write the last one to the target.
1581                          * We only do this for larger writes, so that users who do something like:
1582                          * p *((int*)0xdeadbeef)=8675309
1583                          * will get immediate feedback that that write failed.
1584                          */
1585                         gdb_put_packet(connection, "OK", 2);
1586                 }
1587         } else {
1588                 retval = gdb_error(connection, retval);
1589                 /* now that we have reported the memory write error, we can clear the condition */
1590                 gdb_connection->mem_write_error = false;
1591                 if (retval != ERROR_OK)
1592                         return retval;
1593         }
1594
1595         if (len) {
1596                 LOG_DEBUG("addr: 0x%" PRIx64 ", len: 0x%8.8" PRIx32 "", addr, len);
1597
1598                 retval = target_write_buffer(target, addr, len, (uint8_t *)separator);
1599                 if (retval != ERROR_OK)
1600                         gdb_connection->mem_write_error = true;
1601         }
1602
1603         if (len < fast_limit) {
1604                 if (retval != ERROR_OK) {
1605                         gdb_error(connection, retval);
1606                         gdb_connection->mem_write_error = false;
1607                 } else {
1608                         gdb_put_packet(connection, "OK", 2);
1609                 }
1610         }
1611
1612         return ERROR_OK;
1613 }
1614
1615 static int gdb_step_continue_packet(struct connection *connection,
1616                 char const *packet, int packet_size)
1617 {
1618         struct target *target = get_target_from_connection(connection);
1619         int current = 0;
1620         uint64_t address = 0x0;
1621         int retval = ERROR_OK;
1622
1623         LOG_DEBUG("-");
1624
1625         if (packet_size > 1)
1626                 address = strtoull(packet + 1, NULL, 16);
1627         else
1628                 current = 1;
1629
1630         gdb_running_type = packet[0];
1631         if (packet[0] == 'c') {
1632                 LOG_DEBUG("continue");
1633                 /* resume at current address, don't handle breakpoints, not debugging */
1634                 retval = target_resume(target, current, address, 0, 0);
1635         } else if (packet[0] == 's') {
1636                 LOG_DEBUG("step");
1637                 /* step at current or address, don't handle breakpoints */
1638                 retval = target_step(target, current, address, 0);
1639         }
1640         return retval;
1641 }
1642
1643 static int gdb_breakpoint_watchpoint_packet(struct connection *connection,
1644                 char const *packet, int packet_size)
1645 {
1646         struct target *target = get_target_from_connection(connection);
1647         int type;
1648         enum breakpoint_type bp_type = BKPT_SOFT /* dummy init to avoid warning */;
1649         enum watchpoint_rw wp_type = WPT_READ /* dummy init to avoid warning */;
1650         uint64_t address;
1651         uint32_t size;
1652         char *separator;
1653         int retval;
1654
1655         LOG_DEBUG("[%s]", target_name(target));
1656
1657         type = strtoul(packet + 1, &separator, 16);
1658
1659         if (type == 0)  /* memory breakpoint */
1660                 bp_type = BKPT_SOFT;
1661         else if (type == 1)     /* hardware breakpoint */
1662                 bp_type = BKPT_HARD;
1663         else if (type == 2)     /* write watchpoint */
1664                 wp_type = WPT_WRITE;
1665         else if (type == 3)     /* read watchpoint */
1666                 wp_type = WPT_READ;
1667         else if (type == 4)     /* access watchpoint */
1668                 wp_type = WPT_ACCESS;
1669         else {
1670                 LOG_ERROR("invalid gdb watch/breakpoint type(%d), dropping connection", type);
1671                 return ERROR_SERVER_REMOTE_CLOSED;
1672         }
1673
1674         if (gdb_breakpoint_override && ((bp_type == BKPT_SOFT) || (bp_type == BKPT_HARD)))
1675                 bp_type = gdb_breakpoint_override_type;
1676
1677         if (*separator != ',') {
1678                 LOG_ERROR("incomplete breakpoint/watchpoint packet received, dropping connection");
1679                 return ERROR_SERVER_REMOTE_CLOSED;
1680         }
1681
1682         address = strtoull(separator + 1, &separator, 16);
1683
1684         if (*separator != ',') {
1685                 LOG_ERROR("incomplete breakpoint/watchpoint packet received, dropping connection");
1686                 return ERROR_SERVER_REMOTE_CLOSED;
1687         }
1688
1689         size = strtoul(separator + 1, &separator, 16);
1690
1691         switch (type) {
1692                 case 0:
1693                 case 1:
1694                         if (packet[0] == 'Z') {
1695                                 retval = breakpoint_add(target, address, size, bp_type);
1696                                 if (retval != ERROR_OK) {
1697                                         retval = gdb_error(connection, retval);
1698                                         if (retval != ERROR_OK)
1699                                                 return retval;
1700                                 } else
1701                                         gdb_put_packet(connection, "OK", 2);
1702                         } else {
1703                                 breakpoint_remove(target, address);
1704                                 gdb_put_packet(connection, "OK", 2);
1705                         }
1706                         break;
1707                 case 2:
1708                 case 3:
1709                 case 4:
1710                 {
1711                         if (packet[0] == 'Z') {
1712                                 retval = watchpoint_add(target, address, size, wp_type, 0, 0xffffffffu);
1713                                 if (retval != ERROR_OK) {
1714                                         retval = gdb_error(connection, retval);
1715                                         if (retval != ERROR_OK)
1716                                                 return retval;
1717                                 } else
1718                                         gdb_put_packet(connection, "OK", 2);
1719                         } else {
1720                                 watchpoint_remove(target, address);
1721                                 gdb_put_packet(connection, "OK", 2);
1722                         }
1723                         break;
1724                 }
1725                 default:
1726                         break;
1727         }
1728
1729         return ERROR_OK;
1730 }
1731
1732 /* print out a string and allocate more space as needed,
1733  * mainly used for XML at this point
1734  */
1735 static __attribute__ ((format (PRINTF_ATTRIBUTE_FORMAT, 5, 6))) void xml_printf(int *retval,
1736                 char **xml, int *pos, int *size, const char *fmt, ...)
1737 {
1738         if (*retval != ERROR_OK)
1739                 return;
1740         int first = 1;
1741
1742         for (;; ) {
1743                 if ((*xml == NULL) || (!first)) {
1744                         /* start by 0 to exercise all the code paths.
1745                          * Need minimum 2 bytes to fit 1 char and 0 terminator. */
1746
1747                         *size = *size * 2 + 2;
1748                         char *t = *xml;
1749                         *xml = realloc(*xml, *size);
1750                         if (*xml == NULL) {
1751                                 if (t)
1752                                         free(t);
1753                                 *retval = ERROR_SERVER_REMOTE_CLOSED;
1754                                 return;
1755                         }
1756                 }
1757
1758                 va_list ap;
1759                 int ret;
1760                 va_start(ap, fmt);
1761                 ret = vsnprintf(*xml + *pos, *size - *pos, fmt, ap);
1762                 va_end(ap);
1763                 if ((ret > 0) && ((ret + 1) < *size - *pos)) {
1764                         *pos += ret;
1765                         return;
1766                 }
1767                 /* there was just enough or not enough space, allocate more. */
1768                 first = 0;
1769         }
1770 }
1771
1772 static int decode_xfer_read(char const *buf, char **annex, int *ofs, unsigned int *len)
1773 {
1774         /* Locate the annex. */
1775         const char *annex_end = strchr(buf, ':');
1776         if (annex_end == NULL)
1777                 return ERROR_FAIL;
1778
1779         /* After the read marker and annex, qXfer looks like a
1780          * traditional 'm' packet. */
1781         char *separator;
1782         *ofs = strtoul(annex_end + 1, &separator, 16);
1783
1784         if (*separator != ',')
1785                 return ERROR_FAIL;
1786
1787         *len = strtoul(separator + 1, NULL, 16);
1788
1789         /* Extract the annex if needed */
1790         if (annex != NULL) {
1791                 *annex = strndup(buf, annex_end - buf);
1792                 if (*annex == NULL)
1793                         return ERROR_FAIL;
1794         }
1795
1796         return ERROR_OK;
1797 }
1798
1799 static int compare_bank(const void *a, const void *b)
1800 {
1801         struct flash_bank *b1, *b2;
1802         b1 = *((struct flash_bank **)a);
1803         b2 = *((struct flash_bank **)b);
1804
1805         if (b1->base == b2->base)
1806                 return 0;
1807         else if (b1->base > b2->base)
1808                 return 1;
1809         else
1810                 return -1;
1811 }
1812
1813 static int gdb_memory_map(struct connection *connection,
1814                 char const *packet, int packet_size)
1815 {
1816         /* We get away with only specifying flash here. Regions that are not
1817          * specified are treated as if we provided no memory map(if not we
1818          * could detect the holes and mark them as RAM).
1819          * Normally we only execute this code once, but no big deal if we
1820          * have to regenerate it a couple of times.
1821          */
1822
1823         struct target *target = get_target_from_connection(connection);
1824         struct flash_bank *p;
1825         char *xml = NULL;
1826         int size = 0;
1827         int pos = 0;
1828         int retval = ERROR_OK;
1829         struct flash_bank **banks;
1830         int offset;
1831         int length;
1832         char *separator;
1833         target_addr_t ram_start = 0;
1834         int i;
1835         int target_flash_banks = 0;
1836
1837         /* skip command character */
1838         packet += 23;
1839
1840         offset = strtoul(packet, &separator, 16);
1841         length = strtoul(separator + 1, &separator, 16);
1842
1843         xml_printf(&retval, &xml, &pos, &size, "<memory-map>\n");
1844
1845         /* Sort banks in ascending order.  We need to report non-flash
1846          * memory as ram (or rather read/write) by default for GDB, since
1847          * it has no concept of non-cacheable read/write memory (i/o etc).
1848          */
1849         banks = malloc(sizeof(struct flash_bank *)*flash_get_bank_count());
1850
1851         for (i = 0; i < flash_get_bank_count(); i++) {
1852                 p = get_flash_bank_by_num_noprobe(i);
1853                 if (p->target != target)
1854                         continue;
1855                 retval = get_flash_bank_by_num(i, &p);
1856                 if (retval != ERROR_OK) {
1857                         free(banks);
1858                         gdb_error(connection, retval);
1859                         return retval;
1860                 }
1861                 banks[target_flash_banks++] = p;
1862         }
1863
1864         qsort(banks, target_flash_banks, sizeof(struct flash_bank *),
1865                 compare_bank);
1866
1867         for (i = 0; i < target_flash_banks; i++) {
1868                 int j;
1869                 unsigned sector_size = 0;
1870                 unsigned group_len = 0;
1871
1872                 p = banks[i];
1873
1874                 if (ram_start < p->base)
1875                         xml_printf(&retval, &xml, &pos, &size,
1876                                 "<memory type=\"ram\" start=\"" TARGET_ADDR_FMT "\" "
1877                                 "length=\"" TARGET_ADDR_FMT "\"/>\n",
1878                                 ram_start, p->base - ram_start);
1879
1880                 /* Report adjacent groups of same-size sectors.  So for
1881                  * example top boot CFI flash will list an initial region
1882                  * with several large sectors (maybe 128KB) and several
1883                  * smaller ones at the end (maybe 32KB).  STR7 will have
1884                  * regions with 8KB, 32KB, and 64KB sectors; etc.
1885                  */
1886                 for (j = 0; j < p->num_sectors; j++) {
1887
1888                         /* Maybe start a new group of sectors. */
1889                         if (sector_size == 0) {
1890                                 if (p->sectors[j].offset + p->sectors[j].size > p->size) {
1891                                         LOG_WARNING("The flash sector at offset 0x%08" PRIx32
1892                                                 " overflows the end of %s bank.",
1893                                                 p->sectors[j].offset, p->name);
1894                                         LOG_WARNING("The rest of bank will not show in gdb memory map.");
1895                                         break;
1896                                 }
1897                                 target_addr_t start;
1898                                 start = p->base + p->sectors[j].offset;
1899                                 xml_printf(&retval, &xml, &pos, &size,
1900                                         "<memory type=\"flash\" "
1901                                         "start=\"" TARGET_ADDR_FMT "\" ",
1902                                         start);
1903                                 sector_size = p->sectors[j].size;
1904                                 group_len = sector_size;
1905                         } else {
1906                                 group_len += sector_size; /* equal to p->sectors[j].size */
1907                         }
1908
1909                         /* Does this finish a group of sectors?
1910                          * If not, continue an already-started group.
1911                          */
1912                         if (j < p->num_sectors - 1
1913                                         && p->sectors[j + 1].size == sector_size
1914                                         && p->sectors[j + 1].offset == p->sectors[j].offset + sector_size
1915                                         && p->sectors[j + 1].offset + p->sectors[j + 1].size <= p->size)
1916                                 continue;
1917
1918                         xml_printf(&retval, &xml, &pos, &size,
1919                                 "length=\"0x%x\">\n"
1920                                 "<property name=\"blocksize\">"
1921                                 "0x%x</property>\n"
1922                                 "</memory>\n",
1923                                 group_len,
1924                                 sector_size);
1925                         sector_size = 0;
1926                 }
1927
1928                 ram_start = p->base + p->size;
1929         }
1930
1931         if (ram_start != 0)
1932                 xml_printf(&retval, &xml, &pos, &size,
1933                         "<memory type=\"ram\" start=\"" TARGET_ADDR_FMT "\" "
1934                         "length=\"" TARGET_ADDR_FMT "\"/>\n",
1935                         ram_start, target_address_max(target) - ram_start + 1);
1936         /* ELSE a flash chip could be at the very end of the address space, in
1937          * which case ram_start will be precisely 0 */
1938
1939         free(banks);
1940
1941         xml_printf(&retval, &xml, &pos, &size, "</memory-map>\n");
1942
1943         if (retval != ERROR_OK) {
1944                 free(xml);
1945                 gdb_error(connection, retval);
1946                 return retval;
1947         }
1948
1949         if (offset + length > pos)
1950                 length = pos - offset;
1951
1952         char *t = malloc(length + 1);
1953         t[0] = 'l';
1954         memcpy(t + 1, xml + offset, length);
1955         gdb_put_packet(connection, t, length + 1);
1956
1957         free(t);
1958         free(xml);
1959         return ERROR_OK;
1960 }
1961
1962 static const char *gdb_get_reg_type_name(enum reg_type type)
1963 {
1964         switch (type) {
1965                 case REG_TYPE_BOOL:
1966                         return "bool";
1967                 case REG_TYPE_INT:
1968                         return "int";
1969                 case REG_TYPE_INT8:
1970                         return "int8";
1971                 case REG_TYPE_INT16:
1972                         return "int16";
1973                 case REG_TYPE_INT32:
1974                         return "int32";
1975                 case REG_TYPE_INT64:
1976                         return "int64";
1977                 case REG_TYPE_INT128:
1978                         return "int128";
1979                 case REG_TYPE_UINT:
1980                         return "uint";
1981                 case REG_TYPE_UINT8:
1982                         return "uint8";
1983                 case REG_TYPE_UINT16:
1984                         return "uint16";
1985                 case REG_TYPE_UINT32:
1986                         return "uint32";
1987                 case REG_TYPE_UINT64:
1988                         return "uint64";
1989                 case REG_TYPE_UINT128:
1990                         return "uint128";
1991                 case REG_TYPE_CODE_PTR:
1992                         return "code_ptr";
1993                 case REG_TYPE_DATA_PTR:
1994                         return "data_ptr";
1995                 case REG_TYPE_FLOAT:
1996                         return "float";
1997                 case REG_TYPE_IEEE_SINGLE:
1998                         return "ieee_single";
1999                 case REG_TYPE_IEEE_DOUBLE:
2000                         return "ieee_double";
2001                 case REG_TYPE_ARCH_DEFINED:
2002                         return "int"; /* return arbitrary string to avoid compile warning. */
2003         }
2004
2005         return "int"; /* "int" as default value */
2006 }
2007
2008 static int lookup_add_arch_defined_types(char const **arch_defined_types_list[], const char *type_id,
2009                                         int *num_arch_defined_types)
2010 {
2011         int tbl_sz = *num_arch_defined_types;
2012
2013         if (type_id != NULL && (strcmp(type_id, ""))) {
2014                 for (int j = 0; j < (tbl_sz + 1); j++) {
2015                         if (!((*arch_defined_types_list)[j])) {
2016                                 (*arch_defined_types_list)[tbl_sz++] = type_id;
2017                                 *arch_defined_types_list = realloc(*arch_defined_types_list,
2018                                                                 sizeof(char *) * (tbl_sz + 1));
2019                                 (*arch_defined_types_list)[tbl_sz] = NULL;
2020                                 *num_arch_defined_types = tbl_sz;
2021                                 return 1;
2022                         } else {
2023                                 if (!strcmp((*arch_defined_types_list)[j], type_id))
2024                                         return 0;
2025                         }
2026                 }
2027         }
2028
2029         return -1;
2030 }
2031
2032 static int gdb_generate_reg_type_description(struct target *target,
2033                 char **tdesc, int *pos, int *size, struct reg_data_type *type,
2034                 char const **arch_defined_types_list[], int * num_arch_defined_types)
2035 {
2036         int retval = ERROR_OK;
2037
2038         if (type->type_class == REG_TYPE_CLASS_VECTOR) {
2039                 struct reg_data_type *data_type = type->reg_type_vector->type;
2040                 if (data_type->type == REG_TYPE_ARCH_DEFINED) {
2041                         if (lookup_add_arch_defined_types(arch_defined_types_list, data_type->id,
2042                                                         num_arch_defined_types))
2043                                 gdb_generate_reg_type_description(target, tdesc, pos, size, data_type,
2044                                                                 arch_defined_types_list,
2045                                                                 num_arch_defined_types);
2046                 }
2047                 /* <vector id="id" type="type" count="count"/> */
2048                 xml_printf(&retval, tdesc, pos, size,
2049                                 "<vector id=\"%s\" type=\"%s\" count=\"%d\"/>\n",
2050                                 type->id, type->reg_type_vector->type->id,
2051                                 type->reg_type_vector->count);
2052
2053         } else if (type->type_class == REG_TYPE_CLASS_UNION) {
2054                 struct reg_data_type_union_field *field;
2055                 field = type->reg_type_union->fields;
2056                 while (field != NULL) {
2057                         struct reg_data_type *data_type = field->type;
2058                         if (data_type->type == REG_TYPE_ARCH_DEFINED) {
2059                                 if (lookup_add_arch_defined_types(arch_defined_types_list, data_type->id,
2060                                                                 num_arch_defined_types))
2061                                         gdb_generate_reg_type_description(target, tdesc, pos, size, data_type,
2062                                                                         arch_defined_types_list,
2063                                                                         num_arch_defined_types);
2064                         }
2065
2066                         field = field->next;
2067                 }
2068                 /* <union id="id">
2069                  *  <field name="name" type="type"/> ...
2070                  * </union> */
2071                 xml_printf(&retval, tdesc, pos, size,
2072                                 "<union id=\"%s\">\n",
2073                                 type->id);
2074
2075                 field = type->reg_type_union->fields;
2076                 while (field != NULL) {
2077                         xml_printf(&retval, tdesc, pos, size,
2078                                         "<field name=\"%s\" type=\"%s\"/>\n",
2079                                         field->name, field->type->id);
2080
2081                         field = field->next;
2082                 }
2083
2084                 xml_printf(&retval, tdesc, pos, size,
2085                                 "</union>\n");
2086
2087         } else if (type->type_class == REG_TYPE_CLASS_STRUCT) {
2088                 struct reg_data_type_struct_field *field;
2089                 field = type->reg_type_struct->fields;
2090
2091                 if (field->use_bitfields) {
2092                         /* <struct id="id" size="size">
2093                          *  <field name="name" start="start" end="end"/> ...
2094                          * </struct> */
2095                         xml_printf(&retval, tdesc, pos, size,
2096                                         "<struct id=\"%s\" size=\"%d\">\n",
2097                                         type->id, type->reg_type_struct->size);
2098                         while (field != NULL) {
2099                                 xml_printf(&retval, tdesc, pos, size,
2100                                                 "<field name=\"%s\" start=\"%d\" end=\"%d\" type=\"%s\" />\n",
2101                                                 field->name, field->bitfield->start, field->bitfield->end,
2102                                                 gdb_get_reg_type_name(field->bitfield->type));
2103
2104                                 field = field->next;
2105                         }
2106                 } else {
2107                         while (field != NULL) {
2108                                 struct reg_data_type *data_type = field->type;
2109                                 if (data_type->type == REG_TYPE_ARCH_DEFINED) {
2110                                         if (lookup_add_arch_defined_types(arch_defined_types_list, data_type->id,
2111                                                                         num_arch_defined_types))
2112                                                 gdb_generate_reg_type_description(target, tdesc, pos, size, data_type,
2113                                                                                 arch_defined_types_list,
2114                                                                                 num_arch_defined_types);
2115                                 }
2116                         }
2117
2118                         /* <struct id="id">
2119                          *  <field name="name" type="type"/> ...
2120                          * </struct> */
2121                         xml_printf(&retval, tdesc, pos, size,
2122                                         "<struct id=\"%s\">\n",
2123                                         type->id);
2124                         while (field != NULL) {
2125                                 xml_printf(&retval, tdesc, pos, size,
2126                                                 "<field name=\"%s\" type=\"%s\"/>\n",
2127                                                 field->name, field->type->id);
2128
2129                                 field = field->next;
2130                         }
2131                 }
2132
2133                 xml_printf(&retval, tdesc, pos, size,
2134                                 "</struct>\n");
2135
2136         } else if (type->type_class == REG_TYPE_CLASS_FLAGS) {
2137                 /* <flags id="id" size="size">
2138                  *  <field name="name" start="start" end="end"/> ...
2139                  * </flags> */
2140                 xml_printf(&retval, tdesc, pos, size,
2141                                 "<flags id=\"%s\" size=\"%d\">\n",
2142                                 type->id, type->reg_type_flags->size);
2143
2144                 struct reg_data_type_flags_field *field;
2145                 field = type->reg_type_flags->fields;
2146                 while (field != NULL) {
2147                         xml_printf(&retval, tdesc, pos, size,
2148                                         "<field name=\"%s\" start=\"%d\" end=\"%d\" type=\"%s\" />\n",
2149                                         field->name, field->bitfield->start, field->bitfield->end,
2150                                         gdb_get_reg_type_name(field->bitfield->type));
2151
2152                         field = field->next;
2153                 }
2154
2155                 xml_printf(&retval, tdesc, pos, size,
2156                                 "</flags>\n");
2157
2158         }
2159
2160         return ERROR_OK;
2161 }
2162
2163 /* Get a list of available target registers features. feature_list must
2164  * be freed by caller.
2165  */
2166 static int get_reg_features_list(struct target *target, char const **feature_list[], int *feature_list_size,
2167                 struct reg **reg_list, int reg_list_size)
2168 {
2169         int tbl_sz = 0;
2170
2171         /* Start with only one element */
2172         *feature_list = calloc(1, sizeof(char *));
2173
2174         for (int i = 0; i < reg_list_size; i++) {
2175                 if (reg_list[i]->exist == false)
2176                         continue;
2177
2178                 if (reg_list[i]->feature != NULL
2179                         && reg_list[i]->feature->name != NULL
2180                         && (strcmp(reg_list[i]->feature->name, ""))) {
2181                         /* We found a feature, check if the feature is already in the
2182                          * table. If not, allocate a new entry for the table and
2183                          * put the new feature in it.
2184                          */
2185                         for (int j = 0; j < (tbl_sz + 1); j++) {
2186                                 if (!((*feature_list)[j])) {
2187                                         (*feature_list)[tbl_sz++] = reg_list[i]->feature->name;
2188                                         *feature_list = realloc(*feature_list, sizeof(char *) * (tbl_sz + 1));
2189                                         (*feature_list)[tbl_sz] = NULL;
2190                                         break;
2191                                 } else {
2192                                         if (!strcmp((*feature_list)[j], reg_list[i]->feature->name))
2193                                                 break;
2194                                 }
2195                         }
2196                 }
2197         }
2198
2199         if (feature_list_size)
2200                 *feature_list_size = tbl_sz;
2201
2202         return ERROR_OK;
2203 }
2204
2205 static int gdb_generate_target_description(struct target *target, char **tdesc_out)
2206 {
2207         int retval = ERROR_OK;
2208         struct reg **reg_list = NULL;
2209         int reg_list_size;
2210         char const *architecture;
2211         char const **features = NULL;
2212         int feature_list_size = 0;
2213         char *tdesc = NULL;
2214         int pos = 0;
2215         int size = 0;
2216
2217
2218         retval = target_get_gdb_reg_list_noread(target, &reg_list,
2219                         &reg_list_size, REG_CLASS_ALL);
2220
2221         if (retval != ERROR_OK) {
2222                 LOG_ERROR("get register list failed");
2223                 retval = ERROR_FAIL;
2224                 goto error;
2225         }
2226
2227         if (reg_list_size <= 0) {
2228                 LOG_ERROR("get register list failed");
2229                 retval = ERROR_FAIL;
2230                 goto error;
2231         }
2232
2233         /* Get a list of available target registers features */
2234         retval = get_reg_features_list(target, &features, &feature_list_size, reg_list, reg_list_size);
2235         if (retval != ERROR_OK) {
2236                 LOG_ERROR("Can't get the registers feature list");
2237                 retval = ERROR_FAIL;
2238                 goto error;
2239         }
2240
2241         /* If we found some features associated with registers, create sections */
2242         int current_feature = 0;
2243
2244         xml_printf(&retval, &tdesc, &pos, &size,
2245                         "<?xml version=\"1.0\"?>\n"
2246                         "<!DOCTYPE target SYSTEM \"gdb-target.dtd\">\n"
2247                         "<target version=\"1.0\">\n");
2248
2249         /* generate architecture element if supported by target */
2250         architecture = target_get_gdb_arch(target);
2251         if (architecture != NULL)
2252                 xml_printf(&retval, &tdesc, &pos, &size,
2253                                 "<architecture>%s</architecture>\n", architecture);
2254
2255         /* generate target description according to register list */
2256         if (features != NULL) {
2257                 while (features[current_feature]) {
2258                         char const **arch_defined_types = NULL;
2259                         int num_arch_defined_types = 0;
2260
2261                         arch_defined_types = calloc(1, sizeof(char *));
2262                         xml_printf(&retval, &tdesc, &pos, &size,
2263                                         "<feature name=\"%s\">\n",
2264                                         features[current_feature]);
2265
2266                         int i;
2267                         for (i = 0; i < reg_list_size; i++) {
2268
2269                                 if (reg_list[i]->exist == false)
2270                                         continue;
2271
2272                                 if (strcmp(reg_list[i]->feature->name, features[current_feature]))
2273                                         continue;
2274
2275                                 const char *type_str;
2276                                 if (reg_list[i]->reg_data_type != NULL) {
2277                                         if (reg_list[i]->reg_data_type->type == REG_TYPE_ARCH_DEFINED) {
2278                                                 /* generate <type... first, if there are architecture-defined types. */
2279                                                 if (lookup_add_arch_defined_types(&arch_defined_types,
2280                                                                                 reg_list[i]->reg_data_type->id,
2281                                                                                 &num_arch_defined_types))
2282                                                         gdb_generate_reg_type_description(target, &tdesc, &pos, &size,
2283                                                                                         reg_list[i]->reg_data_type,
2284                                                                                         &arch_defined_types,
2285                                                                                         &num_arch_defined_types);
2286
2287                                                 type_str = reg_list[i]->reg_data_type->id;
2288                                         } else {
2289                                                 /* predefined type */
2290                                                 type_str = gdb_get_reg_type_name(
2291                                                                 reg_list[i]->reg_data_type->type);
2292                                         }
2293                                 } else {
2294                                         /* Default type is "int" */
2295                                         type_str = "int";
2296                                 }
2297
2298                                 xml_printf(&retval, &tdesc, &pos, &size,
2299                                                 "<reg name=\"%s\"", reg_list[i]->name);
2300                                 xml_printf(&retval, &tdesc, &pos, &size,
2301                                                 " bitsize=\"%d\"", reg_list[i]->size);
2302                                 xml_printf(&retval, &tdesc, &pos, &size,
2303                                                 " regnum=\"%d\"", reg_list[i]->number);
2304                                 if (reg_list[i]->caller_save)
2305                                         xml_printf(&retval, &tdesc, &pos, &size,
2306                                                         " save-restore=\"yes\"");
2307                                 else
2308                                         xml_printf(&retval, &tdesc, &pos, &size,
2309                                                         " save-restore=\"no\"");
2310
2311                                 xml_printf(&retval, &tdesc, &pos, &size,
2312                                                 " type=\"%s\"", type_str);
2313
2314                                 if (reg_list[i]->group != NULL)
2315                                         xml_printf(&retval, &tdesc, &pos, &size,
2316                                                         " group=\"%s\"", reg_list[i]->group);
2317
2318                                 xml_printf(&retval, &tdesc, &pos, &size,
2319                                                 "/>\n");
2320                         }
2321
2322                         xml_printf(&retval, &tdesc, &pos, &size,
2323                                         "</feature>\n");
2324
2325                         current_feature++;
2326                         free(arch_defined_types);
2327                 }
2328         }
2329
2330         xml_printf(&retval, &tdesc, &pos, &size,
2331                         "</target>\n");
2332
2333 error:
2334         free(features);
2335         free(reg_list);
2336
2337         if (retval == ERROR_OK)
2338                 *tdesc_out = tdesc;
2339         else
2340                 free(tdesc);
2341
2342         return retval;
2343 }
2344
2345 static int gdb_get_target_description_chunk(struct target *target, struct target_desc_format *target_desc,
2346                 char **chunk, int32_t offset, uint32_t length)
2347 {
2348         if (target_desc == NULL) {
2349                 LOG_ERROR("Unable to Generate Target Description");
2350                 return ERROR_FAIL;
2351         }
2352
2353         char *tdesc = target_desc->tdesc;
2354         uint32_t tdesc_length = target_desc->tdesc_length;
2355
2356         if (tdesc == NULL) {
2357                 int retval = gdb_generate_target_description(target, &tdesc);
2358                 if (retval != ERROR_OK) {
2359                         LOG_ERROR("Unable to Generate Target Description");
2360                         return ERROR_FAIL;
2361                 }
2362
2363                 tdesc_length = strlen(tdesc);
2364         }
2365
2366         char transfer_type;
2367
2368         if (length < (tdesc_length - offset))
2369                 transfer_type = 'm';
2370         else
2371                 transfer_type = 'l';
2372
2373         *chunk = malloc(length + 2);
2374         if (*chunk == NULL) {
2375                 LOG_ERROR("Unable to allocate memory");
2376                 return ERROR_FAIL;
2377         }
2378
2379         (*chunk)[0] = transfer_type;
2380         if (transfer_type == 'm') {
2381                 strncpy((*chunk) + 1, tdesc + offset, length);
2382                 (*chunk)[1 + length] = '\0';
2383         } else {
2384                 strncpy((*chunk) + 1, tdesc + offset, tdesc_length - offset);
2385                 (*chunk)[1 + (tdesc_length - offset)] = '\0';
2386
2387                 /* After gdb-server sends out last chunk, invalidate tdesc. */
2388                 free(tdesc);
2389                 tdesc = NULL;
2390                 tdesc_length = 0;
2391         }
2392
2393         target_desc->tdesc = tdesc;
2394         target_desc->tdesc_length = tdesc_length;
2395
2396         return ERROR_OK;
2397 }
2398
2399 static int gdb_target_description_supported(struct target *target, int *supported)
2400 {
2401         int retval = ERROR_OK;
2402         struct reg **reg_list = NULL;
2403         int reg_list_size = 0;
2404         char const **features = NULL;
2405         int feature_list_size = 0;
2406
2407         char const *architecture = target_get_gdb_arch(target);
2408
2409         retval = target_get_gdb_reg_list_noread(target, &reg_list,
2410                         &reg_list_size, REG_CLASS_ALL);
2411         if (retval != ERROR_OK) {
2412                 LOG_ERROR("get register list failed");
2413                 goto error;
2414         }
2415
2416         if (reg_list_size <= 0) {
2417                 LOG_ERROR("get register list failed");
2418                 retval = ERROR_FAIL;
2419                 goto error;
2420         }
2421
2422         /* Get a list of available target registers features */
2423         retval = get_reg_features_list(target, &features, &feature_list_size, reg_list, reg_list_size);
2424         if (retval != ERROR_OK) {
2425                 LOG_ERROR("Can't get the registers feature list");
2426                 goto error;
2427         }
2428
2429         if (supported) {
2430                 if (architecture || feature_list_size)
2431                         *supported = 1;
2432                 else
2433                         *supported = 0;
2434         }
2435
2436 error:
2437         free(features);
2438
2439         free(reg_list);
2440
2441         return retval;
2442 }
2443
2444 static int gdb_generate_thread_list(struct target *target, char **thread_list_out)
2445 {
2446         struct rtos *rtos = target->rtos;
2447         int retval = ERROR_OK;
2448         char *thread_list = NULL;
2449         int pos = 0;
2450         int size = 0;
2451
2452         xml_printf(&retval, &thread_list, &pos, &size,
2453                    "<?xml version=\"1.0\"?>\n"
2454                    "<threads>\n");
2455
2456         if (rtos != NULL) {
2457                 for (int i = 0; i < rtos->thread_count; i++) {
2458                         struct thread_detail *thread_detail = &rtos->thread_details[i];
2459
2460                         if (!thread_detail->exists)
2461                                 continue;
2462
2463                         xml_printf(&retval, &thread_list, &pos, &size,
2464                                    "<thread id=\"%" PRIx64 "\">", thread_detail->threadid);
2465
2466                         if (thread_detail->thread_name_str != NULL)
2467                                 xml_printf(&retval, &thread_list, &pos, &size,
2468                                            "Name: %s", thread_detail->thread_name_str);
2469
2470                         if (thread_detail->extra_info_str != NULL) {
2471                                 if (thread_detail->thread_name_str != NULL)
2472                                         xml_printf(&retval, &thread_list, &pos, &size,
2473                                                    ", ");
2474                                 xml_printf(&retval, &thread_list, &pos, &size,
2475                                            "%s", thread_detail->extra_info_str);
2476                         }
2477
2478                         xml_printf(&retval, &thread_list, &pos, &size,
2479                                    "</thread>\n");
2480                 }
2481         }
2482
2483         xml_printf(&retval, &thread_list, &pos, &size,
2484                    "</threads>\n");
2485
2486         if (retval == ERROR_OK)
2487                 *thread_list_out = thread_list;
2488         else
2489                 free(thread_list);
2490
2491         return retval;
2492 }
2493
2494 static int gdb_get_thread_list_chunk(struct target *target, char **thread_list,
2495                 char **chunk, int32_t offset, uint32_t length)
2496 {
2497         if (*thread_list == NULL) {
2498                 int retval = gdb_generate_thread_list(target, thread_list);
2499                 if (retval != ERROR_OK) {
2500                         LOG_ERROR("Unable to Generate Thread List");
2501                         return ERROR_FAIL;
2502                 }
2503         }
2504
2505         size_t thread_list_length = strlen(*thread_list);
2506         char transfer_type;
2507
2508         length = MIN(length, thread_list_length - offset);
2509         if (length < (thread_list_length - offset))
2510                 transfer_type = 'm';
2511         else
2512                 transfer_type = 'l';
2513
2514         *chunk = malloc(length + 2 + 3);
2515     /* Allocating extra 3 bytes prevents false positive valgrind report
2516          * of strlen(chunk) word access:
2517          * Invalid read of size 4
2518          * Address 0x4479934 is 44 bytes inside a block of size 45 alloc'd */
2519         if (*chunk == NULL) {
2520                 LOG_ERROR("Unable to allocate memory");
2521                 return ERROR_FAIL;
2522         }
2523
2524         (*chunk)[0] = transfer_type;
2525         strncpy((*chunk) + 1, (*thread_list) + offset, length);
2526         (*chunk)[1 + length] = '\0';
2527
2528         /* After gdb-server sends out last chunk, invalidate thread list. */
2529         if (transfer_type == 'l') {
2530                 free(*thread_list);
2531                 *thread_list = NULL;
2532         }
2533
2534         return ERROR_OK;
2535 }
2536
2537 static int gdb_query_packet(struct connection *connection,
2538                 char const *packet, int packet_size)
2539 {
2540         struct command_context *cmd_ctx = connection->cmd_ctx;
2541         struct gdb_connection *gdb_connection = connection->priv;
2542         struct target *target = get_target_from_connection(connection);
2543
2544         if (strncmp(packet, "qRcmd,", 6) == 0) {
2545                 if (packet_size > 6) {
2546                         char *cmd;
2547                         cmd = malloc((packet_size - 6) / 2 + 1);
2548                         size_t len = unhexify((uint8_t *)cmd, packet + 6, (packet_size - 6) / 2);
2549                         cmd[len] = 0;
2550
2551                         /* We want to print all debug output to GDB connection */
2552                         log_add_callback(gdb_log_callback, connection);
2553                         target_call_timer_callbacks_now();
2554                         /* some commands need to know the GDB connection, make note of current
2555                          * GDB connection. */
2556                         current_gdb_connection = gdb_connection;
2557                         command_run_line(cmd_ctx, cmd);
2558                         current_gdb_connection = NULL;
2559                         target_call_timer_callbacks_now();
2560                         log_remove_callback(gdb_log_callback, connection);
2561                         free(cmd);
2562                 }
2563                 gdb_put_packet(connection, "OK", 2);
2564                 return ERROR_OK;
2565         } else if (strncmp(packet, "qCRC:", 5) == 0) {
2566                 if (packet_size > 5) {
2567                         int retval;
2568                         char gdb_reply[10];
2569                         char *separator;
2570                         uint32_t checksum;
2571                         target_addr_t addr = 0;
2572                         uint32_t len = 0;
2573
2574                         /* skip command character */
2575                         packet += 5;
2576
2577                         addr = strtoull(packet, &separator, 16);
2578
2579                         if (*separator != ',') {
2580                                 LOG_ERROR("incomplete read memory packet received, dropping connection");
2581                                 return ERROR_SERVER_REMOTE_CLOSED;
2582                         }
2583
2584                         len = strtoul(separator + 1, NULL, 16);
2585
2586                         retval = target_checksum_memory(target, addr, len, &checksum);
2587
2588                         if (retval == ERROR_OK) {
2589                                 snprintf(gdb_reply, 10, "C%8.8" PRIx32 "", checksum);
2590                                 gdb_put_packet(connection, gdb_reply, 9);
2591                         } else {
2592                                 retval = gdb_error(connection, retval);
2593                                 if (retval != ERROR_OK)
2594                                         return retval;
2595                         }
2596
2597                         return ERROR_OK;
2598                 }
2599         } else if (strncmp(packet, "qSupported", 10) == 0) {
2600                 /* we currently support packet size and qXfer:memory-map:read (if enabled)
2601                  * qXfer:features:read is supported for some targets */
2602                 int retval = ERROR_OK;
2603                 char *buffer = NULL;
2604                 int pos = 0;
2605                 int size = 0;
2606                 int gdb_target_desc_supported = 0;
2607
2608                 /* we need to test that the target supports target descriptions */
2609                 retval = gdb_target_description_supported(target, &gdb_target_desc_supported);
2610                 if (retval != ERROR_OK) {
2611                         LOG_INFO("Failed detecting Target Description Support, disabling");
2612                         gdb_target_desc_supported = 0;
2613                 }
2614
2615                 /* support may be disabled globally */
2616                 if (gdb_use_target_description == 0) {
2617                         if (gdb_target_desc_supported)
2618                                 LOG_WARNING("Target Descriptions Supported, but disabled");
2619                         gdb_target_desc_supported = 0;
2620                 }
2621
2622                 xml_printf(&retval,
2623                         &buffer,
2624                         &pos,
2625                         &size,
2626                         "PacketSize=%x;qXfer:memory-map:read%c;qXfer:features:read%c;qXfer:threads:read+;QStartNoAckMode+;vContSupported+",
2627                         GDB_BUFFER_SIZE,
2628                         ((gdb_use_memory_map == 1) && (flash_get_bank_count() > 0)) ? '+' : '-',
2629                         (gdb_target_desc_supported == 1) ? '+' : '-');
2630
2631                 if (retval != ERROR_OK) {
2632                         gdb_send_error(connection, 01);
2633                         return ERROR_OK;
2634                 }
2635
2636                 gdb_put_packet(connection, buffer, strlen(buffer));
2637                 free(buffer);
2638
2639                 return ERROR_OK;
2640         } else if ((strncmp(packet, "qXfer:memory-map:read::", 23) == 0)
2641                    && (flash_get_bank_count() > 0))
2642                 return gdb_memory_map(connection, packet, packet_size);
2643         else if (strncmp(packet, "qXfer:features:read:", 20) == 0) {
2644                 char *xml = NULL;
2645                 int retval = ERROR_OK;
2646
2647                 int offset;
2648                 unsigned int length;
2649
2650                 /* skip command character */
2651                 packet += 20;
2652
2653                 if (decode_xfer_read(packet, NULL, &offset, &length) < 0) {
2654                         gdb_send_error(connection, 01);
2655                         return ERROR_OK;
2656                 }
2657
2658                 /* Target should prepare correct target description for annex.
2659                  * The first character of returned xml is 'm' or 'l'. 'm' for
2660                  * there are *more* chunks to transfer. 'l' for it is the *last*
2661                  * chunk of target description.
2662                  */
2663                 retval = gdb_get_target_description_chunk(target, &gdb_connection->target_desc,
2664                                 &xml, offset, length);
2665                 if (retval != ERROR_OK) {
2666                         gdb_error(connection, retval);
2667                         return retval;
2668                 }
2669
2670                 gdb_put_packet(connection, xml, strlen(xml));
2671
2672                 free(xml);
2673                 return ERROR_OK;
2674         } else if (strncmp(packet, "qXfer:threads:read:", 19) == 0) {
2675                 char *xml = NULL;
2676                 int retval = ERROR_OK;
2677
2678                 int offset;
2679                 unsigned int length;
2680
2681                 /* skip command character */
2682                 packet += 19;
2683
2684                 if (decode_xfer_read(packet, NULL, &offset, &length) < 0) {
2685                         gdb_send_error(connection, 01);
2686                         return ERROR_OK;
2687                 }
2688
2689                 /* Target should prepare correct thread list for annex.
2690                  * The first character of returned xml is 'm' or 'l'. 'm' for
2691                  * there are *more* chunks to transfer. 'l' for it is the *last*
2692                  * chunk of target description.
2693                  */
2694                 retval = gdb_get_thread_list_chunk(target, &gdb_connection->thread_list,
2695                                                    &xml, offset, length);
2696                 if (retval != ERROR_OK) {
2697                         gdb_error(connection, retval);
2698                         return retval;
2699                 }
2700
2701                 gdb_put_packet(connection, xml, strlen(xml));
2702
2703                 free(xml);
2704                 return ERROR_OK;
2705         } else if (strncmp(packet, "QStartNoAckMode", 15) == 0) {
2706                 gdb_connection->noack_mode = 1;
2707                 gdb_put_packet(connection, "OK", 2);
2708                 return ERROR_OK;
2709         }
2710
2711         gdb_put_packet(connection, "", 0);
2712         return ERROR_OK;
2713 }
2714
2715 static bool gdb_handle_vcont_packet(struct connection *connection, const char *packet, int packet_size)
2716 {
2717         struct gdb_connection *gdb_connection = connection->priv;
2718         struct target *target = get_target_from_connection(connection);
2719         const char *parse = packet;
2720         int retval;
2721
2722         /* query for vCont supported */
2723         if (parse[0] == '?') {
2724                 if (target->type->step != NULL) {
2725                         /* gdb doesn't accept c without C and s without S */
2726                         gdb_put_packet(connection, "vCont;c;C;s;S", 13);
2727                         return true;
2728                 }
2729                 return false;
2730         }
2731
2732         if (parse[0] == ';') {
2733                 ++parse;
2734                 --packet_size;
2735         }
2736
2737         /* simple case, a continue packet */
2738         if (parse[0] == 'c') {
2739                 gdb_running_type = 'c';
2740                 LOG_DEBUG("target %s continue", target_name(target));
2741                 log_add_callback(gdb_log_callback, connection);
2742                 retval = target_resume(target, 1, 0, 0, 0);
2743                 if (retval == ERROR_TARGET_NOT_HALTED)
2744                         LOG_INFO("target %s was not halted when resume was requested", target_name(target));
2745
2746                 /* poll target in an attempt to make its internal state consistent */
2747                 if (retval != ERROR_OK) {
2748                         retval = target_poll(target);
2749                         if (retval != ERROR_OK)
2750                                 LOG_DEBUG("error polling target %s after failed resume", target_name(target));
2751                 }
2752
2753                 /*
2754                  * We don't report errors to gdb here, move frontend_state to
2755                  * TARGET_RUNNING to stay in sync with gdb's expectation of the
2756                  * target state
2757                  */
2758                 gdb_connection->frontend_state = TARGET_RUNNING;
2759                 target_call_event_callbacks(target, TARGET_EVENT_GDB_START);
2760
2761                 return true;
2762         }
2763
2764         /* single-step or step-over-breakpoint */
2765         if (parse[0] == 's') {
2766                 gdb_running_type = 's';
2767                 bool fake_step = false;
2768
2769                 if (strncmp(parse, "s:", 2) == 0) {
2770                         struct target *ct = target;
2771                         int current_pc = 1;
2772                         int64_t thread_id;
2773                         char *endp;
2774
2775                         parse += 2;
2776                         packet_size -= 2;
2777
2778                         thread_id = strtoll(parse, &endp, 16);
2779                         if (endp != NULL) {
2780                                 packet_size -= endp - parse;
2781                                 parse = endp;
2782                         }
2783
2784                         if (target->rtos != NULL) {
2785                                 /* FIXME: why is this necessary? rtos state should be up-to-date here already! */
2786                                 rtos_update_threads(target);
2787
2788                                 target->rtos->gdb_target_for_threadid(connection, thread_id, &ct);
2789
2790                                 /*
2791                                  * check if the thread to be stepped is the current rtos thread
2792                                  * if not, we must fake the step
2793                                  */
2794                                 if (target->rtos->current_thread != thread_id)
2795                                         fake_step = true;
2796                         }
2797
2798                         if (parse[0] == ';') {
2799                                 ++parse;
2800                                 --packet_size;
2801
2802                                 if (parse[0] == 'c') {
2803                                         parse += 1;
2804
2805                                         /* check if thread-id follows */
2806                                         if (parse[0] == ':') {
2807                                                 int64_t tid;
2808                                                 parse += 1;
2809
2810                                                 tid = strtoll(parse, &endp, 16);
2811                                                 if (tid == thread_id) {
2812                                                         /*
2813                                                          * Special case: only step a single thread (core),
2814                                                          * keep the other threads halted. Currently, only
2815                                                          * aarch64 target understands it. Other target types don't
2816                                                          * care (nobody checks the actual value of 'current')
2817                                                          * and it doesn't really matter. This deserves
2818                                                          * a symbolic constant and a formal interface documentation
2819                                                          * at a later time.
2820                                                          */
2821                                                         LOG_DEBUG("request to step current core only");
2822                                                         /* uncomment after checking that indeed other targets are safe */
2823                                                         /*current_pc = 2;*/
2824                                                 }
2825                                         }
2826                                 }
2827                         }
2828
2829                         LOG_DEBUG("target %s single-step thread %"PRIx64, target_name(ct), thread_id);
2830                         log_add_callback(gdb_log_callback, connection);
2831                         target_call_event_callbacks(ct, TARGET_EVENT_GDB_START);
2832
2833                         /*
2834                          * work around an annoying gdb behaviour: when the current thread
2835                          * is changed in gdb, it assumes that the target can follow and also
2836                          * make the thread current. This is an assumption that cannot hold
2837                          * for a real target running a multi-threading OS. We just fake
2838                          * the step to not trigger an internal error in gdb. See
2839                          * https://sourceware.org/bugzilla/show_bug.cgi?id=22925 for details
2840                          */
2841                         if (fake_step) {
2842                                 int sig_reply_len;
2843                                 char sig_reply[128];
2844
2845                                 LOG_DEBUG("fake step thread %"PRIx64, thread_id);
2846
2847                                 sig_reply_len = snprintf(sig_reply, sizeof(sig_reply),
2848                                                                                  "T05thread:%016"PRIx64";", thread_id);
2849
2850                                 gdb_put_packet(connection, sig_reply, sig_reply_len);
2851                                 log_remove_callback(gdb_log_callback, connection);
2852
2853                                 return true;
2854                         }
2855
2856                         /* support for gdb_sync command */
2857                         if (gdb_connection->sync) {
2858                                 gdb_connection->sync = false;
2859                                 if (ct->state == TARGET_HALTED) {
2860                                         LOG_DEBUG("stepi ignored. GDB will now fetch the register state " \
2861                                                                         "from the target.");
2862                                         gdb_sig_halted(connection);
2863                                         log_remove_callback(gdb_log_callback, connection);
2864                                 } else
2865                                         gdb_connection->frontend_state = TARGET_RUNNING;
2866                                 return true;
2867                         }
2868
2869                         retval = target_step(ct, current_pc, 0, 0);
2870                         if (retval == ERROR_TARGET_NOT_HALTED)
2871                                 LOG_INFO("target %s was not halted when step was requested", target_name(ct));
2872
2873                         /* if step was successful send a reply back to gdb */
2874                         if (retval == ERROR_OK) {
2875                                 retval = target_poll(ct);
2876                                 if (retval != ERROR_OK)
2877                                         LOG_DEBUG("error polling target %s after successful step", target_name(ct));
2878                                 /* send back signal information */
2879                                 gdb_signal_reply(ct, connection);
2880                                 /* stop forwarding log packets! */
2881                                 log_remove_callback(gdb_log_callback, connection);
2882                         } else
2883                                 gdb_connection->frontend_state = TARGET_RUNNING;
2884                 } else {
2885                         LOG_ERROR("Unknown vCont packet");
2886                         return false;
2887                 }
2888                 return true;
2889         }
2890
2891         return false;
2892 }
2893
2894 static char *next_hex_encoded_field(const char **str, char sep)
2895 {
2896         size_t hexlen;
2897         const char *hex = *str;
2898         if (hex[0] == '\0')
2899                 return NULL;
2900
2901         const char *end = strchr(hex, sep);
2902         if (end == NULL)
2903                 hexlen = strlen(hex);
2904         else
2905                 hexlen = end - hex;
2906         *str = hex + hexlen + 1;
2907
2908         if (hexlen % 2 != 0) {
2909                 /* Malformed hex data */
2910                 return NULL;
2911         }
2912
2913         size_t count = hexlen / 2;
2914         char *decoded = malloc(count + 1);
2915         if (decoded == NULL)
2916                 return NULL;
2917
2918         size_t converted = unhexify((void *)decoded, hex, count);
2919         if (converted != count) {
2920                 free(decoded);
2921                 return NULL;
2922         }
2923
2924         decoded[count] = '\0';
2925         return decoded;
2926 }
2927
2928 /* handle extended restart packet */
2929 static void gdb_restart_inferior(struct connection *connection, const char *packet, int packet_size)
2930 {
2931         struct gdb_connection *gdb_con = connection->priv;
2932         struct target *target = get_target_from_connection(connection);
2933
2934         breakpoint_clear_target(target);
2935         watchpoint_clear_target(target);
2936         command_run_linef(connection->cmd_ctx, "ocd_gdb_restart %s",
2937                         target_name(target));
2938         /* set connection as attached after reset */
2939         gdb_con->attached = true;
2940         /*  info rtos parts */
2941         gdb_thread_packet(connection, packet, packet_size);
2942 }
2943
2944 static bool gdb_handle_vrun_packet(struct connection *connection, const char *packet, int packet_size)
2945 {
2946         struct target *target = get_target_from_connection(connection);
2947         const char *parse = packet;
2948
2949         /* Skip "vRun" */
2950         parse += 4;
2951
2952         if (parse[0] != ';')
2953                 return false;
2954         parse++;
2955
2956         /* Skip first field "filename"; don't know what to do with it. */
2957         free(next_hex_encoded_field(&parse, ';'));
2958
2959         char *cmdline = next_hex_encoded_field(&parse, ';');
2960         char *arg;
2961         while (cmdline != NULL && (arg = next_hex_encoded_field(&parse, ';')) != NULL) {
2962                 char *new_cmdline = alloc_printf("%s %s", cmdline, arg);
2963                 free(cmdline);
2964                 free(arg);
2965                 cmdline = new_cmdline;
2966         }
2967
2968         if (cmdline != NULL) {
2969                 if (target->semihosting != NULL) {
2970                         LOG_INFO("GDB set inferior command line to '%s'", cmdline);
2971                         free(target->semihosting->cmdline);
2972                         target->semihosting->cmdline = cmdline;
2973                 } else {
2974                         LOG_INFO("GDB set inferior command line to '%s' but semihosting is unavailable", cmdline);
2975                         free(cmdline);
2976                 }
2977         }
2978
2979         gdb_restart_inferior(connection, packet, packet_size);
2980         gdb_put_packet(connection, "S00", 3);
2981         return true;
2982 }
2983
2984 static int gdb_v_packet(struct connection *connection,
2985                 char const *packet, int packet_size)
2986 {
2987         struct gdb_connection *gdb_connection = connection->priv;
2988         int result;
2989
2990         struct target *target = get_target_from_connection(connection);
2991
2992         if (strncmp(packet, "vCont", 5) == 0) {
2993                 bool handled;
2994
2995                 packet += 5;
2996                 packet_size -= 5;
2997
2998                 handled = gdb_handle_vcont_packet(connection, packet, packet_size);
2999                 if (!handled)
3000                         gdb_put_packet(connection, "", 0);
3001
3002                 return ERROR_OK;
3003         }
3004
3005         if (strncmp(packet, "vRun", 4) == 0) {
3006                 bool handled;
3007
3008                 handled = gdb_handle_vrun_packet(connection, packet, packet_size);
3009                 if (!handled)
3010                         gdb_put_packet(connection, "", 0);
3011
3012                 return ERROR_OK;
3013         }
3014
3015         /* if flash programming disabled - send a empty reply */
3016
3017         if (gdb_flash_program == 0) {
3018                 gdb_put_packet(connection, "", 0);
3019                 return ERROR_OK;
3020         }
3021
3022         if (strncmp(packet, "vFlashErase:", 12) == 0) {
3023                 unsigned long addr;
3024                 unsigned long length;
3025
3026                 char const *parse = packet + 12;
3027                 if (*parse == '\0') {
3028                         LOG_ERROR("incomplete vFlashErase packet received, dropping connection");
3029                         return ERROR_SERVER_REMOTE_CLOSED;
3030                 }
3031
3032                 addr = strtoul(parse, (char **)&parse, 16);
3033
3034                 if (*(parse++) != ',' || *parse == '\0') {
3035                         LOG_ERROR("incomplete vFlashErase packet received, dropping connection");
3036                         return ERROR_SERVER_REMOTE_CLOSED;
3037                 }
3038
3039                 length = strtoul(parse, (char **)&parse, 16);
3040
3041                 if (*parse != '\0') {
3042                         LOG_ERROR("incomplete vFlashErase packet received, dropping connection");
3043                         return ERROR_SERVER_REMOTE_CLOSED;
3044                 }
3045
3046                 /* assume all sectors need erasing - stops any problems
3047                  * when flash_write is called multiple times */
3048                 flash_set_dirty();
3049
3050                 /* perform any target specific operations before the erase */
3051                 target_call_event_callbacks(target,
3052                         TARGET_EVENT_GDB_FLASH_ERASE_START);
3053
3054                 /* vFlashErase:addr,length messages require region start and
3055                  * end to be "block" aligned ... if padding is ever needed,
3056                  * GDB will have become dangerously confused.
3057                  */
3058                 result = flash_erase_address_range(target, false, addr,
3059                         length);
3060
3061                 /* perform any target specific operations after the erase */
3062                 target_call_event_callbacks(target,
3063                         TARGET_EVENT_GDB_FLASH_ERASE_END);
3064
3065                 /* perform erase */
3066                 if (result != ERROR_OK) {
3067                         /* GDB doesn't evaluate the actual error number returned,
3068                          * treat a failed erase as an I/O error
3069                          */
3070                         gdb_send_error(connection, EIO);
3071                         LOG_ERROR("flash_erase returned %i", result);
3072                 } else
3073                         gdb_put_packet(connection, "OK", 2);
3074
3075                 return ERROR_OK;
3076         }
3077
3078         if (strncmp(packet, "vFlashWrite:", 12) == 0) {
3079                 int retval;
3080                 unsigned long addr;
3081                 unsigned long length;
3082                 char const *parse = packet + 12;
3083
3084                 if (*parse == '\0') {
3085                         LOG_ERROR("incomplete vFlashErase packet received, dropping connection");
3086                         return ERROR_SERVER_REMOTE_CLOSED;
3087                 }
3088                 addr = strtoul(parse, (char **)&parse, 16);
3089                 if (*(parse++) != ':') {
3090                         LOG_ERROR("incomplete vFlashErase packet received, dropping connection");
3091                         return ERROR_SERVER_REMOTE_CLOSED;
3092                 }
3093                 length = packet_size - (parse - packet);
3094
3095                 /* create a new image if there isn't already one */
3096                 if (gdb_connection->vflash_image == NULL) {
3097                         gdb_connection->vflash_image = malloc(sizeof(struct image));
3098                         image_open(gdb_connection->vflash_image, "", "build");
3099                 }
3100
3101                 /* create new section with content from packet buffer */
3102                 retval = image_add_section(gdb_connection->vflash_image,
3103                                 addr, length, 0x0, (uint8_t const *)parse);
3104                 if (retval != ERROR_OK)
3105                         return retval;
3106
3107                 gdb_put_packet(connection, "OK", 2);
3108
3109                 return ERROR_OK;
3110         }
3111
3112         if (strncmp(packet, "vFlashDone", 10) == 0) {
3113                 uint32_t written;
3114
3115                 /* process the flashing buffer. No need to erase as GDB
3116                  * always issues a vFlashErase first. */
3117                 target_call_event_callbacks(target,
3118                                 TARGET_EVENT_GDB_FLASH_WRITE_START);
3119                 result = flash_write(target, gdb_connection->vflash_image,
3120                         &written, 0);
3121                 target_call_event_callbacks(target,
3122                         TARGET_EVENT_GDB_FLASH_WRITE_END);
3123                 if (result != ERROR_OK) {
3124                         if (result == ERROR_FLASH_DST_OUT_OF_BANK)
3125                                 gdb_put_packet(connection, "E.memtype", 9);
3126                         else
3127                                 gdb_send_error(connection, EIO);
3128                 } else {
3129                         LOG_DEBUG("wrote %u bytes from vFlash image to flash", (unsigned)written);
3130                         gdb_put_packet(connection, "OK", 2);
3131                 }
3132
3133                 image_close(gdb_connection->vflash_image);
3134                 free(gdb_connection->vflash_image);
3135                 gdb_connection->vflash_image = NULL;
3136
3137                 return ERROR_OK;
3138         }
3139
3140         gdb_put_packet(connection, "", 0);
3141         return ERROR_OK;
3142 }
3143
3144 static int gdb_detach(struct connection *connection)
3145 {
3146         /*
3147          * Only reply "OK" to GDB
3148          * it will close the connection and this will trigger a call to
3149          * gdb_connection_closed() that will in turn trigger the event
3150          * TARGET_EVENT_GDB_DETACH
3151          */
3152         return gdb_put_packet(connection, "OK", 2);
3153 }
3154
3155 /* The format of 'F' response packet is
3156  * Fretcode,errno,Ctrl-C flag;call-specific attachment
3157  */
3158 static int gdb_fileio_response_packet(struct connection *connection,
3159                 char const *packet, int packet_size)
3160 {
3161         struct target *target = get_target_from_connection(connection);
3162         char *separator;
3163         char *parsing_point;
3164         int fileio_retcode = strtoul(packet + 1, &separator, 16);
3165         int fileio_errno = 0;
3166         bool fileio_ctrl_c = false;
3167         int retval;
3168
3169         LOG_DEBUG("-");
3170
3171         if (*separator == ',') {
3172                 parsing_point = separator + 1;
3173                 fileio_errno = strtoul(parsing_point, &separator, 16);
3174                 if (*separator == ',') {
3175                         if (*(separator + 1) == 'C') {
3176                                 /* TODO: process ctrl-c */
3177                                 fileio_ctrl_c = true;
3178                         }
3179                 }
3180         }
3181
3182         LOG_DEBUG("File-I/O response, retcode: 0x%x, errno: 0x%x, ctrl-c: %s",
3183                         fileio_retcode, fileio_errno, fileio_ctrl_c ? "true" : "false");
3184
3185         retval = target_gdb_fileio_end(target, fileio_retcode, fileio_errno, fileio_ctrl_c);
3186         if (retval != ERROR_OK)
3187                 return ERROR_FAIL;
3188
3189         /* After File-I/O ends, keep continue or step */
3190         if (gdb_running_type == 'c')
3191                 retval = target_resume(target, 1, 0x0, 0, 0);
3192         else if (gdb_running_type == 's')
3193                 retval = target_step(target, 1, 0x0, 0);
3194         else
3195                 retval = ERROR_FAIL;
3196
3197         if (retval != ERROR_OK)
3198                 return ERROR_FAIL;
3199
3200         return ERROR_OK;
3201 }
3202
3203 static void gdb_log_callback(void *priv, const char *file, unsigned line,
3204                 const char *function, const char *string)
3205 {
3206         struct connection *connection = priv;
3207         struct gdb_connection *gdb_con = connection->priv;
3208
3209         if (gdb_con->busy) {
3210                 /* do not reply this using the O packet */
3211                 return;
3212         }
3213
3214         gdb_output_con(connection, string);
3215 }
3216
3217 static void gdb_sig_halted(struct connection *connection)
3218 {
3219         char sig_reply[4];
3220         snprintf(sig_reply, 4, "T%2.2x", 2);
3221         gdb_put_packet(connection, sig_reply, 3);
3222 }
3223
3224 static int gdb_input_inner(struct connection *connection)
3225 {
3226         /* Do not allocate this on the stack */
3227         static char gdb_packet_buffer[GDB_BUFFER_SIZE + 1]; /* Extra byte for nul-termination */
3228
3229         struct target *target;
3230         char const *packet = gdb_packet_buffer;
3231         int packet_size;
3232         int retval;
3233         struct gdb_connection *gdb_con = connection->priv;
3234
3235         target = get_target_from_connection(connection);
3236
3237         /* drain input buffer. If one of the packets fail, then an error
3238          * packet is replied, if applicable.
3239          *
3240          * This loop will terminate and the error code is returned.
3241          *
3242          * The calling fn will check if this error is something that
3243          * can be recovered from, or if the connection must be closed.
3244          *
3245          * If the error is recoverable, this fn is called again to
3246          * drain the rest of the buffer.
3247          */
3248         do {
3249                 packet_size = GDB_BUFFER_SIZE;
3250                 retval = gdb_get_packet(connection, gdb_packet_buffer, &packet_size);
3251                 if (retval != ERROR_OK)
3252                         return retval;
3253
3254                 /* terminate with zero */
3255                 gdb_packet_buffer[packet_size] = '\0';
3256
3257                 if (LOG_LEVEL_IS(LOG_LVL_DEBUG)) {
3258                         if (packet[0] == 'X') {
3259                                 /* binary packets spew junk into the debug log stream */
3260                                 char buf[50];
3261                                 int x;
3262                                 for (x = 0; (x < 49) && (packet[x] != ':'); x++)
3263                                         buf[x] = packet[x];
3264                                 buf[x] = 0;
3265                                 LOG_DEBUG("received packet: '%s:<binary-data>'", buf);
3266                         } else
3267                                 LOG_DEBUG("received packet: '%s'", packet);
3268                 }
3269
3270                 if (packet_size > 0) {
3271                         retval = ERROR_OK;
3272                         switch (packet[0]) {
3273                                 case 'T':       /* Is thread alive? */
3274                                         gdb_thread_packet(connection, packet, packet_size);
3275                                         break;
3276                                 case 'H':       /* Set current thread ( 'c' for step and continue,
3277                                                          * 'g' for all other operations ) */
3278                                         gdb_thread_packet(connection, packet, packet_size);
3279                                         break;
3280                                 case 'q':
3281                                 case 'Q':
3282                                         retval = gdb_thread_packet(connection, packet, packet_size);
3283                                         if (retval == GDB_THREAD_PACKET_NOT_CONSUMED)
3284                                                 retval = gdb_query_packet(connection, packet, packet_size);
3285                                         break;
3286                                 case 'g':
3287                                         retval = gdb_get_registers_packet(connection, packet, packet_size);
3288                                         break;
3289                                 case 'G':
3290                                         retval = gdb_set_registers_packet(connection, packet, packet_size);
3291                                         break;
3292                                 case 'p':
3293                                         retval = gdb_get_register_packet(connection, packet, packet_size);
3294                                         break;
3295                                 case 'P':
3296                                         retval = gdb_set_register_packet(connection, packet, packet_size);
3297                                         break;
3298                                 case 'm':
3299                                         retval = gdb_read_memory_packet(connection, packet, packet_size);
3300                                         break;
3301                                 case 'M':
3302                                         retval = gdb_write_memory_packet(connection, packet, packet_size);
3303                                         break;
3304                                 case 'z':
3305                                 case 'Z':
3306                                         retval = gdb_breakpoint_watchpoint_packet(connection, packet, packet_size);
3307                                         break;
3308                                 case '?':
3309                                         gdb_last_signal_packet(connection, packet, packet_size);
3310                                         break;
3311                                 case 'c':
3312                                 case 's':
3313                                 {
3314                                         gdb_thread_packet(connection, packet, packet_size);
3315                                         log_add_callback(gdb_log_callback, connection);
3316
3317                                         if (gdb_con->mem_write_error) {
3318                                                 LOG_ERROR("Memory write failure!");
3319
3320                                                 /* now that we have reported the memory write error,
3321                                                  * we can clear the condition */
3322                                                 gdb_con->mem_write_error = false;
3323                                         }
3324
3325                                         bool nostep = false;
3326                                         bool already_running = false;
3327                                         if (target->state == TARGET_RUNNING) {
3328                                                 LOG_WARNING("WARNING! The target is already running. "
3329                                                                 "All changes GDB did to registers will be discarded! "
3330                                                                 "Waiting for target to halt.");
3331                                                 already_running = true;
3332                                         } else if (target->state != TARGET_HALTED) {
3333                                                 LOG_WARNING("The target is not in the halted nor running stated, " \
3334                                                                 "stepi/continue ignored.");
3335                                                 nostep = true;
3336                                         } else if ((packet[0] == 's') && gdb_con->sync) {
3337                                                 /* Hmm..... when you issue a continue in GDB, then a "stepi" is
3338                                                  * sent by GDB first to OpenOCD, thus defeating the check to
3339                                                  * make only the single stepping have the sync feature...
3340                                                  */
3341                                                 nostep = true;
3342                                                 LOG_DEBUG("stepi ignored. GDB will now fetch the register state " \
3343                                                                 "from the target.");
3344                                         }
3345                                         gdb_con->sync = false;
3346
3347                                         if (!already_running && nostep) {
3348                                                 /* Either the target isn't in the halted state, then we can't
3349                                                  * step/continue. This might be early setup, etc.
3350                                                  *
3351                                                  * Or we want to allow GDB to pick up a fresh set of
3352                                                  * register values without modifying the target state.
3353                                                  *
3354                                                  */
3355                                                 gdb_sig_halted(connection);
3356
3357                                                 /* stop forwarding log packets! */
3358                                                 log_remove_callback(gdb_log_callback, connection);
3359                                         } else {
3360                                                 /* We're running/stepping, in which case we can
3361                                                  * forward log output until the target is halted
3362                                                  */
3363                                                 gdb_con->frontend_state = TARGET_RUNNING;
3364                                                 target_call_event_callbacks(target, TARGET_EVENT_GDB_START);
3365
3366                                                 if (!already_running) {
3367                                                         /* Here we don't want packet processing to stop even if this fails,
3368                                                          * so we use a local variable instead of retval. */
3369                                                         retval = gdb_step_continue_packet(connection, packet, packet_size);
3370                                                         if (retval != ERROR_OK) {
3371                                                                 /* we'll never receive a halted
3372                                                                  * condition... issue a false one..
3373                                                                  */
3374                                                                 gdb_frontend_halted(target, connection);
3375                                                         }
3376                                                 }
3377                                         }
3378                                 }
3379                                 break;
3380                                 case 'v':
3381                                         retval = gdb_v_packet(connection, packet, packet_size);
3382                                         break;
3383                                 case 'D':
3384                                         retval = gdb_detach(connection);
3385                                         break;
3386                                 case 'X':
3387                                         retval = gdb_write_memory_binary_packet(connection, packet, packet_size);
3388                                         if (retval != ERROR_OK)
3389                                                 return retval;
3390                                         break;
3391                                 case 'k':
3392                                         if (gdb_con->extended_protocol) {
3393                                                 gdb_con->attached = false;
3394                                                 break;
3395                                         }
3396                                         gdb_put_packet(connection, "OK", 2);
3397                                         return ERROR_SERVER_REMOTE_CLOSED;
3398                                 case '!':
3399                                         /* handle extended remote protocol */
3400                                         gdb_con->extended_protocol = true;
3401                                         gdb_put_packet(connection, "OK", 2);
3402                                         break;
3403                                 case 'R':
3404                                         /* handle extended restart packet */
3405                                         gdb_restart_inferior(connection, packet, packet_size);
3406                                         break;
3407
3408                                 case 'j':
3409                                         /* packet supported only by smp target i.e cortex_a.c*/
3410                                         /* handle smp packet replying coreid played to gbd */
3411                                         gdb_read_smp_packet(connection, packet, packet_size);
3412                                         break;
3413
3414                                 case 'J':
3415                                         /* packet supported only by smp target i.e cortex_a.c */
3416                                         /* handle smp packet setting coreid to be played at next
3417                                          * resume to gdb */
3418                                         gdb_write_smp_packet(connection, packet, packet_size);
3419                                         break;
3420
3421                                 case 'F':
3422                                         /* File-I/O extension */
3423                                         /* After gdb uses host-side syscall to complete target file
3424                                          * I/O, gdb sends host-side syscall return value to target
3425                                          * by 'F' packet.
3426                                          * The format of 'F' response packet is
3427                                          * Fretcode,errno,Ctrl-C flag;call-specific attachment
3428                                          */
3429                                         gdb_con->frontend_state = TARGET_RUNNING;
3430                                         log_add_callback(gdb_log_callback, connection);
3431                                         gdb_fileio_response_packet(connection, packet, packet_size);
3432                                         break;
3433
3434                                 default:
3435                                         /* ignore unknown packets */
3436                                         LOG_DEBUG("ignoring 0x%2.2x packet", packet[0]);
3437                                         gdb_put_packet(connection, "", 0);
3438                                         break;
3439                         }
3440
3441                         /* if a packet handler returned an error, exit input loop */
3442                         if (retval != ERROR_OK)
3443                                 return retval;
3444                 }
3445
3446                 if (gdb_con->ctrl_c) {
3447                         if (target->state == TARGET_RUNNING) {
3448                                 struct target *t = target;
3449                                 if (target->rtos)
3450                                         target->rtos->gdb_target_for_threadid(connection, target->rtos->current_threadid, &t);
3451                                 retval = target_halt(t);
3452                                 if (retval == ERROR_OK)
3453                                         retval = target_poll(t);
3454                                 if (retval != ERROR_OK)
3455                                         target_call_event_callbacks(target, TARGET_EVENT_GDB_HALT);
3456                                 gdb_con->ctrl_c = 0;
3457                         } else {
3458                                 LOG_INFO("The target is not running when halt was requested, stopping GDB.");
3459                                 target_call_event_callbacks(target, TARGET_EVENT_GDB_HALT);
3460                         }
3461                 }
3462
3463         } while (gdb_con->buf_cnt > 0);
3464
3465         return ERROR_OK;
3466 }
3467
3468 static int gdb_input(struct connection *connection)
3469 {
3470         int retval = gdb_input_inner(connection);
3471         struct gdb_connection *gdb_con = connection->priv;
3472         if (retval == ERROR_SERVER_REMOTE_CLOSED)
3473                 return retval;
3474
3475         /* logging does not propagate the error, yet can set the gdb_con->closed flag */
3476         if (gdb_con->closed)
3477                 return ERROR_SERVER_REMOTE_CLOSED;
3478
3479         /* we'll recover from any other errors(e.g. temporary timeouts, etc.) */
3480         return ERROR_OK;
3481 }
3482
3483 static int gdb_target_start(struct target *target, const char *port)
3484 {
3485         struct gdb_service *gdb_service;
3486         int ret;
3487         gdb_service = malloc(sizeof(struct gdb_service));
3488
3489         if (NULL == gdb_service)
3490                 return -ENOMEM;
3491
3492         LOG_DEBUG("starting gdb server for %s on %s", target_name(target), port);
3493
3494         gdb_service->target = target;
3495         gdb_service->core[0] = -1;
3496         gdb_service->core[1] = -1;
3497         target->gdb_service = gdb_service;
3498
3499         ret = add_service("gdb",
3500                         port, 1, &gdb_new_connection, &gdb_input,
3501                         &gdb_connection_closed, gdb_service);
3502         /* initialialize all targets gdb service with the same pointer */
3503         {
3504                 struct target_list *head;
3505                 struct target *curr;
3506                 head = target->head;
3507                 while (head != (struct target_list *)NULL) {
3508                         curr = head->target;
3509                         if (curr != target)
3510                                 curr->gdb_service = gdb_service;
3511                         head = head->next;
3512                 }
3513         }
3514         return ret;
3515 }
3516
3517 static int gdb_target_add_one(struct target *target)
3518 {
3519         /*  one gdb instance per smp list */
3520         if ((target->smp) && (target->gdb_service))
3521                 return ERROR_OK;
3522
3523         /* skip targets that cannot handle a gdb connections (e.g. mem_ap) */
3524         if (!target_supports_gdb_connection(target)) {
3525                 LOG_DEBUG("skip gdb server for target %s", target_name(target));
3526                 return ERROR_OK;
3527         }
3528
3529         if (target->gdb_port_override) {
3530                 if (strcmp(target->gdb_port_override, "disabled") == 0) {
3531                         LOG_INFO("gdb port disabled");
3532                         return ERROR_OK;
3533                 }
3534                 return gdb_target_start(target, target->gdb_port_override);
3535         }
3536
3537         if (strcmp(gdb_port, "disabled") == 0) {
3538                 LOG_INFO("gdb port disabled");
3539                 return ERROR_OK;
3540         }
3541
3542         int retval = gdb_target_start(target, gdb_port_next);
3543         if (retval == ERROR_OK) {
3544                 /* save the port number so can be queried with
3545                  * $target_name cget -gdb-port
3546                  */
3547                 target->gdb_port_override = strdup(gdb_port_next);
3548
3549                 long portnumber;
3550                 /* If we can parse the port number
3551                  * then we increment the port number for the next target.
3552                  */
3553                 char *end;
3554                 portnumber = strtol(gdb_port_next, &end, 0);
3555                 if (!*end) {
3556                         if (parse_long(gdb_port_next, &portnumber) == ERROR_OK) {
3557                                 free(gdb_port_next);
3558                                 if (portnumber) {
3559                                         gdb_port_next = alloc_printf("%ld", portnumber+1);
3560                                 } else {
3561                                         /* Don't increment if gdb_port is 0, since we're just
3562                                          * trying to allocate an unused port. */
3563                                         gdb_port_next = strdup("0");
3564                                 }
3565                         }
3566                 }
3567         }
3568         return retval;
3569 }
3570
3571 int gdb_target_add_all(struct target *target)
3572 {
3573         if (NULL == target) {
3574                 LOG_WARNING("gdb services need one or more targets defined");
3575                 return ERROR_OK;
3576         }
3577
3578         while (NULL != target) {
3579                 int retval = gdb_target_add_one(target);
3580                 if (ERROR_OK != retval)
3581                         return retval;
3582
3583                 target = target->next;
3584         }
3585
3586         return ERROR_OK;
3587 }
3588
3589 COMMAND_HANDLER(handle_gdb_sync_command)
3590 {
3591         if (CMD_ARGC != 0)
3592                 return ERROR_COMMAND_SYNTAX_ERROR;
3593
3594         if (current_gdb_connection == NULL) {
3595                 command_print(CMD,
3596                         "gdb_sync command can only be run from within gdb using \"monitor gdb_sync\"");
3597                 return ERROR_FAIL;
3598         }
3599
3600         current_gdb_connection->sync = true;
3601
3602         return ERROR_OK;
3603 }
3604
3605 /* daemon configuration command gdb_port */
3606 COMMAND_HANDLER(handle_gdb_port_command)
3607 {
3608         int retval = CALL_COMMAND_HANDLER(server_pipe_command, &gdb_port);
3609         if (ERROR_OK == retval) {
3610                 free(gdb_port_next);
3611                 gdb_port_next = strdup(gdb_port);
3612         }
3613         return retval;
3614 }
3615
3616 COMMAND_HANDLER(handle_gdb_memory_map_command)
3617 {
3618         if (CMD_ARGC != 1)
3619                 return ERROR_COMMAND_SYNTAX_ERROR;
3620
3621         COMMAND_PARSE_ENABLE(CMD_ARGV[0], gdb_use_memory_map);
3622         return ERROR_OK;
3623 }
3624
3625 COMMAND_HANDLER(handle_gdb_flash_program_command)
3626 {
3627         if (CMD_ARGC != 1)
3628                 return ERROR_COMMAND_SYNTAX_ERROR;
3629
3630         COMMAND_PARSE_ENABLE(CMD_ARGV[0], gdb_flash_program);
3631         return ERROR_OK;
3632 }
3633
3634 COMMAND_HANDLER(handle_gdb_report_data_abort_command)
3635 {
3636         if (CMD_ARGC != 1)
3637                 return ERROR_COMMAND_SYNTAX_ERROR;
3638
3639         COMMAND_PARSE_ENABLE(CMD_ARGV[0], gdb_report_data_abort);
3640         return ERROR_OK;
3641 }
3642
3643 COMMAND_HANDLER(handle_gdb_report_register_access_error)
3644 {
3645         if (CMD_ARGC != 1)
3646                 return ERROR_COMMAND_SYNTAX_ERROR;
3647
3648         COMMAND_PARSE_ENABLE(CMD_ARGV[0], gdb_report_register_access_error);
3649         return ERROR_OK;
3650 }
3651
3652 /* gdb_breakpoint_override */
3653 COMMAND_HANDLER(handle_gdb_breakpoint_override_command)
3654 {
3655         if (CMD_ARGC == 0) {
3656                 /* nothing */
3657         } else if (CMD_ARGC == 1) {
3658                 gdb_breakpoint_override = 1;
3659                 if (strcmp(CMD_ARGV[0], "hard") == 0)
3660                         gdb_breakpoint_override_type = BKPT_HARD;
3661                 else if (strcmp(CMD_ARGV[0], "soft") == 0)
3662                         gdb_breakpoint_override_type = BKPT_SOFT;
3663                 else if (strcmp(CMD_ARGV[0], "disable") == 0)
3664                         gdb_breakpoint_override = 0;
3665         } else
3666                 return ERROR_COMMAND_SYNTAX_ERROR;
3667         if (gdb_breakpoint_override)
3668                 LOG_USER("force %s breakpoints",
3669                         (gdb_breakpoint_override_type == BKPT_HARD) ? "hard" : "soft");
3670         else
3671                 LOG_USER("breakpoint type is not overridden");
3672
3673         return ERROR_OK;
3674 }
3675
3676 COMMAND_HANDLER(handle_gdb_target_description_command)
3677 {
3678         if (CMD_ARGC != 1)
3679                 return ERROR_COMMAND_SYNTAX_ERROR;
3680
3681         COMMAND_PARSE_ENABLE(CMD_ARGV[0], gdb_use_target_description);
3682         return ERROR_OK;
3683 }
3684
3685 COMMAND_HANDLER(handle_gdb_save_tdesc_command)
3686 {
3687         char *tdesc;
3688         uint32_t tdesc_length;
3689         struct target *target = get_current_target(CMD_CTX);
3690
3691         int retval = gdb_generate_target_description(target, &tdesc);
3692         if (retval != ERROR_OK) {
3693                 LOG_ERROR("Unable to Generate Target Description");
3694                 return ERROR_FAIL;
3695         }
3696
3697         tdesc_length = strlen(tdesc);
3698
3699         struct fileio *fileio;
3700         size_t size_written;
3701
3702         char *tdesc_filename = alloc_printf("%s.xml", target_type_name(target));
3703         if (tdesc_filename == NULL) {
3704                 retval = ERROR_FAIL;
3705                 goto out;
3706         }
3707
3708         retval = fileio_open(&fileio, tdesc_filename, FILEIO_WRITE, FILEIO_TEXT);
3709
3710         if (retval != ERROR_OK) {
3711                 LOG_ERROR("Can't open %s for writing", tdesc_filename);
3712                 goto out;
3713         }
3714
3715         retval = fileio_write(fileio, tdesc_length, tdesc, &size_written);
3716
3717         fileio_close(fileio);
3718
3719         if (retval != ERROR_OK)
3720                 LOG_ERROR("Error while writing the tdesc file");
3721
3722 out:
3723         free(tdesc_filename);
3724         free(tdesc);
3725
3726         return retval;
3727 }
3728
3729 static const struct command_registration gdb_command_handlers[] = {
3730         {
3731                 .name = "gdb_sync",
3732                 .handler = handle_gdb_sync_command,
3733                 .mode = COMMAND_ANY,
3734                 .help = "next stepi will return immediately allowing "
3735                         "GDB to fetch register state without affecting "
3736                         "target state",
3737                 .usage = ""
3738         },
3739         {
3740                 .name = "gdb_port",
3741                 .handler = handle_gdb_port_command,
3742                 .mode = COMMAND_ANY,
3743                 .help = "Normally gdb listens to a TCP/IP port. Each subsequent GDB "
3744                         "server listens for the next port number after the "
3745                         "base port number specified. "
3746                         "No arguments reports GDB port. \"pipe\" means listen to stdin "
3747                         "output to stdout, an integer is base port number, \"disabled\" disables "
3748                         "port. Any other string is are interpreted as named pipe to listen to. "
3749                         "Output pipe is the same name as input pipe, but with 'o' appended.",
3750                 .usage = "[port_num]",
3751         },
3752         {
3753                 .name = "gdb_memory_map",
3754                 .handler = handle_gdb_memory_map_command,
3755                 .mode = COMMAND_CONFIG,
3756                 .help = "enable or disable memory map",
3757                 .usage = "('enable'|'disable')"
3758         },
3759         {
3760                 .name = "gdb_flash_program",
3761                 .handler = handle_gdb_flash_program_command,
3762                 .mode = COMMAND_CONFIG,
3763                 .help = "enable or disable flash program",
3764                 .usage = "('enable'|'disable')"
3765         },
3766         {
3767                 .name = "gdb_report_data_abort",
3768                 .handler = handle_gdb_report_data_abort_command,
3769                 .mode = COMMAND_CONFIG,
3770                 .help = "enable or disable reporting data aborts",
3771                 .usage = "('enable'|'disable')"
3772         },
3773         {
3774                 .name = "gdb_report_register_access_error",
3775                 .handler = handle_gdb_report_register_access_error,
3776                 .mode = COMMAND_CONFIG,
3777                 .help = "enable or disable reporting register access errors",
3778                 .usage = "('enable'|'disable')"
3779         },
3780         {
3781                 .name = "gdb_breakpoint_override",
3782                 .handler = handle_gdb_breakpoint_override_command,
3783                 .mode = COMMAND_ANY,
3784                 .help = "Display or specify type of breakpoint "
3785                         "to be used by gdb 'break' commands.",
3786                 .usage = "('hard'|'soft'|'disable')"
3787         },
3788         {
3789                 .name = "gdb_target_description",
3790                 .handler = handle_gdb_target_description_command,
3791                 .mode = COMMAND_CONFIG,
3792                 .help = "enable or disable target description",
3793                 .usage = "('enable'|'disable')"
3794         },
3795         {
3796                 .name = "gdb_save_tdesc",
3797                 .handler = handle_gdb_save_tdesc_command,
3798                 .mode = COMMAND_EXEC,
3799                 .help = "Save the target description file",
3800                 .usage = "",
3801         },
3802         COMMAND_REGISTRATION_DONE
3803 };
3804
3805 int gdb_register_commands(struct command_context *cmd_ctx)
3806 {
3807         gdb_port = strdup("3333");
3808         gdb_port_next = strdup("3333");
3809         return register_commands(cmd_ctx, NULL, gdb_command_handlers);
3810 }
3811
3812 void gdb_service_free(void)
3813 {
3814         free(gdb_port);
3815         free(gdb_port_next);
3816 }