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