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