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