]> git.sur5r.net Git - openocd/blob - src/server/gdb_server.c
rtos: facilitate RTOS SMP handling
[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         /* clean previous rtos session if supported*/
965         if ((target->rtos) && (target->rtos->type->clean))
966                 target->rtos->type->clean(target);
967
968         /* remove the initial ACK from the incoming buffer */
969         retval = gdb_get_char(connection, &initial_ack);
970         if (retval != ERROR_OK)
971                 return retval;
972
973         /* FIX!!!??? would we actually ever receive a + here???
974          * Not observed.
975          */
976         if (initial_ack != '+')
977                 gdb_putback_char(connection, initial_ack);
978         target_call_event_callbacks(target, TARGET_EVENT_GDB_ATTACH);
979
980         if (gdb_use_memory_map) {
981                 /* Connect must fail if the memory map can't be set up correctly.
982                  *
983                  * This will cause an auto_probe to be invoked, which is either
984                  * a no-op or it will fail when the target isn't ready(e.g. not halted).
985                  */
986                 int i;
987                 for (i = 0; i < flash_get_bank_count(); i++) {
988                         struct flash_bank *p;
989                         p = get_flash_bank_by_num_noprobe(i);
990                         if (p->target != target)
991                                 continue;
992                         retval = get_flash_bank_by_num(i, &p);
993                         if (retval != ERROR_OK) {
994                                 LOG_ERROR("Connect failed. Consider setting up a gdb-attach event for the target " \
995                                                 "to prepare target for GDB connect, or use 'gdb_memory_map disable'.");
996                                 return retval;
997                         }
998                 }
999         }
1000
1001         gdb_actual_connections++;
1002         log_printf_lf(all_targets->next != NULL ? LOG_LVL_INFO : LOG_LVL_DEBUG,
1003                         __FILE__, __LINE__, __func__,
1004                         "New GDB Connection: %d, Target %s, state: %s",
1005                         gdb_actual_connections,
1006                         target_name(target),
1007                         target_state_name(target));
1008
1009         /* DANGER! If we fail subsequently, we must remove this handler,
1010          * otherwise we occasionally see crashes as the timer can invoke the
1011          * callback fn.
1012          *
1013          * register callback to be informed about target events */
1014         target_register_event_callback(gdb_target_callback_event_handler, connection);
1015
1016         return ERROR_OK;
1017 }
1018
1019 static int gdb_connection_closed(struct connection *connection)
1020 {
1021         struct target *target;
1022         struct gdb_connection *gdb_connection = connection->priv;
1023
1024         target = get_target_from_connection(connection);
1025
1026         /* we're done forwarding messages. Tear down callback before
1027          * cleaning up connection.
1028          */
1029         log_remove_callback(gdb_log_callback, connection);
1030
1031         gdb_actual_connections--;
1032         LOG_DEBUG("GDB Close, Target: %s, state: %s, gdb_actual_connections=%d",
1033                 target_name(target),
1034                 target_state_name(target),
1035                 gdb_actual_connections);
1036
1037         /* see if an image built with vFlash commands is left */
1038         if (gdb_connection->vflash_image) {
1039                 image_close(gdb_connection->vflash_image);
1040                 free(gdb_connection->vflash_image);
1041                 gdb_connection->vflash_image = NULL;
1042         }
1043
1044         /* if this connection registered a debug-message receiver delete it */
1045         delete_debug_msg_receiver(connection->cmd_ctx, target);
1046
1047         if (connection->priv) {
1048                 free(connection->priv);
1049                 connection->priv = NULL;
1050         } else
1051                 LOG_ERROR("BUG: connection->priv == NULL");
1052
1053         target_unregister_event_callback(gdb_target_callback_event_handler, connection);
1054
1055         target_call_event_callbacks(target, TARGET_EVENT_GDB_END);
1056
1057         target_call_event_callbacks(target, TARGET_EVENT_GDB_DETACH);
1058
1059         return ERROR_OK;
1060 }
1061
1062 static void gdb_send_error(struct connection *connection, uint8_t the_error)
1063 {
1064         char err[4];
1065         snprintf(err, 4, "E%2.2X", the_error);
1066         gdb_put_packet(connection, err, 3);
1067 }
1068
1069 static int gdb_last_signal_packet(struct connection *connection,
1070                 char const *packet, int packet_size)
1071 {
1072         struct target *target = get_target_from_connection(connection);
1073         struct gdb_connection *gdb_con = connection->priv;
1074         char sig_reply[4];
1075         int signal_var;
1076
1077         if (!gdb_con->attached) {
1078                 /* if we are here we have received a kill packet
1079                  * reply W stop reply otherwise gdb gets very unhappy */
1080                 gdb_put_packet(connection, "W00", 3);
1081                 return ERROR_OK;
1082         }
1083
1084         signal_var = gdb_last_signal(target);
1085
1086         snprintf(sig_reply, 4, "S%2.2x", signal_var);
1087         gdb_put_packet(connection, sig_reply, 3);
1088
1089         return ERROR_OK;
1090 }
1091
1092 static inline int gdb_reg_pos(struct target *target, int pos, int len)
1093 {
1094         if (target->endianness == TARGET_LITTLE_ENDIAN)
1095                 return pos;
1096         else
1097                 return len - 1 - pos;
1098 }
1099
1100 /* Convert register to string of bytes. NB! The # of bits in the
1101  * register might be non-divisible by 8(a byte), in which
1102  * case an entire byte is shown.
1103  *
1104  * NB! the format on the wire is the target endianness
1105  *
1106  * The format of reg->value is little endian
1107  *
1108  */
1109 static void gdb_str_to_target(struct target *target,
1110                 char *tstr, struct reg *reg)
1111 {
1112         int i;
1113
1114         uint8_t *buf;
1115         int buf_len;
1116         buf = reg->value;
1117         buf_len = DIV_ROUND_UP(reg->size, 8);
1118
1119         for (i = 0; i < buf_len; i++) {
1120                 int j = gdb_reg_pos(target, i, buf_len);
1121                 tstr += sprintf(tstr, "%02x", buf[j]);
1122         }
1123 }
1124
1125 /* copy over in register buffer */
1126 static void gdb_target_to_reg(struct target *target,
1127                 char const *tstr, int str_len, uint8_t *bin)
1128 {
1129         if (str_len % 2) {
1130                 LOG_ERROR("BUG: gdb value with uneven number of characters encountered");
1131                 exit(-1);
1132         }
1133
1134         int i;
1135         for (i = 0; i < str_len; i += 2) {
1136                 unsigned t;
1137                 if (sscanf(tstr + i, "%02x", &t) != 1) {
1138                         LOG_ERROR("BUG: unable to convert register value");
1139                         exit(-1);
1140                 }
1141
1142                 int j = gdb_reg_pos(target, i/2, str_len/2);
1143                 bin[j] = t;
1144         }
1145 }
1146
1147 static int gdb_get_registers_packet(struct connection *connection,
1148                 char const *packet, int packet_size)
1149 {
1150         struct target *target = get_target_from_connection(connection);
1151         struct reg **reg_list;
1152         int reg_list_size;
1153         int retval;
1154         int reg_packet_size = 0;
1155         char *reg_packet;
1156         char *reg_packet_p;
1157         int i;
1158
1159 #ifdef _DEBUG_GDB_IO_
1160         LOG_DEBUG("-");
1161 #endif
1162
1163         if ((target->rtos != NULL) && (ERROR_OK == rtos_get_gdb_reg_list(connection)))
1164                 return ERROR_OK;
1165
1166         retval = target_get_gdb_reg_list(target, &reg_list, &reg_list_size,
1167                         REG_CLASS_GENERAL);
1168         if (retval != ERROR_OK)
1169                 return gdb_error(connection, retval);
1170
1171         for (i = 0; i < reg_list_size; i++)
1172                 reg_packet_size += DIV_ROUND_UP(reg_list[i]->size, 8) * 2;
1173
1174         assert(reg_packet_size > 0);
1175
1176         reg_packet = malloc(reg_packet_size + 1); /* plus one for string termination null */
1177         if (reg_packet == NULL)
1178                 return ERROR_FAIL;
1179
1180         reg_packet_p = reg_packet;
1181
1182         for (i = 0; i < reg_list_size; i++) {
1183                 if (!reg_list[i]->valid)
1184                         reg_list[i]->type->get(reg_list[i]);
1185                 gdb_str_to_target(target, reg_packet_p, reg_list[i]);
1186                 reg_packet_p += DIV_ROUND_UP(reg_list[i]->size, 8) * 2;
1187         }
1188
1189 #ifdef _DEBUG_GDB_IO_
1190         {
1191                 char *reg_packet_p_debug;
1192                 reg_packet_p_debug = strndup(reg_packet, reg_packet_size);
1193                 LOG_DEBUG("reg_packet: %s", reg_packet_p_debug);
1194                 free(reg_packet_p_debug);
1195         }
1196 #endif
1197
1198         gdb_put_packet(connection, reg_packet, reg_packet_size);
1199         free(reg_packet);
1200
1201         free(reg_list);
1202
1203         return ERROR_OK;
1204 }
1205
1206 static int gdb_set_registers_packet(struct connection *connection,
1207                 char const *packet, int packet_size)
1208 {
1209         struct target *target = get_target_from_connection(connection);
1210         int i;
1211         struct reg **reg_list;
1212         int reg_list_size;
1213         int retval;
1214         char const *packet_p;
1215
1216 #ifdef _DEBUG_GDB_IO_
1217         LOG_DEBUG("-");
1218 #endif
1219
1220         /* skip command character */
1221         packet++;
1222         packet_size--;
1223
1224         if (packet_size % 2) {
1225                 LOG_WARNING("GDB set_registers packet with uneven characters received, dropping connection");
1226                 return ERROR_SERVER_REMOTE_CLOSED;
1227         }
1228
1229         retval = target_get_gdb_reg_list(target, &reg_list, &reg_list_size,
1230                         REG_CLASS_GENERAL);
1231         if (retval != ERROR_OK)
1232                 return gdb_error(connection, retval);
1233
1234         packet_p = packet;
1235         for (i = 0; i < reg_list_size; i++) {
1236                 uint8_t *bin_buf;
1237                 int chars = (DIV_ROUND_UP(reg_list[i]->size, 8) * 2);
1238
1239                 if (packet_p + chars > packet + packet_size)
1240                         LOG_ERROR("BUG: register packet is too small for registers");
1241
1242                 bin_buf = malloc(DIV_ROUND_UP(reg_list[i]->size, 8));
1243                 gdb_target_to_reg(target, packet_p, chars, bin_buf);
1244
1245                 reg_list[i]->type->set(reg_list[i], bin_buf);
1246
1247                 /* advance packet pointer */
1248                 packet_p += chars;
1249
1250                 free(bin_buf);
1251         }
1252
1253         /* free struct reg *reg_list[] array allocated by get_gdb_reg_list */
1254         free(reg_list);
1255
1256         gdb_put_packet(connection, "OK", 2);
1257
1258         return ERROR_OK;
1259 }
1260
1261 static int gdb_get_register_packet(struct connection *connection,
1262         char const *packet, int packet_size)
1263 {
1264         struct target *target = get_target_from_connection(connection);
1265         char *reg_packet;
1266         int reg_num = strtoul(packet + 1, NULL, 16);
1267         struct reg **reg_list;
1268         int reg_list_size;
1269         int retval;
1270
1271 #ifdef _DEBUG_GDB_IO_
1272         LOG_DEBUG("-");
1273 #endif
1274
1275         retval = target_get_gdb_reg_list(target, &reg_list, &reg_list_size,
1276                         REG_CLASS_ALL);
1277         if (retval != ERROR_OK)
1278                 return gdb_error(connection, retval);
1279
1280         if (reg_list_size <= reg_num) {
1281                 LOG_ERROR("gdb requested a non-existing register");
1282                 return ERROR_SERVER_REMOTE_CLOSED;
1283         }
1284
1285         if (!reg_list[reg_num]->valid)
1286                 reg_list[reg_num]->type->get(reg_list[reg_num]);
1287
1288         reg_packet = malloc(DIV_ROUND_UP(reg_list[reg_num]->size, 8) * 2 + 1); /* plus one for string termination null */
1289
1290         gdb_str_to_target(target, reg_packet, reg_list[reg_num]);
1291
1292         gdb_put_packet(connection, reg_packet, DIV_ROUND_UP(reg_list[reg_num]->size, 8) * 2);
1293
1294         free(reg_list);
1295         free(reg_packet);
1296
1297         return ERROR_OK;
1298 }
1299
1300 static int gdb_set_register_packet(struct connection *connection,
1301         char const *packet, int packet_size)
1302 {
1303         struct target *target = get_target_from_connection(connection);
1304         char *separator;
1305         uint8_t *bin_buf;
1306         int reg_num = strtoul(packet + 1, &separator, 16);
1307         struct reg **reg_list;
1308         int reg_list_size;
1309         int retval;
1310
1311         LOG_DEBUG("-");
1312
1313         retval = target_get_gdb_reg_list(target, &reg_list, &reg_list_size,
1314                         REG_CLASS_ALL);
1315         if (retval != ERROR_OK)
1316                 return gdb_error(connection, retval);
1317
1318         if (reg_list_size <= reg_num) {
1319                 LOG_ERROR("gdb requested a non-existing register");
1320                 return ERROR_SERVER_REMOTE_CLOSED;
1321         }
1322
1323         if (*separator != '=') {
1324                 LOG_ERROR("GDB 'set register packet', but no '=' following the register number");
1325                 return ERROR_SERVER_REMOTE_CLOSED;
1326         }
1327
1328         /* convert from GDB-string (target-endian) to hex-string (big-endian) */
1329         bin_buf = malloc(DIV_ROUND_UP(reg_list[reg_num]->size, 8));
1330         int chars = (DIV_ROUND_UP(reg_list[reg_num]->size, 8) * 2);
1331
1332         if ((unsigned int)chars != strlen(separator + 1)) {
1333                 LOG_ERROR("gdb sent a packet with wrong register size");
1334                 free(bin_buf);
1335                 return ERROR_SERVER_REMOTE_CLOSED;
1336         }
1337
1338         gdb_target_to_reg(target, separator + 1, chars, bin_buf);
1339
1340         reg_list[reg_num]->type->set(reg_list[reg_num], bin_buf);
1341
1342         gdb_put_packet(connection, "OK", 2);
1343
1344         free(bin_buf);
1345         free(reg_list);
1346
1347         return ERROR_OK;
1348 }
1349
1350 /* No attempt is made to translate the "retval" to
1351  * GDB speak. This has to be done at the calling
1352  * site as no mapping really exists.
1353  */
1354 static int gdb_error(struct connection *connection, int retval)
1355 {
1356         LOG_DEBUG("Reporting %i to GDB as generic error", retval);
1357         gdb_send_error(connection, EFAULT);
1358         return ERROR_OK;
1359 }
1360
1361 /* We don't have to worry about the default 2 second timeout for GDB packets,
1362  * because GDB breaks up large memory reads into smaller reads.
1363  *
1364  * 8191 bytes by the looks of it. Why 8191 bytes instead of 8192?????
1365  */
1366 static int gdb_read_memory_packet(struct connection *connection,
1367                 char const *packet, int packet_size)
1368 {
1369         struct target *target = get_target_from_connection(connection);
1370         char *separator;
1371         uint64_t addr = 0;
1372         uint32_t len = 0;
1373
1374         uint8_t *buffer;
1375         char *hex_buffer;
1376
1377         int retval = ERROR_OK;
1378
1379         /* skip command character */
1380         packet++;
1381
1382         addr = strtoull(packet, &separator, 16);
1383
1384         if (*separator != ',') {
1385                 LOG_ERROR("incomplete read memory packet received, dropping connection");
1386                 return ERROR_SERVER_REMOTE_CLOSED;
1387         }
1388
1389         len = strtoul(separator + 1, NULL, 16);
1390
1391         if (!len) {
1392                 LOG_WARNING("invalid read memory packet received (len == 0)");
1393                 gdb_put_packet(connection, NULL, 0);
1394                 return ERROR_OK;
1395         }
1396
1397         buffer = malloc(len);
1398
1399         LOG_DEBUG("addr: 0x%16.16" PRIx64 ", len: 0x%8.8" PRIx32 "", addr, len);
1400
1401         retval = target_read_buffer(target, addr, len, buffer);
1402
1403         if ((retval != ERROR_OK) && !gdb_report_data_abort) {
1404                 /* TODO : Here we have to lie and send back all zero's lest stack traces won't work.
1405                  * At some point this might be fixed in GDB, in which case this code can be removed.
1406                  *
1407                  * OpenOCD developers are acutely aware of this problem, but there is nothing
1408                  * gained by involving the user in this problem that hopefully will get resolved
1409                  * eventually
1410                  *
1411                  * http://sourceware.org/cgi-bin/gnatsweb.pl? \
1412                  * cmd = view%20audit-trail&database = gdb&pr = 2395
1413                  *
1414                  * For now, the default is to fix up things to make current GDB versions work.
1415                  * This can be overwritten using the gdb_report_data_abort <'enable'|'disable'> command.
1416                  */
1417                 memset(buffer, 0, len);
1418                 retval = ERROR_OK;
1419         }
1420
1421         if (retval == ERROR_OK) {
1422                 hex_buffer = malloc(len * 2 + 1);
1423
1424                 size_t pkt_len = hexify(hex_buffer, buffer, len, len * 2 + 1);
1425
1426                 gdb_put_packet(connection, hex_buffer, pkt_len);
1427
1428                 free(hex_buffer);
1429         } else
1430                 retval = gdb_error(connection, retval);
1431
1432         free(buffer);
1433
1434         return retval;
1435 }
1436
1437 static int gdb_write_memory_packet(struct connection *connection,
1438                 char const *packet, int packet_size)
1439 {
1440         struct target *target = get_target_from_connection(connection);
1441         char *separator;
1442         uint64_t addr = 0;
1443         uint32_t len = 0;
1444
1445         uint8_t *buffer;
1446         int retval;
1447
1448         /* skip command character */
1449         packet++;
1450
1451         addr = strtoull(packet, &separator, 16);
1452
1453         if (*separator != ',') {
1454                 LOG_ERROR("incomplete write memory packet received, dropping connection");
1455                 return ERROR_SERVER_REMOTE_CLOSED;
1456         }
1457
1458         len = strtoul(separator + 1, &separator, 16);
1459
1460         if (*(separator++) != ':') {
1461                 LOG_ERROR("incomplete write memory packet received, dropping connection");
1462                 return ERROR_SERVER_REMOTE_CLOSED;
1463         }
1464
1465         buffer = malloc(len);
1466
1467         LOG_DEBUG("addr: 0x%" PRIx64 ", len: 0x%8.8" PRIx32 "", addr, len);
1468
1469         if (unhexify(buffer, separator, len) != len)
1470                 LOG_ERROR("unable to decode memory packet");
1471
1472         retval = target_write_buffer(target, addr, len, buffer);
1473
1474         if (retval == ERROR_OK)
1475                 gdb_put_packet(connection, "OK", 2);
1476         else
1477                 retval = gdb_error(connection, retval);
1478
1479         free(buffer);
1480
1481         return retval;
1482 }
1483
1484 static int gdb_write_memory_binary_packet(struct connection *connection,
1485                 char const *packet, int packet_size)
1486 {
1487         struct target *target = get_target_from_connection(connection);
1488         char *separator;
1489         uint64_t addr = 0;
1490         uint32_t len = 0;
1491
1492         int retval = ERROR_OK;
1493         /* Packets larger than fast_limit bytes will be acknowledged instantly on
1494          * the assumption that we're in a download and it's important to go as fast
1495          * as possible. */
1496         uint32_t fast_limit = 8;
1497
1498         /* skip command character */
1499         packet++;
1500
1501         addr = strtoull(packet, &separator, 16);
1502
1503         if (*separator != ',') {
1504                 LOG_ERROR("incomplete write memory binary packet received, dropping connection");
1505                 return ERROR_SERVER_REMOTE_CLOSED;
1506         }
1507
1508         len = strtoul(separator + 1, &separator, 16);
1509
1510         if (*(separator++) != ':') {
1511                 LOG_ERROR("incomplete write memory binary packet received, dropping connection");
1512                 return ERROR_SERVER_REMOTE_CLOSED;
1513         }
1514
1515         struct gdb_connection *gdb_connection = connection->priv;
1516
1517         if (gdb_connection->mem_write_error)
1518                 retval = ERROR_FAIL;
1519
1520         if (retval == ERROR_OK) {
1521                 if (len >= fast_limit) {
1522                         /* By replying the packet *immediately* GDB will send us a new packet
1523                          * while we write the last one to the target.
1524                          * We only do this for larger writes, so that users who do something like:
1525                          * p *((int*)0xdeadbeef)=8675309
1526                          * will get immediate feedback that that write failed.
1527                          */
1528                         gdb_put_packet(connection, "OK", 2);
1529                 }
1530         } else {
1531                 retval = gdb_error(connection, retval);
1532                 /* now that we have reported the memory write error, we can clear the condition */
1533                 gdb_connection->mem_write_error = false;
1534                 if (retval != ERROR_OK)
1535                         return retval;
1536         }
1537
1538         if (len) {
1539                 LOG_DEBUG("addr: 0x%" PRIx64 ", len: 0x%8.8" PRIx32 "", addr, len);
1540
1541                 retval = target_write_buffer(target, addr, len, (uint8_t *)separator);
1542                 if (retval != ERROR_OK)
1543                         gdb_connection->mem_write_error = true;
1544         }
1545
1546         if (len < fast_limit) {
1547                 if (retval != ERROR_OK) {
1548                         gdb_error(connection, retval);
1549                         gdb_connection->mem_write_error = false;
1550                 } else {
1551                         gdb_put_packet(connection, "OK", 2);
1552                 }
1553         }
1554
1555         return ERROR_OK;
1556 }
1557
1558 static int gdb_step_continue_packet(struct connection *connection,
1559                 char const *packet, int packet_size)
1560 {
1561         struct target *target = get_target_from_connection(connection);
1562         int current = 0;
1563         uint64_t address = 0x0;
1564         int retval = ERROR_OK;
1565
1566         LOG_DEBUG("-");
1567
1568         if (packet_size > 1)
1569                 address = strtoull(packet + 1, NULL, 16);
1570         else
1571                 current = 1;
1572
1573         gdb_running_type = packet[0];
1574         if (packet[0] == 'c') {
1575                 LOG_DEBUG("continue");
1576                 /* resume at current address, don't handle breakpoints, not debugging */
1577                 retval = target_resume(target, current, address, 0, 0);
1578         } else if (packet[0] == 's') {
1579                 LOG_DEBUG("step");
1580                 /* step at current or address, don't handle breakpoints */
1581                 retval = target_step(target, current, address, 0);
1582         }
1583         return retval;
1584 }
1585
1586 static int gdb_breakpoint_watchpoint_packet(struct connection *connection,
1587                 char const *packet, int packet_size)
1588 {
1589         struct target *target = get_target_from_connection(connection);
1590         int type;
1591         enum breakpoint_type bp_type = BKPT_SOFT /* dummy init to avoid warning */;
1592         enum watchpoint_rw wp_type = WPT_READ /* dummy init to avoid warning */;
1593         uint64_t address;
1594         uint32_t size;
1595         char *separator;
1596         int retval;
1597
1598         LOG_DEBUG("-");
1599
1600         type = strtoul(packet + 1, &separator, 16);
1601
1602         if (type == 0)  /* memory breakpoint */
1603                 bp_type = BKPT_SOFT;
1604         else if (type == 1)     /* hardware breakpoint */
1605                 bp_type = BKPT_HARD;
1606         else if (type == 2)     /* write watchpoint */
1607                 wp_type = WPT_WRITE;
1608         else if (type == 3)     /* read watchpoint */
1609                 wp_type = WPT_READ;
1610         else if (type == 4)     /* access watchpoint */
1611                 wp_type = WPT_ACCESS;
1612         else {
1613                 LOG_ERROR("invalid gdb watch/breakpoint type(%d), dropping connection", type);
1614                 return ERROR_SERVER_REMOTE_CLOSED;
1615         }
1616
1617         if (gdb_breakpoint_override && ((bp_type == BKPT_SOFT) || (bp_type == BKPT_HARD)))
1618                 bp_type = gdb_breakpoint_override_type;
1619
1620         if (*separator != ',') {
1621                 LOG_ERROR("incomplete breakpoint/watchpoint packet received, dropping connection");
1622                 return ERROR_SERVER_REMOTE_CLOSED;
1623         }
1624
1625         address = strtoull(separator + 1, &separator, 16);
1626
1627         if (*separator != ',') {
1628                 LOG_ERROR("incomplete breakpoint/watchpoint packet received, dropping connection");
1629                 return ERROR_SERVER_REMOTE_CLOSED;
1630         }
1631
1632         size = strtoul(separator + 1, &separator, 16);
1633
1634         switch (type) {
1635                 case 0:
1636                 case 1:
1637                         if (packet[0] == 'Z') {
1638                                 retval = breakpoint_add(target, address, size, bp_type);
1639                                 if (retval != ERROR_OK) {
1640                                         retval = gdb_error(connection, retval);
1641                                         if (retval != ERROR_OK)
1642                                                 return retval;
1643                                 } else
1644                                         gdb_put_packet(connection, "OK", 2);
1645                         } else {
1646                                 breakpoint_remove(target, address);
1647                                 gdb_put_packet(connection, "OK", 2);
1648                         }
1649                         break;
1650                 case 2:
1651                 case 3:
1652                 case 4:
1653                 {
1654                         if (packet[0] == 'Z') {
1655                                 retval = watchpoint_add(target, address, size, wp_type, 0, 0xffffffffu);
1656                                 if (retval != ERROR_OK) {
1657                                         retval = gdb_error(connection, retval);
1658                                         if (retval != ERROR_OK)
1659                                                 return retval;
1660                                 } else
1661                                         gdb_put_packet(connection, "OK", 2);
1662                         } else {
1663                                 watchpoint_remove(target, address);
1664                                 gdb_put_packet(connection, "OK", 2);
1665                         }
1666                         break;
1667                 }
1668                 default:
1669                         break;
1670         }
1671
1672         return ERROR_OK;
1673 }
1674
1675 /* print out a string and allocate more space as needed,
1676  * mainly used for XML at this point
1677  */
1678 static void xml_printf(int *retval, char **xml, int *pos, int *size,
1679                 const char *fmt, ...)
1680 {
1681         if (*retval != ERROR_OK)
1682                 return;
1683         int first = 1;
1684
1685         for (;; ) {
1686                 if ((*xml == NULL) || (!first)) {
1687                         /* start by 0 to exercise all the code paths.
1688                          * Need minimum 2 bytes to fit 1 char and 0 terminator. */
1689
1690                         *size = *size * 2 + 2;
1691                         char *t = *xml;
1692                         *xml = realloc(*xml, *size);
1693                         if (*xml == NULL) {
1694                                 if (t)
1695                                         free(t);
1696                                 *retval = ERROR_SERVER_REMOTE_CLOSED;
1697                                 return;
1698                         }
1699                 }
1700
1701                 va_list ap;
1702                 int ret;
1703                 va_start(ap, fmt);
1704                 ret = vsnprintf(*xml + *pos, *size - *pos, fmt, ap);
1705                 va_end(ap);
1706                 if ((ret > 0) && ((ret + 1) < *size - *pos)) {
1707                         *pos += ret;
1708                         return;
1709                 }
1710                 /* there was just enough or not enough space, allocate more. */
1711                 first = 0;
1712         }
1713 }
1714
1715 static int decode_xfer_read(char const *buf, char **annex, int *ofs, unsigned int *len)
1716 {
1717         /* Locate the annex. */
1718         const char *annex_end = strchr(buf, ':');
1719         if (annex_end == NULL)
1720                 return ERROR_FAIL;
1721
1722         /* After the read marker and annex, qXfer looks like a
1723          * traditional 'm' packet. */
1724         char *separator;
1725         *ofs = strtoul(annex_end + 1, &separator, 16);
1726
1727         if (*separator != ',')
1728                 return ERROR_FAIL;
1729
1730         *len = strtoul(separator + 1, NULL, 16);
1731
1732         /* Extract the annex if needed */
1733         if (annex != NULL) {
1734                 *annex = strndup(buf, annex_end - buf);
1735                 if (*annex == NULL)
1736                         return ERROR_FAIL;
1737         }
1738
1739         return ERROR_OK;
1740 }
1741
1742 static int compare_bank(const void *a, const void *b)
1743 {
1744         struct flash_bank *b1, *b2;
1745         b1 = *((struct flash_bank **)a);
1746         b2 = *((struct flash_bank **)b);
1747
1748         if (b1->base == b2->base)
1749                 return 0;
1750         else if (b1->base > b2->base)
1751                 return 1;
1752         else
1753                 return -1;
1754 }
1755
1756 static int gdb_memory_map(struct connection *connection,
1757                 char const *packet, int packet_size)
1758 {
1759         /* We get away with only specifying flash here. Regions that are not
1760          * specified are treated as if we provided no memory map(if not we
1761          * could detect the holes and mark them as RAM).
1762          * Normally we only execute this code once, but no big deal if we
1763          * have to regenerate it a couple of times.
1764          */
1765
1766         struct target *target = get_target_from_connection(connection);
1767         struct flash_bank *p;
1768         char *xml = NULL;
1769         int size = 0;
1770         int pos = 0;
1771         int retval = ERROR_OK;
1772         struct flash_bank **banks;
1773         int offset;
1774         int length;
1775         char *separator;
1776         uint32_t ram_start = 0;
1777         int i;
1778         int target_flash_banks = 0;
1779
1780         /* skip command character */
1781         packet += 23;
1782
1783         offset = strtoul(packet, &separator, 16);
1784         length = strtoul(separator + 1, &separator, 16);
1785
1786         xml_printf(&retval, &xml, &pos, &size, "<memory-map>\n");
1787
1788         /* Sort banks in ascending order.  We need to report non-flash
1789          * memory as ram (or rather read/write) by default for GDB, since
1790          * it has no concept of non-cacheable read/write memory (i/o etc).
1791          *
1792          * FIXME Most non-flash addresses are *NOT* RAM!  Don't lie.
1793          * Current versions of GDB assume unlisted addresses are RAM...
1794          */
1795         banks = malloc(sizeof(struct flash_bank *)*flash_get_bank_count());
1796
1797         for (i = 0; i < flash_get_bank_count(); i++) {
1798                 p = get_flash_bank_by_num_noprobe(i);
1799                 if (p->target != target)
1800                         continue;
1801                 retval = get_flash_bank_by_num(i, &p);
1802                 if (retval != ERROR_OK) {
1803                         free(banks);
1804                         gdb_error(connection, retval);
1805                         return retval;
1806                 }
1807                 banks[target_flash_banks++] = p;
1808         }
1809
1810         qsort(banks, target_flash_banks, sizeof(struct flash_bank *),
1811                 compare_bank);
1812
1813         for (i = 0; i < target_flash_banks; i++) {
1814                 int j;
1815                 unsigned sector_size = 0;
1816                 uint32_t start;
1817
1818                 p = banks[i];
1819                 start = p->base;
1820
1821                 if (ram_start < p->base)
1822                         xml_printf(&retval, &xml, &pos, &size,
1823                                 "<memory type=\"ram\" start=\"0x%x\" "
1824                                 "length=\"0x%x\"/>\n",
1825                                 ram_start, p->base - ram_start);
1826
1827                 /* Report adjacent groups of same-size sectors.  So for
1828                  * example top boot CFI flash will list an initial region
1829                  * with several large sectors (maybe 128KB) and several
1830                  * smaller ones at the end (maybe 32KB).  STR7 will have
1831                  * regions with 8KB, 32KB, and 64KB sectors; etc.
1832                  */
1833                 for (j = 0; j < p->num_sectors; j++) {
1834                         unsigned group_len;
1835
1836                         /* Maybe start a new group of sectors. */
1837                         if (sector_size == 0) {
1838                                 start = p->base + p->sectors[j].offset;
1839                                 xml_printf(&retval, &xml, &pos, &size,
1840                                         "<memory type=\"flash\" "
1841                                         "start=\"0x%x\" ",
1842                                         start);
1843                                 sector_size = p->sectors[j].size;
1844                         }
1845
1846                         /* Does this finish a group of sectors?
1847                          * If not, continue an already-started group.
1848                          */
1849                         if (j == p->num_sectors - 1)
1850                                 group_len = (p->base + p->size) - start;
1851                         else if (p->sectors[j + 1].size != sector_size)
1852                                 group_len = p->base + p->sectors[j + 1].offset
1853                                         - start;
1854                         else
1855                                 continue;
1856
1857                         xml_printf(&retval, &xml, &pos, &size,
1858                                 "length=\"0x%x\">\n"
1859                                 "<property name=\"blocksize\">"
1860                                 "0x%x</property>\n"
1861                                 "</memory>\n",
1862                                 group_len,
1863                                 sector_size);
1864                         sector_size = 0;
1865                 }
1866
1867                 ram_start = p->base + p->size;
1868         }
1869
1870         if (ram_start != 0)
1871                 xml_printf(&retval, &xml, &pos, &size,
1872                         "<memory type=\"ram\" start=\"0x%x\" "
1873                         "length=\"0x%x\"/>\n",
1874                         ram_start, 0-ram_start);
1875         /* ELSE a flash chip could be at the very end of the 32 bit address
1876          * space, in which case ram_start will be precisely 0
1877          */
1878
1879         free(banks);
1880         banks = NULL;
1881
1882         xml_printf(&retval, &xml, &pos, &size, "</memory-map>\n");
1883
1884         if (retval != ERROR_OK) {
1885                 gdb_error(connection, retval);
1886                 return retval;
1887         }
1888
1889         if (offset + length > pos)
1890                 length = pos - offset;
1891
1892         char *t = malloc(length + 1);
1893         t[0] = 'l';
1894         memcpy(t + 1, xml + offset, length);
1895         gdb_put_packet(connection, t, length + 1);
1896
1897         free(t);
1898         free(xml);
1899         return ERROR_OK;
1900 }
1901
1902 static const char *gdb_get_reg_type_name(enum reg_type type)
1903 {
1904         switch (type) {
1905                 case REG_TYPE_INT:
1906                         return "int";
1907                 case REG_TYPE_INT8:
1908                         return "int8";
1909                 case REG_TYPE_INT16:
1910                         return "int16";
1911                 case REG_TYPE_INT32:
1912                         return "int32";
1913                 case REG_TYPE_INT64:
1914                         return "int64";
1915                 case REG_TYPE_INT128:
1916                         return "int128";
1917                 case REG_TYPE_UINT8:
1918                         return "uint8";
1919                 case REG_TYPE_UINT16:
1920                         return "uint16";
1921                 case REG_TYPE_UINT32:
1922                         return "uint32";
1923                 case REG_TYPE_UINT64:
1924                         return "uint64";
1925                 case REG_TYPE_UINT128:
1926                         return "uint128";
1927                 case REG_TYPE_CODE_PTR:
1928                         return "code_ptr";
1929                 case REG_TYPE_DATA_PTR:
1930                         return "data_ptr";
1931                 case REG_TYPE_FLOAT:
1932                         return "float";
1933                 case REG_TYPE_IEEE_SINGLE:
1934                         return "ieee_single";
1935                 case REG_TYPE_IEEE_DOUBLE:
1936                         return "ieee_double";
1937                 case REG_TYPE_ARCH_DEFINED:
1938                         return "int"; /* return arbitrary string to avoid compile warning. */
1939         }
1940
1941         return "int"; /* "int" as default value */
1942 }
1943
1944 static int gdb_generate_reg_type_description(struct target *target,
1945                 char **tdesc, int *pos, int *size, struct reg_data_type *type)
1946 {
1947         int retval = ERROR_OK;
1948
1949         if (type->type_class == REG_TYPE_CLASS_VECTOR) {
1950                 /* <vector id="id" type="type" count="count"/> */
1951                 xml_printf(&retval, tdesc, pos, size,
1952                                 "<vector id=\"%s\" type=\"%s\" count=\"%d\"/>\n",
1953                                 type->id, type->reg_type_vector->type->id,
1954                                 type->reg_type_vector->count);
1955
1956         } else if (type->type_class == REG_TYPE_CLASS_UNION) {
1957                 /* <union id="id">
1958                  *  <field name="name" type="type"/> ...
1959                  * </union> */
1960                 xml_printf(&retval, tdesc, pos, size,
1961                                 "<union id=\"%s\">\n",
1962                                 type->id);
1963
1964                 struct reg_data_type_union_field *field;
1965                 field = type->reg_type_union->fields;
1966                 while (field != NULL) {
1967                         xml_printf(&retval, tdesc, pos, size,
1968                                         "<field name=\"%s\" type=\"%s\"/>\n",
1969                                         field->name, field->type->id);
1970
1971                         field = field->next;
1972                 }
1973
1974                 xml_printf(&retval, tdesc, pos, size,
1975                                 "</union>\n");
1976
1977         } else if (type->type_class == REG_TYPE_CLASS_STRUCT) {
1978                 struct reg_data_type_struct_field *field;
1979                 field = type->reg_type_struct->fields;
1980
1981                 if (field->use_bitfields) {
1982                         /* <struct id="id" size="size">
1983                          *  <field name="name" start="start" end="end"/> ...
1984                          * </struct> */
1985                         xml_printf(&retval, tdesc, pos, size,
1986                                         "<struct id=\"%s\" size=\"%d\">\n",
1987                                         type->id, type->reg_type_struct->size);
1988                         while (field != NULL) {
1989                                 xml_printf(&retval, tdesc, pos, size,
1990                                                 "<field name=\"%s\" start=\"%d\" end=\"%d\"/>\n",
1991                                                 field->name, field->bitfield->start,
1992                                                 field->bitfield->end);
1993
1994                                 field = field->next;
1995                         }
1996                 } else {
1997                         /* <struct id="id">
1998                          *  <field name="name" type="type"/> ...
1999                          * </struct> */
2000                         xml_printf(&retval, tdesc, pos, size,
2001                                         "<struct id=\"%s\">\n",
2002                                         type->id);
2003                         while (field != NULL) {
2004                                 xml_printf(&retval, tdesc, pos, size,
2005                                                 "<field name=\"%s\" type=\"%s\"/>\n",
2006                                                 field->name, field->type->id);
2007
2008                                 field = field->next;
2009                         }
2010                 }
2011
2012                 xml_printf(&retval, tdesc, pos, size,
2013                                 "</struct>\n");
2014
2015         } else if (type->type_class == REG_TYPE_CLASS_FLAGS) {
2016                 /* <flags id="id" size="size">
2017                  *  <field name="name" start="start" end="end"/> ...
2018                  * </flags> */
2019                 xml_printf(&retval, tdesc, pos, size,
2020                                 "<flags id=\"%s\" size=\"%d\">\n",
2021                                 type->id, type->reg_type_flags->size);
2022
2023                 struct reg_data_type_flags_field *field;
2024                 field = type->reg_type_flags->fields;
2025                 while (field != NULL) {
2026                         xml_printf(&retval, tdesc, pos, size,
2027                                         "<field name=\"%s\" start=\"%d\" end=\"%d\"/>\n",
2028                                         field->name, field->bitfield->start, field->bitfield->end);
2029
2030                         field = field->next;
2031                 }
2032
2033                 xml_printf(&retval, tdesc, pos, size,
2034                                 "</flags>\n");
2035
2036         }
2037
2038         return ERROR_OK;
2039 }
2040
2041 /* Get a list of available target registers features. feature_list must
2042  * be freed by caller.
2043  */
2044 static int get_reg_features_list(struct target *target, char const **feature_list[], int *feature_list_size,
2045                 struct reg **reg_list, int reg_list_size)
2046 {
2047         int tbl_sz = 0;
2048
2049         /* Start with only one element */
2050         *feature_list = calloc(1, sizeof(char *));
2051
2052         for (int i = 0; i < reg_list_size; i++) {
2053                 if (reg_list[i]->exist == false)
2054                         continue;
2055
2056                 if (reg_list[i]->feature != NULL
2057                         && reg_list[i]->feature->name != NULL
2058                         && (strcmp(reg_list[i]->feature->name, ""))) {
2059                         /* We found a feature, check if the feature is already in the
2060                          * table. If not, allocate a new entry for the table and
2061                          * put the new feature in it.
2062                          */
2063                         for (int j = 0; j < (tbl_sz + 1); j++) {
2064                                 if (!((*feature_list)[j])) {
2065                                         (*feature_list)[tbl_sz++] = reg_list[i]->feature->name;
2066                                         *feature_list = realloc(*feature_list, sizeof(char *) * (tbl_sz + 1));
2067                                         (*feature_list)[tbl_sz] = NULL;
2068                                         break;
2069                                 } else {
2070                                         if (!strcmp((*feature_list)[j], reg_list[i]->feature->name))
2071                                                 break;
2072                                 }
2073                         }
2074                 }
2075         }
2076
2077         if (feature_list_size)
2078                 *feature_list_size = tbl_sz;
2079
2080         return ERROR_OK;
2081 }
2082
2083 static int gdb_generate_target_description(struct target *target, char **tdesc_out)
2084 {
2085         int retval = ERROR_OK;
2086         struct reg **reg_list = NULL;
2087         int reg_list_size;
2088         char const **features = NULL;
2089         int feature_list_size = 0;
2090         char *tdesc = NULL;
2091         int pos = 0;
2092         int size = 0;
2093
2094         retval = target_get_gdb_reg_list(target, &reg_list,
2095                         &reg_list_size, REG_CLASS_ALL);
2096
2097         if (retval != ERROR_OK) {
2098                 LOG_ERROR("get register list failed");
2099                 retval = ERROR_FAIL;
2100                 goto error;
2101         }
2102
2103         if (reg_list_size <= 0) {
2104                 LOG_ERROR("get register list failed");
2105                 retval = ERROR_FAIL;
2106                 goto error;
2107         }
2108
2109         /* Get a list of available target registers features */
2110         retval = get_reg_features_list(target, &features, &feature_list_size, reg_list, reg_list_size);
2111         if (retval != ERROR_OK) {
2112                 LOG_ERROR("Can't get the registers feature list");
2113                 retval = ERROR_FAIL;
2114                 goto error;
2115         }
2116
2117         /* If we found some features associated with registers, create sections */
2118         int current_feature = 0;
2119
2120         xml_printf(&retval, &tdesc, &pos, &size,
2121                         "<?xml version=\"1.0\"?>\n"
2122                         "<!DOCTYPE target SYSTEM \"gdb-target.dtd\">\n"
2123                         "<target version=\"1.0\">\n");
2124
2125         /* generate target description according to register list */
2126         if (features != NULL) {
2127                 while (features[current_feature]) {
2128
2129                         xml_printf(&retval, &tdesc, &pos, &size,
2130                                         "<feature name=\"%s\">\n",
2131                                         features[current_feature]);
2132
2133                         int i;
2134                         for (i = 0; i < reg_list_size; i++) {
2135
2136                                 if (reg_list[i]->exist == false)
2137                                         continue;
2138
2139                                 if (strcmp(reg_list[i]->feature->name, features[current_feature]))
2140                                         continue;
2141
2142                                 const char *type_str;
2143                                 if (reg_list[i]->reg_data_type != NULL) {
2144                                         if (reg_list[i]->reg_data_type->type == REG_TYPE_ARCH_DEFINED) {
2145                                                 /* generate <type... first, if there are architecture-defined types. */
2146                                                 gdb_generate_reg_type_description(target, &tdesc, &pos, &size,
2147                                                                 reg_list[i]->reg_data_type);
2148
2149                                                 type_str = reg_list[i]->reg_data_type->id;
2150                                         } else {
2151                                                 /* predefined type */
2152                                                 type_str = gdb_get_reg_type_name(
2153                                                                 reg_list[i]->reg_data_type->type);
2154                                         }
2155                                 } else {
2156                                         /* Default type is "int" */
2157                                         type_str = "int";
2158                                 }
2159
2160                                 xml_printf(&retval, &tdesc, &pos, &size,
2161                                                 "<reg name=\"%s\"", reg_list[i]->name);
2162                                 xml_printf(&retval, &tdesc, &pos, &size,
2163                                                 " bitsize=\"%d\"", reg_list[i]->size);
2164                                 xml_printf(&retval, &tdesc, &pos, &size,
2165                                                 " regnum=\"%d\"", reg_list[i]->number);
2166                                 if (reg_list[i]->caller_save)
2167                                         xml_printf(&retval, &tdesc, &pos, &size,
2168                                                         " save-restore=\"yes\"");
2169                                 else
2170                                         xml_printf(&retval, &tdesc, &pos, &size,
2171                                                         " save-restore=\"no\"");
2172
2173                                 xml_printf(&retval, &tdesc, &pos, &size,
2174                                                 " type=\"%s\"", type_str);
2175
2176                                 if (reg_list[i]->group != NULL)
2177                                         xml_printf(&retval, &tdesc, &pos, &size,
2178                                                         " group=\"%s\"", reg_list[i]->group);
2179
2180                                 xml_printf(&retval, &tdesc, &pos, &size,
2181                                                 "/>\n");
2182                         }
2183
2184                         xml_printf(&retval, &tdesc, &pos, &size,
2185                                         "</feature>\n");
2186
2187                         current_feature++;
2188                 }
2189         }
2190
2191         xml_printf(&retval, &tdesc, &pos, &size,
2192                         "</target>\n");
2193
2194 error:
2195         free(features);
2196         free(reg_list);
2197
2198         if (retval == ERROR_OK)
2199                 *tdesc_out = tdesc;
2200         else
2201                 free(tdesc);
2202
2203         return retval;
2204 }
2205
2206 static int gdb_get_target_description_chunk(struct target *target, struct target_desc_format *target_desc,
2207                 char **chunk, int32_t offset, uint32_t length)
2208 {
2209         if (target_desc == NULL) {
2210                 LOG_ERROR("Unable to Generate Target Description");
2211                 return ERROR_FAIL;
2212         }
2213
2214         char *tdesc = target_desc->tdesc;
2215         uint32_t tdesc_length = target_desc->tdesc_length;
2216
2217         if (tdesc == NULL) {
2218                 int retval = gdb_generate_target_description(target, &tdesc);
2219                 if (retval != ERROR_OK) {
2220                         LOG_ERROR("Unable to Generate Target Description");
2221                         return ERROR_FAIL;
2222                 }
2223
2224                 tdesc_length = strlen(tdesc);
2225         }
2226
2227         char transfer_type;
2228
2229         if (length < (tdesc_length - offset))
2230                 transfer_type = 'm';
2231         else
2232                 transfer_type = 'l';
2233
2234         *chunk = malloc(length + 2);
2235         if (*chunk == NULL) {
2236                 LOG_ERROR("Unable to allocate memory");
2237                 return ERROR_FAIL;
2238         }
2239
2240         (*chunk)[0] = transfer_type;
2241         if (transfer_type == 'm') {
2242                 strncpy((*chunk) + 1, tdesc + offset, length);
2243                 (*chunk)[1 + length] = '\0';
2244         } else {
2245                 strncpy((*chunk) + 1, tdesc + offset, tdesc_length - offset);
2246                 (*chunk)[1 + (tdesc_length - offset)] = '\0';
2247
2248                 /* After gdb-server sends out last chunk, invalidate tdesc. */
2249                 free(tdesc);
2250                 tdesc = NULL;
2251                 tdesc_length = 0;
2252         }
2253
2254         target_desc->tdesc = tdesc;
2255         target_desc->tdesc_length = tdesc_length;
2256
2257         return ERROR_OK;
2258 }
2259
2260 static int gdb_target_description_supported(struct target *target, int *supported)
2261 {
2262         int retval = ERROR_OK;
2263         struct reg **reg_list = NULL;
2264         int reg_list_size = 0;
2265         char const **features = NULL;
2266         int feature_list_size = 0;
2267
2268         retval = target_get_gdb_reg_list(target, &reg_list,
2269                         &reg_list_size, REG_CLASS_ALL);
2270         if (retval != ERROR_OK) {
2271                 LOG_ERROR("get register list failed");
2272                 goto error;
2273         }
2274
2275         if (reg_list_size <= 0) {
2276                 LOG_ERROR("get register list failed");
2277                 retval = ERROR_FAIL;
2278                 goto error;
2279         }
2280
2281         /* Get a list of available target registers features */
2282         retval = get_reg_features_list(target, &features, &feature_list_size, reg_list, reg_list_size);
2283         if (retval != ERROR_OK) {
2284                 LOG_ERROR("Can't get the registers feature list");
2285                 goto error;
2286         }
2287
2288         if (supported) {
2289                 if (feature_list_size)
2290                         *supported = 1;
2291                 else
2292                         *supported = 0;
2293         }
2294
2295 error:
2296         free(features);
2297
2298         free(reg_list);
2299
2300         return retval;
2301 }
2302
2303 static int gdb_generate_thread_list(struct target *target, char **thread_list_out)
2304 {
2305         struct rtos *rtos = target->rtos;
2306         int retval = ERROR_OK;
2307         char *thread_list = NULL;
2308         int pos = 0;
2309         int size = 0;
2310
2311         xml_printf(&retval, &thread_list, &pos, &size,
2312                    "<?xml version=\"1.0\"?>\n"
2313                    "<threads>\n");
2314
2315         if (rtos != NULL) {
2316                 for (int i = 0; i < rtos->thread_count; i++) {
2317                         struct thread_detail *thread_detail = &rtos->thread_details[i];
2318
2319                         if (!thread_detail->exists)
2320                                 continue;
2321
2322                         xml_printf(&retval, &thread_list, &pos, &size,
2323                                    "<thread id=\"%" PRIx64 "\">", thread_detail->threadid);
2324
2325                         if (thread_detail->thread_name_str != NULL)
2326                                 xml_printf(&retval, &thread_list, &pos, &size,
2327                                            "Name: %s", thread_detail->thread_name_str);
2328
2329                         if (thread_detail->extra_info_str != NULL) {
2330                                 if (thread_detail->thread_name_str != NULL)
2331                                         xml_printf(&retval, &thread_list, &pos, &size,
2332                                                    ", ");
2333                                 xml_printf(&retval, &thread_list, &pos, &size,
2334                                            thread_detail->extra_info_str);
2335                         }
2336
2337                         xml_printf(&retval, &thread_list, &pos, &size,
2338                                    "</thread>\n");
2339                 }
2340         }
2341
2342         xml_printf(&retval, &thread_list, &pos, &size,
2343                    "</threads>\n");
2344
2345         if (retval == ERROR_OK)
2346                 *thread_list_out = thread_list;
2347         else
2348                 free(thread_list);
2349
2350         return retval;
2351 }
2352
2353 static int gdb_get_thread_list_chunk(struct target *target, char **thread_list,
2354                 char **chunk, int32_t offset, uint32_t length)
2355 {
2356         if (*thread_list == NULL) {
2357                 int retval = gdb_generate_thread_list(target, thread_list);
2358                 if (retval != ERROR_OK) {
2359                         LOG_ERROR("Unable to Generate Thread List");
2360                         return ERROR_FAIL;
2361                 }
2362         }
2363
2364         size_t thread_list_length = strlen(*thread_list);
2365         char transfer_type;
2366
2367         length = MIN(length, thread_list_length - offset);
2368         if (length < (thread_list_length - offset))
2369                 transfer_type = 'm';
2370         else
2371                 transfer_type = 'l';
2372
2373         *chunk = malloc(length + 2);
2374         if (*chunk == NULL) {
2375                 LOG_ERROR("Unable to allocate memory");
2376                 return ERROR_FAIL;
2377         }
2378
2379         (*chunk)[0] = transfer_type;
2380         strncpy((*chunk) + 1, (*thread_list) + offset, length);
2381         (*chunk)[1 + length] = '\0';
2382
2383         /* After gdb-server sends out last chunk, invalidate thread list. */
2384         if (transfer_type == 'l') {
2385                 free(*thread_list);
2386                 *thread_list = NULL;
2387         }
2388
2389         return ERROR_OK;
2390 }
2391
2392 static int gdb_query_packet(struct connection *connection,
2393                 char const *packet, int packet_size)
2394 {
2395         struct command_context *cmd_ctx = connection->cmd_ctx;
2396         struct gdb_connection *gdb_connection = connection->priv;
2397         struct target *target = get_target_from_connection(connection);
2398
2399         if (strncmp(packet, "qRcmd,", 6) == 0) {
2400                 if (packet_size > 6) {
2401                         char *cmd;
2402                         cmd = malloc((packet_size - 6) / 2 + 1);
2403                         size_t len = unhexify((uint8_t *)cmd, packet + 6, (packet_size - 6) / 2);
2404                         cmd[len] = 0;
2405
2406                         /* We want to print all debug output to GDB connection */
2407                         log_add_callback(gdb_log_callback, connection);
2408                         target_call_timer_callbacks_now();
2409                         /* some commands need to know the GDB connection, make note of current
2410                          * GDB connection. */
2411                         current_gdb_connection = gdb_connection;
2412                         command_run_line(cmd_ctx, cmd);
2413                         current_gdb_connection = NULL;
2414                         target_call_timer_callbacks_now();
2415                         log_remove_callback(gdb_log_callback, connection);
2416                         free(cmd);
2417                 }
2418                 gdb_put_packet(connection, "OK", 2);
2419                 return ERROR_OK;
2420         } else if (strncmp(packet, "qCRC:", 5) == 0) {
2421                 if (packet_size > 5) {
2422                         int retval;
2423                         char gdb_reply[10];
2424                         char *separator;
2425                         uint32_t checksum;
2426                         target_addr_t addr = 0;
2427                         uint32_t len = 0;
2428
2429                         /* skip command character */
2430                         packet += 5;
2431
2432                         addr = strtoull(packet, &separator, 16);
2433
2434                         if (*separator != ',') {
2435                                 LOG_ERROR("incomplete read memory packet received, dropping connection");
2436                                 return ERROR_SERVER_REMOTE_CLOSED;
2437                         }
2438
2439                         len = strtoul(separator + 1, NULL, 16);
2440
2441                         retval = target_checksum_memory(target, addr, len, &checksum);
2442
2443                         if (retval == ERROR_OK) {
2444                                 snprintf(gdb_reply, 10, "C%8.8" PRIx32 "", checksum);
2445                                 gdb_put_packet(connection, gdb_reply, 9);
2446                         } else {
2447                                 retval = gdb_error(connection, retval);
2448                                 if (retval != ERROR_OK)
2449                                         return retval;
2450                         }
2451
2452                         return ERROR_OK;
2453                 }
2454         } else if (strncmp(packet, "qSupported", 10) == 0) {
2455                 /* we currently support packet size and qXfer:memory-map:read (if enabled)
2456                  * qXfer:features:read is supported for some targets */
2457                 int retval = ERROR_OK;
2458                 char *buffer = NULL;
2459                 int pos = 0;
2460                 int size = 0;
2461                 int gdb_target_desc_supported = 0;
2462
2463                 /* we need to test that the target supports target descriptions */
2464                 retval = gdb_target_description_supported(target, &gdb_target_desc_supported);
2465                 if (retval != ERROR_OK) {
2466                         LOG_INFO("Failed detecting Target Description Support, disabling");
2467                         gdb_target_desc_supported = 0;
2468                 }
2469
2470                 /* support may be disabled globally */
2471                 if (gdb_use_target_description == 0) {
2472                         if (gdb_target_desc_supported)
2473                                 LOG_WARNING("Target Descriptions Supported, but disabled");
2474                         gdb_target_desc_supported = 0;
2475                 }
2476
2477                 xml_printf(&retval,
2478                         &buffer,
2479                         &pos,
2480                         &size,
2481                         "PacketSize=%x;qXfer:memory-map:read%c;qXfer:features:read%c;qXfer:threads:read+;QStartNoAckMode+;vContSupported+",
2482                         (GDB_BUFFER_SIZE - 1),
2483                         ((gdb_use_memory_map == 1) && (flash_get_bank_count() > 0)) ? '+' : '-',
2484                         (gdb_target_desc_supported == 1) ? '+' : '-');
2485
2486                 if (retval != ERROR_OK) {
2487                         gdb_send_error(connection, 01);
2488                         return ERROR_OK;
2489                 }
2490
2491                 gdb_put_packet(connection, buffer, strlen(buffer));
2492                 free(buffer);
2493
2494                 return ERROR_OK;
2495         } else if ((strncmp(packet, "qXfer:memory-map:read::", 23) == 0)
2496                    && (flash_get_bank_count() > 0))
2497                 return gdb_memory_map(connection, packet, packet_size);
2498         else if (strncmp(packet, "qXfer:features:read:", 20) == 0) {
2499                 char *xml = NULL;
2500                 int retval = ERROR_OK;
2501
2502                 int offset;
2503                 unsigned int length;
2504
2505                 /* skip command character */
2506                 packet += 20;
2507
2508                 if (decode_xfer_read(packet, NULL, &offset, &length) < 0) {
2509                         gdb_send_error(connection, 01);
2510                         return ERROR_OK;
2511                 }
2512
2513                 /* Target should prepare correct target description for annex.
2514                  * The first character of returned xml is 'm' or 'l'. 'm' for
2515                  * there are *more* chunks to transfer. 'l' for it is the *last*
2516                  * chunk of target description.
2517                  */
2518                 retval = gdb_get_target_description_chunk(target, &gdb_connection->target_desc,
2519                                 &xml, offset, length);
2520                 if (retval != ERROR_OK) {
2521                         gdb_error(connection, retval);
2522                         return retval;
2523                 }
2524
2525                 gdb_put_packet(connection, xml, strlen(xml));
2526
2527                 free(xml);
2528                 return ERROR_OK;
2529         } else if (strncmp(packet, "qXfer:threads:read:", 19) == 0) {
2530                 char *xml = NULL;
2531                 int retval = ERROR_OK;
2532
2533                 int offset;
2534                 unsigned int length;
2535
2536                 /* skip command character */
2537                 packet += 19;
2538
2539                 if (decode_xfer_read(packet, NULL, &offset, &length) < 0) {
2540                         gdb_send_error(connection, 01);
2541                         return ERROR_OK;
2542                 }
2543
2544                 /* Target should prepare correct thread list for annex.
2545                  * The first character of returned xml is 'm' or 'l'. 'm' for
2546                  * there are *more* chunks to transfer. 'l' for it is the *last*
2547                  * chunk of target description.
2548                  */
2549                 retval = gdb_get_thread_list_chunk(target, &gdb_connection->thread_list,
2550                                                    &xml, offset, length);
2551                 if (retval != ERROR_OK) {
2552                         gdb_error(connection, retval);
2553                         return retval;
2554                 }
2555
2556                 gdb_put_packet(connection, xml, strlen(xml));
2557
2558                 free(xml);
2559                 return ERROR_OK;
2560         } else if (strncmp(packet, "QStartNoAckMode", 15) == 0) {
2561                 gdb_connection->noack_mode = 1;
2562                 gdb_put_packet(connection, "OK", 2);
2563                 return ERROR_OK;
2564         }
2565
2566         gdb_put_packet(connection, "", 0);
2567         return ERROR_OK;
2568 }
2569
2570 static bool gdb_handle_vcont_packet(struct connection *connection, const char *packet, int packet_size)
2571 {
2572         struct gdb_connection *gdb_connection = connection->priv;
2573         struct target *target = get_target_from_connection(connection);
2574         const char *parse = packet;
2575         int retval;
2576
2577         /* query for vCont supported */
2578         if (parse[0] == '?') {
2579                 if (target->type->step != NULL) {
2580                         /* gdb doesn't accept c without C and s without S */
2581                         gdb_put_packet(connection, "vCont;c;C;s;S", 13);
2582                         return true;
2583                 }
2584                 return false;
2585         }
2586
2587         if (parse[0] == ';') {
2588                 ++parse;
2589                 --packet_size;
2590         }
2591
2592         /* simple case, a continue packet */
2593         if (parse[0] == 'c') {
2594                 LOG_DEBUG("target %s continue", target_name(target));
2595                 log_add_callback(gdb_log_callback, connection);
2596                 retval = target_resume(target, 1, 0, 0, 0);
2597                 if (retval == ERROR_OK) {
2598                         gdb_connection->frontend_state = TARGET_RUNNING;
2599                         target_call_event_callbacks(target, TARGET_EVENT_GDB_START);
2600                 }
2601                 return true;
2602         }
2603
2604         /* single-step or step-over-breakpoint */
2605         if (parse[0] == 's') {
2606                 if (strncmp(parse, "s:", 2) == 0) {
2607                         int handle_breakpoint = 1;
2608                         struct target *ct = target;
2609                         int64_t thread_id;
2610                         char *endp;
2611
2612                         parse += 2;
2613                         packet_size -= 2;
2614
2615                         thread_id = strtoll(parse, &endp, 16);
2616                         if (endp != NULL) {
2617                                 packet_size -= endp - parse;
2618                                 parse = endp;
2619                         }
2620
2621                         if (target->rtos != NULL)
2622                                 target->rtos->gdb_target_for_threadid(connection, thread_id, &ct);
2623
2624                         if (parse[0] == ';') {
2625                                 ++parse;
2626                                 --packet_size;
2627
2628                                 if (parse[0] == 'c') {
2629                                         parse += 1;
2630                                         packet_size -= 1;
2631
2632                                         handle_breakpoint = 0;
2633                                 }
2634                         }
2635
2636                         LOG_DEBUG("target %s single-step thread %"PRId64, target_name(ct), thread_id);
2637                         retval = target_step(ct, 1, 0, handle_breakpoint);
2638                         if (retval == ERROR_OK) {
2639                                 gdb_signal_reply(target, connection);
2640                                 /* stop forwarding log packets! */
2641                                 log_remove_callback(gdb_log_callback, connection);
2642                         } else
2643                         if (retval == ERROR_TARGET_TIMEOUT) {
2644                                 gdb_connection->frontend_state = TARGET_RUNNING;
2645                                 target_call_event_callbacks(ct, TARGET_EVENT_GDB_START);
2646                         }
2647                 } else {
2648                         LOG_ERROR("Unknown vCont packet");
2649                         return false;
2650                 }
2651                 return true;
2652         }
2653
2654         return false;
2655 }
2656
2657 static int gdb_v_packet(struct connection *connection,
2658                 char const *packet, int packet_size)
2659 {
2660         struct gdb_connection *gdb_connection = connection->priv;
2661         struct target *target;
2662         int result;
2663
2664         target = get_target_from_connection(connection);
2665
2666         if (strncmp(packet, "vCont", 5) == 0) {
2667                 bool handled;
2668
2669                 packet += 5;
2670                 packet_size -= 5;
2671
2672                 handled = gdb_handle_vcont_packet(connection, packet, packet_size);
2673                 if (!handled)
2674                         gdb_put_packet(connection, "", 0);
2675
2676                 return ERROR_OK;
2677         }
2678
2679         /* if flash programming disabled - send a empty reply */
2680
2681         if (gdb_flash_program == 0) {
2682                 gdb_put_packet(connection, "", 0);
2683                 return ERROR_OK;
2684         }
2685
2686         if (strncmp(packet, "vFlashErase:", 12) == 0) {
2687                 unsigned long addr;
2688                 unsigned long length;
2689
2690                 char const *parse = packet + 12;
2691                 if (*parse == '\0') {
2692                         LOG_ERROR("incomplete vFlashErase packet received, dropping connection");
2693                         return ERROR_SERVER_REMOTE_CLOSED;
2694                 }
2695
2696                 addr = strtoul(parse, (char **)&parse, 16);
2697
2698                 if (*(parse++) != ',' || *parse == '\0') {
2699                         LOG_ERROR("incomplete vFlashErase packet received, dropping connection");
2700                         return ERROR_SERVER_REMOTE_CLOSED;
2701                 }
2702
2703                 length = strtoul(parse, (char **)&parse, 16);
2704
2705                 if (*parse != '\0') {
2706                         LOG_ERROR("incomplete vFlashErase packet received, dropping connection");
2707                         return ERROR_SERVER_REMOTE_CLOSED;
2708                 }
2709
2710                 /* assume all sectors need erasing - stops any problems
2711                  * when flash_write is called multiple times */
2712                 flash_set_dirty();
2713
2714                 /* perform any target specific operations before the erase */
2715                 target_call_event_callbacks(target,
2716                         TARGET_EVENT_GDB_FLASH_ERASE_START);
2717
2718                 /* vFlashErase:addr,length messages require region start and
2719                  * end to be "block" aligned ... if padding is ever needed,
2720                  * GDB will have become dangerously confused.
2721                  */
2722                 result = flash_erase_address_range(target, false, addr,
2723                         length);
2724
2725                 /* perform any target specific operations after the erase */
2726                 target_call_event_callbacks(target,
2727                         TARGET_EVENT_GDB_FLASH_ERASE_END);
2728
2729                 /* perform erase */
2730                 if (result != ERROR_OK) {
2731                         /* GDB doesn't evaluate the actual error number returned,
2732                          * treat a failed erase as an I/O error
2733                          */
2734                         gdb_send_error(connection, EIO);
2735                         LOG_ERROR("flash_erase returned %i", result);
2736                 } else
2737                         gdb_put_packet(connection, "OK", 2);
2738
2739                 return ERROR_OK;
2740         }
2741
2742         if (strncmp(packet, "vFlashWrite:", 12) == 0) {
2743                 int retval;
2744                 unsigned long addr;
2745                 unsigned long length;
2746                 char const *parse = packet + 12;
2747
2748                 if (*parse == '\0') {
2749                         LOG_ERROR("incomplete vFlashErase packet received, dropping connection");
2750                         return ERROR_SERVER_REMOTE_CLOSED;
2751                 }
2752                 addr = strtoul(parse, (char **)&parse, 16);
2753                 if (*(parse++) != ':') {
2754                         LOG_ERROR("incomplete vFlashErase packet received, dropping connection");
2755                         return ERROR_SERVER_REMOTE_CLOSED;
2756                 }
2757                 length = packet_size - (parse - packet);
2758
2759                 /* create a new image if there isn't already one */
2760                 if (gdb_connection->vflash_image == NULL) {
2761                         gdb_connection->vflash_image = malloc(sizeof(struct image));
2762                         image_open(gdb_connection->vflash_image, "", "build");
2763                 }
2764
2765                 /* create new section with content from packet buffer */
2766                 retval = image_add_section(gdb_connection->vflash_image,
2767                                 addr, length, 0x0, (uint8_t const *)parse);
2768                 if (retval != ERROR_OK)
2769                         return retval;
2770
2771                 gdb_put_packet(connection, "OK", 2);
2772
2773                 return ERROR_OK;
2774         }
2775
2776         if (strncmp(packet, "vFlashDone", 10) == 0) {
2777                 uint32_t written;
2778
2779                 /* process the flashing buffer. No need to erase as GDB
2780                  * always issues a vFlashErase first. */
2781                 target_call_event_callbacks(target,
2782                                 TARGET_EVENT_GDB_FLASH_WRITE_START);
2783                 result = flash_write(target, gdb_connection->vflash_image,
2784                         &written, 0);
2785                 target_call_event_callbacks(target,
2786                         TARGET_EVENT_GDB_FLASH_WRITE_END);
2787                 if (result != ERROR_OK) {
2788                         if (result == ERROR_FLASH_DST_OUT_OF_BANK)
2789                                 gdb_put_packet(connection, "E.memtype", 9);
2790                         else
2791                                 gdb_send_error(connection, EIO);
2792                 } else {
2793                         LOG_DEBUG("wrote %u bytes from vFlash image to flash", (unsigned)written);
2794                         gdb_put_packet(connection, "OK", 2);
2795                 }
2796
2797                 image_close(gdb_connection->vflash_image);
2798                 free(gdb_connection->vflash_image);
2799                 gdb_connection->vflash_image = NULL;
2800
2801                 return ERROR_OK;
2802         }
2803
2804         gdb_put_packet(connection, "", 0);
2805         return ERROR_OK;
2806 }
2807
2808 static int gdb_detach(struct connection *connection)
2809 {
2810         target_call_event_callbacks(get_target_from_connection(connection),
2811                 TARGET_EVENT_GDB_DETACH);
2812
2813         return gdb_put_packet(connection, "OK", 2);
2814 }
2815
2816 /* The format of 'F' response packet is
2817  * Fretcode,errno,Ctrl-C flag;call-specific attachment
2818  */
2819 static int gdb_fileio_response_packet(struct connection *connection,
2820                 char const *packet, int packet_size)
2821 {
2822         struct target *target = get_target_from_connection(connection);
2823         char *separator;
2824         char *parsing_point;
2825         int fileio_retcode = strtoul(packet + 1, &separator, 16);
2826         int fileio_errno = 0;
2827         bool fileio_ctrl_c = false;
2828         int retval;
2829
2830         LOG_DEBUG("-");
2831
2832         if (*separator == ',') {
2833                 parsing_point = separator + 1;
2834                 fileio_errno = strtoul(parsing_point, &separator, 16);
2835                 if (*separator == ',') {
2836                         if (*(separator + 1) == 'C') {
2837                                 /* TODO: process ctrl-c */
2838                                 fileio_ctrl_c = true;
2839                         }
2840                 }
2841         }
2842
2843         LOG_DEBUG("File-I/O response, retcode: 0x%x, errno: 0x%x, ctrl-c: %s",
2844                         fileio_retcode, fileio_errno, fileio_ctrl_c ? "true" : "false");
2845
2846         retval = target_gdb_fileio_end(target, fileio_retcode, fileio_errno, fileio_ctrl_c);
2847         if (retval != ERROR_OK)
2848                 return ERROR_FAIL;
2849
2850         /* After File-I/O ends, keep continue or step */
2851         if (gdb_running_type == 'c')
2852                 retval = target_resume(target, 1, 0x0, 0, 0);
2853         else if (gdb_running_type == 's')
2854                 retval = target_step(target, 1, 0x0, 0);
2855         else
2856                 retval = ERROR_FAIL;
2857
2858         if (retval != ERROR_OK)
2859                 return ERROR_FAIL;
2860
2861         return ERROR_OK;
2862 }
2863
2864 static void gdb_log_callback(void *priv, const char *file, unsigned line,
2865                 const char *function, const char *string)
2866 {
2867         struct connection *connection = priv;
2868         struct gdb_connection *gdb_con = connection->priv;
2869
2870         if (gdb_con->busy) {
2871                 /* do not reply this using the O packet */
2872                 return;
2873         }
2874
2875         gdb_output_con(connection, string);
2876 }
2877
2878 static void gdb_sig_halted(struct connection *connection)
2879 {
2880         char sig_reply[4];
2881         snprintf(sig_reply, 4, "T%2.2x", 2);
2882         gdb_put_packet(connection, sig_reply, 3);
2883 }
2884
2885 static int gdb_input_inner(struct connection *connection)
2886 {
2887         /* Do not allocate this on the stack */
2888         static char gdb_packet_buffer[GDB_BUFFER_SIZE];
2889
2890         struct target *target;
2891         char const *packet = gdb_packet_buffer;
2892         int packet_size;
2893         int retval;
2894         struct gdb_connection *gdb_con = connection->priv;
2895         static int extended_protocol;
2896
2897         target = get_target_from_connection(connection);
2898
2899         /* drain input buffer. If one of the packets fail, then an error
2900          * packet is replied, if applicable.
2901          *
2902          * This loop will terminate and the error code is returned.
2903          *
2904          * The calling fn will check if this error is something that
2905          * can be recovered from, or if the connection must be closed.
2906          *
2907          * If the error is recoverable, this fn is called again to
2908          * drain the rest of the buffer.
2909          */
2910         do {
2911                 packet_size = GDB_BUFFER_SIZE-1;
2912                 retval = gdb_get_packet(connection, gdb_packet_buffer, &packet_size);
2913                 if (retval != ERROR_OK)
2914                         return retval;
2915
2916                 /* terminate with zero */
2917                 gdb_packet_buffer[packet_size] = '\0';
2918
2919                 if (LOG_LEVEL_IS(LOG_LVL_DEBUG)) {
2920                         if (packet[0] == 'X') {
2921                                 /* binary packets spew junk into the debug log stream */
2922                                 char buf[50];
2923                                 int x;
2924                                 for (x = 0; (x < 49) && (packet[x] != ':'); x++)
2925                                         buf[x] = packet[x];
2926                                 buf[x] = 0;
2927                                 LOG_DEBUG("received packet: '%s:<binary-data>'", buf);
2928                         } else
2929                                 LOG_DEBUG("received packet: '%s'", packet);
2930                 }
2931
2932                 if (packet_size > 0) {
2933                         retval = ERROR_OK;
2934                         switch (packet[0]) {
2935                                 case 'T':       /* Is thread alive? */
2936                                         gdb_thread_packet(connection, packet, packet_size);
2937                                         break;
2938                                 case 'H':       /* Set current thread ( 'c' for step and continue,
2939                                                          * 'g' for all other operations ) */
2940                                         gdb_thread_packet(connection, packet, packet_size);
2941                                         break;
2942                                 case 'q':
2943                                 case 'Q':
2944                                         retval = gdb_thread_packet(connection, packet, packet_size);
2945                                         if (retval == GDB_THREAD_PACKET_NOT_CONSUMED)
2946                                                 retval = gdb_query_packet(connection, packet, packet_size);
2947                                         break;
2948                                 case 'g':
2949                                         retval = gdb_get_registers_packet(connection, packet, packet_size);
2950                                         break;
2951                                 case 'G':
2952                                         retval = gdb_set_registers_packet(connection, packet, packet_size);
2953                                         break;
2954                                 case 'p':
2955                                         retval = gdb_get_register_packet(connection, packet, packet_size);
2956                                         break;
2957                                 case 'P':
2958                                         retval = gdb_set_register_packet(connection, packet, packet_size);
2959                                         break;
2960                                 case 'm':
2961                                         retval = gdb_read_memory_packet(connection, packet, packet_size);
2962                                         break;
2963                                 case 'M':
2964                                         retval = gdb_write_memory_packet(connection, packet, packet_size);
2965                                         break;
2966                                 case 'z':
2967                                 case 'Z':
2968                                         retval = gdb_breakpoint_watchpoint_packet(connection, packet, packet_size);
2969                                         break;
2970                                 case '?':
2971                                         gdb_last_signal_packet(connection, packet, packet_size);
2972                                         break;
2973                                 case 'c':
2974                                 case 's':
2975                                 {
2976                                         gdb_thread_packet(connection, packet, packet_size);
2977                                         log_add_callback(gdb_log_callback, connection);
2978
2979                                         if (gdb_con->mem_write_error) {
2980                                                 LOG_ERROR("Memory write failure!");
2981
2982                                                 /* now that we have reported the memory write error,
2983                                                  * we can clear the condition */
2984                                                 gdb_con->mem_write_error = false;
2985                                         }
2986
2987                                         bool nostep = false;
2988                                         bool already_running = false;
2989                                         if (target->state == TARGET_RUNNING) {
2990                                                 LOG_WARNING("WARNING! The target is already running. "
2991                                                                 "All changes GDB did to registers will be discarded! "
2992                                                                 "Waiting for target to halt.");
2993                                                 already_running = true;
2994                                         } else if (target->state != TARGET_HALTED) {
2995                                                 LOG_WARNING("The target is not in the halted nor running stated, " \
2996                                                                 "stepi/continue ignored.");
2997                                                 nostep = true;
2998                                         } else if ((packet[0] == 's') && gdb_con->sync) {
2999                                                 /* Hmm..... when you issue a continue in GDB, then a "stepi" is
3000                                                  * sent by GDB first to OpenOCD, thus defeating the check to
3001                                                  * make only the single stepping have the sync feature...
3002                                                  */
3003                                                 nostep = true;
3004                                                 LOG_WARNING("stepi ignored. GDB will now fetch the register state " \
3005                                                                 "from the target.");
3006                                         }
3007                                         gdb_con->sync = false;
3008
3009                                         if (!already_running && nostep) {
3010                                                 /* Either the target isn't in the halted state, then we can't
3011                                                  * step/continue. This might be early setup, etc.
3012                                                  *
3013                                                  * Or we want to allow GDB to pick up a fresh set of
3014                                                  * register values without modifying the target state.
3015                                                  *
3016                                                  */
3017                                                 gdb_sig_halted(connection);
3018
3019                                                 /* stop forwarding log packets! */
3020                                                 log_remove_callback(gdb_log_callback, connection);
3021                                         } else {
3022                                                 /* We're running/stepping, in which case we can
3023                                                  * forward log output until the target is halted
3024                                                  */
3025                                                 gdb_con->frontend_state = TARGET_RUNNING;
3026                                                 target_call_event_callbacks(target, TARGET_EVENT_GDB_START);
3027
3028                                                 if (!already_running) {
3029                                                         /* Here we don't want packet processing to stop even if this fails,
3030                                                          * so we use a local variable instead of retval. */
3031                                                         retval = gdb_step_continue_packet(connection, packet, packet_size);
3032                                                         if (retval != ERROR_OK) {
3033                                                                 /* we'll never receive a halted
3034                                                                  * condition... issue a false one..
3035                                                                  */
3036                                                                 gdb_frontend_halted(target, connection);
3037                                                         }
3038                                                 }
3039                                         }
3040                                 }
3041                                 break;
3042                                 case 'v':
3043                                         retval = gdb_v_packet(connection, packet, packet_size);
3044                                         break;
3045                                 case 'D':
3046                                         retval = gdb_detach(connection);
3047                                         extended_protocol = 0;
3048                                         break;
3049                                 case 'X':
3050                                         retval = gdb_write_memory_binary_packet(connection, packet, packet_size);
3051                                         if (retval != ERROR_OK)
3052                                                 return retval;
3053                                         break;
3054                                 case 'k':
3055                                         if (extended_protocol != 0) {
3056                                                 gdb_con->attached = false;
3057                                                 break;
3058                                         }
3059                                         gdb_put_packet(connection, "OK", 2);
3060                                         return ERROR_SERVER_REMOTE_CLOSED;
3061                                 case '!':
3062                                         /* handle extended remote protocol */
3063                                         extended_protocol = 1;
3064                                         gdb_put_packet(connection, "OK", 2);
3065                                         break;
3066                                 case 'R':
3067                                         /* handle extended restart packet */
3068                                         breakpoint_clear_target(target);
3069                                         watchpoint_clear_target(target);
3070                                         command_run_linef(connection->cmd_ctx, "ocd_gdb_restart %s",
3071                                                         target_name(target));
3072                                         /* set connection as attached after reset */
3073                                         gdb_con->attached = true;
3074                                         /*  info rtos parts */
3075                                         gdb_thread_packet(connection, packet, packet_size);
3076                                         break;
3077
3078                                 case 'j':
3079                                         /* packet supported only by smp target i.e cortex_a.c*/
3080                                         /* handle smp packet replying coreid played to gbd */
3081                                         gdb_read_smp_packet(connection, packet, packet_size);
3082                                         break;
3083
3084                                 case 'J':
3085                                         /* packet supported only by smp target i.e cortex_a.c */
3086                                         /* handle smp packet setting coreid to be played at next
3087                                          * resume to gdb */
3088                                         gdb_write_smp_packet(connection, packet, packet_size);
3089                                         break;
3090
3091                                 case 'F':
3092                                         /* File-I/O extension */
3093                                         /* After gdb uses host-side syscall to complete target file
3094                                          * I/O, gdb sends host-side syscall return value to target
3095                                          * by 'F' packet.
3096                                          * The format of 'F' response packet is
3097                                          * Fretcode,errno,Ctrl-C flag;call-specific attachment
3098                                          */
3099                                         gdb_con->frontend_state = TARGET_RUNNING;
3100                                         log_add_callback(gdb_log_callback, connection);
3101                                         gdb_fileio_response_packet(connection, packet, packet_size);
3102                                         break;
3103
3104                                 default:
3105                                         /* ignore unknown packets */
3106                                         LOG_DEBUG("ignoring 0x%2.2x packet", packet[0]);
3107                                         gdb_put_packet(connection, NULL, 0);
3108                                         break;
3109                         }
3110
3111                         /* if a packet handler returned an error, exit input loop */
3112                         if (retval != ERROR_OK)
3113                                 return retval;
3114                 }
3115
3116                 if (gdb_con->ctrl_c) {
3117                         if (target->state == TARGET_RUNNING) {
3118                                 struct target *t = target;
3119                                 if (target->rtos)
3120                                         target->rtos->gdb_target_for_threadid(connection, target->rtos->current_threadid, &t);
3121                                 retval = target_halt(t);
3122                                 if (retval != ERROR_OK)
3123                                         target_call_event_callbacks(target, TARGET_EVENT_GDB_HALT);
3124                                 gdb_con->ctrl_c = 0;
3125                         } else {
3126                                 LOG_INFO("The target is not running when halt was requested, stopping GDB.");
3127                                 target_call_event_callbacks(target, TARGET_EVENT_GDB_HALT);
3128                         }
3129                 }
3130
3131         } while (gdb_con->buf_cnt > 0);
3132
3133         return ERROR_OK;
3134 }
3135
3136 static int gdb_input(struct connection *connection)
3137 {
3138         int retval = gdb_input_inner(connection);
3139         struct gdb_connection *gdb_con = connection->priv;
3140         if (retval == ERROR_SERVER_REMOTE_CLOSED)
3141                 return retval;
3142
3143         /* logging does not propagate the error, yet can set the gdb_con->closed flag */
3144         if (gdb_con->closed)
3145                 return ERROR_SERVER_REMOTE_CLOSED;
3146
3147         /* we'll recover from any other errors(e.g. temporary timeouts, etc.) */
3148         return ERROR_OK;
3149 }
3150
3151 static int gdb_target_start(struct target *target, const char *port)
3152 {
3153         struct gdb_service *gdb_service;
3154         int ret;
3155         gdb_service = malloc(sizeof(struct gdb_service));
3156
3157         if (NULL == gdb_service)
3158                 return -ENOMEM;
3159
3160         gdb_service->target = target;
3161         gdb_service->core[0] = -1;
3162         gdb_service->core[1] = -1;
3163         target->gdb_service = gdb_service;
3164
3165         ret = add_service("gdb",
3166                         port, 1, &gdb_new_connection, &gdb_input,
3167                         &gdb_connection_closed, gdb_service);
3168         /* initialialize all targets gdb service with the same pointer */
3169         {
3170                 struct target_list *head;
3171                 struct target *curr;
3172                 head = target->head;
3173                 while (head != (struct target_list *)NULL) {
3174                         curr = head->target;
3175                         if (curr != target)
3176                                 curr->gdb_service = gdb_service;
3177                         head = head->next;
3178                 }
3179         }
3180         return ret;
3181 }
3182
3183 static int gdb_target_add_one(struct target *target)
3184 {
3185         if (strcmp(gdb_port, "disabled") == 0) {
3186                 LOG_INFO("gdb port disabled");
3187                 return ERROR_OK;
3188         }
3189
3190         /*  one gdb instance per smp list */
3191         if ((target->smp) && (target->gdb_service))
3192                 return ERROR_OK;
3193         int retval = gdb_target_start(target, gdb_port_next);
3194         if (retval == ERROR_OK) {
3195                 long portnumber;
3196                 /* If we can parse the port number
3197                  * then we increment the port number for the next target.
3198                  */
3199                 char *end;
3200                 portnumber = strtol(gdb_port_next, &end, 0);
3201                 if (!*end) {
3202                         if (parse_long(gdb_port_next, &portnumber) == ERROR_OK) {
3203                                 free(gdb_port_next);
3204                                 if (portnumber) {
3205                                         gdb_port_next = alloc_printf("%d", portnumber+1);
3206                                 } else {
3207                                         /* Don't increment if gdb_port is 0, since we're just
3208                                          * trying to allocate an unused port. */
3209                                         gdb_port_next = strdup("0");
3210                                 }
3211                         }
3212                 }
3213         }
3214         return retval;
3215 }
3216
3217 int gdb_target_add_all(struct target *target)
3218 {
3219         if (strcmp(gdb_port, "disabled") == 0) {
3220                 LOG_INFO("gdb server disabled");
3221                 return ERROR_OK;
3222         }
3223
3224         if (NULL == target) {
3225                 LOG_WARNING("gdb services need one or more targets defined");
3226                 return ERROR_OK;
3227         }
3228
3229         while (NULL != target) {
3230                 int retval = gdb_target_add_one(target);
3231                 if (ERROR_OK != retval)
3232                         return retval;
3233
3234                 target = target->next;
3235         }
3236
3237         return ERROR_OK;
3238 }
3239
3240 COMMAND_HANDLER(handle_gdb_sync_command)
3241 {
3242         if (CMD_ARGC != 0)
3243                 return ERROR_COMMAND_SYNTAX_ERROR;
3244
3245         if (current_gdb_connection == NULL) {
3246                 command_print(CMD_CTX,
3247                         "gdb_sync command can only be run from within gdb using \"monitor gdb_sync\"");
3248                 return ERROR_FAIL;
3249         }
3250
3251         current_gdb_connection->sync = true;
3252
3253         return ERROR_OK;
3254 }
3255
3256 /* daemon configuration command gdb_port */
3257 COMMAND_HANDLER(handle_gdb_port_command)
3258 {
3259         int retval = CALL_COMMAND_HANDLER(server_pipe_command, &gdb_port);
3260         if (ERROR_OK == retval) {
3261                 free(gdb_port_next);
3262                 gdb_port_next = strdup(gdb_port);
3263         }
3264         return retval;
3265 }
3266
3267 COMMAND_HANDLER(handle_gdb_memory_map_command)
3268 {
3269         if (CMD_ARGC != 1)
3270                 return ERROR_COMMAND_SYNTAX_ERROR;
3271
3272         COMMAND_PARSE_ENABLE(CMD_ARGV[0], gdb_use_memory_map);
3273         return ERROR_OK;
3274 }
3275
3276 COMMAND_HANDLER(handle_gdb_flash_program_command)
3277 {
3278         if (CMD_ARGC != 1)
3279                 return ERROR_COMMAND_SYNTAX_ERROR;
3280
3281         COMMAND_PARSE_ENABLE(CMD_ARGV[0], gdb_flash_program);
3282         return ERROR_OK;
3283 }
3284
3285 COMMAND_HANDLER(handle_gdb_report_data_abort_command)
3286 {
3287         if (CMD_ARGC != 1)
3288                 return ERROR_COMMAND_SYNTAX_ERROR;
3289
3290         COMMAND_PARSE_ENABLE(CMD_ARGV[0], gdb_report_data_abort);
3291         return ERROR_OK;
3292 }
3293
3294 /* gdb_breakpoint_override */
3295 COMMAND_HANDLER(handle_gdb_breakpoint_override_command)
3296 {
3297         if (CMD_ARGC == 0) {
3298                 /* nothing */
3299         } else if (CMD_ARGC == 1) {
3300                 gdb_breakpoint_override = 1;
3301                 if (strcmp(CMD_ARGV[0], "hard") == 0)
3302                         gdb_breakpoint_override_type = BKPT_HARD;
3303                 else if (strcmp(CMD_ARGV[0], "soft") == 0)
3304                         gdb_breakpoint_override_type = BKPT_SOFT;
3305                 else if (strcmp(CMD_ARGV[0], "disable") == 0)
3306                         gdb_breakpoint_override = 0;
3307         } else
3308                 return ERROR_COMMAND_SYNTAX_ERROR;
3309         if (gdb_breakpoint_override)
3310                 LOG_USER("force %s breakpoints",
3311                         (gdb_breakpoint_override_type == BKPT_HARD) ? "hard" : "soft");
3312         else
3313                 LOG_USER("breakpoint type is not overridden");
3314
3315         return ERROR_OK;
3316 }
3317
3318 COMMAND_HANDLER(handle_gdb_target_description_command)
3319 {
3320         if (CMD_ARGC != 1)
3321                 return ERROR_COMMAND_SYNTAX_ERROR;
3322
3323         COMMAND_PARSE_ENABLE(CMD_ARGV[0], gdb_use_target_description);
3324         return ERROR_OK;
3325 }
3326
3327 COMMAND_HANDLER(handle_gdb_save_tdesc_command)
3328 {
3329         char *tdesc;
3330         uint32_t tdesc_length;
3331         struct target *target = get_current_target(CMD_CTX);
3332
3333         int retval = gdb_generate_target_description(target, &tdesc);
3334         if (retval != ERROR_OK) {
3335                 LOG_ERROR("Unable to Generate Target Description");
3336                 return ERROR_FAIL;
3337         }
3338
3339         tdesc_length = strlen(tdesc);
3340
3341         struct fileio *fileio;
3342         size_t size_written;
3343
3344         char *tdesc_filename = alloc_printf("%s.xml", target_type_name(target));
3345         if (tdesc_filename == NULL) {
3346                 retval = ERROR_FAIL;
3347                 goto out;
3348         }
3349
3350         retval = fileio_open(&fileio, tdesc_filename, FILEIO_WRITE, FILEIO_TEXT);
3351
3352         if (retval != ERROR_OK) {
3353                 LOG_ERROR("Can't open %s for writing", tdesc_filename);
3354                 goto out;
3355         }
3356
3357         retval = fileio_write(fileio, tdesc_length, tdesc, &size_written);
3358
3359         fileio_close(fileio);
3360
3361         if (retval != ERROR_OK)
3362                 LOG_ERROR("Error while writing the tdesc file");
3363
3364 out:
3365         free(tdesc_filename);
3366         free(tdesc);
3367
3368         return retval;
3369 }
3370
3371 static const struct command_registration gdb_command_handlers[] = {
3372         {
3373                 .name = "gdb_sync",
3374                 .handler = handle_gdb_sync_command,
3375                 .mode = COMMAND_ANY,
3376                 .help = "next stepi will return immediately allowing "
3377                         "GDB to fetch register state without affecting "
3378                         "target state",
3379                 .usage = ""
3380         },
3381         {
3382                 .name = "gdb_port",
3383                 .handler = handle_gdb_port_command,
3384                 .mode = COMMAND_ANY,
3385                 .help = "Normally gdb listens to a TCP/IP port. Each subsequent GDB "
3386                         "server listens for the next port number after the "
3387                         "base port number specified. "
3388                         "No arguments reports GDB port. \"pipe\" means listen to stdin "
3389                         "output to stdout, an integer is base port number, \"disabled\" disables "
3390                         "port. Any other string is are interpreted as named pipe to listen to. "
3391                         "Output pipe is the same name as input pipe, but with 'o' appended.",
3392                 .usage = "[port_num]",
3393         },
3394         {
3395                 .name = "gdb_memory_map",
3396                 .handler = handle_gdb_memory_map_command,
3397                 .mode = COMMAND_CONFIG,
3398                 .help = "enable or disable memory map",
3399                 .usage = "('enable'|'disable')"
3400         },
3401         {
3402                 .name = "gdb_flash_program",
3403                 .handler = handle_gdb_flash_program_command,
3404                 .mode = COMMAND_CONFIG,
3405                 .help = "enable or disable flash program",
3406                 .usage = "('enable'|'disable')"
3407         },
3408         {
3409                 .name = "gdb_report_data_abort",
3410                 .handler = handle_gdb_report_data_abort_command,
3411                 .mode = COMMAND_CONFIG,
3412                 .help = "enable or disable reporting data aborts",
3413                 .usage = "('enable'|'disable')"
3414         },
3415         {
3416                 .name = "gdb_breakpoint_override",
3417                 .handler = handle_gdb_breakpoint_override_command,
3418                 .mode = COMMAND_ANY,
3419                 .help = "Display or specify type of breakpoint "
3420                         "to be used by gdb 'break' commands.",
3421                 .usage = "('hard'|'soft'|'disable')"
3422         },
3423         {
3424                 .name = "gdb_target_description",
3425                 .handler = handle_gdb_target_description_command,
3426                 .mode = COMMAND_CONFIG,
3427                 .help = "enable or disable target description",
3428                 .usage = "('enable'|'disable')"
3429         },
3430         {
3431                 .name = "gdb_save_tdesc",
3432                 .handler = handle_gdb_save_tdesc_command,
3433                 .mode = COMMAND_EXEC,
3434                 .help = "Save the target description file",
3435         },
3436         COMMAND_REGISTRATION_DONE
3437 };
3438
3439 int gdb_register_commands(struct command_context *cmd_ctx)
3440 {
3441         gdb_port = strdup("3333");
3442         gdb_port_next = strdup("3333");
3443         return register_commands(cmd_ctx, NULL, gdb_command_handlers);
3444 }