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