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