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