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