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