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