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