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