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