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