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