gdb_server: refuse gdb connection if target is not examined
[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 null-termination */
72         char *buf_p;
73         int buf_cnt;
74         bool 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 = true;
281         else
282                 connection->input_pending = false;
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 = true;
306                 else
307                         connection->input_pending = false;
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 = true;
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 = true;
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 = false;
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 = false;
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                 for (unsigned int i = 0; i < flash_get_bank_count(); i++) {
1000                         struct flash_bank *p;
1001                         p = get_flash_bank_by_num_noprobe(i);
1002                         if (p->target != target)
1003                                 continue;
1004                         retval = get_flash_bank_by_num(i, &p);
1005                         if (retval != ERROR_OK) {
1006                                 LOG_ERROR("Connect failed. Consider setting up a gdb-attach event for the target "
1007                                                 "to prepare target for GDB connect, or use 'gdb_memory_map disable'.");
1008                                 return retval;
1009                         }
1010                 }
1011         }
1012
1013         gdb_actual_connections++;
1014         log_printf_lf(all_targets->next != NULL ? LOG_LVL_INFO : LOG_LVL_DEBUG,
1015                         __FILE__, __LINE__, __func__,
1016                         "New GDB Connection: %d, Target %s, state: %s",
1017                         gdb_actual_connections,
1018                         target_name(target),
1019                         target_state_name(target));
1020
1021         if (!target_was_examined(target)) {
1022                 LOG_ERROR("Target %s not examined yet, refuse gdb connection %d!",
1023                                   target_name(target), gdb_actual_connections);
1024                 gdb_actual_connections--;
1025                 return ERROR_TARGET_NOT_EXAMINED;
1026         }
1027
1028         if (target->state == TARGET_HALTED)
1029                 LOG_WARNING("GDB connection %d on target %s not halted",
1030                                         gdb_actual_connections, target_name(target));
1031
1032         /* DANGER! If we fail subsequently, we must remove this handler,
1033          * otherwise we occasionally see crashes as the timer can invoke the
1034          * callback fn.
1035          *
1036          * register callback to be informed about target events */
1037         target_register_event_callback(gdb_target_callback_event_handler, connection);
1038
1039         return ERROR_OK;
1040 }
1041
1042 static int gdb_connection_closed(struct connection *connection)
1043 {
1044         struct target *target;
1045         struct gdb_connection *gdb_connection = connection->priv;
1046
1047         target = get_target_from_connection(connection);
1048
1049         /* we're done forwarding messages. Tear down callback before
1050          * cleaning up connection.
1051          */
1052         log_remove_callback(gdb_log_callback, connection);
1053
1054         gdb_actual_connections--;
1055         LOG_DEBUG("GDB Close, Target: %s, state: %s, gdb_actual_connections=%d",
1056                 target_name(target),
1057                 target_state_name(target),
1058                 gdb_actual_connections);
1059
1060         /* see if an image built with vFlash commands is left */
1061         if (gdb_connection->vflash_image) {
1062                 image_close(gdb_connection->vflash_image);
1063                 free(gdb_connection->vflash_image);
1064                 gdb_connection->vflash_image = NULL;
1065         }
1066
1067         /* if this connection registered a debug-message receiver delete it */
1068         delete_debug_msg_receiver(connection->cmd_ctx, target);
1069
1070         if (connection->priv) {
1071                 free(connection->priv);
1072                 connection->priv = NULL;
1073         } else
1074                 LOG_ERROR("BUG: connection->priv == NULL");
1075
1076         target_unregister_event_callback(gdb_target_callback_event_handler, connection);
1077
1078         target_call_event_callbacks(target, TARGET_EVENT_GDB_END);
1079
1080         target_call_event_callbacks(target, TARGET_EVENT_GDB_DETACH);
1081
1082         return ERROR_OK;
1083 }
1084
1085 static void gdb_send_error(struct connection *connection, uint8_t the_error)
1086 {
1087         char err[4];
1088         snprintf(err, 4, "E%2.2X", the_error);
1089         gdb_put_packet(connection, err, 3);
1090 }
1091
1092 static int gdb_last_signal_packet(struct connection *connection,
1093                 char const *packet, int packet_size)
1094 {
1095         struct target *target = get_target_from_connection(connection);
1096         struct gdb_connection *gdb_con = connection->priv;
1097         char sig_reply[4];
1098         int signal_var;
1099
1100         if (!gdb_con->attached) {
1101                 /* if we are here we have received a kill packet
1102                  * reply W stop reply otherwise gdb gets very unhappy */
1103                 gdb_put_packet(connection, "W00", 3);
1104                 return ERROR_OK;
1105         }
1106
1107         signal_var = gdb_last_signal(target);
1108
1109         snprintf(sig_reply, 4, "S%2.2x", signal_var);
1110         gdb_put_packet(connection, sig_reply, 3);
1111
1112         return ERROR_OK;
1113 }
1114
1115 static inline int gdb_reg_pos(struct target *target, int pos, int len)
1116 {
1117         if (target->endianness == TARGET_LITTLE_ENDIAN)
1118                 return pos;
1119         else
1120                 return len - 1 - pos;
1121 }
1122
1123 /* Convert register to string of bytes. NB! The # of bits in the
1124  * register might be non-divisible by 8(a byte), in which
1125  * case an entire byte is shown.
1126  *
1127  * NB! the format on the wire is the target endianness
1128  *
1129  * The format of reg->value is little endian
1130  *
1131  */
1132 static void gdb_str_to_target(struct target *target,
1133                 char *tstr, struct reg *reg)
1134 {
1135         int i;
1136
1137         uint8_t *buf;
1138         int buf_len;
1139         buf = reg->value;
1140         buf_len = DIV_ROUND_UP(reg->size, 8);
1141
1142         for (i = 0; i < buf_len; i++) {
1143                 int j = gdb_reg_pos(target, i, buf_len);
1144                 tstr += sprintf(tstr, "%02x", buf[j]);
1145         }
1146 }
1147
1148 /* copy over in register buffer */
1149 static void gdb_target_to_reg(struct target *target,
1150                 char const *tstr, int str_len, uint8_t *bin)
1151 {
1152         if (str_len % 2) {
1153                 LOG_ERROR("BUG: gdb value with uneven number of characters encountered");
1154                 exit(-1);
1155         }
1156
1157         int i;
1158         for (i = 0; i < str_len; i += 2) {
1159                 unsigned t;
1160                 if (sscanf(tstr + i, "%02x", &t) != 1) {
1161                         LOG_ERROR("BUG: unable to convert register value");
1162                         exit(-1);
1163                 }
1164
1165                 int j = gdb_reg_pos(target, i/2, str_len/2);
1166                 bin[j] = t;
1167         }
1168 }
1169
1170 static int gdb_get_registers_packet(struct connection *connection,
1171                 char const *packet, int packet_size)
1172 {
1173         struct target *target = get_target_from_connection(connection);
1174         struct reg **reg_list;
1175         int reg_list_size;
1176         int retval;
1177         int reg_packet_size = 0;
1178         char *reg_packet;
1179         char *reg_packet_p;
1180         int i;
1181
1182 #ifdef _DEBUG_GDB_IO_
1183         LOG_DEBUG("-");
1184 #endif
1185
1186         if ((target->rtos != NULL) && (ERROR_OK == rtos_get_gdb_reg_list(connection)))
1187                 return ERROR_OK;
1188
1189         retval = target_get_gdb_reg_list(target, &reg_list, &reg_list_size,
1190                         REG_CLASS_GENERAL);
1191         if (retval != ERROR_OK)
1192                 return gdb_error(connection, retval);
1193
1194         for (i = 0; i < reg_list_size; i++) {
1195                 if (reg_list[i] == NULL || reg_list[i]->exist == false)
1196                         continue;
1197                 reg_packet_size += DIV_ROUND_UP(reg_list[i]->size, 8) * 2;
1198         }
1199
1200         assert(reg_packet_size > 0);
1201
1202         reg_packet = malloc(reg_packet_size + 1); /* plus one for string termination null */
1203         if (reg_packet == NULL)
1204                 return ERROR_FAIL;
1205
1206         reg_packet_p = reg_packet;
1207
1208         for (i = 0; i < reg_list_size; i++) {
1209                 if (reg_list[i] == NULL || reg_list[i]->exist == false)
1210                         continue;
1211                 if (!reg_list[i]->valid) {
1212                         retval = reg_list[i]->type->get(reg_list[i]);
1213                         if (retval != ERROR_OK && gdb_report_register_access_error) {
1214                                 LOG_DEBUG("Couldn't get register %s.", reg_list[i]->name);
1215                                 free(reg_packet);
1216                                 free(reg_list);
1217                                 return gdb_error(connection, retval);
1218                         }
1219                 }
1220                 gdb_str_to_target(target, reg_packet_p, reg_list[i]);
1221                 reg_packet_p += DIV_ROUND_UP(reg_list[i]->size, 8) * 2;
1222         }
1223
1224 #ifdef _DEBUG_GDB_IO_
1225         {
1226                 char *reg_packet_p_debug;
1227                 reg_packet_p_debug = strndup(reg_packet, reg_packet_size);
1228                 LOG_DEBUG("reg_packet: %s", reg_packet_p_debug);
1229                 free(reg_packet_p_debug);
1230         }
1231 #endif
1232
1233         gdb_put_packet(connection, reg_packet, reg_packet_size);
1234         free(reg_packet);
1235
1236         free(reg_list);
1237
1238         return ERROR_OK;
1239 }
1240
1241 static int gdb_set_registers_packet(struct connection *connection,
1242                 char const *packet, int packet_size)
1243 {
1244         struct target *target = get_target_from_connection(connection);
1245         int i;
1246         struct reg **reg_list;
1247         int reg_list_size;
1248         int retval;
1249         char const *packet_p;
1250
1251 #ifdef _DEBUG_GDB_IO_
1252         LOG_DEBUG("-");
1253 #endif
1254
1255         /* skip command character */
1256         packet++;
1257         packet_size--;
1258
1259         if (packet_size % 2) {
1260                 LOG_WARNING("GDB set_registers packet with uneven characters received, dropping connection");
1261                 return ERROR_SERVER_REMOTE_CLOSED;
1262         }
1263
1264         retval = target_get_gdb_reg_list(target, &reg_list, &reg_list_size,
1265                         REG_CLASS_GENERAL);
1266         if (retval != ERROR_OK)
1267                 return gdb_error(connection, retval);
1268
1269         packet_p = packet;
1270         for (i = 0; i < reg_list_size; i++) {
1271                 uint8_t *bin_buf;
1272                 int chars = (DIV_ROUND_UP(reg_list[i]->size, 8) * 2);
1273
1274                 if (packet_p + chars > packet + packet_size)
1275                         LOG_ERROR("BUG: register packet is too small for registers");
1276
1277                 bin_buf = malloc(DIV_ROUND_UP(reg_list[i]->size, 8));
1278                 gdb_target_to_reg(target, packet_p, chars, bin_buf);
1279
1280                 retval = reg_list[i]->type->set(reg_list[i], bin_buf);
1281                 if (retval != ERROR_OK && gdb_report_register_access_error) {
1282                         LOG_DEBUG("Couldn't set register %s.", reg_list[i]->name);
1283                         free(reg_list);
1284                         free(bin_buf);
1285                         return gdb_error(connection, retval);
1286                 }
1287
1288                 /* advance packet pointer */
1289                 packet_p += chars;
1290
1291                 free(bin_buf);
1292         }
1293
1294         /* free struct reg *reg_list[] array allocated by get_gdb_reg_list */
1295         free(reg_list);
1296
1297         gdb_put_packet(connection, "OK", 2);
1298
1299         return ERROR_OK;
1300 }
1301
1302 static int gdb_get_register_packet(struct connection *connection,
1303         char const *packet, int packet_size)
1304 {
1305         struct target *target = get_target_from_connection(connection);
1306         char *reg_packet;
1307         int reg_num = strtoul(packet + 1, NULL, 16);
1308         struct reg **reg_list;
1309         int reg_list_size;
1310         int retval;
1311
1312 #ifdef _DEBUG_GDB_IO_
1313         LOG_DEBUG("-");
1314 #endif
1315
1316         if ((target->rtos != NULL) && (ERROR_OK == rtos_get_gdb_reg(connection, reg_num)))
1317                 return ERROR_OK;
1318
1319         retval = target_get_gdb_reg_list_noread(target, &reg_list, &reg_list_size,
1320                         REG_CLASS_ALL);
1321         if (retval != ERROR_OK)
1322                 return gdb_error(connection, retval);
1323
1324         if (reg_list_size <= reg_num) {
1325                 LOG_ERROR("gdb requested a non-existing register");
1326                 return ERROR_SERVER_REMOTE_CLOSED;
1327         }
1328
1329         if (!reg_list[reg_num]->valid) {
1330                 retval = reg_list[reg_num]->type->get(reg_list[reg_num]);
1331                 if (retval != ERROR_OK && gdb_report_register_access_error) {
1332                         LOG_DEBUG("Couldn't get register %s.", reg_list[reg_num]->name);
1333                         free(reg_list);
1334                         return gdb_error(connection, retval);
1335                 }
1336         }
1337
1338         reg_packet = malloc(DIV_ROUND_UP(reg_list[reg_num]->size, 8) * 2 + 1); /* plus one for string termination null */
1339
1340         gdb_str_to_target(target, reg_packet, reg_list[reg_num]);
1341
1342         gdb_put_packet(connection, reg_packet, DIV_ROUND_UP(reg_list[reg_num]->size, 8) * 2);
1343
1344         free(reg_list);
1345         free(reg_packet);
1346
1347         return ERROR_OK;
1348 }
1349
1350 static int gdb_set_register_packet(struct connection *connection,
1351         char const *packet, int packet_size)
1352 {
1353         struct target *target = get_target_from_connection(connection);
1354         char *separator;
1355         int reg_num = strtoul(packet + 1, &separator, 16);
1356         struct reg **reg_list;
1357         int reg_list_size;
1358         int retval;
1359
1360 #ifdef _DEBUG_GDB_IO_
1361         LOG_DEBUG("-");
1362 #endif
1363
1364         if (*separator != '=') {
1365                 LOG_ERROR("GDB 'set register packet', but no '=' following the register number");
1366                 return ERROR_SERVER_REMOTE_CLOSED;
1367         }
1368         size_t chars = strlen(separator + 1);
1369         uint8_t *bin_buf = malloc(chars / 2);
1370         gdb_target_to_reg(target, separator + 1, chars, bin_buf);
1371
1372         if ((target->rtos != NULL) &&
1373                         (ERROR_OK == rtos_set_reg(connection, reg_num, bin_buf))) {
1374                 free(bin_buf);
1375                 gdb_put_packet(connection, "OK", 2);
1376                 return ERROR_OK;
1377         }
1378
1379         retval = target_get_gdb_reg_list_noread(target, &reg_list, &reg_list_size,
1380                         REG_CLASS_ALL);
1381         if (retval != ERROR_OK) {
1382                 free(bin_buf);
1383                 return gdb_error(connection, retval);
1384         }
1385
1386         if (reg_list_size <= reg_num) {
1387                 LOG_ERROR("gdb requested a non-existing register");
1388                 free(bin_buf);
1389                 free(reg_list);
1390                 return ERROR_SERVER_REMOTE_CLOSED;
1391         }
1392
1393         if (chars != (DIV_ROUND_UP(reg_list[reg_num]->size, 8) * 2)) {
1394                 LOG_ERROR("gdb sent %d bits for a %d-bit register (%s)",
1395                                 (int) chars * 4, reg_list[reg_num]->size, reg_list[reg_num]->name);
1396                 free(bin_buf);
1397                 free(reg_list);
1398                 return ERROR_SERVER_REMOTE_CLOSED;
1399         }
1400
1401         gdb_target_to_reg(target, separator + 1, chars, bin_buf);
1402
1403         retval = reg_list[reg_num]->type->set(reg_list[reg_num], bin_buf);
1404         if (retval != ERROR_OK && gdb_report_register_access_error) {
1405                 LOG_DEBUG("Couldn't set register %s.", reg_list[reg_num]->name);
1406                 free(bin_buf);
1407                 free(reg_list);
1408                 return gdb_error(connection, retval);
1409         }
1410
1411         gdb_put_packet(connection, "OK", 2);
1412
1413         free(bin_buf);
1414         free(reg_list);
1415
1416         return ERROR_OK;
1417 }
1418
1419 /* No attempt is made to translate the "retval" to
1420  * GDB speak. This has to be done at the calling
1421  * site as no mapping really exists.
1422  */
1423 static int gdb_error(struct connection *connection, int retval)
1424 {
1425         LOG_DEBUG("Reporting %i to GDB as generic error", retval);
1426         gdb_send_error(connection, EFAULT);
1427         return ERROR_OK;
1428 }
1429
1430 /* We don't have to worry about the default 2 second timeout for GDB packets,
1431  * because GDB breaks up large memory reads into smaller reads.
1432  */
1433 static int gdb_read_memory_packet(struct connection *connection,
1434                 char const *packet, int packet_size)
1435 {
1436         struct target *target = get_target_from_connection(connection);
1437         char *separator;
1438         uint64_t addr = 0;
1439         uint32_t len = 0;
1440
1441         uint8_t *buffer;
1442         char *hex_buffer;
1443
1444         int retval = ERROR_OK;
1445
1446         /* skip command character */
1447         packet++;
1448
1449         addr = strtoull(packet, &separator, 16);
1450
1451         if (*separator != ',') {
1452                 LOG_ERROR("incomplete read memory packet received, dropping connection");
1453                 return ERROR_SERVER_REMOTE_CLOSED;
1454         }
1455
1456         len = strtoul(separator + 1, NULL, 16);
1457
1458         if (!len) {
1459                 LOG_WARNING("invalid read memory packet received (len == 0)");
1460                 gdb_put_packet(connection, "", 0);
1461                 return ERROR_OK;
1462         }
1463
1464         buffer = malloc(len);
1465
1466         LOG_DEBUG("addr: 0x%16.16" PRIx64 ", len: 0x%8.8" PRIx32 "", addr, len);
1467
1468         retval = target_read_buffer(target, addr, len, buffer);
1469
1470         if ((retval != ERROR_OK) && !gdb_report_data_abort) {
1471                 /* TODO : Here we have to lie and send back all zero's lest stack traces won't work.
1472                  * At some point this might be fixed in GDB, in which case this code can be removed.
1473                  *
1474                  * OpenOCD developers are acutely aware of this problem, but there is nothing
1475                  * gained by involving the user in this problem that hopefully will get resolved
1476                  * eventually
1477                  *
1478                  * http://sourceware.org/cgi-bin/gnatsweb.pl? \
1479                  * cmd = view%20audit-trail&database = gdb&pr = 2395
1480                  *
1481                  * For now, the default is to fix up things to make current GDB versions work.
1482                  * This can be overwritten using the gdb_report_data_abort <'enable'|'disable'> command.
1483                  */
1484                 memset(buffer, 0, len);
1485                 retval = ERROR_OK;
1486         }
1487
1488         if (retval == ERROR_OK) {
1489                 hex_buffer = malloc(len * 2 + 1);
1490
1491                 size_t pkt_len = hexify(hex_buffer, buffer, len, len * 2 + 1);
1492
1493                 gdb_put_packet(connection, hex_buffer, pkt_len);
1494
1495                 free(hex_buffer);
1496         } else
1497                 retval = gdb_error(connection, retval);
1498
1499         free(buffer);
1500
1501         return retval;
1502 }
1503
1504 static int gdb_write_memory_packet(struct connection *connection,
1505                 char const *packet, int packet_size)
1506 {
1507         struct target *target = get_target_from_connection(connection);
1508         char *separator;
1509         uint64_t addr = 0;
1510         uint32_t len = 0;
1511
1512         uint8_t *buffer;
1513         int retval;
1514
1515         /* skip command character */
1516         packet++;
1517
1518         addr = strtoull(packet, &separator, 16);
1519
1520         if (*separator != ',') {
1521                 LOG_ERROR("incomplete write memory packet received, dropping connection");
1522                 return ERROR_SERVER_REMOTE_CLOSED;
1523         }
1524
1525         len = strtoul(separator + 1, &separator, 16);
1526
1527         if (*(separator++) != ':') {
1528                 LOG_ERROR("incomplete write memory packet received, dropping connection");
1529                 return ERROR_SERVER_REMOTE_CLOSED;
1530         }
1531
1532         buffer = malloc(len);
1533
1534         LOG_DEBUG("addr: 0x%" PRIx64 ", len: 0x%8.8" PRIx32 "", addr, len);
1535
1536         if (unhexify(buffer, separator, len) != len)
1537                 LOG_ERROR("unable to decode memory packet");
1538
1539         retval = target_write_buffer(target, addr, len, buffer);
1540
1541         if (retval == ERROR_OK)
1542                 gdb_put_packet(connection, "OK", 2);
1543         else
1544                 retval = gdb_error(connection, retval);
1545
1546         free(buffer);
1547
1548         return retval;
1549 }
1550
1551 static int gdb_write_memory_binary_packet(struct connection *connection,
1552                 char const *packet, int packet_size)
1553 {
1554         struct target *target = get_target_from_connection(connection);
1555         char *separator;
1556         uint64_t addr = 0;
1557         uint32_t len = 0;
1558
1559         int retval = ERROR_OK;
1560         /* Packets larger than fast_limit bytes will be acknowledged instantly on
1561          * the assumption that we're in a download and it's important to go as fast
1562          * as possible. */
1563         uint32_t fast_limit = 8;
1564
1565         /* skip command character */
1566         packet++;
1567
1568         addr = strtoull(packet, &separator, 16);
1569
1570         if (*separator != ',') {
1571                 LOG_ERROR("incomplete write memory binary packet received, dropping connection");
1572                 return ERROR_SERVER_REMOTE_CLOSED;
1573         }
1574
1575         len = strtoul(separator + 1, &separator, 16);
1576
1577         if (*(separator++) != ':') {
1578                 LOG_ERROR("incomplete write memory binary packet received, dropping connection");
1579                 return ERROR_SERVER_REMOTE_CLOSED;
1580         }
1581
1582         struct gdb_connection *gdb_connection = connection->priv;
1583
1584         if (gdb_connection->mem_write_error)
1585                 retval = ERROR_FAIL;
1586
1587         if (retval == ERROR_OK) {
1588                 if (len >= fast_limit) {
1589                         /* By replying the packet *immediately* GDB will send us a new packet
1590                          * while we write the last one to the target.
1591                          * We only do this for larger writes, so that users who do something like:
1592                          * p *((int*)0xdeadbeef)=8675309
1593                          * will get immediate feedback that that write failed.
1594                          */
1595                         gdb_put_packet(connection, "OK", 2);
1596                 }
1597         } else {
1598                 retval = gdb_error(connection, retval);
1599                 /* now that we have reported the memory write error, we can clear the condition */
1600                 gdb_connection->mem_write_error = false;
1601                 if (retval != ERROR_OK)
1602                         return retval;
1603         }
1604
1605         if (len) {
1606                 LOG_DEBUG("addr: 0x%" PRIx64 ", len: 0x%8.8" PRIx32 "", addr, len);
1607
1608                 retval = target_write_buffer(target, addr, len, (uint8_t *)separator);
1609                 if (retval != ERROR_OK)
1610                         gdb_connection->mem_write_error = true;
1611         }
1612
1613         if (len < fast_limit) {
1614                 if (retval != ERROR_OK) {
1615                         gdb_error(connection, retval);
1616                         gdb_connection->mem_write_error = false;
1617                 } else {
1618                         gdb_put_packet(connection, "OK", 2);
1619                 }
1620         }
1621
1622         return ERROR_OK;
1623 }
1624
1625 static int gdb_step_continue_packet(struct connection *connection,
1626                 char const *packet, int packet_size)
1627 {
1628         struct target *target = get_target_from_connection(connection);
1629         int current = 0;
1630         uint64_t address = 0x0;
1631         int retval = ERROR_OK;
1632
1633         LOG_DEBUG("-");
1634
1635         if (packet_size > 1)
1636                 address = strtoull(packet + 1, NULL, 16);
1637         else
1638                 current = 1;
1639
1640         gdb_running_type = packet[0];
1641         if (packet[0] == 'c') {
1642                 LOG_DEBUG("continue");
1643                 /* resume at current address, don't handle breakpoints, not debugging */
1644                 retval = target_resume(target, current, address, 0, 0);
1645         } else if (packet[0] == 's') {
1646                 LOG_DEBUG("step");
1647                 /* step at current or address, don't handle breakpoints */
1648                 retval = target_step(target, current, address, 0);
1649         }
1650         return retval;
1651 }
1652
1653 static int gdb_breakpoint_watchpoint_packet(struct connection *connection,
1654                 char const *packet, int packet_size)
1655 {
1656         struct target *target = get_target_from_connection(connection);
1657         int type;
1658         enum breakpoint_type bp_type = BKPT_SOFT /* dummy init to avoid warning */;
1659         enum watchpoint_rw wp_type = WPT_READ /* dummy init to avoid warning */;
1660         uint64_t address;
1661         uint32_t size;
1662         char *separator;
1663         int retval;
1664
1665         LOG_DEBUG("[%s]", target_name(target));
1666
1667         type = strtoul(packet + 1, &separator, 16);
1668
1669         if (type == 0)  /* memory breakpoint */
1670                 bp_type = BKPT_SOFT;
1671         else if (type == 1)     /* hardware breakpoint */
1672                 bp_type = BKPT_HARD;
1673         else if (type == 2)     /* write watchpoint */
1674                 wp_type = WPT_WRITE;
1675         else if (type == 3)     /* read watchpoint */
1676                 wp_type = WPT_READ;
1677         else if (type == 4)     /* access watchpoint */
1678                 wp_type = WPT_ACCESS;
1679         else {
1680                 LOG_ERROR("invalid gdb watch/breakpoint type(%d), dropping connection", type);
1681                 return ERROR_SERVER_REMOTE_CLOSED;
1682         }
1683
1684         if (gdb_breakpoint_override && ((bp_type == BKPT_SOFT) || (bp_type == BKPT_HARD)))
1685                 bp_type = gdb_breakpoint_override_type;
1686
1687         if (*separator != ',') {
1688                 LOG_ERROR("incomplete breakpoint/watchpoint packet received, dropping connection");
1689                 return ERROR_SERVER_REMOTE_CLOSED;
1690         }
1691
1692         address = strtoull(separator + 1, &separator, 16);
1693
1694         if (*separator != ',') {
1695                 LOG_ERROR("incomplete breakpoint/watchpoint packet received, dropping connection");
1696                 return ERROR_SERVER_REMOTE_CLOSED;
1697         }
1698
1699         size = strtoul(separator + 1, &separator, 16);
1700
1701         switch (type) {
1702                 case 0:
1703                 case 1:
1704                         if (packet[0] == 'Z') {
1705                                 retval = breakpoint_add(target, address, size, bp_type);
1706                                 if (retval != ERROR_OK) {
1707                                         retval = gdb_error(connection, retval);
1708                                         if (retval != ERROR_OK)
1709                                                 return retval;
1710                                 } else
1711                                         gdb_put_packet(connection, "OK", 2);
1712                         } else {
1713                                 breakpoint_remove(target, address);
1714                                 gdb_put_packet(connection, "OK", 2);
1715                         }
1716                         break;
1717                 case 2:
1718                 case 3:
1719                 case 4:
1720                 {
1721                         if (packet[0] == 'Z') {
1722                                 retval = watchpoint_add(target, address, size, wp_type, 0, 0xffffffffu);
1723                                 if (retval != ERROR_OK) {
1724                                         retval = gdb_error(connection, retval);
1725                                         if (retval != ERROR_OK)
1726                                                 return retval;
1727                                 } else
1728                                         gdb_put_packet(connection, "OK", 2);
1729                         } else {
1730                                 watchpoint_remove(target, address);
1731                                 gdb_put_packet(connection, "OK", 2);
1732                         }
1733                         break;
1734                 }
1735                 default:
1736                         break;
1737         }
1738
1739         return ERROR_OK;
1740 }
1741
1742 /* print out a string and allocate more space as needed,
1743  * mainly used for XML at this point
1744  */
1745 static __attribute__ ((format (PRINTF_ATTRIBUTE_FORMAT, 5, 6))) void xml_printf(int *retval,
1746                 char **xml, int *pos, int *size, const char *fmt, ...)
1747 {
1748         if (*retval != ERROR_OK)
1749                 return;
1750         int first = 1;
1751
1752         for (;; ) {
1753                 if ((*xml == NULL) || (!first)) {
1754                         /* start by 0 to exercise all the code paths.
1755                          * Need minimum 2 bytes to fit 1 char and 0 terminator. */
1756
1757                         *size = *size * 2 + 2;
1758                         char *t = *xml;
1759                         *xml = realloc(*xml, *size);
1760                         if (*xml == NULL) {
1761                                 if (t)
1762                                         free(t);
1763                                 *retval = ERROR_SERVER_REMOTE_CLOSED;
1764                                 return;
1765                         }
1766                 }
1767
1768                 va_list ap;
1769                 int ret;
1770                 va_start(ap, fmt);
1771                 ret = vsnprintf(*xml + *pos, *size - *pos, fmt, ap);
1772                 va_end(ap);
1773                 if ((ret > 0) && ((ret + 1) < *size - *pos)) {
1774                         *pos += ret;
1775                         return;
1776                 }
1777                 /* there was just enough or not enough space, allocate more. */
1778                 first = 0;
1779         }
1780 }
1781
1782 static int decode_xfer_read(char const *buf, char **annex, int *ofs, unsigned int *len)
1783 {
1784         /* Locate the annex. */
1785         const char *annex_end = strchr(buf, ':');
1786         if (annex_end == NULL)
1787                 return ERROR_FAIL;
1788
1789         /* After the read marker and annex, qXfer looks like a
1790          * traditional 'm' packet. */
1791         char *separator;
1792         *ofs = strtoul(annex_end + 1, &separator, 16);
1793
1794         if (*separator != ',')
1795                 return ERROR_FAIL;
1796
1797         *len = strtoul(separator + 1, NULL, 16);
1798
1799         /* Extract the annex if needed */
1800         if (annex != NULL) {
1801                 *annex = strndup(buf, annex_end - buf);
1802                 if (*annex == NULL)
1803                         return ERROR_FAIL;
1804         }
1805
1806         return ERROR_OK;
1807 }
1808
1809 static int compare_bank(const void *a, const void *b)
1810 {
1811         struct flash_bank *b1, *b2;
1812         b1 = *((struct flash_bank **)a);
1813         b2 = *((struct flash_bank **)b);
1814
1815         if (b1->base == b2->base)
1816                 return 0;
1817         else if (b1->base > b2->base)
1818                 return 1;
1819         else
1820                 return -1;
1821 }
1822
1823 static int gdb_memory_map(struct connection *connection,
1824                 char const *packet, int packet_size)
1825 {
1826         /* We get away with only specifying flash here. Regions that are not
1827          * specified are treated as if we provided no memory map(if not we
1828          * could detect the holes and mark them as RAM).
1829          * Normally we only execute this code once, but no big deal if we
1830          * have to regenerate it a couple of times.
1831          */
1832
1833         struct target *target = get_target_from_connection(connection);
1834         struct flash_bank *p;
1835         char *xml = NULL;
1836         int size = 0;
1837         int pos = 0;
1838         int retval = ERROR_OK;
1839         struct flash_bank **banks;
1840         int offset;
1841         int length;
1842         char *separator;
1843         target_addr_t ram_start = 0;
1844         unsigned int target_flash_banks = 0;
1845
1846         /* skip command character */
1847         packet += 23;
1848
1849         offset = strtoul(packet, &separator, 16);
1850         length = strtoul(separator + 1, &separator, 16);
1851
1852         xml_printf(&retval, &xml, &pos, &size, "<memory-map>\n");
1853
1854         /* Sort banks in ascending order.  We need to report non-flash
1855          * memory as ram (or rather read/write) by default for GDB, since
1856          * it has no concept of non-cacheable read/write memory (i/o etc).
1857          */
1858         banks = malloc(sizeof(struct flash_bank *)*flash_get_bank_count());
1859
1860         for (unsigned int i = 0; i < flash_get_bank_count(); i++) {
1861                 p = get_flash_bank_by_num_noprobe(i);
1862                 if (p->target != target)
1863                         continue;
1864                 retval = get_flash_bank_by_num(i, &p);
1865                 if (retval != ERROR_OK) {
1866                         free(banks);
1867                         gdb_error(connection, retval);
1868                         return retval;
1869                 }
1870                 banks[target_flash_banks++] = p;
1871         }
1872
1873         qsort(banks, target_flash_banks, sizeof(struct flash_bank *),
1874                 compare_bank);
1875
1876         for (unsigned int i = 0; i < target_flash_banks; i++) {
1877                 unsigned sector_size = 0;
1878                 unsigned group_len = 0;
1879
1880                 p = banks[i];
1881
1882                 if (ram_start < p->base)
1883                         xml_printf(&retval, &xml, &pos, &size,
1884                                 "<memory type=\"ram\" start=\"" TARGET_ADDR_FMT "\" "
1885                                 "length=\"" TARGET_ADDR_FMT "\"/>\n",
1886                                 ram_start, p->base - ram_start);
1887
1888                 /* Report adjacent groups of same-size sectors.  So for
1889                  * example top boot CFI flash will list an initial region
1890                  * with several large sectors (maybe 128KB) and several
1891                  * smaller ones at the end (maybe 32KB).  STR7 will have
1892                  * regions with 8KB, 32KB, and 64KB sectors; etc.
1893                  */
1894                 for (unsigned int j = 0; j < p->num_sectors; j++) {
1895
1896                         /* Maybe start a new group of sectors. */
1897                         if (sector_size == 0) {
1898                                 if (p->sectors[j].offset + p->sectors[j].size > p->size) {
1899                                         LOG_WARNING("The flash sector at offset 0x%08" PRIx32
1900                                                 " overflows the end of %s bank.",
1901                                                 p->sectors[j].offset, p->name);
1902                                         LOG_WARNING("The rest of bank will not show in gdb memory map.");
1903                                         break;
1904                                 }
1905                                 target_addr_t start;
1906                                 start = p->base + p->sectors[j].offset;
1907                                 xml_printf(&retval, &xml, &pos, &size,
1908                                         "<memory type=\"flash\" "
1909                                         "start=\"" TARGET_ADDR_FMT "\" ",
1910                                         start);
1911                                 sector_size = p->sectors[j].size;
1912                                 group_len = sector_size;
1913                         } else {
1914                                 group_len += sector_size; /* equal to p->sectors[j].size */
1915                         }
1916
1917                         /* Does this finish a group of sectors?
1918                          * If not, continue an already-started group.
1919                          */
1920                         if (j < p->num_sectors - 1
1921                                         && p->sectors[j + 1].size == sector_size
1922                                         && p->sectors[j + 1].offset == p->sectors[j].offset + sector_size
1923                                         && p->sectors[j + 1].offset + p->sectors[j + 1].size <= p->size)
1924                                 continue;
1925
1926                         xml_printf(&retval, &xml, &pos, &size,
1927                                 "length=\"0x%x\">\n"
1928                                 "<property name=\"blocksize\">"
1929                                 "0x%x</property>\n"
1930                                 "</memory>\n",
1931                                 group_len,
1932                                 sector_size);
1933                         sector_size = 0;
1934                 }
1935
1936                 ram_start = p->base + p->size;
1937         }
1938
1939         if (ram_start != 0)
1940                 xml_printf(&retval, &xml, &pos, &size,
1941                         "<memory type=\"ram\" start=\"" TARGET_ADDR_FMT "\" "
1942                         "length=\"" TARGET_ADDR_FMT "\"/>\n",
1943                         ram_start, target_address_max(target) - ram_start + 1);
1944         /* ELSE a flash chip could be at the very end of the address space, in
1945          * which case ram_start will be precisely 0 */
1946
1947         free(banks);
1948
1949         xml_printf(&retval, &xml, &pos, &size, "</memory-map>\n");
1950
1951         if (retval != ERROR_OK) {
1952                 free(xml);
1953                 gdb_error(connection, retval);
1954                 return retval;
1955         }
1956
1957         if (offset + length > pos)
1958                 length = pos - offset;
1959
1960         char *t = malloc(length + 1);
1961         t[0] = 'l';
1962         memcpy(t + 1, xml + offset, length);
1963         gdb_put_packet(connection, t, length + 1);
1964
1965         free(t);
1966         free(xml);
1967         return ERROR_OK;
1968 }
1969
1970 static const char *gdb_get_reg_type_name(enum reg_type type)
1971 {
1972         switch (type) {
1973                 case REG_TYPE_BOOL:
1974                         return "bool";
1975                 case REG_TYPE_INT:
1976                         return "int";
1977                 case REG_TYPE_INT8:
1978                         return "int8";
1979                 case REG_TYPE_INT16:
1980                         return "int16";
1981                 case REG_TYPE_INT32:
1982                         return "int32";
1983                 case REG_TYPE_INT64:
1984                         return "int64";
1985                 case REG_TYPE_INT128:
1986                         return "int128";
1987                 case REG_TYPE_UINT:
1988                         return "uint";
1989                 case REG_TYPE_UINT8:
1990                         return "uint8";
1991                 case REG_TYPE_UINT16:
1992                         return "uint16";
1993                 case REG_TYPE_UINT32:
1994                         return "uint32";
1995                 case REG_TYPE_UINT64:
1996                         return "uint64";
1997                 case REG_TYPE_UINT128:
1998                         return "uint128";
1999                 case REG_TYPE_CODE_PTR:
2000                         return "code_ptr";
2001                 case REG_TYPE_DATA_PTR:
2002                         return "data_ptr";
2003                 case REG_TYPE_FLOAT:
2004                         return "float";
2005                 case REG_TYPE_IEEE_SINGLE:
2006                         return "ieee_single";
2007                 case REG_TYPE_IEEE_DOUBLE:
2008                         return "ieee_double";
2009                 case REG_TYPE_ARCH_DEFINED:
2010                         return "int"; /* return arbitrary string to avoid compile warning. */
2011         }
2012
2013         return "int"; /* "int" as default value */
2014 }
2015
2016 static int lookup_add_arch_defined_types(char const **arch_defined_types_list[], const char *type_id,
2017                                         int *num_arch_defined_types)
2018 {
2019         int tbl_sz = *num_arch_defined_types;
2020
2021         if (type_id != NULL && (strcmp(type_id, ""))) {
2022                 for (int j = 0; j < (tbl_sz + 1); j++) {
2023                         if (!((*arch_defined_types_list)[j])) {
2024                                 (*arch_defined_types_list)[tbl_sz++] = type_id;
2025                                 *arch_defined_types_list = realloc(*arch_defined_types_list,
2026                                                                 sizeof(char *) * (tbl_sz + 1));
2027                                 (*arch_defined_types_list)[tbl_sz] = NULL;
2028                                 *num_arch_defined_types = tbl_sz;
2029                                 return 1;
2030                         } else {
2031                                 if (!strcmp((*arch_defined_types_list)[j], type_id))
2032                                         return 0;
2033                         }
2034                 }
2035         }
2036
2037         return -1;
2038 }
2039
2040 static int gdb_generate_reg_type_description(struct target *target,
2041                 char **tdesc, int *pos, int *size, struct reg_data_type *type,
2042                 char const **arch_defined_types_list[], int *num_arch_defined_types)
2043 {
2044         int retval = ERROR_OK;
2045
2046         if (type->type_class == REG_TYPE_CLASS_VECTOR) {
2047                 struct reg_data_type *data_type = type->reg_type_vector->type;
2048                 if (data_type->type == REG_TYPE_ARCH_DEFINED) {
2049                         if (lookup_add_arch_defined_types(arch_defined_types_list, data_type->id,
2050                                                         num_arch_defined_types))
2051                                 gdb_generate_reg_type_description(target, tdesc, pos, size, data_type,
2052                                                                 arch_defined_types_list,
2053                                                                 num_arch_defined_types);
2054                 }
2055                 /* <vector id="id" type="type" count="count"/> */
2056                 xml_printf(&retval, tdesc, pos, size,
2057                                 "<vector id=\"%s\" type=\"%s\" count=\"%d\"/>\n",
2058                                 type->id, type->reg_type_vector->type->id,
2059                                 type->reg_type_vector->count);
2060
2061         } else if (type->type_class == REG_TYPE_CLASS_UNION) {
2062                 struct reg_data_type_union_field *field;
2063                 field = type->reg_type_union->fields;
2064                 while (field != NULL) {
2065                         struct reg_data_type *data_type = field->type;
2066                         if (data_type->type == REG_TYPE_ARCH_DEFINED) {
2067                                 if (lookup_add_arch_defined_types(arch_defined_types_list, data_type->id,
2068                                                                 num_arch_defined_types))
2069                                         gdb_generate_reg_type_description(target, tdesc, pos, size, data_type,
2070                                                                         arch_defined_types_list,
2071                                                                         num_arch_defined_types);
2072                         }
2073
2074                         field = field->next;
2075                 }
2076                 /* <union id="id">
2077                  *  <field name="name" type="type"/> ...
2078                  * </union> */
2079                 xml_printf(&retval, tdesc, pos, size,
2080                                 "<union id=\"%s\">\n",
2081                                 type->id);
2082
2083                 field = type->reg_type_union->fields;
2084                 while (field != NULL) {
2085                         xml_printf(&retval, tdesc, pos, size,
2086                                         "<field name=\"%s\" type=\"%s\"/>\n",
2087                                         field->name, field->type->id);
2088
2089                         field = field->next;
2090                 }
2091
2092                 xml_printf(&retval, tdesc, pos, size,
2093                                 "</union>\n");
2094
2095         } else if (type->type_class == REG_TYPE_CLASS_STRUCT) {
2096                 struct reg_data_type_struct_field *field;
2097                 field = type->reg_type_struct->fields;
2098
2099                 if (field->use_bitfields) {
2100                         /* <struct id="id" size="size">
2101                          *  <field name="name" start="start" end="end"/> ...
2102                          * </struct> */
2103                         xml_printf(&retval, tdesc, pos, size,
2104                                         "<struct id=\"%s\" size=\"%d\">\n",
2105                                         type->id, type->reg_type_struct->size);
2106                         while (field != NULL) {
2107                                 xml_printf(&retval, tdesc, pos, size,
2108                                                 "<field name=\"%s\" start=\"%d\" end=\"%d\" type=\"%s\" />\n",
2109                                                 field->name, field->bitfield->start, field->bitfield->end,
2110                                                 gdb_get_reg_type_name(field->bitfield->type));
2111
2112                                 field = field->next;
2113                         }
2114                 } else {
2115                         while (field != NULL) {
2116                                 struct reg_data_type *data_type = field->type;
2117                                 if (data_type->type == REG_TYPE_ARCH_DEFINED) {
2118                                         if (lookup_add_arch_defined_types(arch_defined_types_list, data_type->id,
2119                                                                         num_arch_defined_types))
2120                                                 gdb_generate_reg_type_description(target, tdesc, pos, size, data_type,
2121                                                                                 arch_defined_types_list,
2122                                                                                 num_arch_defined_types);
2123                                 }
2124                         }
2125
2126                         /* <struct id="id">
2127                          *  <field name="name" type="type"/> ...
2128                          * </struct> */
2129                         xml_printf(&retval, tdesc, pos, size,
2130                                         "<struct id=\"%s\">\n",
2131                                         type->id);
2132                         while (field != NULL) {
2133                                 xml_printf(&retval, tdesc, pos, size,
2134                                                 "<field name=\"%s\" type=\"%s\"/>\n",
2135                                                 field->name, field->type->id);
2136
2137                                 field = field->next;
2138                         }
2139                 }
2140
2141                 xml_printf(&retval, tdesc, pos, size,
2142                                 "</struct>\n");
2143
2144         } else if (type->type_class == REG_TYPE_CLASS_FLAGS) {
2145                 /* <flags id="id" size="size">
2146                  *  <field name="name" start="start" end="end"/> ...
2147                  * </flags> */
2148                 xml_printf(&retval, tdesc, pos, size,
2149                                 "<flags id=\"%s\" size=\"%d\">\n",
2150                                 type->id, type->reg_type_flags->size);
2151
2152                 struct reg_data_type_flags_field *field;
2153                 field = type->reg_type_flags->fields;
2154                 while (field != NULL) {
2155                         xml_printf(&retval, tdesc, pos, size,
2156                                         "<field name=\"%s\" start=\"%d\" end=\"%d\" type=\"%s\" />\n",
2157                                         field->name, field->bitfield->start, field->bitfield->end,
2158                                         gdb_get_reg_type_name(field->bitfield->type));
2159
2160                         field = field->next;
2161                 }
2162
2163                 xml_printf(&retval, tdesc, pos, size,
2164                                 "</flags>\n");
2165
2166         }
2167
2168         return ERROR_OK;
2169 }
2170
2171 /* Get a list of available target registers features. feature_list must
2172  * be freed by caller.
2173  */
2174 static int get_reg_features_list(struct target *target, char const **feature_list[], int *feature_list_size,
2175                 struct reg **reg_list, int reg_list_size)
2176 {
2177         int tbl_sz = 0;
2178
2179         /* Start with only one element */
2180         *feature_list = calloc(1, sizeof(char *));
2181
2182         for (int i = 0; i < reg_list_size; i++) {
2183                 if (reg_list[i]->exist == false)
2184                         continue;
2185
2186                 if (reg_list[i]->feature != NULL
2187                         && reg_list[i]->feature->name != NULL
2188                         && (strcmp(reg_list[i]->feature->name, ""))) {
2189                         /* We found a feature, check if the feature is already in the
2190                          * table. If not, allocate a new entry for the table and
2191                          * put the new feature in it.
2192                          */
2193                         for (int j = 0; j < (tbl_sz + 1); j++) {
2194                                 if (!((*feature_list)[j])) {
2195                                         (*feature_list)[tbl_sz++] = reg_list[i]->feature->name;
2196                                         *feature_list = realloc(*feature_list, sizeof(char *) * (tbl_sz + 1));
2197                                         (*feature_list)[tbl_sz] = NULL;
2198                                         break;
2199                                 } else {
2200                                         if (!strcmp((*feature_list)[j], reg_list[i]->feature->name))
2201                                                 break;
2202                                 }
2203                         }
2204                 }
2205         }
2206
2207         if (feature_list_size)
2208                 *feature_list_size = tbl_sz;
2209
2210         return ERROR_OK;
2211 }
2212
2213 static int gdb_generate_target_description(struct target *target, char **tdesc_out)
2214 {
2215         int retval = ERROR_OK;
2216         struct reg **reg_list = NULL;
2217         int reg_list_size;
2218         char const *architecture;
2219         char const **features = NULL;
2220         int feature_list_size = 0;
2221         char *tdesc = NULL;
2222         int pos = 0;
2223         int size = 0;
2224
2225
2226         retval = target_get_gdb_reg_list_noread(target, &reg_list,
2227                         &reg_list_size, REG_CLASS_ALL);
2228
2229         if (retval != ERROR_OK) {
2230                 LOG_ERROR("get register list failed");
2231                 retval = ERROR_FAIL;
2232                 goto error;
2233         }
2234
2235         if (reg_list_size <= 0) {
2236                 LOG_ERROR("get register list failed");
2237                 retval = ERROR_FAIL;
2238                 goto error;
2239         }
2240
2241         /* Get a list of available target registers features */
2242         retval = get_reg_features_list(target, &features, &feature_list_size, reg_list, reg_list_size);
2243         if (retval != ERROR_OK) {
2244                 LOG_ERROR("Can't get the registers feature list");
2245                 retval = ERROR_FAIL;
2246                 goto error;
2247         }
2248
2249         /* If we found some features associated with registers, create sections */
2250         int current_feature = 0;
2251
2252         xml_printf(&retval, &tdesc, &pos, &size,
2253                         "<?xml version=\"1.0\"?>\n"
2254                         "<!DOCTYPE target SYSTEM \"gdb-target.dtd\">\n"
2255                         "<target version=\"1.0\">\n");
2256
2257         /* generate architecture element if supported by target */
2258         architecture = target_get_gdb_arch(target);
2259         if (architecture != NULL)
2260                 xml_printf(&retval, &tdesc, &pos, &size,
2261                                 "<architecture>%s</architecture>\n", architecture);
2262
2263         /* generate target description according to register list */
2264         if (features != NULL) {
2265                 while (features[current_feature]) {
2266                         char const **arch_defined_types = NULL;
2267                         int num_arch_defined_types = 0;
2268
2269                         arch_defined_types = calloc(1, sizeof(char *));
2270                         xml_printf(&retval, &tdesc, &pos, &size,
2271                                         "<feature name=\"%s\">\n",
2272                                         features[current_feature]);
2273
2274                         int i;
2275                         for (i = 0; i < reg_list_size; i++) {
2276
2277                                 if (reg_list[i]->exist == false)
2278                                         continue;
2279
2280                                 if (strcmp(reg_list[i]->feature->name, features[current_feature]))
2281                                         continue;
2282
2283                                 const char *type_str;
2284                                 if (reg_list[i]->reg_data_type != NULL) {
2285                                         if (reg_list[i]->reg_data_type->type == REG_TYPE_ARCH_DEFINED) {
2286                                                 /* generate <type... first, if there are architecture-defined types. */
2287                                                 if (lookup_add_arch_defined_types(&arch_defined_types,
2288                                                                                 reg_list[i]->reg_data_type->id,
2289                                                                                 &num_arch_defined_types))
2290                                                         gdb_generate_reg_type_description(target, &tdesc, &pos, &size,
2291                                                                                         reg_list[i]->reg_data_type,
2292                                                                                         &arch_defined_types,
2293                                                                                         &num_arch_defined_types);
2294
2295                                                 type_str = reg_list[i]->reg_data_type->id;
2296                                         } else {
2297                                                 /* predefined type */
2298                                                 type_str = gdb_get_reg_type_name(
2299                                                                 reg_list[i]->reg_data_type->type);
2300                                         }
2301                                 } else {
2302                                         /* Default type is "int" */
2303                                         type_str = "int";
2304                                 }
2305
2306                                 xml_printf(&retval, &tdesc, &pos, &size,
2307                                                 "<reg name=\"%s\"", reg_list[i]->name);
2308                                 xml_printf(&retval, &tdesc, &pos, &size,
2309                                                 " bitsize=\"%d\"", reg_list[i]->size);
2310                                 xml_printf(&retval, &tdesc, &pos, &size,
2311                                                 " regnum=\"%d\"", reg_list[i]->number);
2312                                 if (reg_list[i]->caller_save)
2313                                         xml_printf(&retval, &tdesc, &pos, &size,
2314                                                         " save-restore=\"yes\"");
2315                                 else
2316                                         xml_printf(&retval, &tdesc, &pos, &size,
2317                                                         " save-restore=\"no\"");
2318
2319                                 xml_printf(&retval, &tdesc, &pos, &size,
2320                                                 " type=\"%s\"", type_str);
2321
2322                                 if (reg_list[i]->group != NULL)
2323                                         xml_printf(&retval, &tdesc, &pos, &size,
2324                                                         " group=\"%s\"", reg_list[i]->group);
2325
2326                                 xml_printf(&retval, &tdesc, &pos, &size,
2327                                                 "/>\n");
2328                         }
2329
2330                         xml_printf(&retval, &tdesc, &pos, &size,
2331                                         "</feature>\n");
2332
2333                         current_feature++;
2334                         free(arch_defined_types);
2335                 }
2336         }
2337
2338         xml_printf(&retval, &tdesc, &pos, &size,
2339                         "</target>\n");
2340
2341 error:
2342         free(features);
2343         free(reg_list);
2344
2345         if (retval == ERROR_OK)
2346                 *tdesc_out = tdesc;
2347         else
2348                 free(tdesc);
2349
2350         return retval;
2351 }
2352
2353 static int gdb_get_target_description_chunk(struct target *target, struct target_desc_format *target_desc,
2354                 char **chunk, int32_t offset, uint32_t length)
2355 {
2356         if (target_desc == NULL) {
2357                 LOG_ERROR("Unable to Generate Target Description");
2358                 return ERROR_FAIL;
2359         }
2360
2361         char *tdesc = target_desc->tdesc;
2362         uint32_t tdesc_length = target_desc->tdesc_length;
2363
2364         if (tdesc == NULL) {
2365                 int retval = gdb_generate_target_description(target, &tdesc);
2366                 if (retval != ERROR_OK) {
2367                         LOG_ERROR("Unable to Generate Target Description");
2368                         return ERROR_FAIL;
2369                 }
2370
2371                 tdesc_length = strlen(tdesc);
2372         }
2373
2374         char transfer_type;
2375
2376         if (length < (tdesc_length - offset))
2377                 transfer_type = 'm';
2378         else
2379                 transfer_type = 'l';
2380
2381         *chunk = malloc(length + 2);
2382         if (*chunk == NULL) {
2383                 LOG_ERROR("Unable to allocate memory");
2384                 return ERROR_FAIL;
2385         }
2386
2387         (*chunk)[0] = transfer_type;
2388         if (transfer_type == 'm') {
2389                 strncpy((*chunk) + 1, tdesc + offset, length);
2390                 (*chunk)[1 + length] = '\0';
2391         } else {
2392                 strncpy((*chunk) + 1, tdesc + offset, tdesc_length - offset);
2393                 (*chunk)[1 + (tdesc_length - offset)] = '\0';
2394
2395                 /* After gdb-server sends out last chunk, invalidate tdesc. */
2396                 free(tdesc);
2397                 tdesc = NULL;
2398                 tdesc_length = 0;
2399         }
2400
2401         target_desc->tdesc = tdesc;
2402         target_desc->tdesc_length = tdesc_length;
2403
2404         return ERROR_OK;
2405 }
2406
2407 static int gdb_target_description_supported(struct target *target, int *supported)
2408 {
2409         int retval = ERROR_OK;
2410         struct reg **reg_list = NULL;
2411         int reg_list_size = 0;
2412         char const **features = NULL;
2413         int feature_list_size = 0;
2414
2415         char const *architecture = target_get_gdb_arch(target);
2416
2417         retval = target_get_gdb_reg_list_noread(target, &reg_list,
2418                         &reg_list_size, REG_CLASS_ALL);
2419         if (retval != ERROR_OK) {
2420                 LOG_ERROR("get register list failed");
2421                 goto error;
2422         }
2423
2424         if (reg_list_size <= 0) {
2425                 LOG_ERROR("get register list failed");
2426                 retval = ERROR_FAIL;
2427                 goto error;
2428         }
2429
2430         /* Get a list of available target registers features */
2431         retval = get_reg_features_list(target, &features, &feature_list_size, reg_list, reg_list_size);
2432         if (retval != ERROR_OK) {
2433                 LOG_ERROR("Can't get the registers feature list");
2434                 goto error;
2435         }
2436
2437         if (supported) {
2438                 if (architecture || feature_list_size)
2439                         *supported = 1;
2440                 else
2441                         *supported = 0;
2442         }
2443
2444 error:
2445         free(features);
2446
2447         free(reg_list);
2448
2449         return retval;
2450 }
2451
2452 static int gdb_generate_thread_list(struct target *target, char **thread_list_out)
2453 {
2454         struct rtos *rtos = target->rtos;
2455         int retval = ERROR_OK;
2456         char *thread_list = NULL;
2457         int pos = 0;
2458         int size = 0;
2459
2460         xml_printf(&retval, &thread_list, &pos, &size,
2461                    "<?xml version=\"1.0\"?>\n"
2462                    "<threads>\n");
2463
2464         if (rtos != NULL) {
2465                 for (int i = 0; i < rtos->thread_count; i++) {
2466                         struct thread_detail *thread_detail = &rtos->thread_details[i];
2467
2468                         if (!thread_detail->exists)
2469                                 continue;
2470
2471                         xml_printf(&retval, &thread_list, &pos, &size,
2472                                    "<thread id=\"%" PRIx64 "\">", thread_detail->threadid);
2473
2474                         if (thread_detail->thread_name_str != NULL)
2475                                 xml_printf(&retval, &thread_list, &pos, &size,
2476                                            "Name: %s", thread_detail->thread_name_str);
2477
2478                         if (thread_detail->extra_info_str != NULL) {
2479                                 if (thread_detail->thread_name_str != NULL)
2480                                         xml_printf(&retval, &thread_list, &pos, &size,
2481                                                    ", ");
2482                                 xml_printf(&retval, &thread_list, &pos, &size,
2483                                            "%s", thread_detail->extra_info_str);
2484                         }
2485
2486                         xml_printf(&retval, &thread_list, &pos, &size,
2487                                    "</thread>\n");
2488                 }
2489         }
2490
2491         xml_printf(&retval, &thread_list, &pos, &size,
2492                    "</threads>\n");
2493
2494         if (retval == ERROR_OK)
2495                 *thread_list_out = thread_list;
2496         else
2497                 free(thread_list);
2498
2499         return retval;
2500 }
2501
2502 static int gdb_get_thread_list_chunk(struct target *target, char **thread_list,
2503                 char **chunk, int32_t offset, uint32_t length)
2504 {
2505         if (*thread_list == NULL) {
2506                 int retval = gdb_generate_thread_list(target, thread_list);
2507                 if (retval != ERROR_OK) {
2508                         LOG_ERROR("Unable to Generate Thread List");
2509                         return ERROR_FAIL;
2510                 }
2511         }
2512
2513         size_t thread_list_length = strlen(*thread_list);
2514         char transfer_type;
2515
2516         length = MIN(length, thread_list_length - offset);
2517         if (length < (thread_list_length - offset))
2518                 transfer_type = 'm';
2519         else
2520                 transfer_type = 'l';
2521
2522         *chunk = malloc(length + 2 + 3);
2523     /* Allocating extra 3 bytes prevents false positive valgrind report
2524          * of strlen(chunk) word access:
2525          * Invalid read of size 4
2526          * Address 0x4479934 is 44 bytes inside a block of size 45 alloc'd */
2527         if (*chunk == NULL) {
2528                 LOG_ERROR("Unable to allocate memory");
2529                 return ERROR_FAIL;
2530         }
2531
2532         (*chunk)[0] = transfer_type;
2533         strncpy((*chunk) + 1, (*thread_list) + offset, length);
2534         (*chunk)[1 + length] = '\0';
2535
2536         /* After gdb-server sends out last chunk, invalidate thread list. */
2537         if (transfer_type == 'l') {
2538                 free(*thread_list);
2539                 *thread_list = NULL;
2540         }
2541
2542         return ERROR_OK;
2543 }
2544
2545 static int gdb_query_packet(struct connection *connection,
2546                 char const *packet, int packet_size)
2547 {
2548         struct command_context *cmd_ctx = connection->cmd_ctx;
2549         struct gdb_connection *gdb_connection = connection->priv;
2550         struct target *target = get_target_from_connection(connection);
2551
2552         if (strncmp(packet, "qRcmd,", 6) == 0) {
2553                 if (packet_size > 6) {
2554                         char *cmd;
2555                         cmd = malloc((packet_size - 6) / 2 + 1);
2556                         size_t len = unhexify((uint8_t *)cmd, packet + 6, (packet_size - 6) / 2);
2557                         cmd[len] = 0;
2558
2559                         /* We want to print all debug output to GDB connection */
2560                         log_add_callback(gdb_log_callback, connection);
2561                         target_call_timer_callbacks_now();
2562                         /* some commands need to know the GDB connection, make note of current
2563                          * GDB connection. */
2564                         current_gdb_connection = gdb_connection;
2565                         command_run_line(cmd_ctx, cmd);
2566                         current_gdb_connection = NULL;
2567                         target_call_timer_callbacks_now();
2568                         log_remove_callback(gdb_log_callback, connection);
2569                         free(cmd);
2570                 }
2571                 gdb_put_packet(connection, "OK", 2);
2572                 return ERROR_OK;
2573         } else if (strncmp(packet, "qCRC:", 5) == 0) {
2574                 if (packet_size > 5) {
2575                         int retval;
2576                         char gdb_reply[10];
2577                         char *separator;
2578                         uint32_t checksum;
2579                         target_addr_t addr = 0;
2580                         uint32_t len = 0;
2581
2582                         /* skip command character */
2583                         packet += 5;
2584
2585                         addr = strtoull(packet, &separator, 16);
2586
2587                         if (*separator != ',') {
2588                                 LOG_ERROR("incomplete read memory packet received, dropping connection");
2589                                 return ERROR_SERVER_REMOTE_CLOSED;
2590                         }
2591
2592                         len = strtoul(separator + 1, NULL, 16);
2593
2594                         retval = target_checksum_memory(target, addr, len, &checksum);
2595
2596                         if (retval == ERROR_OK) {
2597                                 snprintf(gdb_reply, 10, "C%8.8" PRIx32 "", checksum);
2598                                 gdb_put_packet(connection, gdb_reply, 9);
2599                         } else {
2600                                 retval = gdb_error(connection, retval);
2601                                 if (retval != ERROR_OK)
2602                                         return retval;
2603                         }
2604
2605                         return ERROR_OK;
2606                 }
2607         } else if (strncmp(packet, "qSupported", 10) == 0) {
2608                 /* we currently support packet size and qXfer:memory-map:read (if enabled)
2609                  * qXfer:features:read is supported for some targets */
2610                 int retval = ERROR_OK;
2611                 char *buffer = NULL;
2612                 int pos = 0;
2613                 int size = 0;
2614                 int gdb_target_desc_supported = 0;
2615
2616                 /* we need to test that the target supports target descriptions */
2617                 retval = gdb_target_description_supported(target, &gdb_target_desc_supported);
2618                 if (retval != ERROR_OK) {
2619                         LOG_INFO("Failed detecting Target Description Support, disabling");
2620                         gdb_target_desc_supported = 0;
2621                 }
2622
2623                 /* support may be disabled globally */
2624                 if (gdb_use_target_description == 0) {
2625                         if (gdb_target_desc_supported)
2626                                 LOG_WARNING("Target Descriptions Supported, but disabled");
2627                         gdb_target_desc_supported = 0;
2628                 }
2629
2630                 xml_printf(&retval,
2631                         &buffer,
2632                         &pos,
2633                         &size,
2634                         "PacketSize=%x;qXfer:memory-map:read%c;qXfer:features:read%c;qXfer:threads:read+;QStartNoAckMode+;vContSupported+",
2635                         GDB_BUFFER_SIZE,
2636                         ((gdb_use_memory_map == 1) && (flash_get_bank_count() > 0)) ? '+' : '-',
2637                         (gdb_target_desc_supported == 1) ? '+' : '-');
2638
2639                 if (retval != ERROR_OK) {
2640                         gdb_send_error(connection, 01);
2641                         return ERROR_OK;
2642                 }
2643
2644                 gdb_put_packet(connection, buffer, strlen(buffer));
2645                 free(buffer);
2646
2647                 return ERROR_OK;
2648         } else if ((strncmp(packet, "qXfer:memory-map:read::", 23) == 0)
2649                    && (flash_get_bank_count() > 0))
2650                 return gdb_memory_map(connection, packet, packet_size);
2651         else if (strncmp(packet, "qXfer:features:read:", 20) == 0) {
2652                 char *xml = NULL;
2653                 int retval = ERROR_OK;
2654
2655                 int offset;
2656                 unsigned int length;
2657
2658                 /* skip command character */
2659                 packet += 20;
2660
2661                 if (decode_xfer_read(packet, NULL, &offset, &length) < 0) {
2662                         gdb_send_error(connection, 01);
2663                         return ERROR_OK;
2664                 }
2665
2666                 /* Target should prepare correct target description for annex.
2667                  * The first character of returned xml is 'm' or 'l'. 'm' for
2668                  * there are *more* chunks to transfer. 'l' for it is the *last*
2669                  * chunk of target description.
2670                  */
2671                 retval = gdb_get_target_description_chunk(target, &gdb_connection->target_desc,
2672                                 &xml, offset, length);
2673                 if (retval != ERROR_OK) {
2674                         gdb_error(connection, retval);
2675                         return retval;
2676                 }
2677
2678                 gdb_put_packet(connection, xml, strlen(xml));
2679
2680                 free(xml);
2681                 return ERROR_OK;
2682         } else if (strncmp(packet, "qXfer:threads:read:", 19) == 0) {
2683                 char *xml = NULL;
2684                 int retval = ERROR_OK;
2685
2686                 int offset;
2687                 unsigned int length;
2688
2689                 /* skip command character */
2690                 packet += 19;
2691
2692                 if (decode_xfer_read(packet, NULL, &offset, &length) < 0) {
2693                         gdb_send_error(connection, 01);
2694                         return ERROR_OK;
2695                 }
2696
2697                 /* Target should prepare correct thread list for annex.
2698                  * The first character of returned xml is 'm' or 'l'. 'm' for
2699                  * there are *more* chunks to transfer. 'l' for it is the *last*
2700                  * chunk of target description.
2701                  */
2702                 retval = gdb_get_thread_list_chunk(target, &gdb_connection->thread_list,
2703                                                    &xml, offset, length);
2704                 if (retval != ERROR_OK) {
2705                         gdb_error(connection, retval);
2706                         return retval;
2707                 }
2708
2709                 gdb_put_packet(connection, xml, strlen(xml));
2710
2711                 free(xml);
2712                 return ERROR_OK;
2713         } else if (strncmp(packet, "QStartNoAckMode", 15) == 0) {
2714                 gdb_connection->noack_mode = 1;
2715                 gdb_put_packet(connection, "OK", 2);
2716                 return ERROR_OK;
2717         }
2718
2719         gdb_put_packet(connection, "", 0);
2720         return ERROR_OK;
2721 }
2722
2723 static bool gdb_handle_vcont_packet(struct connection *connection, const char *packet, int packet_size)
2724 {
2725         struct gdb_connection *gdb_connection = connection->priv;
2726         struct target *target = get_target_from_connection(connection);
2727         const char *parse = packet;
2728         int retval;
2729
2730         /* query for vCont supported */
2731         if (parse[0] == '?') {
2732                 if (target->type->step != NULL) {
2733                         /* gdb doesn't accept c without C and s without S */
2734                         gdb_put_packet(connection, "vCont;c;C;s;S", 13);
2735                         return true;
2736                 }
2737                 return false;
2738         }
2739
2740         if (parse[0] == ';') {
2741                 ++parse;
2742                 --packet_size;
2743         }
2744
2745         /* simple case, a continue packet */
2746         if (parse[0] == 'c') {
2747                 gdb_running_type = 'c';
2748                 LOG_DEBUG("target %s continue", target_name(target));
2749                 log_add_callback(gdb_log_callback, connection);
2750                 retval = target_resume(target, 1, 0, 0, 0);
2751                 if (retval == ERROR_TARGET_NOT_HALTED)
2752                         LOG_INFO("target %s was not halted when resume was requested", target_name(target));
2753
2754                 /* poll target in an attempt to make its internal state consistent */
2755                 if (retval != ERROR_OK) {
2756                         retval = target_poll(target);
2757                         if (retval != ERROR_OK)
2758                                 LOG_DEBUG("error polling target %s after failed resume", target_name(target));
2759                 }
2760
2761                 /*
2762                  * We don't report errors to gdb here, move frontend_state to
2763                  * TARGET_RUNNING to stay in sync with gdb's expectation of the
2764                  * target state
2765                  */
2766                 gdb_connection->frontend_state = TARGET_RUNNING;
2767                 target_call_event_callbacks(target, TARGET_EVENT_GDB_START);
2768
2769                 return true;
2770         }
2771
2772         /* single-step or step-over-breakpoint */
2773         if (parse[0] == 's') {
2774                 gdb_running_type = 's';
2775                 bool fake_step = false;
2776
2777                 if (strncmp(parse, "s:", 2) == 0) {
2778                         struct target *ct = target;
2779                         int current_pc = 1;
2780                         int64_t thread_id;
2781                         char *endp;
2782
2783                         parse += 2;
2784                         packet_size -= 2;
2785
2786                         thread_id = strtoll(parse, &endp, 16);
2787                         if (endp != NULL) {
2788                                 packet_size -= endp - parse;
2789                                 parse = endp;
2790                         }
2791
2792                         if (target->rtos != NULL) {
2793                                 /* FIXME: why is this necessary? rtos state should be up-to-date here already! */
2794                                 rtos_update_threads(target);
2795
2796                                 target->rtos->gdb_target_for_threadid(connection, thread_id, &ct);
2797
2798                                 /*
2799                                  * check if the thread to be stepped is the current rtos thread
2800                                  * if not, we must fake the step
2801                                  */
2802                                 if (target->rtos->current_thread != thread_id)
2803                                         fake_step = true;
2804                         }
2805
2806                         if (parse[0] == ';') {
2807                                 ++parse;
2808                                 --packet_size;
2809
2810                                 if (parse[0] == 'c') {
2811                                         parse += 1;
2812
2813                                         /* check if thread-id follows */
2814                                         if (parse[0] == ':') {
2815                                                 int64_t tid;
2816                                                 parse += 1;
2817
2818                                                 tid = strtoll(parse, &endp, 16);
2819                                                 if (tid == thread_id) {
2820                                                         /*
2821                                                          * Special case: only step a single thread (core),
2822                                                          * keep the other threads halted. Currently, only
2823                                                          * aarch64 target understands it. Other target types don't
2824                                                          * care (nobody checks the actual value of 'current')
2825                                                          * and it doesn't really matter. This deserves
2826                                                          * a symbolic constant and a formal interface documentation
2827                                                          * at a later time.
2828                                                          */
2829                                                         LOG_DEBUG("request to step current core only");
2830                                                         /* uncomment after checking that indeed other targets are safe */
2831                                                         /*current_pc = 2;*/
2832                                                 }
2833                                         }
2834                                 }
2835                         }
2836
2837                         LOG_DEBUG("target %s single-step thread %"PRIx64, target_name(ct), thread_id);
2838                         log_add_callback(gdb_log_callback, connection);
2839                         target_call_event_callbacks(ct, TARGET_EVENT_GDB_START);
2840
2841                         /*
2842                          * work around an annoying gdb behaviour: when the current thread
2843                          * is changed in gdb, it assumes that the target can follow and also
2844                          * make the thread current. This is an assumption that cannot hold
2845                          * for a real target running a multi-threading OS. We just fake
2846                          * the step to not trigger an internal error in gdb. See
2847                          * https://sourceware.org/bugzilla/show_bug.cgi?id=22925 for details
2848                          */
2849                         if (fake_step) {
2850                                 int sig_reply_len;
2851                                 char sig_reply[128];
2852
2853                                 LOG_DEBUG("fake step thread %"PRIx64, thread_id);
2854
2855                                 sig_reply_len = snprintf(sig_reply, sizeof(sig_reply),
2856                                                                                  "T05thread:%016"PRIx64";", thread_id);
2857
2858                                 gdb_put_packet(connection, sig_reply, sig_reply_len);
2859                                 log_remove_callback(gdb_log_callback, connection);
2860
2861                                 return true;
2862                         }
2863
2864                         /* support for gdb_sync command */
2865                         if (gdb_connection->sync) {
2866                                 gdb_connection->sync = false;
2867                                 if (ct->state == TARGET_HALTED) {
2868                                         LOG_DEBUG("stepi ignored. GDB will now fetch the register state "
2869                                                                         "from the target.");
2870                                         gdb_sig_halted(connection);
2871                                         log_remove_callback(gdb_log_callback, connection);
2872                                 } else
2873                                         gdb_connection->frontend_state = TARGET_RUNNING;
2874                                 return true;
2875                         }
2876
2877                         retval = target_step(ct, current_pc, 0, 0);
2878                         if (retval == ERROR_TARGET_NOT_HALTED)
2879                                 LOG_INFO("target %s was not halted when step was requested", target_name(ct));
2880
2881                         /* if step was successful send a reply back to gdb */
2882                         if (retval == ERROR_OK) {
2883                                 retval = target_poll(ct);
2884                                 if (retval != ERROR_OK)
2885                                         LOG_DEBUG("error polling target %s after successful step", target_name(ct));
2886                                 /* send back signal information */
2887                                 gdb_signal_reply(ct, connection);
2888                                 /* stop forwarding log packets! */
2889                                 log_remove_callback(gdb_log_callback, connection);
2890                         } else
2891                                 gdb_connection->frontend_state = TARGET_RUNNING;
2892                 } else {
2893                         LOG_ERROR("Unknown vCont packet");
2894                         return false;
2895                 }
2896                 return true;
2897         }
2898
2899         return false;
2900 }
2901
2902 static char *next_hex_encoded_field(const char **str, char sep)
2903 {
2904         size_t hexlen;
2905         const char *hex = *str;
2906         if (hex[0] == '\0')
2907                 return NULL;
2908
2909         const char *end = strchr(hex, sep);
2910         if (end == NULL)
2911                 hexlen = strlen(hex);
2912         else
2913                 hexlen = end - hex;
2914         *str = hex + hexlen + 1;
2915
2916         if (hexlen % 2 != 0) {
2917                 /* Malformed hex data */
2918                 return NULL;
2919         }
2920
2921         size_t count = hexlen / 2;
2922         char *decoded = malloc(count + 1);
2923         if (decoded == NULL)
2924                 return NULL;
2925
2926         size_t converted = unhexify((void *)decoded, hex, count);
2927         if (converted != count) {
2928                 free(decoded);
2929                 return NULL;
2930         }
2931
2932         decoded[count] = '\0';
2933         return decoded;
2934 }
2935
2936 /* handle extended restart packet */
2937 static void gdb_restart_inferior(struct connection *connection, const char *packet, int packet_size)
2938 {
2939         struct gdb_connection *gdb_con = connection->priv;
2940         struct target *target = get_target_from_connection(connection);
2941
2942         breakpoint_clear_target(target);
2943         watchpoint_clear_target(target);
2944         command_run_linef(connection->cmd_ctx, "ocd_gdb_restart %s",
2945                         target_name(target));
2946         /* set connection as attached after reset */
2947         gdb_con->attached = true;
2948         /*  info rtos parts */
2949         gdb_thread_packet(connection, packet, packet_size);
2950 }
2951
2952 static bool gdb_handle_vrun_packet(struct connection *connection, const char *packet, int packet_size)
2953 {
2954         struct target *target = get_target_from_connection(connection);
2955         const char *parse = packet;
2956
2957         /* Skip "vRun" */
2958         parse += 4;
2959
2960         if (parse[0] != ';')
2961                 return false;
2962         parse++;
2963
2964         /* Skip first field "filename"; don't know what to do with it. */
2965         free(next_hex_encoded_field(&parse, ';'));
2966
2967         char *cmdline = next_hex_encoded_field(&parse, ';');
2968         char *arg;
2969         while (cmdline != NULL && (arg = next_hex_encoded_field(&parse, ';')) != NULL) {
2970                 char *new_cmdline = alloc_printf("%s %s", cmdline, arg);
2971                 free(cmdline);
2972                 free(arg);
2973                 cmdline = new_cmdline;
2974         }
2975
2976         if (cmdline != NULL) {
2977                 if (target->semihosting != NULL) {
2978                         LOG_INFO("GDB set inferior command line to '%s'", cmdline);
2979                         free(target->semihosting->cmdline);
2980                         target->semihosting->cmdline = cmdline;
2981                 } else {
2982                         LOG_INFO("GDB set inferior command line to '%s' but semihosting is unavailable", cmdline);
2983                         free(cmdline);
2984                 }
2985         }
2986
2987         gdb_restart_inferior(connection, packet, packet_size);
2988         gdb_put_packet(connection, "S00", 3);
2989         return true;
2990 }
2991
2992 static int gdb_v_packet(struct connection *connection,
2993                 char const *packet, int packet_size)
2994 {
2995         struct gdb_connection *gdb_connection = connection->priv;
2996         int result;
2997
2998         struct target *target = get_target_from_connection(connection);
2999
3000         if (strncmp(packet, "vCont", 5) == 0) {
3001                 bool handled;
3002
3003                 packet += 5;
3004                 packet_size -= 5;
3005
3006                 handled = gdb_handle_vcont_packet(connection, packet, packet_size);
3007                 if (!handled)
3008                         gdb_put_packet(connection, "", 0);
3009
3010                 return ERROR_OK;
3011         }
3012
3013         if (strncmp(packet, "vRun", 4) == 0) {
3014                 bool handled;
3015
3016                 handled = gdb_handle_vrun_packet(connection, packet, packet_size);
3017                 if (!handled)
3018                         gdb_put_packet(connection, "", 0);
3019
3020                 return ERROR_OK;
3021         }
3022
3023         /* if flash programming disabled - send a empty reply */
3024
3025         if (gdb_flash_program == 0) {
3026                 gdb_put_packet(connection, "", 0);
3027                 return ERROR_OK;
3028         }
3029
3030         if (strncmp(packet, "vFlashErase:", 12) == 0) {
3031                 unsigned long addr;
3032                 unsigned long length;
3033
3034                 char const *parse = packet + 12;
3035                 if (*parse == '\0') {
3036                         LOG_ERROR("incomplete vFlashErase packet received, dropping connection");
3037                         return ERROR_SERVER_REMOTE_CLOSED;
3038                 }
3039
3040                 addr = strtoul(parse, (char **)&parse, 16);
3041
3042                 if (*(parse++) != ',' || *parse == '\0') {
3043                         LOG_ERROR("incomplete vFlashErase packet received, dropping connection");
3044                         return ERROR_SERVER_REMOTE_CLOSED;
3045                 }
3046
3047                 length = strtoul(parse, (char **)&parse, 16);
3048
3049                 if (*parse != '\0') {
3050                         LOG_ERROR("incomplete vFlashErase packet received, dropping connection");
3051                         return ERROR_SERVER_REMOTE_CLOSED;
3052                 }
3053
3054                 /* assume all sectors need erasing - stops any problems
3055                  * when flash_write is called multiple times */
3056                 flash_set_dirty();
3057
3058                 /* perform any target specific operations before the erase */
3059                 target_call_event_callbacks(target,
3060                         TARGET_EVENT_GDB_FLASH_ERASE_START);
3061
3062                 /* vFlashErase:addr,length messages require region start and
3063                  * end to be "block" aligned ... if padding is ever needed,
3064                  * GDB will have become dangerously confused.
3065                  */
3066                 result = flash_erase_address_range(target, false, addr,
3067                         length);
3068
3069                 /* perform any target specific operations after the erase */
3070                 target_call_event_callbacks(target,
3071                         TARGET_EVENT_GDB_FLASH_ERASE_END);
3072
3073                 /* perform erase */
3074                 if (result != ERROR_OK) {
3075                         /* GDB doesn't evaluate the actual error number returned,
3076                          * treat a failed erase as an I/O error
3077                          */
3078                         gdb_send_error(connection, EIO);
3079                         LOG_ERROR("flash_erase returned %i", result);
3080                 } else
3081                         gdb_put_packet(connection, "OK", 2);
3082
3083                 return ERROR_OK;
3084         }
3085
3086         if (strncmp(packet, "vFlashWrite:", 12) == 0) {
3087                 int retval;
3088                 unsigned long addr;
3089                 unsigned long length;
3090                 char const *parse = packet + 12;
3091
3092                 if (*parse == '\0') {
3093                         LOG_ERROR("incomplete vFlashErase packet received, dropping connection");
3094                         return ERROR_SERVER_REMOTE_CLOSED;
3095                 }
3096                 addr = strtoul(parse, (char **)&parse, 16);
3097                 if (*(parse++) != ':') {
3098                         LOG_ERROR("incomplete vFlashErase packet received, dropping connection");
3099                         return ERROR_SERVER_REMOTE_CLOSED;
3100                 }
3101                 length = packet_size - (parse - packet);
3102
3103                 /* create a new image if there isn't already one */
3104                 if (gdb_connection->vflash_image == NULL) {
3105                         gdb_connection->vflash_image = malloc(sizeof(struct image));
3106                         image_open(gdb_connection->vflash_image, "", "build");
3107                 }
3108
3109                 /* create new section with content from packet buffer */
3110                 retval = image_add_section(gdb_connection->vflash_image,
3111                                 addr, length, 0x0, (uint8_t const *)parse);
3112                 if (retval != ERROR_OK)
3113                         return retval;
3114
3115                 gdb_put_packet(connection, "OK", 2);
3116
3117                 return ERROR_OK;
3118         }
3119
3120         if (strncmp(packet, "vFlashDone", 10) == 0) {
3121                 uint32_t written;
3122
3123                 /* process the flashing buffer. No need to erase as GDB
3124                  * always issues a vFlashErase first. */
3125                 target_call_event_callbacks(target,
3126                                 TARGET_EVENT_GDB_FLASH_WRITE_START);
3127                 result = flash_write(target, gdb_connection->vflash_image,
3128                         &written, false);
3129                 target_call_event_callbacks(target,
3130                         TARGET_EVENT_GDB_FLASH_WRITE_END);
3131                 if (result != ERROR_OK) {
3132                         if (result == ERROR_FLASH_DST_OUT_OF_BANK)
3133                                 gdb_put_packet(connection, "E.memtype", 9);
3134                         else
3135                                 gdb_send_error(connection, EIO);
3136                 } else {
3137                         LOG_DEBUG("wrote %u bytes from vFlash image to flash", (unsigned)written);
3138                         gdb_put_packet(connection, "OK", 2);
3139                 }
3140
3141                 image_close(gdb_connection->vflash_image);
3142                 free(gdb_connection->vflash_image);
3143                 gdb_connection->vflash_image = NULL;
3144
3145                 return ERROR_OK;
3146         }
3147
3148         gdb_put_packet(connection, "", 0);
3149         return ERROR_OK;
3150 }
3151
3152 static int gdb_detach(struct connection *connection)
3153 {
3154         /*
3155          * Only reply "OK" to GDB
3156          * it will close the connection and this will trigger a call to
3157          * gdb_connection_closed() that will in turn trigger the event
3158          * TARGET_EVENT_GDB_DETACH
3159          */
3160         return gdb_put_packet(connection, "OK", 2);
3161 }
3162
3163 /* The format of 'F' response packet is
3164  * Fretcode,errno,Ctrl-C flag;call-specific attachment
3165  */
3166 static int gdb_fileio_response_packet(struct connection *connection,
3167                 char const *packet, int packet_size)
3168 {
3169         struct target *target = get_target_from_connection(connection);
3170         char *separator;
3171         char *parsing_point;
3172         int fileio_retcode = strtoul(packet + 1, &separator, 16);
3173         int fileio_errno = 0;
3174         bool fileio_ctrl_c = false;
3175         int retval;
3176
3177         LOG_DEBUG("-");
3178
3179         if (*separator == ',') {
3180                 parsing_point = separator + 1;
3181                 fileio_errno = strtoul(parsing_point, &separator, 16);
3182                 if (*separator == ',') {
3183                         if (*(separator + 1) == 'C') {
3184                                 /* TODO: process ctrl-c */
3185                                 fileio_ctrl_c = true;
3186                         }
3187                 }
3188         }
3189
3190         LOG_DEBUG("File-I/O response, retcode: 0x%x, errno: 0x%x, ctrl-c: %s",
3191                         fileio_retcode, fileio_errno, fileio_ctrl_c ? "true" : "false");
3192
3193         retval = target_gdb_fileio_end(target, fileio_retcode, fileio_errno, fileio_ctrl_c);
3194         if (retval != ERROR_OK)
3195                 return ERROR_FAIL;
3196
3197         /* After File-I/O ends, keep continue or step */
3198         if (gdb_running_type == 'c')
3199                 retval = target_resume(target, 1, 0x0, 0, 0);
3200         else if (gdb_running_type == 's')
3201                 retval = target_step(target, 1, 0x0, 0);
3202         else
3203                 retval = ERROR_FAIL;
3204
3205         if (retval != ERROR_OK)
3206                 return ERROR_FAIL;
3207
3208         return ERROR_OK;
3209 }
3210
3211 static void gdb_log_callback(void *priv, const char *file, unsigned line,
3212                 const char *function, const char *string)
3213 {
3214         struct connection *connection = priv;
3215         struct gdb_connection *gdb_con = connection->priv;
3216
3217         if (gdb_con->busy) {
3218                 /* do not reply this using the O packet */
3219                 return;
3220         }
3221
3222         gdb_output_con(connection, string);
3223 }
3224
3225 static void gdb_sig_halted(struct connection *connection)
3226 {
3227         char sig_reply[4];
3228         snprintf(sig_reply, 4, "T%2.2x", 2);
3229         gdb_put_packet(connection, sig_reply, 3);
3230 }
3231
3232 static int gdb_input_inner(struct connection *connection)
3233 {
3234         /* Do not allocate this on the stack */
3235         static char gdb_packet_buffer[GDB_BUFFER_SIZE + 1]; /* Extra byte for null-termination */
3236
3237         struct target *target;
3238         char const *packet = gdb_packet_buffer;
3239         int packet_size;
3240         int retval;
3241         struct gdb_connection *gdb_con = connection->priv;
3242         static bool warn_use_ext;
3243
3244         target = get_target_from_connection(connection);
3245
3246         /* drain input buffer. If one of the packets fail, then an error
3247          * packet is replied, if applicable.
3248          *
3249          * This loop will terminate and the error code is returned.
3250          *
3251          * The calling fn will check if this error is something that
3252          * can be recovered from, or if the connection must be closed.
3253          *
3254          * If the error is recoverable, this fn is called again to
3255          * drain the rest of the buffer.
3256          */
3257         do {
3258                 packet_size = GDB_BUFFER_SIZE;
3259                 retval = gdb_get_packet(connection, gdb_packet_buffer, &packet_size);
3260                 if (retval != ERROR_OK)
3261                         return retval;
3262
3263                 /* terminate with zero */
3264                 gdb_packet_buffer[packet_size] = '\0';
3265
3266                 if (LOG_LEVEL_IS(LOG_LVL_DEBUG)) {
3267                         if (packet[0] == 'X') {
3268                                 /* binary packets spew junk into the debug log stream */
3269                                 char buf[50];
3270                                 int x;
3271                                 for (x = 0; (x < 49) && (packet[x] != ':'); x++)
3272                                         buf[x] = packet[x];
3273                                 buf[x] = 0;
3274                                 LOG_DEBUG("received packet: '%s:<binary-data>'", buf);
3275                         } else
3276                                 LOG_DEBUG("received packet: '%s'", packet);
3277                 }
3278
3279                 if (packet_size > 0) {
3280                         retval = ERROR_OK;
3281                         switch (packet[0]) {
3282                                 case 'T':       /* Is thread alive? */
3283                                         gdb_thread_packet(connection, packet, packet_size);
3284                                         break;
3285                                 case 'H':       /* Set current thread ( 'c' for step and continue,
3286                                                          * 'g' for all other operations ) */
3287                                         gdb_thread_packet(connection, packet, packet_size);
3288                                         break;
3289                                 case 'q':
3290                                 case 'Q':
3291                                         retval = gdb_thread_packet(connection, packet, packet_size);
3292                                         if (retval == GDB_THREAD_PACKET_NOT_CONSUMED)
3293                                                 retval = gdb_query_packet(connection, packet, packet_size);
3294                                         break;
3295                                 case 'g':
3296                                         retval = gdb_get_registers_packet(connection, packet, packet_size);
3297                                         break;
3298                                 case 'G':
3299                                         retval = gdb_set_registers_packet(connection, packet, packet_size);
3300                                         break;
3301                                 case 'p':
3302                                         retval = gdb_get_register_packet(connection, packet, packet_size);
3303                                         break;
3304                                 case 'P':
3305                                         retval = gdb_set_register_packet(connection, packet, packet_size);
3306                                         break;
3307                                 case 'm':
3308                                         retval = gdb_read_memory_packet(connection, packet, packet_size);
3309                                         break;
3310                                 case 'M':
3311                                         retval = gdb_write_memory_packet(connection, packet, packet_size);
3312                                         break;
3313                                 case 'z':
3314                                 case 'Z':
3315                                         retval = gdb_breakpoint_watchpoint_packet(connection, packet, packet_size);
3316                                         break;
3317                                 case '?':
3318                                         gdb_last_signal_packet(connection, packet, packet_size);
3319                                         /* '?' is sent after the eventual '!' */
3320                                         if (!warn_use_ext && !gdb_con->extended_protocol) {
3321                                                 warn_use_ext = true;
3322                                                 LOG_WARNING("Prefer GDB command \"target extended-remote %s\" instead of \"target remote %s\"",
3323                                                                         connection->service->port, connection->service->port);
3324                                         }
3325                                         break;
3326                                 case 'c':
3327                                 case 's':
3328                                 {
3329                                         gdb_thread_packet(connection, packet, packet_size);
3330                                         log_add_callback(gdb_log_callback, connection);
3331
3332                                         if (gdb_con->mem_write_error) {
3333                                                 LOG_ERROR("Memory write failure!");
3334
3335                                                 /* now that we have reported the memory write error,
3336                                                  * we can clear the condition */
3337                                                 gdb_con->mem_write_error = false;
3338                                         }
3339
3340                                         bool nostep = false;
3341                                         bool already_running = false;
3342                                         if (target->state == TARGET_RUNNING) {
3343                                                 LOG_WARNING("WARNING! The target is already running. "
3344                                                                 "All changes GDB did to registers will be discarded! "
3345                                                                 "Waiting for target to halt.");
3346                                                 already_running = true;
3347                                         } else if (target->state != TARGET_HALTED) {
3348                                                 LOG_WARNING("The target is not in the halted nor running stated, "
3349                                                                 "stepi/continue ignored.");
3350                                                 nostep = true;
3351                                         } else if ((packet[0] == 's') && gdb_con->sync) {
3352                                                 /* Hmm..... when you issue a continue in GDB, then a "stepi" is
3353                                                  * sent by GDB first to OpenOCD, thus defeating the check to
3354                                                  * make only the single stepping have the sync feature...
3355                                                  */
3356                                                 nostep = true;
3357                                                 LOG_DEBUG("stepi ignored. GDB will now fetch the register state "
3358                                                                 "from the target.");
3359                                         }
3360                                         gdb_con->sync = false;
3361
3362                                         if (!already_running && nostep) {
3363                                                 /* Either the target isn't in the halted state, then we can't
3364                                                  * step/continue. This might be early setup, etc.
3365                                                  *
3366                                                  * Or we want to allow GDB to pick up a fresh set of
3367                                                  * register values without modifying the target state.
3368                                                  *
3369                                                  */
3370                                                 gdb_sig_halted(connection);
3371
3372                                                 /* stop forwarding log packets! */
3373                                                 log_remove_callback(gdb_log_callback, connection);
3374                                         } else {
3375                                                 /* We're running/stepping, in which case we can
3376                                                  * forward log output until the target is halted
3377                                                  */
3378                                                 gdb_con->frontend_state = TARGET_RUNNING;
3379                                                 target_call_event_callbacks(target, TARGET_EVENT_GDB_START);
3380
3381                                                 if (!already_running) {
3382                                                         /* Here we don't want packet processing to stop even if this fails,
3383                                                          * so we use a local variable instead of retval. */
3384                                                         retval = gdb_step_continue_packet(connection, packet, packet_size);
3385                                                         if (retval != ERROR_OK) {
3386                                                                 /* we'll never receive a halted
3387                                                                  * condition... issue a false one..
3388                                                                  */
3389                                                                 gdb_frontend_halted(target, connection);
3390                                                         }
3391                                                 }
3392                                         }
3393                                 }
3394                                 break;
3395                                 case 'v':
3396                                         retval = gdb_v_packet(connection, packet, packet_size);
3397                                         break;
3398                                 case 'D':
3399                                         retval = gdb_detach(connection);
3400                                         break;
3401                                 case 'X':
3402                                         retval = gdb_write_memory_binary_packet(connection, packet, packet_size);
3403                                         if (retval != ERROR_OK)
3404                                                 return retval;
3405                                         break;
3406                                 case 'k':
3407                                         if (gdb_con->extended_protocol) {
3408                                                 gdb_con->attached = false;
3409                                                 break;
3410                                         }
3411                                         gdb_put_packet(connection, "OK", 2);
3412                                         return ERROR_SERVER_REMOTE_CLOSED;
3413                                 case '!':
3414                                         /* handle extended remote protocol */
3415                                         gdb_con->extended_protocol = true;
3416                                         gdb_put_packet(connection, "OK", 2);
3417                                         break;
3418                                 case 'R':
3419                                         /* handle extended restart packet */
3420                                         gdb_restart_inferior(connection, packet, packet_size);
3421                                         break;
3422
3423                                 case 'j':
3424                                         /* packet supported only by smp target i.e cortex_a.c*/
3425                                         /* handle smp packet replying coreid played to gbd */
3426                                         gdb_read_smp_packet(connection, packet, packet_size);
3427                                         break;
3428
3429                                 case 'J':
3430                                         /* packet supported only by smp target i.e cortex_a.c */
3431                                         /* handle smp packet setting coreid to be played at next
3432                                          * resume to gdb */
3433                                         gdb_write_smp_packet(connection, packet, packet_size);
3434                                         break;
3435
3436                                 case 'F':
3437                                         /* File-I/O extension */
3438                                         /* After gdb uses host-side syscall to complete target file
3439                                          * I/O, gdb sends host-side syscall return value to target
3440                                          * by 'F' packet.
3441                                          * The format of 'F' response packet is
3442                                          * Fretcode,errno,Ctrl-C flag;call-specific attachment
3443                                          */
3444                                         gdb_con->frontend_state = TARGET_RUNNING;
3445                                         log_add_callback(gdb_log_callback, connection);
3446                                         gdb_fileio_response_packet(connection, packet, packet_size);
3447                                         break;
3448
3449                                 default:
3450                                         /* ignore unknown packets */
3451                                         LOG_DEBUG("ignoring 0x%2.2x packet", packet[0]);
3452                                         gdb_put_packet(connection, "", 0);
3453                                         break;
3454                         }
3455
3456                         /* if a packet handler returned an error, exit input loop */
3457                         if (retval != ERROR_OK)
3458                                 return retval;
3459                 }
3460
3461                 if (gdb_con->ctrl_c) {
3462                         if (target->state == TARGET_RUNNING) {
3463                                 struct target *t = target;
3464                                 if (target->rtos)
3465                                         target->rtos->gdb_target_for_threadid(connection, target->rtos->current_threadid, &t);
3466                                 retval = target_halt(t);
3467                                 if (retval == ERROR_OK)
3468                                         retval = target_poll(t);
3469                                 if (retval != ERROR_OK)
3470                                         target_call_event_callbacks(target, TARGET_EVENT_GDB_HALT);
3471                                 gdb_con->ctrl_c = false;
3472                         } else {
3473                                 LOG_INFO("The target is not running when halt was requested, stopping GDB.");
3474                                 target_call_event_callbacks(target, TARGET_EVENT_GDB_HALT);
3475                         }
3476                 }
3477
3478         } while (gdb_con->buf_cnt > 0);
3479
3480         return ERROR_OK;
3481 }
3482
3483 static int gdb_input(struct connection *connection)
3484 {
3485         int retval = gdb_input_inner(connection);
3486         struct gdb_connection *gdb_con = connection->priv;
3487         if (retval == ERROR_SERVER_REMOTE_CLOSED)
3488                 return retval;
3489
3490         /* logging does not propagate the error, yet can set the gdb_con->closed flag */
3491         if (gdb_con->closed)
3492                 return ERROR_SERVER_REMOTE_CLOSED;
3493
3494         /* we'll recover from any other errors(e.g. temporary timeouts, etc.) */
3495         return ERROR_OK;
3496 }
3497
3498 static int gdb_target_start(struct target *target, const char *port)
3499 {
3500         struct gdb_service *gdb_service;
3501         int ret;
3502         gdb_service = malloc(sizeof(struct gdb_service));
3503
3504         if (NULL == gdb_service)
3505                 return -ENOMEM;
3506
3507         LOG_INFO("starting gdb server for %s on %s", target_name(target), port);
3508
3509         gdb_service->target = target;
3510         gdb_service->core[0] = -1;
3511         gdb_service->core[1] = -1;
3512         target->gdb_service = gdb_service;
3513
3514         ret = add_service("gdb",
3515                         port, 1, &gdb_new_connection, &gdb_input,
3516                         &gdb_connection_closed, gdb_service);
3517         /* initialize all targets gdb service with the same pointer */
3518         {
3519                 struct target_list *head;
3520                 struct target *curr;
3521                 head = target->head;
3522                 while (head != (struct target_list *)NULL) {
3523                         curr = head->target;
3524                         if (curr != target)
3525                                 curr->gdb_service = gdb_service;
3526                         head = head->next;
3527                 }
3528         }
3529         return ret;
3530 }
3531
3532 static int gdb_target_add_one(struct target *target)
3533 {
3534         /*  one gdb instance per smp list */
3535         if ((target->smp) && (target->gdb_service))
3536                 return ERROR_OK;
3537
3538         /* skip targets that cannot handle a gdb connections (e.g. mem_ap) */
3539         if (!target_supports_gdb_connection(target)) {
3540                 LOG_DEBUG("skip gdb server for target %s", target_name(target));
3541                 return ERROR_OK;
3542         }
3543
3544         if (target->gdb_port_override) {
3545                 if (strcmp(target->gdb_port_override, "disabled") == 0) {
3546                         LOG_INFO("gdb port disabled");
3547                         return ERROR_OK;
3548                 }
3549                 return gdb_target_start(target, target->gdb_port_override);
3550         }
3551
3552         if (strcmp(gdb_port, "disabled") == 0) {
3553                 LOG_INFO("gdb port disabled");
3554                 return ERROR_OK;
3555         }
3556
3557         int retval = gdb_target_start(target, gdb_port_next);
3558         if (retval == ERROR_OK) {
3559                 /* save the port number so can be queried with
3560                  * $target_name cget -gdb-port
3561                  */
3562                 target->gdb_port_override = strdup(gdb_port_next);
3563
3564                 long portnumber;
3565                 /* If we can parse the port number
3566                  * then we increment the port number for the next target.
3567                  */
3568                 char *end;
3569                 portnumber = strtol(gdb_port_next, &end, 0);
3570                 if (!*end) {
3571                         if (parse_long(gdb_port_next, &portnumber) == ERROR_OK) {
3572                                 free(gdb_port_next);
3573                                 if (portnumber) {
3574                                         gdb_port_next = alloc_printf("%ld", portnumber+1);
3575                                 } else {
3576                                         /* Don't increment if gdb_port is 0, since we're just
3577                                          * trying to allocate an unused port. */
3578                                         gdb_port_next = strdup("0");
3579                                 }
3580                         }
3581                 }
3582         }
3583         return retval;
3584 }
3585
3586 int gdb_target_add_all(struct target *target)
3587 {
3588         if (NULL == target) {
3589                 LOG_WARNING("gdb services need one or more targets defined");
3590                 return ERROR_OK;
3591         }
3592
3593         while (NULL != target) {
3594                 int retval = gdb_target_add_one(target);
3595                 if (ERROR_OK != retval)
3596                         return retval;
3597
3598                 target = target->next;
3599         }
3600
3601         return ERROR_OK;
3602 }
3603
3604 COMMAND_HANDLER(handle_gdb_sync_command)
3605 {
3606         if (CMD_ARGC != 0)
3607                 return ERROR_COMMAND_SYNTAX_ERROR;
3608
3609         if (current_gdb_connection == NULL) {
3610                 command_print(CMD,
3611                         "gdb_sync command can only be run from within gdb using \"monitor gdb_sync\"");
3612                 return ERROR_FAIL;
3613         }
3614
3615         current_gdb_connection->sync = true;
3616
3617         return ERROR_OK;
3618 }
3619
3620 /* daemon configuration command gdb_port */
3621 COMMAND_HANDLER(handle_gdb_port_command)
3622 {
3623         int retval = CALL_COMMAND_HANDLER(server_pipe_command, &gdb_port);
3624         if (ERROR_OK == retval) {
3625                 free(gdb_port_next);
3626                 gdb_port_next = strdup(gdb_port);
3627         }
3628         return retval;
3629 }
3630
3631 COMMAND_HANDLER(handle_gdb_memory_map_command)
3632 {
3633         if (CMD_ARGC != 1)
3634                 return ERROR_COMMAND_SYNTAX_ERROR;
3635
3636         COMMAND_PARSE_ENABLE(CMD_ARGV[0], gdb_use_memory_map);
3637         return ERROR_OK;
3638 }
3639
3640 COMMAND_HANDLER(handle_gdb_flash_program_command)
3641 {
3642         if (CMD_ARGC != 1)
3643                 return ERROR_COMMAND_SYNTAX_ERROR;
3644
3645         COMMAND_PARSE_ENABLE(CMD_ARGV[0], gdb_flash_program);
3646         return ERROR_OK;
3647 }
3648
3649 COMMAND_HANDLER(handle_gdb_report_data_abort_command)
3650 {
3651         if (CMD_ARGC != 1)
3652                 return ERROR_COMMAND_SYNTAX_ERROR;
3653
3654         COMMAND_PARSE_ENABLE(CMD_ARGV[0], gdb_report_data_abort);
3655         return ERROR_OK;
3656 }
3657
3658 COMMAND_HANDLER(handle_gdb_report_register_access_error)
3659 {
3660         if (CMD_ARGC != 1)
3661                 return ERROR_COMMAND_SYNTAX_ERROR;
3662
3663         COMMAND_PARSE_ENABLE(CMD_ARGV[0], gdb_report_register_access_error);
3664         return ERROR_OK;
3665 }
3666
3667 /* gdb_breakpoint_override */
3668 COMMAND_HANDLER(handle_gdb_breakpoint_override_command)
3669 {
3670         if (CMD_ARGC == 0) {
3671                 /* nothing */
3672         } else if (CMD_ARGC == 1) {
3673                 gdb_breakpoint_override = 1;
3674                 if (strcmp(CMD_ARGV[0], "hard") == 0)
3675                         gdb_breakpoint_override_type = BKPT_HARD;
3676                 else if (strcmp(CMD_ARGV[0], "soft") == 0)
3677                         gdb_breakpoint_override_type = BKPT_SOFT;
3678                 else if (strcmp(CMD_ARGV[0], "disable") == 0)
3679                         gdb_breakpoint_override = 0;
3680         } else
3681                 return ERROR_COMMAND_SYNTAX_ERROR;
3682         if (gdb_breakpoint_override)
3683                 LOG_USER("force %s breakpoints",
3684                         (gdb_breakpoint_override_type == BKPT_HARD) ? "hard" : "soft");
3685         else
3686                 LOG_USER("breakpoint type is not overridden");
3687
3688         return ERROR_OK;
3689 }
3690
3691 COMMAND_HANDLER(handle_gdb_target_description_command)
3692 {
3693         if (CMD_ARGC != 1)
3694                 return ERROR_COMMAND_SYNTAX_ERROR;
3695
3696         COMMAND_PARSE_ENABLE(CMD_ARGV[0], gdb_use_target_description);
3697         return ERROR_OK;
3698 }
3699
3700 COMMAND_HANDLER(handle_gdb_save_tdesc_command)
3701 {
3702         char *tdesc;
3703         uint32_t tdesc_length;
3704         struct target *target = get_current_target(CMD_CTX);
3705
3706         int retval = gdb_generate_target_description(target, &tdesc);
3707         if (retval != ERROR_OK) {
3708                 LOG_ERROR("Unable to Generate Target Description");
3709                 return ERROR_FAIL;
3710         }
3711
3712         tdesc_length = strlen(tdesc);
3713
3714         struct fileio *fileio;
3715         size_t size_written;
3716
3717         char *tdesc_filename = alloc_printf("%s.xml", target_type_name(target));
3718         if (tdesc_filename == NULL) {
3719                 retval = ERROR_FAIL;
3720                 goto out;
3721         }
3722
3723         retval = fileio_open(&fileio, tdesc_filename, FILEIO_WRITE, FILEIO_TEXT);
3724
3725         if (retval != ERROR_OK) {
3726                 LOG_ERROR("Can't open %s for writing", tdesc_filename);
3727                 goto out;
3728         }
3729
3730         retval = fileio_write(fileio, tdesc_length, tdesc, &size_written);
3731
3732         fileio_close(fileio);
3733
3734         if (retval != ERROR_OK)
3735                 LOG_ERROR("Error while writing the tdesc file");
3736
3737 out:
3738         free(tdesc_filename);
3739         free(tdesc);
3740
3741         return retval;
3742 }
3743
3744 static const struct command_registration gdb_command_handlers[] = {
3745         {
3746                 .name = "gdb_sync",
3747                 .handler = handle_gdb_sync_command,
3748                 .mode = COMMAND_ANY,
3749                 .help = "next stepi will return immediately allowing "
3750                         "GDB to fetch register state without affecting "
3751                         "target state",
3752                 .usage = ""
3753         },
3754         {
3755                 .name = "gdb_port",
3756                 .handler = handle_gdb_port_command,
3757                 .mode = COMMAND_CONFIG,
3758                 .help = "Normally gdb listens to a TCP/IP port. Each subsequent GDB "
3759                         "server listens for the next port number after the "
3760                         "base port number specified. "
3761                         "No arguments reports GDB port. \"pipe\" means listen to stdin "
3762                         "output to stdout, an integer is base port number, \"disabled\" disables "
3763                         "port. Any other string is are interpreted as named pipe to listen to. "
3764                         "Output pipe is the same name as input pipe, but with 'o' appended.",
3765                 .usage = "[port_num]",
3766         },
3767         {
3768                 .name = "gdb_memory_map",
3769                 .handler = handle_gdb_memory_map_command,
3770                 .mode = COMMAND_CONFIG,
3771                 .help = "enable or disable memory map",
3772                 .usage = "('enable'|'disable')"
3773         },
3774         {
3775                 .name = "gdb_flash_program",
3776                 .handler = handle_gdb_flash_program_command,
3777                 .mode = COMMAND_CONFIG,
3778                 .help = "enable or disable flash program",
3779                 .usage = "('enable'|'disable')"
3780         },
3781         {
3782                 .name = "gdb_report_data_abort",
3783                 .handler = handle_gdb_report_data_abort_command,
3784                 .mode = COMMAND_CONFIG,
3785                 .help = "enable or disable reporting data aborts",
3786                 .usage = "('enable'|'disable')"
3787         },
3788         {
3789                 .name = "gdb_report_register_access_error",
3790                 .handler = handle_gdb_report_register_access_error,
3791                 .mode = COMMAND_CONFIG,
3792                 .help = "enable or disable reporting register access errors",
3793                 .usage = "('enable'|'disable')"
3794         },
3795         {
3796                 .name = "gdb_breakpoint_override",
3797                 .handler = handle_gdb_breakpoint_override_command,
3798                 .mode = COMMAND_ANY,
3799                 .help = "Display or specify type of breakpoint "
3800                         "to be used by gdb 'break' commands.",
3801                 .usage = "('hard'|'soft'|'disable')"
3802         },
3803         {
3804                 .name = "gdb_target_description",
3805                 .handler = handle_gdb_target_description_command,
3806                 .mode = COMMAND_CONFIG,
3807                 .help = "enable or disable target description",
3808                 .usage = "('enable'|'disable')"
3809         },
3810         {
3811                 .name = "gdb_save_tdesc",
3812                 .handler = handle_gdb_save_tdesc_command,
3813                 .mode = COMMAND_EXEC,
3814                 .help = "Save the target description file",
3815                 .usage = "",
3816         },
3817         COMMAND_REGISTRATION_DONE
3818 };
3819
3820 int gdb_register_commands(struct command_context *cmd_ctx)
3821 {
3822         gdb_port = strdup("3333");
3823         gdb_port_next = strdup("3333");
3824         return register_commands(cmd_ctx, NULL, gdb_command_handlers);
3825 }
3826
3827 void gdb_service_free(void)
3828 {
3829         free(gdb_port);
3830         free(gdb_port_next);
3831 }