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