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