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