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