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