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