gdb_server: support gdb target description
[fw/openocd] / src / server / gdb_server.c
1 /***************************************************************************
2  *   Copyright (C) 2005 by Dominic Rath                                    *
3  *   Dominic.Rath@gmx.de                                                   *
4  *                                                                         *
5  *   Copyright (C) 2007-2010 Ã˜yvind Harboe                                 *
6  *   oyvind.harboe@zylin.com                                               *
7  *                                                                         *
8  *   Copyright (C) 2008 by Spencer Oliver                                  *
9  *   spen@spen-soft.co.uk                                                  *
10  *                                                                         *
11  *   Copyright (C) 2011 by Broadcom Corporation                            *
12  *   Evan Hunter - ehunter@broadcom.com                                    *
13  *                                                                         *
14  *   Copyright (C) ST-Ericsson SA 2011                                     *
15  *   michel.jaouen@stericsson.com : smp minimum support                    *
16  *                                                                         *
17  *   Copyright (C) 2013 Andes Technology                                   *
18  *   Hsiangkai Wang <hkwang@andestech.com>                                 *
19  *                                                                         *
20  *   Copyright (C) 2013 Franck Jullien                                     *
21  *   elec4fun@gmail.com                                                    *
22  *                                                                         *
23  *   This program is free software; you can redistribute it and/or modify  *
24  *   it under the terms of the GNU General Public License as published by  *
25  *   the Free Software Foundation; either version 2 of the License, or     *
26  *   (at your option) any later version.                                   *
27  *                                                                         *
28  *   This program is distributed in the hope that it will be useful,       *
29  *   but WITHOUT ANY WARRANTY; without even the implied warranty of        *
30  *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the         *
31  *   GNU General Public License for more details.                          *
32  *                                                                         *
33  *   You should have received a copy of the GNU General Public License     *
34  *   along with this program; if not, write to the                         *
35  *   Free Software Foundation, Inc.,                                       *
36  *   51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.           *
37  ***************************************************************************/
38
39 #ifdef HAVE_CONFIG_H
40 #include "config.h"
41 #endif
42
43 #include <target/breakpoints.h>
44 #include <target/target_request.h>
45 #include <target/register.h>
46 #include "server.h"
47 #include <flash/nor/core.h>
48 #include "gdb_server.h"
49 #include <target/image.h>
50 #include <jtag/jtag.h>
51 #include "rtos/rtos.h"
52 #include "target/smp.h"
53
54 /**
55  * @file
56  * GDB server implementation.
57  *
58  * This implements the GDB Remote Serial Protocol, over TCP connections,
59  * giving GDB access to the JTAG or other hardware debugging facilities
60  * found in most modern embedded processors.
61  */
62
63 /* private connection data for GDB */
64 struct gdb_connection {
65         char buffer[GDB_BUFFER_SIZE];
66         char *buf_p;
67         int buf_cnt;
68         int ctrl_c;
69         enum target_state frontend_state;
70         struct image *vflash_image;
71         int closed;
72         int busy;
73         int noack_mode;
74         /* set flag to true if you want the next stepi to return immediately.
75          * allowing GDB to pick up a fresh set of register values from the target
76          * without modifying the target state. */
77         bool sync;
78         /* We delay reporting memory write errors until next step/continue or memory
79          * write. This improves performance of gdb load significantly as the GDB packet
80          * can be replied immediately and a new GDB packet will be ready without delay
81          * (ca. 10% or so...). */
82         bool mem_write_error;
83         /* with extended-remote it seems we need to better emulate attach/detach.
84          * what this means is we reply with a W stop reply after a kill packet,
85          * normally we reply with a S reply via gdb_last_signal_packet.
86          * as a side note this behaviour only effects gdb > 6.8 */
87         bool attached;
88 };
89
90 #if 0
91 #define _DEBUG_GDB_IO_
92 #endif
93
94 static struct gdb_connection *current_gdb_connection;
95
96 static int gdb_breakpoint_override;
97 static enum breakpoint_type gdb_breakpoint_override_type;
98
99 static int gdb_error(struct connection *connection, int retval);
100 static const char *gdb_port;
101 static const char *gdb_port_next;
102
103 static void gdb_log_callback(void *priv, const char *file, unsigned line,
104                 const char *function, const char *string);
105
106 /* number of gdb connections, mainly to suppress gdb related debugging spam
107  * in helper/log.c when no gdb connections are actually active */
108 int gdb_actual_connections;
109
110 /* set if we are sending a memory map to gdb
111  * via qXfer:memory-map:read packet */
112 /* enabled by default*/
113 static int gdb_use_memory_map = 1;
114 /* enabled by default*/
115 static int gdb_flash_program = 1;
116
117 /* if set, data aborts cause an error to be reported in memory read packets
118  * see the code in gdb_read_memory_packet() for further explanations.
119  * Disabled by default.
120  */
121 static int gdb_report_data_abort;
122
123 /* set if we are sending target descriptions to gdb
124  * via qXfer:features:read packet */
125 /* 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[4];
709                 int signal_var;
710
711                 /* stop forwarding log packets! */
712                 log_remove_callback(gdb_log_callback, connection);
713
714                 if (gdb_connection->ctrl_c) {
715                         signal_var = 0x2;
716                         gdb_connection->ctrl_c = 0;
717                 } else
718                         signal_var = gdb_last_signal(target);
719
720                 snprintf(sig_reply, 4, "T%2.2x", signal_var);
721                 gdb_put_packet(connection, sig_reply, 3);
722                 gdb_connection->frontend_state = TARGET_HALTED;
723                 rtos_update_threads(target);
724         }
725 }
726
727 static int gdb_target_callback_event_handler(struct target *target,
728                 enum target_event event, void *priv)
729 {
730         int retval;
731         struct connection *connection = priv;
732
733         switch (event) {
734                 case TARGET_EVENT_GDB_HALT:
735                         gdb_frontend_halted(target, connection);
736                         break;
737                 case TARGET_EVENT_HALTED:
738                         target_call_event_callbacks(target, TARGET_EVENT_GDB_END);
739                         break;
740                 case TARGET_EVENT_GDB_FLASH_ERASE_START:
741                         retval = jtag_execute_queue();
742                         if (retval != ERROR_OK)
743                                 return retval;
744                         break;
745                 default:
746                         break;
747         }
748
749         return ERROR_OK;
750 }
751
752 static int gdb_new_connection(struct connection *connection)
753 {
754         struct gdb_connection *gdb_connection = malloc(sizeof(struct gdb_connection));
755         struct gdb_service *gdb_service = connection->service->priv;
756         int retval;
757         int initial_ack;
758
759         connection->priv = gdb_connection;
760
761         /* initialize gdb connection information */
762         gdb_connection->buf_p = gdb_connection->buffer;
763         gdb_connection->buf_cnt = 0;
764         gdb_connection->ctrl_c = 0;
765         gdb_connection->frontend_state = TARGET_HALTED;
766         gdb_connection->vflash_image = NULL;
767         gdb_connection->closed = 0;
768         gdb_connection->busy = 0;
769         gdb_connection->noack_mode = 0;
770         gdb_connection->sync = true;
771         gdb_connection->mem_write_error = false;
772         gdb_connection->attached = true;
773
774         /* send ACK to GDB for debug request */
775         gdb_write(connection, "+", 1);
776
777         /* output goes through gdb connection */
778         command_set_output_handler(connection->cmd_ctx, gdb_output, connection);
779
780         /* we must remove all breakpoints registered to the target as a previous
781          * GDB session could leave dangling breakpoints if e.g. communication
782          * timed out.
783          */
784         breakpoint_clear_target(gdb_service->target);
785         watchpoint_clear_target(gdb_service->target);
786
787         /* clean previous rtos session if supported*/
788         if ((gdb_service->target->rtos) && (gdb_service->target->rtos->type->clean))
789                 gdb_service->target->rtos->type->clean(gdb_service->target);
790
791         /* remove the initial ACK from the incoming buffer */
792         retval = gdb_get_char(connection, &initial_ack);
793         if (retval != ERROR_OK)
794                 return retval;
795
796         /* FIX!!!??? would we actually ever receive a + here???
797          * Not observed.
798          */
799         if (initial_ack != '+')
800                 gdb_putback_char(connection, initial_ack);
801         target_call_event_callbacks(gdb_service->target, TARGET_EVENT_GDB_ATTACH);
802
803         if (gdb_use_memory_map) {
804                 /* Connect must fail if the memory map can't be set up correctly.
805                  *
806                  * This will cause an auto_probe to be invoked, which is either
807                  * a no-op or it will fail when the target isn't ready(e.g. not halted).
808                  */
809                 int i;
810                 for (i = 0; i < flash_get_bank_count(); i++) {
811                         struct flash_bank *p;
812                         retval = get_flash_bank_by_num(i, &p);
813                         if (retval != ERROR_OK) {
814                                 LOG_ERROR("Connect failed. Consider setting up a gdb-attach event for the target " \
815                                                 "to prepare target for GDB connect, or use 'gdb_memory_map disable'.");
816                                 return retval;
817                         }
818                 }
819         }
820
821         gdb_actual_connections++;
822         LOG_DEBUG("New GDB Connection: %d, Target %s, state: %s",
823                         gdb_actual_connections,
824                         target_name(gdb_service->target),
825                         target_state_name(gdb_service->target));
826
827         /* DANGER! If we fail subsequently, we must remove this handler,
828          * otherwise we occasionally see crashes as the timer can invoke the
829          * callback fn.
830          *
831          * register callback to be informed about target events */
832         target_register_event_callback(gdb_target_callback_event_handler, connection);
833
834         return ERROR_OK;
835 }
836
837 static int gdb_connection_closed(struct connection *connection)
838 {
839         struct gdb_service *gdb_service = connection->service->priv;
840         struct gdb_connection *gdb_connection = connection->priv;
841
842         /* we're done forwarding messages. Tear down callback before
843          * cleaning up connection.
844          */
845         log_remove_callback(gdb_log_callback, connection);
846
847         gdb_actual_connections--;
848         LOG_DEBUG("GDB Close, Target: %s, state: %s, gdb_actual_connections=%d",
849                 target_name(gdb_service->target),
850                 target_state_name(gdb_service->target),
851                 gdb_actual_connections);
852
853         /* see if an image built with vFlash commands is left */
854         if (gdb_connection->vflash_image) {
855                 image_close(gdb_connection->vflash_image);
856                 free(gdb_connection->vflash_image);
857                 gdb_connection->vflash_image = NULL;
858         }
859
860         /* if this connection registered a debug-message receiver delete it */
861         delete_debug_msg_receiver(connection->cmd_ctx, gdb_service->target);
862
863         if (connection->priv) {
864                 free(connection->priv);
865                 connection->priv = NULL;
866         } else
867                 LOG_ERROR("BUG: connection->priv == NULL");
868
869         target_unregister_event_callback(gdb_target_callback_event_handler, connection);
870
871         target_call_event_callbacks(gdb_service->target, TARGET_EVENT_GDB_END);
872
873         target_call_event_callbacks(gdb_service->target, TARGET_EVENT_GDB_DETACH);
874
875         return ERROR_OK;
876 }
877
878 static void gdb_send_error(struct connection *connection, uint8_t the_error)
879 {
880         char err[4];
881         snprintf(err, 4, "E%2.2X", the_error);
882         gdb_put_packet(connection, err, 3);
883 }
884
885 static int gdb_last_signal_packet(struct connection *connection,
886                 char *packet, int packet_size)
887 {
888         struct target *target = get_target_from_connection(connection);
889         struct gdb_connection *gdb_con = connection->priv;
890         char sig_reply[4];
891         int signal_var;
892
893         if (!gdb_con->attached) {
894                 /* if we are here we have received a kill packet
895                  * reply W stop reply otherwise gdb gets very unhappy */
896                 gdb_put_packet(connection, "W00", 3);
897                 return ERROR_OK;
898         }
899
900         signal_var = gdb_last_signal(target);
901
902         snprintf(sig_reply, 4, "S%2.2x", signal_var);
903         gdb_put_packet(connection, sig_reply, 3);
904
905         return ERROR_OK;
906 }
907
908 static inline int gdb_reg_pos(struct target *target, int pos, int len)
909 {
910         if (target->endianness == TARGET_LITTLE_ENDIAN)
911                 return pos;
912         else
913                 return len - 1 - pos;
914 }
915
916 /* Convert register to string of bytes. NB! The # of bits in the
917  * register might be non-divisible by 8(a byte), in which
918  * case an entire byte is shown.
919  *
920  * NB! the format on the wire is the target endianness
921  *
922  * The format of reg->value is little endian
923  *
924  */
925 static void gdb_str_to_target(struct target *target,
926                 char *tstr, struct reg *reg)
927 {
928         int i;
929
930         uint8_t *buf;
931         int buf_len;
932         buf = reg->value;
933         buf_len = DIV_ROUND_UP(reg->size, 8);
934
935         for (i = 0; i < buf_len; i++) {
936                 int j = gdb_reg_pos(target, i, buf_len);
937                 tstr += sprintf(tstr, "%02x", buf[j]);
938         }
939 }
940
941 /* copy over in register buffer */
942 static void gdb_target_to_reg(struct target *target,
943                 char *tstr, int str_len, uint8_t *bin)
944 {
945         if (str_len % 2) {
946                 LOG_ERROR("BUG: gdb value with uneven number of characters encountered");
947                 exit(-1);
948         }
949
950         int i;
951         for (i = 0; i < str_len; i += 2) {
952                 unsigned t;
953                 if (sscanf(tstr + i, "%02x", &t) != 1) {
954                         LOG_ERROR("BUG: unable to convert register value");
955                         exit(-1);
956                 }
957
958                 int j = gdb_reg_pos(target, i/2, str_len/2);
959                 bin[j] = t;
960         }
961 }
962
963 static int gdb_get_registers_packet(struct connection *connection,
964                 char *packet, int packet_size)
965 {
966         struct target *target = get_target_from_connection(connection);
967         struct reg **reg_list;
968         int reg_list_size;
969         int retval;
970         int reg_packet_size = 0;
971         char *reg_packet;
972         char *reg_packet_p;
973         int i;
974
975 #ifdef _DEBUG_GDB_IO_
976         LOG_DEBUG("-");
977 #endif
978
979         if ((target->rtos != NULL) && (ERROR_OK == rtos_get_gdb_reg_list(connection)))
980                 return ERROR_OK;
981
982         retval = target_get_gdb_reg_list(target, &reg_list, &reg_list_size,
983                         REG_CLASS_GENERAL);
984         if (retval != ERROR_OK)
985                 return gdb_error(connection, retval);
986
987         for (i = 0; i < reg_list_size; i++)
988                 reg_packet_size += DIV_ROUND_UP(reg_list[i]->size, 8) * 2;
989
990         assert(reg_packet_size > 0);
991
992         reg_packet = malloc(reg_packet_size + 1); /* plus one for string termination null */
993         reg_packet_p = reg_packet;
994
995         for (i = 0; i < reg_list_size; i++) {
996                 if (!reg_list[i]->valid)
997                         reg_list[i]->type->get(reg_list[i]);
998                 gdb_str_to_target(target, reg_packet_p, reg_list[i]);
999                 reg_packet_p += DIV_ROUND_UP(reg_list[i]->size, 8) * 2;
1000         }
1001
1002 #ifdef _DEBUG_GDB_IO_
1003         {
1004                 char *reg_packet_p_debug;
1005                 reg_packet_p_debug = strndup(reg_packet, reg_packet_size);
1006                 LOG_DEBUG("reg_packet: %s", reg_packet_p_debug);
1007                 free(reg_packet_p_debug);
1008         }
1009 #endif
1010
1011         gdb_put_packet(connection, reg_packet, reg_packet_size);
1012         free(reg_packet);
1013
1014         free(reg_list);
1015
1016         return ERROR_OK;
1017 }
1018
1019 static int gdb_set_registers_packet(struct connection *connection,
1020                 char *packet, int packet_size)
1021 {
1022         struct target *target = get_target_from_connection(connection);
1023         int i;
1024         struct reg **reg_list;
1025         int reg_list_size;
1026         int retval;
1027         char *packet_p;
1028
1029 #ifdef _DEBUG_GDB_IO_
1030         LOG_DEBUG("-");
1031 #endif
1032
1033         /* skip command character */
1034         packet++;
1035         packet_size--;
1036
1037         if (packet_size % 2) {
1038                 LOG_WARNING("GDB set_registers packet with uneven characters received, dropping connection");
1039                 return ERROR_SERVER_REMOTE_CLOSED;
1040         }
1041
1042         retval = target_get_gdb_reg_list(target, &reg_list, &reg_list_size,
1043                         REG_CLASS_GENERAL);
1044         if (retval != ERROR_OK)
1045                 return gdb_error(connection, retval);
1046
1047         packet_p = packet;
1048         for (i = 0; i < reg_list_size; i++) {
1049                 uint8_t *bin_buf;
1050                 int chars = (DIV_ROUND_UP(reg_list[i]->size, 8) * 2);
1051
1052                 if (packet_p + chars > packet + packet_size)
1053                         LOG_ERROR("BUG: register packet is too small for registers");
1054
1055                 bin_buf = malloc(DIV_ROUND_UP(reg_list[i]->size, 8));
1056                 gdb_target_to_reg(target, packet_p, chars, bin_buf);
1057
1058                 reg_list[i]->type->set(reg_list[i], bin_buf);
1059
1060                 /* advance packet pointer */
1061                 packet_p += chars;
1062
1063                 free(bin_buf);
1064         }
1065
1066         /* free struct reg *reg_list[] array allocated by get_gdb_reg_list */
1067         free(reg_list);
1068
1069         gdb_put_packet(connection, "OK", 2);
1070
1071         return ERROR_OK;
1072 }
1073
1074 static int gdb_get_register_packet(struct connection *connection,
1075         char *packet, int packet_size)
1076 {
1077         struct target *target = get_target_from_connection(connection);
1078         char *reg_packet;
1079         int reg_num = strtoul(packet + 1, NULL, 16);
1080         struct reg **reg_list;
1081         int reg_list_size;
1082         int retval;
1083
1084 #ifdef _DEBUG_GDB_IO_
1085         LOG_DEBUG("-");
1086 #endif
1087
1088         retval = target_get_gdb_reg_list(target, &reg_list, &reg_list_size,
1089                         REG_CLASS_ALL);
1090         if (retval != ERROR_OK)
1091                 return gdb_error(connection, retval);
1092
1093         if (reg_list_size <= reg_num) {
1094                 LOG_ERROR("gdb requested a non-existing register");
1095                 return ERROR_SERVER_REMOTE_CLOSED;
1096         }
1097
1098         if (!reg_list[reg_num]->valid)
1099                 reg_list[reg_num]->type->get(reg_list[reg_num]);
1100
1101         reg_packet = malloc(DIV_ROUND_UP(reg_list[reg_num]->size, 8) * 2 + 1); /* plus one for string termination null */
1102
1103         gdb_str_to_target(target, reg_packet, reg_list[reg_num]);
1104
1105         gdb_put_packet(connection, reg_packet, DIV_ROUND_UP(reg_list[reg_num]->size, 8) * 2);
1106
1107         free(reg_list);
1108         free(reg_packet);
1109
1110         return ERROR_OK;
1111 }
1112
1113 static int gdb_set_register_packet(struct connection *connection,
1114         char *packet, int packet_size)
1115 {
1116         struct target *target = get_target_from_connection(connection);
1117         char *separator;
1118         uint8_t *bin_buf;
1119         int reg_num = strtoul(packet + 1, &separator, 16);
1120         struct reg **reg_list;
1121         int reg_list_size;
1122         int retval;
1123
1124         LOG_DEBUG("-");
1125
1126         retval = target_get_gdb_reg_list(target, &reg_list, &reg_list_size,
1127                         REG_CLASS_ALL);
1128         if (retval != ERROR_OK)
1129                 return gdb_error(connection, retval);
1130
1131         if (reg_list_size <= reg_num) {
1132                 LOG_ERROR("gdb requested a non-existing register");
1133                 return ERROR_SERVER_REMOTE_CLOSED;
1134         }
1135
1136         if (*separator != '=') {
1137                 LOG_ERROR("GDB 'set register packet', but no '=' following the register number");
1138                 return ERROR_SERVER_REMOTE_CLOSED;
1139         }
1140
1141         /* convert from GDB-string (target-endian) to hex-string (big-endian) */
1142         bin_buf = malloc(DIV_ROUND_UP(reg_list[reg_num]->size, 8));
1143         int chars = (DIV_ROUND_UP(reg_list[reg_num]->size, 8) * 2);
1144
1145         if ((unsigned int)chars != strlen(separator + 1)) {
1146                 LOG_ERROR("gdb sent a packet with wrong register size");
1147                 free(bin_buf);
1148                 return ERROR_SERVER_REMOTE_CLOSED;
1149         }
1150
1151         gdb_target_to_reg(target, separator + 1, chars, bin_buf);
1152
1153         reg_list[reg_num]->type->set(reg_list[reg_num], bin_buf);
1154
1155         gdb_put_packet(connection, "OK", 2);
1156
1157         free(bin_buf);
1158         free(reg_list);
1159
1160         return ERROR_OK;
1161 }
1162
1163 /* No attempt is made to translate the "retval" to
1164  * GDB speak. This has to be done at the calling
1165  * site as no mapping really exists.
1166  */
1167 static int gdb_error(struct connection *connection, int retval)
1168 {
1169         LOG_DEBUG("Reporting %i to GDB as generic error", retval);
1170         gdb_send_error(connection, EFAULT);
1171         return ERROR_OK;
1172 }
1173
1174 /* We don't have to worry about the default 2 second timeout for GDB packets,
1175  * because GDB breaks up large memory reads into smaller reads.
1176  *
1177  * 8191 bytes by the looks of it. Why 8191 bytes instead of 8192?????
1178  */
1179 static int gdb_read_memory_packet(struct connection *connection,
1180                 char *packet, int packet_size)
1181 {
1182         struct target *target = get_target_from_connection(connection);
1183         char *separator;
1184         uint32_t addr = 0;
1185         uint32_t len = 0;
1186
1187         uint8_t *buffer;
1188         char *hex_buffer;
1189
1190         int retval = ERROR_OK;
1191
1192         /* skip command character */
1193         packet++;
1194
1195         addr = strtoul(packet, &separator, 16);
1196
1197         if (*separator != ',') {
1198                 LOG_ERROR("incomplete read memory packet received, dropping connection");
1199                 return ERROR_SERVER_REMOTE_CLOSED;
1200         }
1201
1202         len = strtoul(separator + 1, NULL, 16);
1203
1204         buffer = malloc(len);
1205
1206         LOG_DEBUG("addr: 0x%8.8" PRIx32 ", len: 0x%8.8" PRIx32 "", addr, len);
1207
1208         retval = target_read_buffer(target, addr, len, buffer);
1209
1210         if ((retval != ERROR_OK) && !gdb_report_data_abort) {
1211                 /* TODO : Here we have to lie and send back all zero's lest stack traces won't work.
1212                  * At some point this might be fixed in GDB, in which case this code can be removed.
1213                  *
1214                  * OpenOCD developers are acutely aware of this problem, but there is nothing
1215                  * gained by involving the user in this problem that hopefully will get resolved
1216                  * eventually
1217                  *
1218                  * http://sourceware.org/cgi-bin/gnatsweb.pl? \
1219                  * cmd = view%20audit-trail&database = gdb&pr = 2395
1220                  *
1221                  * For now, the default is to fix up things to make current GDB versions work.
1222                  * This can be overwritten using the gdb_report_data_abort <'enable'|'disable'> command.
1223                  */
1224                 memset(buffer, 0, len);
1225                 retval = ERROR_OK;
1226         }
1227
1228         if (retval == ERROR_OK) {
1229                 hex_buffer = malloc(len * 2 + 1);
1230
1231                 int pkt_len = hexify(hex_buffer, (char *)buffer, len, len * 2 + 1);
1232
1233                 gdb_put_packet(connection, hex_buffer, pkt_len);
1234
1235                 free(hex_buffer);
1236         } else
1237                 retval = gdb_error(connection, retval);
1238
1239         free(buffer);
1240
1241         return retval;
1242 }
1243
1244 static int gdb_write_memory_packet(struct connection *connection,
1245                 char *packet, int packet_size)
1246 {
1247         struct target *target = get_target_from_connection(connection);
1248         char *separator;
1249         uint32_t addr = 0;
1250         uint32_t len = 0;
1251
1252         uint8_t *buffer;
1253         int retval;
1254
1255         /* skip command character */
1256         packet++;
1257
1258         addr = strtoul(packet, &separator, 16);
1259
1260         if (*separator != ',') {
1261                 LOG_ERROR("incomplete write memory packet received, dropping connection");
1262                 return ERROR_SERVER_REMOTE_CLOSED;
1263         }
1264
1265         len = strtoul(separator + 1, &separator, 16);
1266
1267         if (*(separator++) != ':') {
1268                 LOG_ERROR("incomplete write memory packet received, dropping connection");
1269                 return ERROR_SERVER_REMOTE_CLOSED;
1270         }
1271
1272         buffer = malloc(len);
1273
1274         LOG_DEBUG("addr: 0x%8.8" PRIx32 ", len: 0x%8.8" PRIx32 "", addr, len);
1275
1276         if (unhexify((char *)buffer, separator, len) != (int)len)
1277                 LOG_ERROR("unable to decode memory packet");
1278
1279         retval = target_write_buffer(target, addr, len, buffer);
1280
1281         if (retval == ERROR_OK)
1282                 gdb_put_packet(connection, "OK", 2);
1283         else
1284                 retval = gdb_error(connection, retval);
1285
1286         free(buffer);
1287
1288         return retval;
1289 }
1290
1291 static int gdb_write_memory_binary_packet(struct connection *connection,
1292                 char *packet, int packet_size)
1293 {
1294         struct target *target = get_target_from_connection(connection);
1295         char *separator;
1296         uint32_t addr = 0;
1297         uint32_t len = 0;
1298
1299         int retval = ERROR_OK;
1300
1301         /* skip command character */
1302         packet++;
1303
1304         addr = strtoul(packet, &separator, 16);
1305
1306         if (*separator != ',') {
1307                 LOG_ERROR("incomplete write memory binary packet received, dropping connection");
1308                 return ERROR_SERVER_REMOTE_CLOSED;
1309         }
1310
1311         len = strtoul(separator + 1, &separator, 16);
1312
1313         if (*(separator++) != ':') {
1314                 LOG_ERROR("incomplete write memory binary packet received, dropping connection");
1315                 return ERROR_SERVER_REMOTE_CLOSED;
1316         }
1317
1318         struct gdb_connection *gdb_connection = connection->priv;
1319
1320         if (gdb_connection->mem_write_error) {
1321                 retval = ERROR_FAIL;
1322                 /* now that we have reported the memory write error, we can clear the condition */
1323                 gdb_connection->mem_write_error = false;
1324         }
1325
1326         /* By replying the packet *immediately* GDB will send us a new packet
1327          * while we write the last one to the target.
1328          */
1329         if (retval == ERROR_OK)
1330                 gdb_put_packet(connection, "OK", 2);
1331         else {
1332                 retval = gdb_error(connection, retval);
1333                 if (retval != ERROR_OK)
1334                         return retval;
1335         }
1336
1337         if (len) {
1338                 LOG_DEBUG("addr: 0x%8.8" PRIx32 ", len: 0x%8.8" PRIx32 "", addr, len);
1339
1340                 retval = target_write_buffer(target, addr, len, (uint8_t *)separator);
1341                 if (retval != ERROR_OK)
1342                         gdb_connection->mem_write_error = true;
1343         }
1344
1345         return ERROR_OK;
1346 }
1347
1348 static int gdb_step_continue_packet(struct connection *connection,
1349                 char *packet, int packet_size)
1350 {
1351         struct target *target = get_target_from_connection(connection);
1352         int current = 0;
1353         uint32_t address = 0x0;
1354         int retval = ERROR_OK;
1355
1356         LOG_DEBUG("-");
1357
1358         if (packet_size > 1) {
1359                 packet[packet_size] = 0;
1360                 address = strtoul(packet + 1, NULL, 16);
1361         } else
1362                 current = 1;
1363
1364         if (packet[0] == 'c') {
1365                 LOG_DEBUG("continue");
1366                 /* resume at current address, don't handle breakpoints, not debugging */
1367                 retval = target_resume(target, current, address, 0, 0);
1368         } else if (packet[0] == 's') {
1369                 LOG_DEBUG("step");
1370                 /* step at current or address, don't handle breakpoints */
1371                 retval = target_step(target, current, address, 0);
1372         }
1373         return retval;
1374 }
1375
1376 static int gdb_breakpoint_watchpoint_packet(struct connection *connection,
1377                 char *packet, int packet_size)
1378 {
1379         struct target *target = get_target_from_connection(connection);
1380         int type;
1381         enum breakpoint_type bp_type = BKPT_SOFT /* dummy init to avoid warning */;
1382         enum watchpoint_rw wp_type = WPT_READ /* dummy init to avoid warning */;
1383         uint32_t address;
1384         uint32_t size;
1385         char *separator;
1386         int retval;
1387
1388         LOG_DEBUG("-");
1389
1390         type = strtoul(packet + 1, &separator, 16);
1391
1392         if (type == 0)  /* memory breakpoint */
1393                 bp_type = BKPT_SOFT;
1394         else if (type == 1)     /* hardware breakpoint */
1395                 bp_type = BKPT_HARD;
1396         else if (type == 2)     /* write watchpoint */
1397                 wp_type = WPT_WRITE;
1398         else if (type == 3)     /* read watchpoint */
1399                 wp_type = WPT_READ;
1400         else if (type == 4)     /* access watchpoint */
1401                 wp_type = WPT_ACCESS;
1402         else {
1403                 LOG_ERROR("invalid gdb watch/breakpoint type(%d), dropping connection", type);
1404                 return ERROR_SERVER_REMOTE_CLOSED;
1405         }
1406
1407         if (gdb_breakpoint_override && ((bp_type == BKPT_SOFT) || (bp_type == BKPT_HARD)))
1408                 bp_type = gdb_breakpoint_override_type;
1409
1410         if (*separator != ',') {
1411                 LOG_ERROR("incomplete breakpoint/watchpoint packet received, dropping connection");
1412                 return ERROR_SERVER_REMOTE_CLOSED;
1413         }
1414
1415         address = strtoul(separator + 1, &separator, 16);
1416
1417         if (*separator != ',') {
1418                 LOG_ERROR("incomplete breakpoint/watchpoint packet received, dropping connection");
1419                 return ERROR_SERVER_REMOTE_CLOSED;
1420         }
1421
1422         size = strtoul(separator + 1, &separator, 16);
1423
1424         switch (type) {
1425                 case 0:
1426                 case 1:
1427                         if (packet[0] == 'Z') {
1428                                 retval = breakpoint_add(target, address, size, bp_type);
1429                                 if (retval != ERROR_OK) {
1430                                         retval = gdb_error(connection, retval);
1431                                         if (retval != ERROR_OK)
1432                                                 return retval;
1433                                 } else
1434                                         gdb_put_packet(connection, "OK", 2);
1435                         } else {
1436                                 breakpoint_remove(target, address);
1437                                 gdb_put_packet(connection, "OK", 2);
1438                         }
1439                         break;
1440                 case 2:
1441                 case 3:
1442                 case 4:
1443                 {
1444                         if (packet[0] == 'Z') {
1445                                 retval = watchpoint_add(target, address, size, wp_type, 0, 0xffffffffu);
1446                                 if (retval != ERROR_OK) {
1447                                         retval = gdb_error(connection, retval);
1448                                         if (retval != ERROR_OK)
1449                                                 return retval;
1450                                 } else
1451                                         gdb_put_packet(connection, "OK", 2);
1452                         } else {
1453                                 watchpoint_remove(target, address);
1454                                 gdb_put_packet(connection, "OK", 2);
1455                         }
1456                         break;
1457                 }
1458                 default:
1459                         break;
1460         }
1461
1462         return ERROR_OK;
1463 }
1464
1465 /* print out a string and allocate more space as needed,
1466  * mainly used for XML at this point
1467  */
1468 static void xml_printf(int *retval, char **xml, int *pos, int *size,
1469                 const char *fmt, ...)
1470 {
1471         if (*retval != ERROR_OK)
1472                 return;
1473         int first = 1;
1474
1475         for (;; ) {
1476                 if ((*xml == NULL) || (!first)) {
1477                         /* start by 0 to exercise all the code paths.
1478                          * Need minimum 2 bytes to fit 1 char and 0 terminator. */
1479
1480                         *size = *size * 2 + 2;
1481                         char *t = *xml;
1482                         *xml = realloc(*xml, *size);
1483                         if (*xml == NULL) {
1484                                 if (t)
1485                                         free(t);
1486                                 *retval = ERROR_SERVER_REMOTE_CLOSED;
1487                                 return;
1488                         }
1489                 }
1490
1491                 va_list ap;
1492                 int ret;
1493                 va_start(ap, fmt);
1494                 ret = vsnprintf(*xml + *pos, *size - *pos, fmt, ap);
1495                 va_end(ap);
1496                 if ((ret > 0) && ((ret + 1) < *size - *pos)) {
1497                         *pos += ret;
1498                         return;
1499                 }
1500                 /* there was just enough or not enough space, allocate more. */
1501                 first = 0;
1502         }
1503 }
1504
1505 static int decode_xfer_read(char *buf, char **annex, int *ofs, unsigned int *len)
1506 {
1507         char *separator;
1508
1509         /* Extract and NUL-terminate the annex. */
1510         *annex = buf;
1511         while (*buf && *buf != ':')
1512                 buf++;
1513         if (*buf == '\0')
1514                 return -1;
1515         *buf++ = 0;
1516
1517         /* After the read marker and annex, qXfer looks like a
1518          * traditional 'm' packet. */
1519
1520         *ofs = strtoul(buf, &separator, 16);
1521
1522         if (*separator != ',')
1523                 return -1;
1524
1525         *len = strtoul(separator + 1, NULL, 16);
1526
1527         return 0;
1528 }
1529
1530 static int compare_bank(const void *a, const void *b)
1531 {
1532         struct flash_bank *b1, *b2;
1533         b1 = *((struct flash_bank **)a);
1534         b2 = *((struct flash_bank **)b);
1535
1536         if (b1->base == b2->base)
1537                 return 0;
1538         else if (b1->base > b2->base)
1539                 return 1;
1540         else
1541                 return -1;
1542 }
1543
1544 static int gdb_memory_map(struct connection *connection,
1545                 char *packet, int packet_size)
1546 {
1547         /* We get away with only specifying flash here. Regions that are not
1548          * specified are treated as if we provided no memory map(if not we
1549          * could detect the holes and mark them as RAM).
1550          * Normally we only execute this code once, but no big deal if we
1551          * have to regenerate it a couple of times.
1552          */
1553
1554         struct target *target = get_target_from_connection(connection);
1555         struct flash_bank *p;
1556         char *xml = NULL;
1557         int size = 0;
1558         int pos = 0;
1559         int retval = ERROR_OK;
1560         struct flash_bank **banks;
1561         int offset;
1562         int length;
1563         char *separator;
1564         uint32_t ram_start = 0;
1565         int i;
1566         int target_flash_banks = 0;
1567
1568         /* skip command character */
1569         packet += 23;
1570
1571         offset = strtoul(packet, &separator, 16);
1572         length = strtoul(separator + 1, &separator, 16);
1573
1574         xml_printf(&retval, &xml, &pos, &size, "<memory-map>\n");
1575
1576         /* Sort banks in ascending order.  We need to report non-flash
1577          * memory as ram (or rather read/write) by default for GDB, since
1578          * it has no concept of non-cacheable read/write memory (i/o etc).
1579          *
1580          * FIXME Most non-flash addresses are *NOT* RAM!  Don't lie.
1581          * Current versions of GDB assume unlisted addresses are RAM...
1582          */
1583         banks = malloc(sizeof(struct flash_bank *)*flash_get_bank_count());
1584
1585         for (i = 0; i < flash_get_bank_count(); i++) {
1586                 retval = get_flash_bank_by_num(i, &p);
1587                 if (retval != ERROR_OK) {
1588                         free(banks);
1589                         gdb_error(connection, retval);
1590                         return retval;
1591                 }
1592                 if (p->target == target)
1593                         banks[target_flash_banks++] = p;
1594         }
1595
1596         qsort(banks, target_flash_banks, sizeof(struct flash_bank *),
1597                 compare_bank);
1598
1599         for (i = 0; i < target_flash_banks; i++) {
1600                 int j;
1601                 unsigned sector_size = 0;
1602                 uint32_t start;
1603
1604                 p = banks[i];
1605                 start = p->base;
1606
1607                 if (ram_start < p->base)
1608                         xml_printf(&retval, &xml, &pos, &size,
1609                                 "<memory type=\"ram\" start=\"0x%x\" "
1610                                 "length=\"0x%x\"/>\n",
1611                                 ram_start, p->base - ram_start);
1612
1613                 /* Report adjacent groups of same-size sectors.  So for
1614                  * example top boot CFI flash will list an initial region
1615                  * with several large sectors (maybe 128KB) and several
1616                  * smaller ones at the end (maybe 32KB).  STR7 will have
1617                  * regions with 8KB, 32KB, and 64KB sectors; etc.
1618                  */
1619                 for (j = 0; j < p->num_sectors; j++) {
1620                         unsigned group_len;
1621
1622                         /* Maybe start a new group of sectors. */
1623                         if (sector_size == 0) {
1624                                 start = p->base + p->sectors[j].offset;
1625                                 xml_printf(&retval, &xml, &pos, &size,
1626                                         "<memory type=\"flash\" "
1627                                         "start=\"0x%x\" ",
1628                                         start);
1629                                 sector_size = p->sectors[j].size;
1630                         }
1631
1632                         /* Does this finish a group of sectors?
1633                          * If not, continue an already-started group.
1634                          */
1635                         if (j == p->num_sectors - 1)
1636                                 group_len = (p->base + p->size) - start;
1637                         else if (p->sectors[j + 1].size != sector_size)
1638                                 group_len = p->base + p->sectors[j + 1].offset
1639                                         - start;
1640                         else
1641                                 continue;
1642
1643                         xml_printf(&retval, &xml, &pos, &size,
1644                                 "length=\"0x%x\">\n"
1645                                 "<property name=\"blocksize\">"
1646                                 "0x%x</property>\n"
1647                                 "</memory>\n",
1648                                 group_len,
1649                                 sector_size);
1650                         sector_size = 0;
1651                 }
1652
1653                 ram_start = p->base + p->size;
1654         }
1655
1656         if (ram_start != 0)
1657                 xml_printf(&retval, &xml, &pos, &size,
1658                         "<memory type=\"ram\" start=\"0x%x\" "
1659                         "length=\"0x%x\"/>\n",
1660                         ram_start, 0-ram_start);
1661         /* ELSE a flash chip could be at the very end of the 32 bit address
1662          * space, in which case ram_start will be precisely 0
1663          */
1664
1665         free(banks);
1666         banks = NULL;
1667
1668         xml_printf(&retval, &xml, &pos, &size, "</memory-map>\n");
1669
1670         if (retval != ERROR_OK) {
1671                 gdb_error(connection, retval);
1672                 return retval;
1673         }
1674
1675         if (offset + length > pos)
1676                 length = pos - offset;
1677
1678         char *t = malloc(length + 1);
1679         t[0] = 'l';
1680         memcpy(t + 1, xml + offset, length);
1681         gdb_put_packet(connection, t, length + 1);
1682
1683         free(t);
1684         free(xml);
1685         return ERROR_OK;
1686 }
1687
1688 static const char *gdb_get_reg_type_name(enum reg_type type)
1689 {
1690         switch (type) {
1691                 case REG_TYPE_INT8:
1692                         return "int8";
1693                 case REG_TYPE_INT16:
1694                         return "int16";
1695                 case REG_TYPE_INT32:
1696                         return "int32";
1697                 case REG_TYPE_INT64:
1698                         return "int64";
1699                 case REG_TYPE_INT128:
1700                         return "int128";
1701                 case REG_TYPE_UINT8:
1702                         return "uint8";
1703                 case REG_TYPE_UINT16:
1704                         return "uint16";
1705                 case REG_TYPE_UINT32:
1706                         return "uint32";
1707                 case REG_TYPE_UINT64:
1708                         return "uint64";
1709                 case REG_TYPE_UINT128:
1710                         return "uint128";
1711                 case REG_TYPE_CODE_PTR:
1712                         return "code_ptr";
1713                 case REG_TYPE_DATA_PTR:
1714                         return "data_ptr";
1715                 case REG_TYPE_IEEE_SINGLE:
1716                         return "ieee_single";
1717                 case REG_TYPE_IEEE_DOUBLE:
1718                         return "ieee_double";
1719                 case REG_TYPE_ARCH_DEFINED:
1720                         return "int"; /* return arbitrary string to avoid compile warning. */
1721         }
1722
1723         return "int"; /* "int" as default value */
1724 }
1725
1726 static int gdb_generate_reg_type_description(struct target *target,
1727                 char **tdesc, int *pos, int *size, struct reg_data_type *type)
1728 {
1729         int retval = ERROR_OK;
1730
1731         if (type->type_class == REG_TYPE_CLASS_VECTOR) {
1732                 /* <vector id="id" type="type" count="count"/> */
1733                 xml_printf(&retval, tdesc, pos, size,
1734                                 "<vector id=\"%s\" type=\"%s\" count=\"%d\"/>\n",
1735                                 type->id, type->reg_type_vector->type->id,
1736                                 type->reg_type_vector->count);
1737
1738         } else if (type->type_class == REG_TYPE_CLASS_UNION) {
1739                 /* <union id="id">
1740                  *  <field name="name" type="type"/> ...
1741                  * </union> */
1742                 xml_printf(&retval, tdesc, pos, size,
1743                                 "<union id=\"%s\">\n",
1744                                 type->id);
1745
1746                 struct reg_data_type_union_field *field;
1747                 field = type->reg_type_union->fields;
1748                 while (field != NULL) {
1749                         xml_printf(&retval, tdesc, pos, size,
1750                                         "<field name=\"%s\" type=\"%s\"/>\n",
1751                                         field->name, field->type->id);
1752
1753                         field = field->next;
1754                 }
1755
1756                 xml_printf(&retval, tdesc, pos, size,
1757                                 "</union>\n");
1758
1759         } else if (type->type_class == REG_TYPE_CLASS_STRUCT) {
1760                 struct reg_data_type_struct_field *field;
1761                 field = type->reg_type_struct->fields;
1762
1763                 if (field->use_bitfields) {
1764                         /* <struct id="id" size="size">
1765                          *  <field name="name" start="start" end="end"/> ...
1766                          * </struct> */
1767                         xml_printf(&retval, tdesc, pos, size,
1768                                         "<struct id=\"%s\" size=\"%d\">\n",
1769                                         type->id, type->reg_type_struct->size);
1770                         while (field != NULL) {
1771                                 xml_printf(&retval, tdesc, pos, size,
1772                                                 "<field name=\"%s\" start=\"%d\" end=\"%d\"/>\n",
1773                                                 field->name, field->bitfield->start,
1774                                                 field->bitfield->end);
1775
1776                                 field = field->next;
1777                         }
1778                 } else {
1779                         /* <struct id="id">
1780                          *  <field name="name" type="type"/> ...
1781                          * </struct> */
1782                         xml_printf(&retval, tdesc, pos, size,
1783                                         "<struct id=\"%s\">\n",
1784                                         type->id);
1785                         while (field != NULL) {
1786                                 xml_printf(&retval, tdesc, pos, size,
1787                                                 "<field name=\"%s\" type=\"%s\"/>\n",
1788                                                 field->name, field->type->id);
1789
1790                                 field = field->next;
1791                         }
1792                 }
1793
1794                 xml_printf(&retval, tdesc, pos, size,
1795                                 "</struct>\n");
1796
1797         } else if (type->type_class == REG_TYPE_CLASS_FLAGS) {
1798                 /* <flags id="id" size="size">
1799                  *  <field name="name" start="start" end="end"/> ...
1800                  * </flags> */
1801                 xml_printf(&retval, tdesc, pos, size,
1802                                 "<flags id=\"%s\" size=\"%d\">\n",
1803                                 type->id, type->reg_type_flags->size);
1804
1805                 struct reg_data_type_flags_field *field;
1806                 field = type->reg_type_flags->fields;
1807                 while (field != NULL) {
1808                         xml_printf(&retval, tdesc, pos, size,
1809                                         "<field name=\"%s\" start=\"%d\" end=\"%d\"/>\n",
1810                                         field->name, field->bitfield->start, field->bitfield->end);
1811
1812                         field = field->next;
1813                 }
1814
1815                 xml_printf(&retval, tdesc, pos, size,
1816                                 "</flags>\n");
1817
1818         }
1819
1820         return ERROR_OK;
1821 }
1822
1823 /* Get a list of available target registers features. feature_list must
1824  * be freed by caller.
1825  */
1826 int get_reg_features_list(struct target *target, char **feature_list[], int *feature_list_size,
1827                 struct reg **reg_list, int reg_list_size)
1828 {
1829         int tbl_sz = 0;
1830
1831         /* Start with only one element */
1832         *feature_list = calloc(1, sizeof(char *));
1833
1834         for (int i = 0; i < reg_list_size; i++) {
1835                 if (reg_list[i]->exist == false)
1836                         continue;
1837
1838                 if ((reg_list[i]->feature->name != NULL)
1839                         && (strcmp(reg_list[i]->feature->name, ""))) {
1840                         /* We found a feature, check if the feature is already in the
1841                          * table. If not, allocate a new entry for the table and
1842                          * put the new feature in it.
1843                          */
1844                         for (int j = 0; j < (tbl_sz + 1); j++) {
1845                                 if (!((*feature_list)[j])) {
1846                                         (*feature_list)[tbl_sz++] = strdup(reg_list[i]->feature->name);
1847                                         *feature_list = realloc(*feature_list, sizeof(char *) * (tbl_sz + 1));
1848                                         (*feature_list)[tbl_sz] = NULL;
1849                                         break;
1850                                 } else {
1851                                         if (!strcmp((*feature_list)[j], reg_list[i]->feature->name))
1852                                                 break;
1853                                 }
1854                         }
1855                 }
1856         }
1857
1858         if (feature_list_size)
1859                 *feature_list_size = tbl_sz;
1860
1861         return ERROR_OK;
1862 }
1863
1864 static int gdb_generate_target_description(struct target *target, char **tdesc)
1865 {
1866         int retval = ERROR_OK;
1867         struct reg **reg_list;
1868         int reg_list_size;
1869         int pos = 0;
1870         int size = 0;
1871
1872         xml_printf(&retval, tdesc, &pos, &size,
1873                         "<?xml version=\"1.0\"?>\n"
1874                         "<!DOCTYPE target SYSTEM \"gdb-target.dtd\">\n"
1875                         "<target version=\"1.0\">\n");
1876
1877         retval = target_get_gdb_reg_list(target, &reg_list,
1878                         &reg_list_size, REG_CLASS_ALL);
1879
1880         if (retval != ERROR_OK) {
1881                 LOG_ERROR("get register list failed");
1882                 return ERROR_FAIL;
1883         }
1884
1885         if (reg_list_size <= 0)
1886                 return ERROR_FAIL;
1887
1888         char **features = NULL;
1889         /* Get a list of available target registers features */
1890         retval = get_reg_features_list(target, &features, NULL, reg_list, reg_list_size);
1891         if (retval != ERROR_OK) {
1892                 LOG_ERROR("Can't get the registers feature list");
1893                 return ERROR_FAIL;
1894         }
1895
1896         /* If we found some features associated with registers, create sections */
1897         int current_feature = 0;
1898
1899         /* generate target description according to register list */
1900         if (features != NULL) {
1901                 while (features[current_feature]) {
1902
1903                         xml_printf(&retval, tdesc, &pos, &size,
1904                                         "<feature name=\"%s\">\n",
1905                                         features[current_feature]);
1906
1907                         int i;
1908                         for (i = 0; i < reg_list_size; i++) {
1909
1910                                 if (reg_list[i]->exist == false)
1911                                         continue;
1912
1913                                 if (strcmp(reg_list[i]->feature->name, features[current_feature]))
1914                                         continue;
1915
1916                                 const char *type_str;
1917                                 if (reg_list[i]->reg_data_type != NULL) {
1918                                         if (reg_list[i]->reg_data_type->type == REG_TYPE_ARCH_DEFINED) {
1919                                                 /* generate <type... first, if there are architecture-defined types. */
1920                                                 gdb_generate_reg_type_description(target, tdesc, &pos, &size,
1921                                                                 reg_list[i]->reg_data_type);
1922
1923                                                 type_str = reg_list[i]->reg_data_type->id;
1924                                         } else {
1925                                                 /* predefined type */
1926                                                 type_str = gdb_get_reg_type_name(
1927                                                                 reg_list[i]->reg_data_type->type);
1928                                         }
1929                                 } else {
1930                                         /* Default type is "int" */
1931                                         type_str = "int";
1932                                 }
1933
1934                                 xml_printf(&retval, tdesc, &pos, &size,
1935                                                 "<reg name=\"%s\"", reg_list[i]->name);
1936                                 xml_printf(&retval, tdesc, &pos, &size,
1937                                                 " bitsize=\"%d\"", reg_list[i]->size);
1938                                 xml_printf(&retval, tdesc, &pos, &size,
1939                                                 " regnum=\"%d\"", reg_list[i]->number);
1940                                 if (reg_list[i]->caller_save)
1941                                         xml_printf(&retval, tdesc, &pos, &size,
1942                                                         " save-restore=\"yes\"");
1943                                 else
1944                                         xml_printf(&retval, tdesc, &pos, &size,
1945                                                         " save-restore=\"no\"");
1946
1947                                 xml_printf(&retval, tdesc, &pos, &size,
1948                                                 " type=\"%s\"", type_str);
1949
1950                                 if (reg_list[i]->group != NULL)
1951                                         xml_printf(&retval, tdesc, &pos, &size,
1952                                                         " group=\"%s\"", reg_list[i]->group);
1953
1954                                 xml_printf(&retval, tdesc, &pos, &size,
1955                                                 "/>\n");
1956                         }
1957
1958                         xml_printf(&retval, tdesc, &pos, &size,
1959                                         "</feature>\n");
1960
1961                         current_feature++;
1962                 }
1963         }
1964
1965         xml_printf(&retval, tdesc, &pos, &size,
1966                         "</target>\n");
1967
1968         if (reg_list != NULL)
1969                 free(reg_list);
1970
1971         if (features != NULL)
1972                 free(features);
1973
1974         return ERROR_OK;
1975 }
1976
1977 static int gdb_get_target_description_chunk(struct target *target, char **chunk,
1978                 int32_t offset, uint32_t length)
1979 {
1980         static char *tdesc;
1981         static uint32_t tdesc_length;
1982
1983         if (tdesc == NULL) {
1984                 gdb_generate_target_description(target, &tdesc);
1985                 tdesc_length = strlen(tdesc);
1986         }
1987
1988         char transfer_type;
1989
1990         if (length < (tdesc_length - offset))
1991                 transfer_type = 'm';
1992         else
1993                 transfer_type = 'l';
1994
1995         *chunk = malloc(length + 2);
1996         (*chunk)[0] = transfer_type;
1997         if (transfer_type == 'm') {
1998                 strncpy((*chunk) + 1, tdesc + offset, length);
1999                 (*chunk)[1 + length] = '\0';
2000         } else {
2001                 strncpy((*chunk) + 1, tdesc + offset, tdesc_length - offset);
2002                 (*chunk)[1 + (tdesc_length - offset)] = '\0';
2003
2004                 /* After gdb-server sends out last chunk, invalidate tdesc. */
2005                 free(tdesc);
2006                 tdesc = NULL;
2007                 tdesc_length = 0;
2008         }
2009
2010         return ERROR_OK;
2011 }
2012
2013 static int gdb_query_packet(struct connection *connection,
2014                 char *packet, int packet_size)
2015 {
2016         struct command_context *cmd_ctx = connection->cmd_ctx;
2017         struct gdb_connection *gdb_connection = connection->priv;
2018         struct target *target = get_target_from_connection(connection);
2019
2020         if (strncmp(packet, "qRcmd,", 6) == 0) {
2021                 if (packet_size > 6) {
2022                         char *cmd;
2023                         cmd = malloc((packet_size - 6) / 2 + 1);
2024                         int len = unhexify(cmd, packet + 6, (packet_size - 6) / 2);
2025                         cmd[len] = 0;
2026
2027                         /* We want to print all debug output to GDB connection */
2028                         log_add_callback(gdb_log_callback, connection);
2029                         target_call_timer_callbacks_now();
2030                         /* some commands need to know the GDB connection, make note of current
2031                          * GDB connection. */
2032                         current_gdb_connection = gdb_connection;
2033                         command_run_line(cmd_ctx, cmd);
2034                         current_gdb_connection = NULL;
2035                         target_call_timer_callbacks_now();
2036                         log_remove_callback(gdb_log_callback, connection);
2037                         free(cmd);
2038                 }
2039                 gdb_put_packet(connection, "OK", 2);
2040                 return ERROR_OK;
2041         } else if (strncmp(packet, "qCRC:", 5) == 0) {
2042                 if (packet_size > 5) {
2043                         int retval;
2044                         char gdb_reply[10];
2045                         char *separator;
2046                         uint32_t checksum;
2047                         uint32_t addr = 0;
2048                         uint32_t len = 0;
2049
2050                         /* skip command character */
2051                         packet += 5;
2052
2053                         addr = strtoul(packet, &separator, 16);
2054
2055                         if (*separator != ',') {
2056                                 LOG_ERROR("incomplete read memory packet received, dropping connection");
2057                                 return ERROR_SERVER_REMOTE_CLOSED;
2058                         }
2059
2060                         len = strtoul(separator + 1, NULL, 16);
2061
2062                         retval = target_checksum_memory(target, addr, len, &checksum);
2063
2064                         if (retval == ERROR_OK) {
2065                                 snprintf(gdb_reply, 10, "C%8.8" PRIx32 "", checksum);
2066                                 gdb_put_packet(connection, gdb_reply, 9);
2067                         } else {
2068                                 retval = gdb_error(connection, retval);
2069                                 if (retval != ERROR_OK)
2070                                         return retval;
2071                         }
2072
2073                         return ERROR_OK;
2074                 }
2075         } else if (strncmp(packet, "qSupported", 10) == 0) {
2076                 /* we currently support packet size and qXfer:memory-map:read (if enabled)
2077                  * disable qXfer:features:read for the moment */
2078                 int retval = ERROR_OK;
2079                 char *buffer = NULL;
2080                 int pos = 0;
2081                 int size = 0;
2082
2083                 xml_printf(&retval,
2084                         &buffer,
2085                         &pos,
2086                         &size,
2087                         "PacketSize=%x;qXfer:memory-map:read%c;qXfer:features:read%c;QStartNoAckMode+",
2088                         (GDB_BUFFER_SIZE - 1),
2089                         ((gdb_use_memory_map == 1) && (flash_get_bank_count() > 0)) ? '+' : '-',
2090                         (gdb_use_target_description == 1) ? '+' : '-');
2091
2092                 if (retval != ERROR_OK) {
2093                         gdb_send_error(connection, 01);
2094                         return ERROR_OK;
2095                 }
2096
2097                 gdb_put_packet(connection, buffer, strlen(buffer));
2098                 free(buffer);
2099
2100                 return ERROR_OK;
2101         } else if ((strncmp(packet, "qXfer:memory-map:read::", 23) == 0)
2102                    && (flash_get_bank_count() > 0))
2103                 return gdb_memory_map(connection, packet, packet_size);
2104         else if (strncmp(packet, "qXfer:features:read:", 20) == 0) {
2105                 char *xml = NULL;
2106                 int retval = ERROR_OK;
2107
2108                 int offset;
2109                 unsigned int length;
2110                 char *annex;
2111
2112                 /* skip command character */
2113                 packet += 20;
2114
2115                 if (decode_xfer_read(packet, &annex, &offset, &length) < 0) {
2116                         gdb_send_error(connection, 01);
2117                         return ERROR_OK;
2118                 }
2119
2120                 /* Target should prepare correct target description for annex.
2121                  * The first character of returned xml is 'm' or 'l'. 'm' for
2122                  * there are *more* chunks to transfer. 'l' for it is the *last*
2123                  * chunk of target description.
2124                  */
2125                 retval = gdb_get_target_description_chunk(target, &xml, offset, length);
2126                 if (retval != ERROR_OK) {
2127                         gdb_error(connection, retval);
2128                         return retval;
2129                 }
2130
2131                 gdb_put_packet(connection, xml, strlen(xml));
2132
2133                 free(xml);
2134                 return ERROR_OK;
2135         } else if (strncmp(packet, "QStartNoAckMode", 15) == 0) {
2136                 gdb_connection->noack_mode = 1;
2137                 gdb_put_packet(connection, "OK", 2);
2138                 return ERROR_OK;
2139         }
2140
2141         gdb_put_packet(connection, "", 0);
2142         return ERROR_OK;
2143 }
2144
2145 static int gdb_v_packet(struct connection *connection,
2146                 char *packet, int packet_size)
2147 {
2148         struct gdb_connection *gdb_connection = connection->priv;
2149         struct gdb_service *gdb_service = connection->service->priv;
2150         int result;
2151
2152         /* if flash programming disabled - send a empty reply */
2153
2154         if (gdb_flash_program == 0) {
2155                 gdb_put_packet(connection, "", 0);
2156                 return ERROR_OK;
2157         }
2158
2159         if (strncmp(packet, "vFlashErase:", 12) == 0) {
2160                 unsigned long addr;
2161                 unsigned long length;
2162
2163                 char *parse = packet + 12;
2164                 if (*parse == '\0') {
2165                         LOG_ERROR("incomplete vFlashErase packet received, dropping connection");
2166                         return ERROR_SERVER_REMOTE_CLOSED;
2167                 }
2168
2169                 addr = strtoul(parse, &parse, 16);
2170
2171                 if (*(parse++) != ',' || *parse == '\0') {
2172                         LOG_ERROR("incomplete vFlashErase packet received, dropping connection");
2173                         return ERROR_SERVER_REMOTE_CLOSED;
2174                 }
2175
2176                 length = strtoul(parse, &parse, 16);
2177
2178                 if (*parse != '\0') {
2179                         LOG_ERROR("incomplete vFlashErase packet received, dropping connection");
2180                         return ERROR_SERVER_REMOTE_CLOSED;
2181                 }
2182
2183                 /* assume all sectors need erasing - stops any problems
2184                  * when flash_write is called multiple times */
2185                 flash_set_dirty();
2186
2187                 /* perform any target specific operations before the erase */
2188                 target_call_event_callbacks(gdb_service->target,
2189                         TARGET_EVENT_GDB_FLASH_ERASE_START);
2190
2191                 /* vFlashErase:addr,length messages require region start and
2192                  * end to be "block" aligned ... if padding is ever needed,
2193                  * GDB will have become dangerously confused.
2194                  */
2195                 result = flash_erase_address_range(gdb_service->target,
2196                                 false, addr, length);
2197
2198                 /* perform any target specific operations after the erase */
2199                 target_call_event_callbacks(gdb_service->target,
2200                         TARGET_EVENT_GDB_FLASH_ERASE_END);
2201
2202                 /* perform erase */
2203                 if (result != ERROR_OK) {
2204                         /* GDB doesn't evaluate the actual error number returned,
2205                          * treat a failed erase as an I/O error
2206                          */
2207                         gdb_send_error(connection, EIO);
2208                         LOG_ERROR("flash_erase returned %i", result);
2209                 } else
2210                         gdb_put_packet(connection, "OK", 2);
2211
2212                 return ERROR_OK;
2213         }
2214
2215         if (strncmp(packet, "vFlashWrite:", 12) == 0) {
2216                 int retval;
2217                 unsigned long addr;
2218                 unsigned long length;
2219                 char *parse = packet + 12;
2220
2221                 if (*parse == '\0') {
2222                         LOG_ERROR("incomplete vFlashErase packet received, dropping connection");
2223                         return ERROR_SERVER_REMOTE_CLOSED;
2224                 }
2225                 addr = strtoul(parse, &parse, 16);
2226                 if (*(parse++) != ':') {
2227                         LOG_ERROR("incomplete vFlashErase packet received, dropping connection");
2228                         return ERROR_SERVER_REMOTE_CLOSED;
2229                 }
2230                 length = packet_size - (parse - packet);
2231
2232                 /* create a new image if there isn't already one */
2233                 if (gdb_connection->vflash_image == NULL) {
2234                         gdb_connection->vflash_image = malloc(sizeof(struct image));
2235                         image_open(gdb_connection->vflash_image, "", "build");
2236                 }
2237
2238                 /* create new section with content from packet buffer */
2239                 retval = image_add_section(gdb_connection->vflash_image,
2240                                 addr, length, 0x0, (uint8_t *)parse);
2241                 if (retval != ERROR_OK)
2242                         return retval;
2243
2244                 gdb_put_packet(connection, "OK", 2);
2245
2246                 return ERROR_OK;
2247         }
2248
2249         if (strncmp(packet, "vFlashDone", 10) == 0) {
2250                 uint32_t written;
2251
2252                 /* process the flashing buffer. No need to erase as GDB
2253                  * always issues a vFlashErase first. */
2254                 target_call_event_callbacks(gdb_service->target,
2255                                 TARGET_EVENT_GDB_FLASH_WRITE_START);
2256                 result = flash_write(gdb_service->target, gdb_connection->vflash_image, &written, 0);
2257                 target_call_event_callbacks(gdb_service->target, TARGET_EVENT_GDB_FLASH_WRITE_END);
2258                 if (result != ERROR_OK) {
2259                         if (result == ERROR_FLASH_DST_OUT_OF_BANK)
2260                                 gdb_put_packet(connection, "E.memtype", 9);
2261                         else
2262                                 gdb_send_error(connection, EIO);
2263                 } else {
2264                         LOG_DEBUG("wrote %u bytes from vFlash image to flash", (unsigned)written);
2265                         gdb_put_packet(connection, "OK", 2);
2266                 }
2267
2268                 image_close(gdb_connection->vflash_image);
2269                 free(gdb_connection->vflash_image);
2270                 gdb_connection->vflash_image = NULL;
2271
2272                 return ERROR_OK;
2273         }
2274
2275         gdb_put_packet(connection, "", 0);
2276         return ERROR_OK;
2277 }
2278
2279 static int gdb_detach(struct connection *connection)
2280 {
2281         struct gdb_service *gdb_service = connection->service->priv;
2282
2283         target_call_event_callbacks(gdb_service->target, TARGET_EVENT_GDB_DETACH);
2284
2285         return gdb_put_packet(connection, "OK", 2);
2286 }
2287
2288 static void gdb_log_callback(void *priv, const char *file, unsigned line,
2289                 const char *function, const char *string)
2290 {
2291         struct connection *connection = priv;
2292         struct gdb_connection *gdb_con = connection->priv;
2293
2294         if (gdb_con->busy) {
2295                 /* do not reply this using the O packet */
2296                 return;
2297         }
2298
2299         gdb_output_con(connection, string);
2300 }
2301
2302 static void gdb_sig_halted(struct connection *connection)
2303 {
2304         char sig_reply[4];
2305         snprintf(sig_reply, 4, "T%2.2x", 2);
2306         gdb_put_packet(connection, sig_reply, 3);
2307 }
2308
2309 static int gdb_input_inner(struct connection *connection)
2310 {
2311         /* Do not allocate this on the stack */
2312         static char gdb_packet_buffer[GDB_BUFFER_SIZE];
2313
2314         struct gdb_service *gdb_service = connection->service->priv;
2315         struct target *target = gdb_service->target;
2316         char *packet = gdb_packet_buffer;
2317         int packet_size;
2318         int retval;
2319         struct gdb_connection *gdb_con = connection->priv;
2320         static int extended_protocol;
2321
2322         /* drain input buffer. If one of the packets fail, then an error
2323          * packet is replied, if applicable.
2324          *
2325          * This loop will terminate and the error code is returned.
2326          *
2327          * The calling fn will check if this error is something that
2328          * can be recovered from, or if the connection must be closed.
2329          *
2330          * If the error is recoverable, this fn is called again to
2331          * drain the rest of the buffer.
2332          */
2333         do {
2334                 packet_size = GDB_BUFFER_SIZE-1;
2335                 retval = gdb_get_packet(connection, packet, &packet_size);
2336                 if (retval != ERROR_OK)
2337                         return retval;
2338
2339                 /* terminate with zero */
2340                 packet[packet_size] = 0;
2341
2342                 if (LOG_LEVEL_IS(LOG_LVL_DEBUG)) {
2343                         if (packet[0] == 'X') {
2344                                 /* binary packets spew junk into the debug log stream */
2345                                 char buf[50];
2346                                 int x;
2347                                 for (x = 0; (x < 49) && (packet[x] != ':'); x++)
2348                                         buf[x] = packet[x];
2349                                 buf[x] = 0;
2350                                 LOG_DEBUG("received packet: '%s:<binary-data>'", buf);
2351                         } else
2352                                 LOG_DEBUG("received packet: '%s'", packet);
2353                 }
2354
2355                 if (packet_size > 0) {
2356                         retval = ERROR_OK;
2357                         switch (packet[0]) {
2358                                 case 'T':       /* Is thread alive? */
2359                                         gdb_thread_packet(connection, packet, packet_size);
2360                                         break;
2361                                 case 'H':       /* Set current thread ( 'c' for step and continue,
2362                                                          * 'g' for all other operations ) */
2363                                         gdb_thread_packet(connection, packet, packet_size);
2364                                         break;
2365                                 case 'q':
2366                                 case 'Q':
2367                                         retval = gdb_thread_packet(connection, packet, packet_size);
2368                                         if (retval == GDB_THREAD_PACKET_NOT_CONSUMED)
2369                                                 retval = gdb_query_packet(connection, packet, packet_size);
2370                                         break;
2371                                 case 'g':
2372                                         retval = gdb_get_registers_packet(connection, packet, packet_size);
2373                                         break;
2374                                 case 'G':
2375                                         retval = gdb_set_registers_packet(connection, packet, packet_size);
2376                                         break;
2377                                 case 'p':
2378                                         retval = gdb_get_register_packet(connection, packet, packet_size);
2379                                         break;
2380                                 case 'P':
2381                                         retval = gdb_set_register_packet(connection, packet, packet_size);
2382                                         break;
2383                                 case 'm':
2384                                         retval = gdb_read_memory_packet(connection, packet, packet_size);
2385                                         break;
2386                                 case 'M':
2387                                         retval = gdb_write_memory_packet(connection, packet, packet_size);
2388                                         break;
2389                                 case 'z':
2390                                 case 'Z':
2391                                         retval = gdb_breakpoint_watchpoint_packet(connection, packet, packet_size);
2392                                         break;
2393                                 case '?':
2394                                         gdb_last_signal_packet(connection, packet, packet_size);
2395                                         break;
2396                                 case 'c':
2397                                 case 's':
2398                                 {
2399                                         gdb_thread_packet(connection, packet, packet_size);
2400                                         log_add_callback(gdb_log_callback, connection);
2401
2402                                         if (gdb_con->mem_write_error) {
2403                                                 LOG_ERROR("Memory write failure!");
2404
2405                                                 /* now that we have reported the memory write error,
2406                                                  * we can clear the condition */
2407                                                 gdb_con->mem_write_error = false;
2408                                         }
2409
2410                                         bool nostep = false;
2411                                         bool already_running = false;
2412                                         if (target->state == TARGET_RUNNING) {
2413                                                 LOG_WARNING("WARNING! The target is already running. "
2414                                                                 "All changes GDB did to registers will be discarded! "
2415                                                                 "Waiting for target to halt.");
2416                                                 already_running = true;
2417                                         } else if (target->state != TARGET_HALTED) {
2418                                                 LOG_WARNING("The target is not in the halted nor running stated, " \
2419                                                                 "stepi/continue ignored.");
2420                                                 nostep = true;
2421                                         } else if ((packet[0] == 's') && gdb_con->sync) {
2422                                                 /* Hmm..... when you issue a continue in GDB, then a "stepi" is
2423                                                  * sent by GDB first to OpenOCD, thus defeating the check to
2424                                                  * make only the single stepping have the sync feature...
2425                                                  */
2426                                                 nostep = true;
2427                                                 LOG_WARNING("stepi ignored. GDB will now fetch the register state " \
2428                                                                 "from the target.");
2429                                         }
2430                                         gdb_con->sync = false;
2431
2432                                         if (!already_running && nostep) {
2433                                                 /* Either the target isn't in the halted state, then we can't
2434                                                  * step/continue. This might be early setup, etc.
2435                                                  *
2436                                                  * Or we want to allow GDB to pick up a fresh set of
2437                                                  * register values without modifying the target state.
2438                                                  *
2439                                                  */
2440                                                 gdb_sig_halted(connection);
2441
2442                                                 /* stop forwarding log packets! */
2443                                                 log_remove_callback(gdb_log_callback, connection);
2444                                         } else {
2445                                                 /* We're running/stepping, in which case we can
2446                                                  * forward log output until the target is halted
2447                                                  */
2448                                                 gdb_con->frontend_state = TARGET_RUNNING;
2449                                                 target_call_event_callbacks(target, TARGET_EVENT_GDB_START);
2450
2451                                                 if (!already_running) {
2452                                                         /* Here we don't want packet processing to stop even if this fails,
2453                                                          * so we use a local variable instead of retval. */
2454                                                         retval = gdb_step_continue_packet(connection, packet, packet_size);
2455                                                         if (retval != ERROR_OK) {
2456                                                                 /* we'll never receive a halted
2457                                                                  * condition... issue a false one..
2458                                                                  */
2459                                                                 gdb_frontend_halted(target, connection);
2460                                                         }
2461                                                 }
2462                                         }
2463                                 }
2464                                 break;
2465                                 case 'v':
2466                                         retval = gdb_v_packet(connection, packet, packet_size);
2467                                         break;
2468                                 case 'D':
2469                                         retval = gdb_detach(connection);
2470                                         extended_protocol = 0;
2471                                         break;
2472                                 case 'X':
2473                                         retval = gdb_write_memory_binary_packet(connection, packet, packet_size);
2474                                         if (retval != ERROR_OK)
2475                                                 return retval;
2476                                         break;
2477                                 case 'k':
2478                                         if (extended_protocol != 0) {
2479                                                 gdb_con->attached = false;
2480                                                 break;
2481                                         }
2482                                         gdb_put_packet(connection, "OK", 2);
2483                                         return ERROR_SERVER_REMOTE_CLOSED;
2484                                 case '!':
2485                                         /* handle extended remote protocol */
2486                                         extended_protocol = 1;
2487                                         gdb_put_packet(connection, "OK", 2);
2488                                         break;
2489                                 case 'R':
2490                                         /* handle extended restart packet */
2491                                         breakpoint_clear_target(gdb_service->target);
2492                                         watchpoint_clear_target(gdb_service->target);
2493                                         command_run_linef(connection->cmd_ctx, "ocd_gdb_restart %s",
2494                                                         target_name(target));
2495                                         /* set connection as attached after reset */
2496                                         gdb_con->attached = true;
2497                                         /*  info rtos parts */
2498                                         gdb_thread_packet(connection, packet, packet_size);
2499                                         break;
2500
2501                                 case 'j':
2502                                         /* packet supported only by smp target i.e cortex_a.c*/
2503                                         /* handle smp packet replying coreid played to gbd */
2504                                         gdb_read_smp_packet(connection, packet, packet_size);
2505                                         break;
2506
2507                                 case 'J':
2508                                         /* packet supported only by smp target i.e cortex_a.c */
2509                                         /* handle smp packet setting coreid to be played at next
2510                                          * resume to gdb */
2511                                         gdb_write_smp_packet(connection, packet, packet_size);
2512                                         break;
2513
2514                                 default:
2515                                         /* ignore unknown packets */
2516                                         LOG_DEBUG("ignoring 0x%2.2x packet", packet[0]);
2517                                         gdb_put_packet(connection, NULL, 0);
2518                                         break;
2519                         }
2520
2521                         /* if a packet handler returned an error, exit input loop */
2522                         if (retval != ERROR_OK)
2523                                 return retval;
2524                 }
2525
2526                 if (gdb_con->ctrl_c) {
2527                         if (target->state == TARGET_RUNNING) {
2528                                 retval = target_halt(target);
2529                                 if (retval != ERROR_OK)
2530                                         target_call_event_callbacks(target, TARGET_EVENT_GDB_HALT);
2531                                 gdb_con->ctrl_c = 0;
2532                         } else {
2533                                 LOG_INFO("The target is not running when halt was requested, stopping GDB.");
2534                                 target_call_event_callbacks(target, TARGET_EVENT_GDB_HALT);
2535                         }
2536                 }
2537
2538         } while (gdb_con->buf_cnt > 0);
2539
2540         return ERROR_OK;
2541 }
2542
2543 static int gdb_input(struct connection *connection)
2544 {
2545         int retval = gdb_input_inner(connection);
2546         struct gdb_connection *gdb_con = connection->priv;
2547         if (retval == ERROR_SERVER_REMOTE_CLOSED)
2548                 return retval;
2549
2550         /* logging does not propagate the error, yet can set the gdb_con->closed flag */
2551         if (gdb_con->closed)
2552                 return ERROR_SERVER_REMOTE_CLOSED;
2553
2554         /* we'll recover from any other errors(e.g. temporary timeouts, etc.) */
2555         return ERROR_OK;
2556 }
2557
2558 static int gdb_target_start(struct target *target, const char *port)
2559 {
2560         struct gdb_service *gdb_service;
2561         int ret;
2562         gdb_service = malloc(sizeof(struct gdb_service));
2563
2564         if (NULL == gdb_service)
2565                 return -ENOMEM;
2566
2567         gdb_service->target = target;
2568         gdb_service->core[0] = -1;
2569         gdb_service->core[1] = -1;
2570         target->gdb_service = gdb_service;
2571
2572         ret = add_service("gdb",
2573                         port, 1, &gdb_new_connection, &gdb_input,
2574                         &gdb_connection_closed, gdb_service);
2575         /* initialialize all targets gdb service with the same pointer */
2576         {
2577                 struct target_list *head;
2578                 struct target *curr;
2579                 head = target->head;
2580                 while (head != (struct target_list *)NULL) {
2581                         curr = head->target;
2582                         if (curr != target)
2583                                 curr->gdb_service = gdb_service;
2584                         head = head->next;
2585                 }
2586         }
2587         return ret;
2588 }
2589
2590 static int gdb_target_add_one(struct target *target)
2591 {
2592         /*  one gdb instance per smp list */
2593         if ((target->smp) && (target->gdb_service))
2594                 return ERROR_OK;
2595         int retval = gdb_target_start(target, gdb_port_next);
2596         if (retval == ERROR_OK) {
2597                 long portnumber;
2598                 /* If we can parse the port number
2599                  * then we increment the port number for the next target.
2600                  */
2601                 char *end;
2602                 portnumber = strtol(gdb_port_next, &end, 0);
2603                 if (!*end) {
2604                         if (parse_long(gdb_port_next, &portnumber) == ERROR_OK) {
2605                                 free((void *)gdb_port_next);
2606                                 gdb_port_next = alloc_printf("%d", portnumber+1);
2607                         }
2608                 }
2609         }
2610         return retval;
2611 }
2612
2613 int gdb_target_add_all(struct target *target)
2614 {
2615         if (NULL == target) {
2616                 LOG_WARNING("gdb services need one or more targets defined");
2617                 return ERROR_OK;
2618         }
2619
2620         while (NULL != target) {
2621                 int retval = gdb_target_add_one(target);
2622                 if (ERROR_OK != retval)
2623                         return retval;
2624
2625                 target = target->next;
2626         }
2627
2628         return ERROR_OK;
2629 }
2630
2631 COMMAND_HANDLER(handle_gdb_sync_command)
2632 {
2633         if (CMD_ARGC != 0)
2634                 return ERROR_COMMAND_SYNTAX_ERROR;
2635
2636         if (current_gdb_connection == NULL) {
2637                 command_print(CMD_CTX,
2638                         "gdb_sync command can only be run from within gdb using \"monitor gdb_sync\"");
2639                 return ERROR_FAIL;
2640         }
2641
2642         current_gdb_connection->sync = true;
2643
2644         return ERROR_OK;
2645 }
2646
2647 /* daemon configuration command gdb_port */
2648 COMMAND_HANDLER(handle_gdb_port_command)
2649 {
2650         int retval = CALL_COMMAND_HANDLER(server_pipe_command, &gdb_port);
2651         if (ERROR_OK == retval) {
2652                 free((void *)gdb_port_next);
2653                 gdb_port_next = strdup(gdb_port);
2654         }
2655         return retval;
2656 }
2657
2658 COMMAND_HANDLER(handle_gdb_memory_map_command)
2659 {
2660         if (CMD_ARGC != 1)
2661                 return ERROR_COMMAND_SYNTAX_ERROR;
2662
2663         COMMAND_PARSE_ENABLE(CMD_ARGV[0], gdb_use_memory_map);
2664         return ERROR_OK;
2665 }
2666
2667 COMMAND_HANDLER(handle_gdb_flash_program_command)
2668 {
2669         if (CMD_ARGC != 1)
2670                 return ERROR_COMMAND_SYNTAX_ERROR;
2671
2672         COMMAND_PARSE_ENABLE(CMD_ARGV[0], gdb_flash_program);
2673         return ERROR_OK;
2674 }
2675
2676 COMMAND_HANDLER(handle_gdb_report_data_abort_command)
2677 {
2678         if (CMD_ARGC != 1)
2679                 return ERROR_COMMAND_SYNTAX_ERROR;
2680
2681         COMMAND_PARSE_ENABLE(CMD_ARGV[0], gdb_report_data_abort);
2682         return ERROR_OK;
2683 }
2684
2685 /* gdb_breakpoint_override */
2686 COMMAND_HANDLER(handle_gdb_breakpoint_override_command)
2687 {
2688         if (CMD_ARGC == 0) {
2689                 /* nothing */
2690         } else if (CMD_ARGC == 1) {
2691                 gdb_breakpoint_override = 1;
2692                 if (strcmp(CMD_ARGV[0], "hard") == 0)
2693                         gdb_breakpoint_override_type = BKPT_HARD;
2694                 else if (strcmp(CMD_ARGV[0], "soft") == 0)
2695                         gdb_breakpoint_override_type = BKPT_SOFT;
2696                 else if (strcmp(CMD_ARGV[0], "disable") == 0)
2697                         gdb_breakpoint_override = 0;
2698         } else
2699                 return ERROR_COMMAND_SYNTAX_ERROR;
2700         if (gdb_breakpoint_override)
2701                 LOG_USER("force %s breakpoints",
2702                         (gdb_breakpoint_override_type == BKPT_HARD) ? "hard" : "soft");
2703         else
2704                 LOG_USER("breakpoint type is not overridden");
2705
2706         return ERROR_OK;
2707 }
2708
2709 COMMAND_HANDLER(handle_gdb_target_description_command)
2710 {
2711         if (CMD_ARGC != 1)
2712                 return ERROR_COMMAND_SYNTAX_ERROR;
2713
2714         COMMAND_PARSE_ENABLE(CMD_ARGV[0], gdb_use_target_description);
2715         return ERROR_OK;
2716 }
2717
2718 COMMAND_HANDLER(handle_gdb_save_tdesc_command)
2719 {
2720         static char *tdesc;
2721         static uint32_t tdesc_length;
2722         struct target *target = get_current_target(CMD_CTX);
2723         char *tdesc_filename;
2724
2725         if (tdesc == NULL) {
2726                 gdb_generate_target_description(target, &tdesc);
2727                 tdesc_length = strlen(tdesc);
2728         }
2729
2730         struct fileio fileio;
2731         size_t size_written;
2732
2733         tdesc_filename = malloc(strlen(target_type_name(target)) + 5);
2734         sprintf(tdesc_filename, "%s.xml", target_type_name(target));
2735
2736         int retval = fileio_open(&fileio, tdesc_filename, FILEIO_WRITE, FILEIO_TEXT);
2737
2738         free(tdesc_filename);
2739
2740         if (retval != ERROR_OK) {
2741                 LOG_WARNING("Can't open %s for writing", tdesc_filename);
2742                 return ERROR_FAIL;
2743         }
2744
2745         retval = fileio_write(&fileio, tdesc_length, tdesc, &size_written);
2746
2747         fileio_close(&fileio);
2748
2749         if (retval != ERROR_OK) {
2750                 LOG_WARNING("Error while writing the tdesc file");
2751                 return ERROR_FAIL;
2752         }
2753
2754         return ERROR_OK;
2755 }
2756
2757 static const struct command_registration gdb_command_handlers[] = {
2758         {
2759                 .name = "gdb_sync",
2760                 .handler = handle_gdb_sync_command,
2761                 .mode = COMMAND_ANY,
2762                 .help = "next stepi will return immediately allowing "
2763                         "GDB to fetch register state without affecting "
2764                         "target state",
2765                 .usage = ""
2766         },
2767         {
2768                 .name = "gdb_port",
2769                 .handler = handle_gdb_port_command,
2770                 .mode = COMMAND_ANY,
2771                 .help = "Normally gdb listens to a TCP/IP port. Each subsequent GDB "
2772                         "server listens for the next port number after the "
2773                         "base port number specified. "
2774                         "No arguments reports GDB port. \"pipe\" means listen to stdin "
2775                         "output to stdout, an integer is base port number, \"disable\" disables "
2776                         "port. Any other string is are interpreted as named pipe to listen to. "
2777                         "Output pipe is the same name as input pipe, but with 'o' appended.",
2778                 .usage = "[port_num]",
2779         },
2780         {
2781                 .name = "gdb_memory_map",
2782                 .handler = handle_gdb_memory_map_command,
2783                 .mode = COMMAND_CONFIG,
2784                 .help = "enable or disable memory map",
2785                 .usage = "('enable'|'disable')"
2786         },
2787         {
2788                 .name = "gdb_flash_program",
2789                 .handler = handle_gdb_flash_program_command,
2790                 .mode = COMMAND_CONFIG,
2791                 .help = "enable or disable flash program",
2792                 .usage = "('enable'|'disable')"
2793         },
2794         {
2795                 .name = "gdb_report_data_abort",
2796                 .handler = handle_gdb_report_data_abort_command,
2797                 .mode = COMMAND_CONFIG,
2798                 .help = "enable or disable reporting data aborts",
2799                 .usage = "('enable'|'disable')"
2800         },
2801         {
2802                 .name = "gdb_breakpoint_override",
2803                 .handler = handle_gdb_breakpoint_override_command,
2804                 .mode = COMMAND_ANY,
2805                 .help = "Display or specify type of breakpoint "
2806                         "to be used by gdb 'break' commands.",
2807                 .usage = "('hard'|'soft'|'disable')"
2808         },
2809         {
2810                 .name = "gdb_target_description",
2811                 .handler = handle_gdb_target_description_command,
2812                 .mode = COMMAND_CONFIG,
2813                 .help = "enable or disable target description",
2814                 .usage = "('enable'|'disable')"
2815         },
2816         {
2817                 .name = "gdb_save_tdesc",
2818                 .handler = handle_gdb_save_tdesc_command,
2819                 .mode = COMMAND_EXEC,
2820                 .help = "Save the target description file",
2821         },
2822         COMMAND_REGISTRATION_DONE
2823 };
2824
2825 int gdb_register_commands(struct command_context *cmd_ctx)
2826 {
2827         gdb_port = strdup("3333");
2828         gdb_port_next = strdup("3333");
2829         return register_commands(cmd_ctx, NULL, gdb_command_handlers);
2830 }