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