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