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