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