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