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