wait 500ms for target to halt upon connect.
[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         int gotdata;
291         for (;;)
292         {
293                 if ((retval=check_pending(connection, 0, &gotdata))!=ERROR_OK)
294                         return retval;
295                 if (!gotdata)
296                         break;
297                 if ((retval = gdb_get_char(connection, &reply)) != ERROR_OK)
298                         return retval;
299                 LOG_WARNING("Discard unexpected char %c", reply);
300         }
301 #endif
302
303         while (1)
304         {
305 #ifdef _DEBUG_GDB_IO_
306                 debug_buffer = malloc(len + 1);
307                 memcpy(debug_buffer, buffer, len);
308                 debug_buffer[len] = 0;
309                 LOG_DEBUG("sending packet '$%s#%2.2x'", debug_buffer, my_checksum);
310                 free(debug_buffer);
311 #endif
312
313                 char local_buffer[1024];
314                 local_buffer[0] = '$';
315                 if (len+4 <= sizeof(local_buffer))
316                 {
317                         /* performance gain on smaller packets by only a single call to gdb_write() */
318                         memcpy(local_buffer+1, buffer, len++);
319                         local_buffer[len++] = '#';
320                         local_buffer[len++] = DIGITS[(my_checksum >> 4) & 0xf];
321                         local_buffer[len++] = DIGITS[my_checksum & 0xf];
322                         gdb_write(connection, local_buffer, len);
323                 }
324                 else
325                 {
326                         /* larger packets are transmitted directly from caller supplied buffer
327                            by several calls to gdb_write() to avoid dynamic allocation */
328                         local_buffer[1] = '#';
329                         local_buffer[2] = DIGITS[(my_checksum >> 4) & 0xf];
330                         local_buffer[3] = DIGITS[my_checksum & 0xf];
331                         gdb_write(connection, local_buffer, 1);
332                         gdb_write(connection, buffer, len);
333                         gdb_write(connection, local_buffer+1, 3);
334                 }
335
336                 if ((retval = gdb_get_char(connection, &reply)) != ERROR_OK)
337                         return retval;
338
339                 if (reply == '+')
340                         break;
341                 else if (reply == '-')
342                 {
343                         /* Stop sending output packets for now */
344                         log_remove_callback(gdb_log_callback, connection);
345                         LOG_WARNING("negative reply, retrying");
346                 }
347                 else if (reply == 0x3)
348                 {
349                         gdb_con->ctrl_c = 1;
350                         if ((retval = gdb_get_char(connection, &reply)) != ERROR_OK)
351                                 return retval;
352                         if (reply == '+')
353                                 break;
354                         else if (reply == '-')
355                         {
356                                 /* Stop sending output packets for now */
357                                 log_remove_callback(gdb_log_callback, connection);
358                                 LOG_WARNING("negative reply, retrying");
359                         }
360                         else
361                         {
362                                 LOG_ERROR("unknown character 0x%2.2x in reply, dropping connection", reply);
363                                 gdb_con->closed=1;
364                                 return ERROR_SERVER_REMOTE_CLOSED;
365                         }
366                 }
367                 else
368                 {
369                         LOG_ERROR("unknown character 0x%2.2x in reply, dropping connection", reply);
370                         gdb_con->closed=1;
371                         return ERROR_SERVER_REMOTE_CLOSED;
372                 }
373         }
374         if (gdb_con->closed)
375                 return ERROR_SERVER_REMOTE_CLOSED;
376
377         return ERROR_OK;
378 }
379
380 int gdb_put_packet(connection_t *connection, char *buffer, int len)
381 {
382         gdb_connection_t *gdb_con = connection->priv;
383         gdb_con->busy = 1;
384         int retval = gdb_put_packet_inner(connection, buffer, len);
385         gdb_con->busy = 0;
386         return retval;
387 }
388
389 int gdb_get_packet_inner(connection_t *connection, char *buffer, int *len)
390 {
391         int character;
392         int count = 0;
393         int retval;
394         char checksum[3];
395         unsigned char my_checksum = 0;
396         gdb_connection_t *gdb_con = connection->priv;
397
398         while (1)
399         {
400                 do
401                 {
402                         if ((retval = gdb_get_char(connection, &character)) != ERROR_OK)
403                                 return retval;
404
405 #ifdef _DEBUG_GDB_IO_
406                         LOG_DEBUG("character: '%c'", character);
407 #endif
408
409                         switch (character)
410                         {
411                                 case '$':
412                                         break;
413                                 case '+':
414                                         /* gdb sends a dummy ack '+' at every remote connect - see remote_start_remote (remote.c)
415                                          * incase anyone tries to debug why they receive this warning every time */
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         /* FIX!!!! could extended-remote work better here?
683          * 
684          *  wait a tiny bit for halted state or we just continue. The
685          * GDB register packet will then contain garbage 
686          */
687         target_wait_state(gdb_service->target, TARGET_HALTED, 500);
688         
689         /* remove the initial ACK from the incoming buffer */
690         if ((retval = gdb_get_char(connection, &initial_ack)) != ERROR_OK)
691                 return retval;
692
693         /* FIX!!!??? would we actually ever receive a + here??? 
694          * Not observed.
695          */
696         if (initial_ack != '+')
697                 gdb_putback_char(connection, initial_ack);
698
699         return ERROR_OK;
700 }
701
702 int gdb_connection_closed(connection_t *connection)
703 {
704         gdb_service_t *gdb_service = connection->service->priv;
705         gdb_connection_t *gdb_connection = connection->priv;
706
707         /* see if an image built with vFlash commands is left */
708         if (gdb_connection->vflash_image)
709         {
710                 image_close(gdb_connection->vflash_image);
711                 free(gdb_connection->vflash_image);
712                 gdb_connection->vflash_image = NULL;
713         }
714
715         /* if this connection registered a debug-message receiver delete it */
716         delete_debug_msg_receiver(connection->cmd_ctx, gdb_service->target);
717
718         if (connection->priv)
719         {
720                 free(connection->priv);
721                 connection->priv = NULL;
722         }
723         else
724         {
725                 LOG_ERROR("BUG: connection->priv == NULL");
726         }
727
728         target_unregister_event_callback(gdb_target_callback_event_handler, connection);
729         log_remove_callback(gdb_log_callback, connection);
730
731         return ERROR_OK;
732 }
733
734 void gdb_send_error(connection_t *connection, u8 the_error)
735 {
736         char err[4];
737         snprintf(err, 4, "E%2.2X", the_error );
738         gdb_put_packet(connection, err, 3);
739 }
740
741 int gdb_last_signal_packet(connection_t *connection, target_t *target, char* packet, int packet_size)
742 {
743         char sig_reply[4];
744         int signal;
745
746         signal = gdb_last_signal(target);
747
748         snprintf(sig_reply, 4, "S%2.2x", signal);
749         gdb_put_packet(connection, sig_reply, 3);
750
751         return ERROR_OK;
752 }
753
754 /* Convert register to string of bits. NB! The # of bits in the
755  * register might be non-divisible by 8(a byte), in which
756  * case an entire byte is shown. */
757 void gdb_str_to_target(target_t *target, char *tstr, reg_t *reg)
758 {
759         int i;
760
761         u8 *buf;
762         int buf_len;
763         buf = reg->value;
764         buf_len = CEIL(reg->size, 8);
765
766         for (i = 0; i < buf_len; i++)
767         {
768                 tstr[i*2]   = DIGITS[(buf[i]>>4) & 0xf];
769                 tstr[i*2+1] = DIGITS[buf[i]&0xf];
770         }
771 }
772
773 void gdb_target_to_str(target_t *target, char *tstr, char *str)
774 {
775         int str_len = strlen(tstr);
776         int i;
777
778         if (str_len % 2)
779         {
780                 LOG_ERROR("BUG: gdb value with uneven number of characters encountered");
781                 exit(-1);
782         }
783
784         for (i = 0; i < str_len; i+=2)
785         {
786                 str[str_len - i - 1] = tstr[i + 1];
787                 str[str_len - i - 2] = tstr[i];
788         }
789 }
790
791 int gdb_get_registers_packet(connection_t *connection, target_t *target, char* packet, int packet_size)
792 {
793         reg_t **reg_list;
794         int reg_list_size;
795         int retval;
796         int reg_packet_size = 0;
797         char *reg_packet;
798         char *reg_packet_p;
799         int i;
800
801 #ifdef _DEBUG_GDB_IO_
802         LOG_DEBUG("-");
803 #endif
804
805         if ((retval = target->type->get_gdb_reg_list(target, &reg_list, &reg_list_size)) != ERROR_OK)
806         {
807                 return gdb_error(connection, retval);
808         }
809
810         for (i = 0; i < reg_list_size; i++)
811         {
812                 reg_packet_size += reg_list[i]->size;
813         }
814
815         reg_packet = malloc(CEIL(reg_packet_size, 8) * 2);
816         reg_packet_p = reg_packet;
817
818         for (i = 0; i < reg_list_size; i++)
819         {
820                 gdb_str_to_target(target, reg_packet_p, reg_list[i]);
821                 reg_packet_p += CEIL(reg_list[i]->size, 8) * 2;
822         }
823
824 #ifdef _DEBUG_GDB_IO_
825         {
826                 char *reg_packet_p;
827                 reg_packet_p = strndup(reg_packet, CEIL(reg_packet_size, 8) * 2);
828                 LOG_DEBUG("reg_packet: %s", reg_packet_p);
829                 free(reg_packet_p);
830         }
831 #endif
832
833         gdb_put_packet(connection, reg_packet, CEIL(reg_packet_size, 8) * 2);
834         free(reg_packet);
835
836         free(reg_list);
837
838         return ERROR_OK;
839 }
840
841 int gdb_set_registers_packet(connection_t *connection, target_t *target, char *packet, int packet_size)
842 {
843         int i;
844         reg_t **reg_list;
845         int reg_list_size;
846         int retval;
847         char *packet_p;
848
849 #ifdef _DEBUG_GDB_IO_
850         LOG_DEBUG("-");
851 #endif
852
853         /* skip command character */
854         packet++;
855         packet_size--;
856
857         if (packet_size % 2)
858         {
859                 LOG_WARNING("GDB set_registers packet with uneven characters received, dropping connection");
860                 return ERROR_SERVER_REMOTE_CLOSED;
861         }
862
863         if ((retval = target->type->get_gdb_reg_list(target, &reg_list, &reg_list_size)) != ERROR_OK)
864         {
865                 return gdb_error(connection, retval);
866         }
867
868         packet_p = packet;
869         for (i = 0; i < reg_list_size; i++)
870         {
871                 u8 *bin_buf;
872                 char *hex_buf;
873                 reg_arch_type_t *arch_type;
874
875                 /* convert from GDB-string (target-endian) to hex-string (big-endian) */
876                 hex_buf = malloc(CEIL(reg_list[i]->size, 8) * 2);
877                 gdb_target_to_str(target, packet_p, hex_buf);
878
879                 /* convert hex-string to binary buffer */
880                 bin_buf = malloc(CEIL(reg_list[i]->size, 8));
881                 str_to_buf(hex_buf, CEIL(reg_list[i]->size, 8) * 2, bin_buf, reg_list[i]->size, 16);
882
883                 /* get register arch_type, and call set method */
884                 arch_type = register_get_arch_type(reg_list[i]->arch_type);
885                 if (arch_type == NULL)
886                 {
887                         LOG_ERROR("BUG: encountered unregistered arch type");
888                         exit(-1);
889                 }
890                 arch_type->set(reg_list[i], bin_buf);
891
892                 /* advance packet pointer */
893                 packet_p += (CEIL(reg_list[i]->size, 8) * 2);
894
895                 free(bin_buf);
896                 free(hex_buf);
897         }
898
899         /* free reg_t *reg_list[] array allocated by get_gdb_reg_list */
900         free(reg_list);
901
902         gdb_put_packet(connection, "OK", 2);
903
904         return ERROR_OK;
905 }
906
907 int gdb_get_register_packet(connection_t *connection, target_t *target, char *packet, int packet_size)
908 {
909         char *reg_packet;
910         int reg_num = strtoul(packet + 1, NULL, 16);
911         reg_t **reg_list;
912         int reg_list_size;
913         int retval;
914
915 #ifdef _DEBUG_GDB_IO_
916         LOG_DEBUG("-");
917 #endif
918
919         if ((retval = target->type->get_gdb_reg_list(target, &reg_list, &reg_list_size)) != ERROR_OK)
920         {
921                 return gdb_error(connection, retval);
922         }
923
924         if (reg_list_size <= reg_num)
925         {
926                 LOG_ERROR("gdb requested a non-existing register");
927                 exit(-1);
928         }
929
930         reg_packet = malloc(CEIL(reg_list[reg_num]->size, 8) * 2);
931
932         gdb_str_to_target(target, reg_packet, reg_list[reg_num]);
933
934         gdb_put_packet(connection, reg_packet, CEIL(reg_list[reg_num]->size, 8) * 2);
935
936         free(reg_list);
937         free(reg_packet);
938
939         return ERROR_OK;
940 }
941
942 int gdb_set_register_packet(connection_t *connection, target_t *target, char *packet, int packet_size)
943 {
944         char *separator;
945         char *hex_buf;
946         u8 *bin_buf;
947         int reg_num = strtoul(packet + 1, &separator, 16);
948         reg_t **reg_list;
949         int reg_list_size;
950         int retval;
951         reg_arch_type_t *arch_type;
952
953         LOG_DEBUG("-");
954
955         if ((retval = target->type->get_gdb_reg_list(target, &reg_list, &reg_list_size)) != ERROR_OK)
956         {
957                 return gdb_error(connection, retval);
958         }
959
960         if (reg_list_size < reg_num)
961         {
962                 LOG_ERROR("gdb requested a non-existing register");
963                 return ERROR_SERVER_REMOTE_CLOSED;      
964         }
965
966         if (*separator != '=')
967         {
968                 LOG_ERROR("GDB 'set register packet', but no '=' following the register number");
969                 return ERROR_SERVER_REMOTE_CLOSED;
970         }
971
972         /* convert from GDB-string (target-endian) to hex-string (big-endian) */
973         hex_buf = malloc(CEIL(reg_list[reg_num]->size, 8) * 2);
974         gdb_target_to_str(target, separator + 1, hex_buf);
975
976         /* convert hex-string to binary buffer */
977         bin_buf = malloc(CEIL(reg_list[reg_num]->size, 8));
978         str_to_buf(hex_buf, CEIL(reg_list[reg_num]->size, 8) * 2, bin_buf, reg_list[reg_num]->size, 16);
979
980         /* get register arch_type, and call set method */
981         arch_type = register_get_arch_type(reg_list[reg_num]->arch_type);
982         if (arch_type == NULL)
983         {
984                 LOG_ERROR("BUG: encountered unregistered arch type");
985                 exit(-1);
986         }
987         arch_type->set(reg_list[reg_num], bin_buf);
988
989         gdb_put_packet(connection, "OK", 2);
990
991         free(bin_buf);
992         free(hex_buf);
993         free(reg_list);
994
995         return ERROR_OK;
996 }
997
998 int gdb_error(connection_t *connection, int retval)
999 {
1000         switch (retval)
1001         {
1002                 case ERROR_TARGET_DATA_ABORT:
1003                         gdb_send_error(connection, EIO);
1004                         break;
1005                 case ERROR_TARGET_TRANSLATION_FAULT:
1006                         gdb_send_error(connection, EFAULT);
1007                         break;
1008                 case ERROR_TARGET_UNALIGNED_ACCESS:
1009                         gdb_send_error(connection, EFAULT);
1010                         break;
1011                 case ERROR_TARGET_NOT_HALTED:
1012                         gdb_send_error(connection, EFAULT);
1013                         break;
1014                 default:
1015                         /* This could be that the target reset itself. */
1016                         LOG_ERROR("unexpected error %i", retval);
1017                         gdb_send_error(connection, EFAULT);
1018                         break;
1019         }
1020
1021         return ERROR_OK;
1022 }
1023
1024 /* We don't have to worry about the default 2 second timeout for GDB packets,
1025  * because GDB breaks up large memory reads into smaller reads.
1026  *
1027  * 8191 bytes by the looks of it. Why 8191 bytes instead of 8192?????
1028  */
1029 int gdb_read_memory_packet(connection_t *connection, target_t *target, char *packet, int packet_size)
1030 {
1031         char *separator;
1032         u32 addr = 0;
1033         u32 len = 0;
1034
1035         u8 *buffer;
1036         char *hex_buffer;
1037
1038         int retval = ERROR_OK;
1039
1040         /* skip command character */
1041         packet++;
1042
1043         addr = strtoul(packet, &separator, 16);
1044
1045         if (*separator != ',')
1046         {
1047                 LOG_ERROR("incomplete read memory packet received, dropping connection");
1048                 return ERROR_SERVER_REMOTE_CLOSED;
1049         }
1050
1051         len = strtoul(separator+1, NULL, 16);
1052
1053         buffer = malloc(len);
1054
1055         LOG_DEBUG("addr: 0x%8.8x, len: 0x%8.8x", addr, len);
1056
1057         retval = target_read_buffer(target, addr, len, buffer);
1058
1059         if ((retval == ERROR_TARGET_DATA_ABORT) && (!gdb_report_data_abort))
1060         {
1061                 /* TODO : Here we have to lie and send back all zero's lest stack traces won't work.
1062                  * At some point this might be fixed in GDB, in which case this code can be removed.
1063                  *
1064                  * OpenOCD developers are acutely aware of this problem, but there is nothing
1065                  * gained by involving the user in this problem that hopefully will get resolved
1066                  * eventually
1067                  *
1068                  * http://sourceware.org/cgi-bin/gnatsweb.pl?cmd=view%20audit-trail&database=gdb&pr=2395
1069                  *
1070                  * For now, the default is to fix up things to make current GDB versions work.
1071                  * This can be overwritten using the gdb_report_data_abort <'enable'|'disable'> command.
1072                  */
1073                 memset(buffer, 0, len);
1074                 retval = ERROR_OK;
1075         }
1076
1077         if (retval == ERROR_OK)
1078         {
1079                 hex_buffer = malloc(len * 2 + 1);
1080
1081                 int i;
1082                 for (i = 0; i < len; i++)
1083                 {
1084                         u8 t = buffer[i];
1085                         hex_buffer[2 * i] = DIGITS[(t >> 4) & 0xf];
1086                         hex_buffer[2 * i + 1] = DIGITS[t & 0xf];
1087                 }
1088
1089                 gdb_put_packet(connection, hex_buffer, len * 2);
1090
1091                 free(hex_buffer);
1092         }
1093         else
1094         {
1095                 retval = gdb_error(connection, retval);
1096         }
1097
1098         free(buffer);
1099
1100         return retval;
1101 }
1102
1103 int gdb_write_memory_packet(connection_t *connection, target_t *target, char *packet, int packet_size)
1104 {
1105         char *separator;
1106         u32 addr = 0;
1107         u32 len = 0;
1108
1109         u8 *buffer;
1110
1111         int i;
1112         int retval;
1113
1114         /* skip command character */
1115         packet++;
1116
1117         addr = strtoul(packet, &separator, 16);
1118
1119         if (*separator != ',')
1120         {
1121                 LOG_ERROR("incomplete write memory packet received, dropping connection");
1122                 return ERROR_SERVER_REMOTE_CLOSED;
1123         }
1124
1125         len = strtoul(separator+1, &separator, 16);
1126
1127         if (*(separator++) != ':')
1128         {
1129                 LOG_ERROR("incomplete write memory packet received, dropping connection");
1130                 return ERROR_SERVER_REMOTE_CLOSED;
1131         }
1132
1133         buffer = malloc(len);
1134
1135         LOG_DEBUG("addr: 0x%8.8x, len: 0x%8.8x", addr, len);
1136
1137         for (i=0; i<len; i++)
1138         {
1139                 u32 tmp;
1140                 sscanf(separator + 2*i, "%2x", &tmp);
1141                 buffer[i] = tmp;
1142         }
1143
1144         retval = target_write_buffer(target, addr, len, buffer);
1145
1146         if (retval == ERROR_OK)
1147         {
1148                 gdb_put_packet(connection, "OK", 2);
1149         }
1150         else
1151         {
1152                 retval = gdb_error(connection, retval);
1153         }
1154
1155         free(buffer);
1156
1157         return retval;
1158 }
1159
1160 int gdb_write_memory_binary_packet(connection_t *connection, target_t *target, char *packet, int packet_size)
1161 {
1162         char *separator;
1163         u32 addr = 0;
1164         u32 len = 0;
1165
1166         int retval;
1167
1168         /* skip command character */
1169         packet++;
1170
1171         addr = strtoul(packet, &separator, 16);
1172
1173         if (*separator != ',')
1174         {
1175                 LOG_ERROR("incomplete write memory binary packet received, dropping connection");
1176                 return ERROR_SERVER_REMOTE_CLOSED;
1177         }
1178
1179         len = strtoul(separator+1, &separator, 16);
1180
1181         if (*(separator++) != ':')
1182         {
1183                 LOG_ERROR("incomplete write memory binary packet received, dropping connection");
1184                 return ERROR_SERVER_REMOTE_CLOSED;
1185         }
1186
1187         retval = ERROR_OK;
1188         if (len)
1189         {
1190                 LOG_DEBUG("addr: 0x%8.8x, len: 0x%8.8x", addr, len);
1191
1192                 retval = target_write_buffer(target, addr, len, (u8*)separator);
1193         }
1194
1195         if (retval == ERROR_OK)
1196         {
1197                 gdb_put_packet(connection, "OK", 2);
1198         }
1199         else
1200         {
1201                 if ((retval = gdb_error(connection, retval)) != ERROR_OK)
1202                         return retval;
1203         }
1204
1205         return ERROR_OK;
1206 }
1207
1208 void gdb_step_continue_packet(connection_t *connection, target_t *target, char *packet, int packet_size)
1209 {
1210         int current = 0;
1211         u32 address = 0x0;
1212
1213         LOG_DEBUG("-");
1214
1215         if (packet_size > 1)
1216         {
1217                 packet[packet_size] = 0;
1218                 address = strtoul(packet + 1, NULL, 16);
1219         }
1220         else
1221         {
1222                 current = 1;
1223         }
1224
1225         if (packet[0] == 'c')
1226         {
1227                 LOG_DEBUG("continue");
1228                 target_invoke_script(connection->cmd_ctx, target, "pre_resume");
1229                 target_resume(target, current, address, 0, 0); /* resume at current address, don't handle breakpoints, not debugging */
1230         }
1231         else if (packet[0] == 's')
1232         {
1233                 LOG_DEBUG("step");
1234                 target->type->step(target, current, address, 0); /* step at current or address, don't handle breakpoints */
1235         }
1236 }
1237
1238 int gdb_breakpoint_watchpoint_packet(connection_t *connection, target_t *target, char *packet, int packet_size)
1239 {
1240         int type;
1241         enum breakpoint_type bp_type = BKPT_SOFT /* dummy init to avoid warning */;
1242         enum watchpoint_rw wp_type;
1243         u32 address;
1244         u32 size;
1245         char *separator;
1246         int retval;
1247
1248         LOG_DEBUG("-");
1249
1250         type = strtoul(packet + 1, &separator, 16);
1251
1252         if (type == 0)  /* memory breakpoint */
1253                 bp_type = BKPT_SOFT;
1254         else if (type == 1) /* hardware breakpoint */
1255                 bp_type = BKPT_HARD;
1256         else if (type == 2) /* write watchpoint */
1257                 wp_type = WPT_WRITE;
1258         else if (type == 3) /* read watchpoint */
1259                 wp_type = WPT_READ;
1260         else if (type == 4) /* access watchpoint */
1261                 wp_type = WPT_ACCESS;
1262
1263         if (*separator != ',')
1264         {
1265                 LOG_ERROR("incomplete breakpoint/watchpoint packet received, dropping connection");
1266                 return ERROR_SERVER_REMOTE_CLOSED;
1267         }
1268
1269         address = strtoul(separator+1, &separator, 16);
1270
1271         if (*separator != ',')
1272         {
1273                 LOG_ERROR("incomplete breakpoint/watchpoint packet received, dropping connection");
1274                 return ERROR_SERVER_REMOTE_CLOSED;
1275         }
1276
1277         size = strtoul(separator+1, &separator, 16);
1278
1279         switch (type)
1280         {
1281                 case 0:
1282                 case 1:
1283                         if (packet[0] == 'Z')
1284                         {
1285                                 if ((retval = breakpoint_add(target, address, size, bp_type)) != ERROR_OK)
1286                                 {
1287                                         if ((retval = gdb_error(connection, retval)) != ERROR_OK)
1288                                                 return retval;
1289                                 }
1290                                 else
1291                                 {
1292                                         gdb_put_packet(connection, "OK", 2);
1293                                 }
1294                         }
1295                         else
1296                         {
1297                                 breakpoint_remove(target, address);
1298                                 gdb_put_packet(connection, "OK", 2);
1299                         }
1300                         break;
1301                 case 2:
1302                 case 3:
1303                 case 4:
1304                 {
1305                         if (packet[0] == 'Z')
1306                         {
1307                                 if ((retval = watchpoint_add(target, address, size, type-2, 0, 0xffffffffu)) != ERROR_OK)
1308                                 {
1309                                         if ((retval = gdb_error(connection, retval)) != ERROR_OK)
1310                                                 return retval;
1311                                 }
1312                                 else
1313                                 {
1314                                         gdb_put_packet(connection, "OK", 2);
1315                                 }
1316                         }
1317                         else
1318                         {
1319                                 watchpoint_remove(target, address);
1320                                 gdb_put_packet(connection, "OK", 2);
1321                         }
1322                         break;
1323                 }
1324                 default:
1325                         break;
1326         }
1327
1328         return ERROR_OK;
1329 }
1330
1331 /* print out a string and allocate more space as needed, mainly used for XML at this point */
1332 void xml_printf(int *retval, char **xml, int *pos, int *size, const char *fmt, ...)
1333 {
1334         if (*retval != ERROR_OK)
1335         {
1336                 return;
1337         }
1338         int first = 1;
1339
1340         for (;;)
1341         {
1342                 if ((*xml == NULL) || (!first))
1343                 {
1344                         /* start by 0 to exercise all the code paths.
1345                          * Need minimum 2 bytes to fit 1 char and 0 terminator. */
1346
1347                         *size = *size * 2 + 2;
1348                         char *t = *xml;
1349                         *xml = realloc(*xml, *size);
1350                         if (*xml == NULL)
1351                         {
1352                                 if (t)
1353                                         free(t);
1354                                 *retval = ERROR_SERVER_REMOTE_CLOSED;
1355                                 return;
1356                         }
1357                 }
1358
1359                 va_list ap;
1360                 int ret;
1361                 va_start(ap, fmt);
1362                 ret = vsnprintf(*xml + *pos, *size - *pos, fmt, ap);
1363                 va_end(ap);
1364                 if ((ret > 0) && ((ret + 1) < *size - *pos))
1365                 {
1366                         *pos += ret;
1367                         return;
1368                 }
1369                 /* there was just enough or not enough space, allocate more. */
1370                 first = 0;
1371         }
1372 }
1373
1374 static int decode_xfer_read(char *buf, char **annex, int *ofs, unsigned int *len)
1375 {
1376         char *separator;
1377
1378         /* Extract and NUL-terminate the annex. */
1379         *annex = buf;
1380         while (*buf && *buf != ':')
1381                 buf++;
1382         if (*buf == '\0')
1383                 return -1;
1384         *buf++ = 0;
1385
1386         /* After the read marker and annex, qXfer looks like a
1387          * traditional 'm' packet. */
1388
1389         *ofs = strtoul(buf, &separator, 16);
1390
1391         if (*separator != ',')
1392                 return -1;
1393
1394         *len = strtoul(separator+1, NULL, 16);
1395
1396         return 0;
1397 }
1398
1399 int gdb_calc_blocksize(flash_bank_t *bank)
1400 {
1401         int i;
1402         int block_size = 0xffffffff;
1403
1404         /* loop through all sectors and return smallest sector size */
1405
1406         for (i = 0; i < bank->num_sectors; i++)
1407         {
1408                 if (bank->sectors[i].size < block_size)
1409                         block_size = bank->sectors[i].size;
1410         }
1411
1412         return block_size;
1413 }
1414
1415 static int compare_bank (const void * a, const void * b)
1416 {
1417         flash_bank_t *b1, *b2;
1418         b1=*((flash_bank_t **)a);
1419         b2=*((flash_bank_t **)b);
1420         
1421         if (b1->base==b2->base)
1422         {
1423                 return 0;
1424         } else if (b1->base>b2->base)
1425         {
1426                 return 1;
1427         } else
1428         {
1429                 return -1;
1430         }
1431 }
1432
1433 int gdb_query_packet(connection_t *connection, target_t *target, char *packet, int packet_size)
1434 {
1435         command_context_t *cmd_ctx = connection->cmd_ctx;
1436
1437         if (strstr(packet, "qRcmd,"))
1438         {
1439                 if (packet_size > 6)
1440                 {
1441                         char *cmd;
1442                         int i;
1443                         cmd = malloc((packet_size - 6)/2 + 1);
1444                         for (i=0; i < (packet_size - 6)/2; i++)
1445                         {
1446                                 u32 tmp;
1447                                 sscanf(packet + 6 + 2*i, "%2x", &tmp);
1448                                 cmd[i] = tmp;
1449                         }
1450                         cmd[(packet_size - 6)/2] = 0x0;
1451
1452                         /* We want to print all debug output to GDB connection */
1453                         log_add_callback(gdb_log_callback, connection);
1454                         target_call_timer_callbacks_now();
1455                         command_run_line(cmd_ctx, cmd);
1456                         target_call_timer_callbacks_now();
1457                         log_remove_callback(gdb_log_callback, connection);
1458                         free(cmd);
1459                 }
1460                 gdb_put_packet(connection, "OK", 2);
1461                 return ERROR_OK;
1462         }
1463         else if (strstr(packet, "qCRC:"))
1464         {
1465                 if (packet_size > 5)
1466                 {
1467                         int retval;
1468                         char gdb_reply[10];
1469                         char *separator;
1470                         u32 checksum;
1471                         u32 addr = 0;
1472                         u32 len = 0;
1473
1474                         /* skip command character */
1475                         packet += 5;
1476
1477                         addr = strtoul(packet, &separator, 16);
1478
1479                         if (*separator != ',')
1480                         {
1481                                 LOG_ERROR("incomplete read memory packet received, dropping connection");
1482                                 return ERROR_SERVER_REMOTE_CLOSED;
1483                         }
1484
1485                         len = strtoul(separator + 1, NULL, 16);
1486
1487                         retval = target_checksum_memory(target, addr, len, &checksum);
1488
1489                         if (retval == ERROR_OK)
1490                         {
1491                                 snprintf(gdb_reply, 10, "C%8.8x", checksum);
1492                                 gdb_put_packet(connection, gdb_reply, 9);
1493                         }
1494                         else
1495                         {
1496                                 if ((retval = gdb_error(connection, retval)) != ERROR_OK)
1497                                         return retval;
1498                         }
1499
1500                         return ERROR_OK;
1501                 }
1502         }
1503         else if (strstr(packet, "qSupported"))
1504         {
1505                 /* we currently support packet size and qXfer:memory-map:read (if enabled)
1506                  * disable qXfer:features:read for the moment */
1507                 int retval = ERROR_OK;
1508                 char *buffer = NULL;
1509                 int pos = 0;
1510                 int size = 0;
1511
1512                 xml_printf(&retval, &buffer, &pos, &size,
1513                                 "PacketSize=%x;qXfer:memory-map:read%c;qXfer:features:read-",
1514                                 (GDB_BUFFER_SIZE - 1), ((gdb_use_memory_map == 1)&&(flash_get_bank_count()>0)) ? '+' : '-');
1515
1516                 if (retval != ERROR_OK)
1517                 {
1518                         gdb_send_error(connection, 01);
1519                         return ERROR_OK;
1520                 }
1521
1522                 gdb_put_packet(connection, buffer, strlen(buffer));
1523                 free(buffer);
1524
1525                 return ERROR_OK;
1526         }
1527         else if (strstr(packet, "qXfer:memory-map:read::")&&(flash_get_bank_count()>0))
1528         {
1529                 /* We get away with only specifying flash here. Regions that are not
1530                  * specified are treated as if we provided no memory map(if not we
1531                  * could detect the holes and mark them as RAM).
1532                  * Normally we only execute this code once, but no big deal if we
1533                  * have to regenerate it a couple of times. */
1534
1535                 flash_bank_t *p;
1536                 char *xml = NULL;
1537                 int size = 0;
1538                 int pos = 0;
1539                 int retval = ERROR_OK;
1540
1541                 int offset;
1542                 int length;
1543                 char *separator;
1544                 int blocksize;
1545
1546                 /* skip command character */
1547                 packet += 23;
1548
1549                 offset = strtoul(packet, &separator, 16);
1550                 length = strtoul(separator + 1, &separator, 16);
1551
1552                 xml_printf(&retval, &xml, &pos, &size, "<memory-map>\n");
1553         
1554                 /* 
1555                 sort banks in ascending order, we need to make non-flash memory be ram(or rather
1556                 read/write) by default for GDB.
1557                 GDB does not have a concept of non-cacheable read/write memory.
1558                  */
1559                 flash_bank_t **banks=malloc(sizeof(flash_bank_t *)*flash_get_bank_count());
1560                 int i;
1561                 
1562                 for (i=0; i<flash_get_bank_count(); i++)
1563                 {
1564                         p = get_flash_bank_by_num(i);
1565                         if (p == NULL)
1566                         {
1567                                 free(banks);
1568                                 retval = ERROR_FAIL;
1569                                 gdb_send_error(connection, retval);
1570                                 return retval;
1571                         }
1572                         banks[i]=p;
1573                 }
1574                 
1575                 qsort(banks, flash_get_bank_count(), sizeof(flash_bank_t *), compare_bank);
1576                 
1577                 u32 ram_start=0;
1578                 for (i=0; i<flash_get_bank_count(); i++)
1579                 {
1580                         p = banks[i];
1581                         
1582                         if (ram_start<p->base)
1583                         {
1584                                 xml_printf(&retval, &xml, &pos, &size, "<memory type=\"ram\" start=\"0x%x\" length=\"0x%x\"/>\n",
1585                                         ram_start, p->base-ram_start);
1586                         }
1587                         
1588                         /* if device has uneven sector sizes, eg. str7, lpc
1589                          * we pass the smallest sector size to gdb memory map */
1590                         blocksize = gdb_calc_blocksize(p);
1591         
1592                         xml_printf(&retval, &xml, &pos, &size, "<memory type=\"flash\" start=\"0x%x\" length=\"0x%x\">\n" \
1593                                 "<property name=\"blocksize\">0x%x</property>\n" \
1594                                 "</memory>\n", \
1595                                 p->base, p->size, blocksize);
1596                         ram_start=p->base+p->size;                      
1597                 }
1598                 if (ram_start!=0)
1599                 {
1600                         xml_printf(&retval, &xml, &pos, &size, "<memory type=\"ram\" start=\"0x%x\" length=\"0x%x\"/>\n",
1601                                 ram_start, 0-ram_start);
1602                 } else
1603                 {
1604                         /* a flash chip could be at the very end of the 32 bit address space, in which case
1605                         ram_start will be precisely 0 */
1606                 }
1607                 
1608                 free(banks);
1609                 banks = NULL;
1610
1611                 xml_printf(&retval, &xml, &pos, &size, "</memory-map>\n");
1612
1613                 if (retval != ERROR_OK)
1614                 {
1615                         gdb_send_error(connection, retval);
1616                         return retval;
1617                 }
1618
1619                 if (offset + length > pos)
1620                 {
1621                         length = pos - offset;
1622                 }
1623
1624                 char *t = malloc(length + 1);
1625                 t[0] = 'l';
1626                 memcpy(t + 1, xml + offset, length);
1627                 gdb_put_packet(connection, t, length + 1);
1628
1629                 free(t);
1630                 free(xml);
1631                 return ERROR_OK;
1632         }
1633         else if (strstr(packet, "qXfer:features:read:"))
1634         {
1635                 char *xml = NULL;
1636                 int size = 0;
1637                 int pos = 0;
1638                 int retval = ERROR_OK;
1639
1640                 int offset;
1641                 unsigned int length;
1642                 char *annex;
1643
1644                 /* skip command character */
1645                 packet += 20;
1646
1647                 if (decode_xfer_read(packet, &annex, &offset, &length) < 0)
1648                 {
1649                         gdb_send_error(connection, 01);
1650                         return ERROR_OK;
1651                 }
1652
1653                 if (strcmp(annex, "target.xml") != 0)
1654                 {
1655                         gdb_send_error(connection, 01);
1656                         return ERROR_OK;
1657                 }
1658
1659                 xml_printf(&retval, &xml, &pos, &size, \
1660                         "l<target version=\"1.0\">\n<architecture>arm</architecture>\n</target>\n");
1661
1662                 if (retval != ERROR_OK)
1663                 {
1664                         gdb_send_error(connection, retval);
1665                         return retval;
1666                 }
1667
1668                 gdb_put_packet(connection, xml, strlen(xml));
1669
1670                 free(xml);
1671                 return ERROR_OK;
1672         }
1673
1674         gdb_put_packet(connection, "", 0);
1675         return ERROR_OK;
1676 }
1677
1678 int gdb_v_packet(connection_t *connection, target_t *target, char *packet, int packet_size)
1679 {
1680         gdb_connection_t *gdb_connection = connection->priv;
1681         gdb_service_t *gdb_service = connection->service->priv;
1682         int result;
1683
1684         /* if flash programming disabled - send a empty reply */
1685
1686         if (gdb_flash_program == 0)
1687         {
1688                 gdb_put_packet(connection, "", 0);
1689                 return ERROR_OK;
1690         }
1691
1692         if (strstr(packet, "vFlashErase:"))
1693         {
1694                 unsigned long addr;
1695                 unsigned long length;
1696
1697                 char *parse = packet + 12;
1698                 if (*parse == '\0')
1699                 {
1700                         LOG_ERROR("incomplete vFlashErase packet received, dropping connection");
1701                         return ERROR_SERVER_REMOTE_CLOSED;
1702                 }
1703
1704                 addr = strtoul(parse, &parse, 16);
1705
1706                 if (*(parse++) != ',' || *parse == '\0')
1707                 {
1708                         LOG_ERROR("incomplete vFlashErase packet received, dropping connection");
1709                         return ERROR_SERVER_REMOTE_CLOSED;
1710                 }
1711
1712                 length = strtoul(parse, &parse, 16);
1713
1714                 if (*parse != '\0')
1715                 {
1716                         LOG_ERROR("incomplete vFlashErase packet received, dropping connection");
1717                         return ERROR_SERVER_REMOTE_CLOSED;
1718                 }
1719
1720                 /* assume all sectors need erasing - stops any problems
1721                  * when flash_write is called multiple times */
1722                 flash_set_dirty();
1723
1724                 /* perform any target specific operations before the erase */
1725                 target_call_event_callbacks(gdb_service->target, TARGET_EVENT_GDB_PROGRAM);
1726
1727                 /* perform erase */
1728                 if ((result = flash_erase_address_range(gdb_service->target, addr, length)) != ERROR_OK)
1729                 {
1730                         /* GDB doesn't evaluate the actual error number returned,
1731                          * treat a failed erase as an I/O error
1732                          */
1733                         gdb_send_error(connection, EIO);
1734                         LOG_ERROR("flash_erase returned %i", result);
1735                 }
1736                 else
1737                         gdb_put_packet(connection, "OK", 2);
1738
1739                 return ERROR_OK;
1740         }
1741
1742         if (strstr(packet, "vFlashWrite:"))
1743         {
1744                 unsigned long addr;
1745                 unsigned long length;
1746                 char *parse = packet + 12;
1747
1748                 if (*parse == '\0')
1749                 {
1750                         LOG_ERROR("incomplete vFlashErase packet received, dropping connection");
1751                         return ERROR_SERVER_REMOTE_CLOSED;
1752                 }
1753                 addr = strtoul(parse, &parse, 16);
1754                 if (*(parse++) != ':')
1755                 {
1756                         LOG_ERROR("incomplete vFlashErase packet received, dropping connection");
1757                         return ERROR_SERVER_REMOTE_CLOSED;
1758                 }
1759                 length = packet_size - (parse - packet);
1760
1761                 /* create a new image if there isn't already one */
1762                 if (gdb_connection->vflash_image == NULL)
1763                 {
1764                         gdb_connection->vflash_image = malloc(sizeof(image_t));
1765                         image_open(gdb_connection->vflash_image, "", "build");
1766                 }
1767
1768                 /* create new section with content from packet buffer */
1769                 image_add_section(gdb_connection->vflash_image, addr, length, 0x0, (u8*)parse);
1770
1771                 gdb_put_packet(connection, "OK", 2);
1772
1773                 return ERROR_OK;
1774         }
1775
1776         if (!strcmp(packet, "vFlashDone"))
1777         {
1778                 u32 written;
1779
1780                 /* process the flashing buffer. No need to erase as GDB
1781                  * always issues a vFlashErase first. */
1782                 if ((result = flash_write(gdb_service->target, gdb_connection->vflash_image, &written, 0)) != ERROR_OK)
1783                 {
1784                         if (result == ERROR_FLASH_DST_OUT_OF_BANK)
1785                                 gdb_put_packet(connection, "E.memtype", 9);
1786                         else
1787                                 gdb_send_error(connection, EIO);
1788                         }
1789                 else
1790                 {
1791                         LOG_DEBUG("wrote %u bytes from vFlash image to flash", written);
1792                         gdb_put_packet(connection, "OK", 2);
1793                 }
1794
1795                 image_close(gdb_connection->vflash_image);
1796                 free(gdb_connection->vflash_image);
1797                 gdb_connection->vflash_image = NULL;
1798
1799                 return ERROR_OK;
1800         }
1801
1802         gdb_put_packet(connection, "", 0);
1803         return ERROR_OK;
1804 }
1805
1806 int gdb_detach(connection_t *connection, target_t *target)
1807 {
1808         switch( detach_mode )
1809         {
1810                 case GDB_DETACH_RESUME:
1811                         target_invoke_script(connection->cmd_ctx, target, "pre_resume");
1812                         target_resume(target, 1, 0, 1, 0);
1813                         break;
1814
1815                 case GDB_DETACH_RESET:
1816                         /* FIX?? make this configurable?? */
1817                         target_process_reset(connection->cmd_ctx, RESET_HALT);
1818                         break;
1819
1820                 case GDB_DETACH_HALT:
1821                         target_halt(target);
1822                         break;
1823
1824                 case GDB_DETACH_NOTHING:
1825                         break;
1826         }
1827
1828         gdb_put_packet(connection, "OK", 2);
1829
1830         return ERROR_OK;
1831 }
1832
1833 static void gdb_log_callback(void *priv, const char *file, int line,
1834                 const char *function, const char *string)
1835 {
1836         connection_t *connection = priv;
1837         gdb_connection_t *gdb_con = connection->priv;
1838
1839         if (gdb_con->busy)
1840         {
1841                 /* do not reply this using the O packet */
1842                 return;
1843         }
1844
1845         gdb_output_con(connection, string);
1846 }
1847
1848 /* Do not allocate this on the stack */
1849 char gdb_packet_buffer[GDB_BUFFER_SIZE];
1850
1851 int gdb_input_inner(connection_t *connection)
1852 {
1853         gdb_service_t *gdb_service = connection->service->priv;
1854         target_t *target = gdb_service->target;
1855         char *packet=gdb_packet_buffer;
1856         int packet_size;
1857         int retval;
1858         gdb_connection_t *gdb_con = connection->priv;
1859         static int extended_protocol = 0;
1860
1861         /* drain input buffer */
1862         do
1863         {
1864                 packet_size = GDB_BUFFER_SIZE-1;
1865                 if ((retval = gdb_get_packet(connection, packet, &packet_size)) != ERROR_OK)
1866                 {
1867                         return retval;
1868                 }
1869
1870                 /* terminate with zero */
1871                 packet[packet_size] = 0;
1872
1873                 LOG_DEBUG("received packet: '%s'", packet);
1874
1875                 if (packet_size > 0)
1876                 {
1877                         retval = ERROR_OK;
1878                         switch (packet[0])
1879                         {
1880                                 case 'H':
1881                                         /* Hct... -- set thread
1882                                          * we don't have threads, send empty reply */
1883                                         gdb_put_packet(connection, NULL, 0);
1884                                         break;
1885                                 case 'q':
1886                                         retval = gdb_query_packet(connection, target, packet, packet_size);
1887                                         break;
1888                                 case 'g':
1889                                         retval = gdb_get_registers_packet(connection, target, packet, packet_size);
1890                                         break;
1891                                 case 'G':
1892                                         retval = gdb_set_registers_packet(connection, target, packet, packet_size);
1893                                         break;
1894                                 case 'p':
1895                                         retval = gdb_get_register_packet(connection, target, packet, packet_size);
1896                                         break;
1897                                 case 'P':
1898                                         retval = gdb_set_register_packet(connection, target, packet, packet_size);
1899                                         break;
1900                                 case 'm':
1901                                         retval = gdb_read_memory_packet(connection, target, packet, packet_size);
1902                                         break;
1903                                 case 'M':
1904                                         retval = gdb_write_memory_packet(connection, target, packet, packet_size);
1905                                         break;
1906                                 case 'z':
1907                                 case 'Z':
1908                                         retval = gdb_breakpoint_watchpoint_packet(connection, target, packet, packet_size);
1909                                         break;
1910                                 case '?':
1911                                         gdb_last_signal_packet(connection, target, packet, packet_size);
1912                                         break;
1913                                 case 'c':
1914                                 case 's':
1915                                         {
1916                                                 if (target->state != TARGET_HALTED)
1917                                                 {
1918                                                         /* If the target isn't in the halted state, then we can't
1919                                                          * step/continue. This might be early setup, etc.
1920                                                          */
1921                                                         char sig_reply[4];
1922                                                         snprintf(sig_reply, 4, "T%2.2x", 2);
1923                                                         gdb_put_packet(connection, sig_reply, 3);
1924                                                 } else
1925                                                 {
1926                                                         /* We're running/stepping, in which case we can
1927                                                          * forward log output until the target is halted 
1928                                                          */
1929                                                         gdb_connection_t *gdb_con = connection->priv;
1930                                                         gdb_con->frontend_state = TARGET_RUNNING;
1931                                                         log_add_callback(gdb_log_callback, connection);
1932                                                         gdb_step_continue_packet(connection, target, packet, packet_size);
1933                                                 }
1934                                         }
1935                                         break;
1936                                 case 'v':
1937                                         retval = gdb_v_packet(connection, target, packet, packet_size);
1938                                         break;
1939                                 case 'D':
1940                                         retval = gdb_detach(connection, target);
1941                                         extended_protocol = 0;
1942                                         break;
1943                                 case 'X':
1944                                         if ((retval = gdb_write_memory_binary_packet(connection, target, packet, packet_size)) != ERROR_OK)
1945                                                 return retval;
1946                                         break;
1947                                 case 'k':
1948                                         if (extended_protocol != 0)
1949                                                 break;
1950                                         gdb_put_packet(connection, "OK", 2);
1951                                         return ERROR_SERVER_REMOTE_CLOSED;
1952                                 case '!':
1953                                         /* handle extended remote protocol */
1954                                         extended_protocol = 1;
1955                                         gdb_put_packet(connection, "OK", 2);
1956                                         break;
1957                                 case 'R':
1958                                         /* handle extended restart packet */
1959                                         command_run_linef(connection->cmd_ctx, "ocd_gdb_restart %d", get_num_by_target(target));
1960                                         break;
1961                                 default:
1962                                         /* ignore unkown packets */
1963                                         LOG_DEBUG("ignoring 0x%2.2x packet", packet[0]);
1964                                         gdb_put_packet(connection, NULL, 0);
1965                                         break;
1966                         }
1967
1968                         /* if a packet handler returned an error, exit input loop */
1969                         if (retval != ERROR_OK)
1970                                 return retval;
1971                 }
1972
1973                 if (gdb_con->ctrl_c)
1974                 {
1975                         if (target->state == TARGET_RUNNING)
1976                         {
1977                                 target_halt(target);
1978                                 gdb_con->ctrl_c = 0;
1979                         }
1980                 }
1981
1982         } while (gdb_con->buf_cnt > 0);
1983
1984         return ERROR_OK;
1985 }
1986
1987 int gdb_input(connection_t *connection)
1988 {
1989         int retval = gdb_input_inner(connection);
1990         gdb_connection_t *gdb_con = connection->priv;
1991         if (retval == ERROR_SERVER_REMOTE_CLOSED)
1992                 return retval;
1993
1994         /* logging does not propagate the error, yet can set th gdb_con->closed flag */
1995         if (gdb_con->closed)
1996                 return ERROR_SERVER_REMOTE_CLOSED;
1997         
1998         /* we'll recover from any other errors(e.g. temporary timeouts, etc.) */
1999         return ERROR_OK;
2000 }
2001
2002 int gdb_init()
2003 {
2004         gdb_service_t *gdb_service;
2005         target_t *target = targets;
2006         int i = 0;
2007
2008         if (!target)
2009         {
2010                 LOG_WARNING("no gdb ports allocated as no target has been specified");
2011                 return ERROR_OK;
2012         }
2013
2014         if (gdb_port == 0)
2015         {
2016                 LOG_WARNING("no gdb port specified, using default port 3333");
2017                 gdb_port = 3333;
2018         }
2019
2020         while (target)
2021         {
2022                 char service_name[8];
2023
2024                 snprintf(service_name, 8, "gdb-%2.2i", i);
2025
2026                 gdb_service = malloc(sizeof(gdb_service_t));
2027                 gdb_service->target = target;
2028
2029                 add_service("gdb", CONNECTION_GDB, gdb_port + i, 1, gdb_new_connection, gdb_input, gdb_connection_closed, gdb_service);
2030
2031                 LOG_DEBUG("gdb service for target %s at port %i", target->type->name, gdb_port + i);
2032
2033                 i++;
2034                 target = target->next;
2035         }
2036
2037         return ERROR_OK;
2038 }
2039
2040 /* daemon configuration command gdb_port */
2041 int handle_gdb_port_command(struct command_context_s *cmd_ctx, char *cmd, char **args, int argc)
2042 {
2043         if (argc == 0)
2044                 return ERROR_OK;
2045
2046         /* only if the port wasn't overwritten by cmdline */
2047         if (gdb_port == 0)
2048                 gdb_port = strtoul(args[0], NULL, 0);
2049
2050         return ERROR_OK;
2051 }
2052
2053 int handle_gdb_detach_command(struct command_context_s *cmd_ctx, char *cmd, char **args, int argc)
2054 {
2055         if (argc == 1)
2056         {
2057                 if (strcmp(args[0], "resume") == 0)
2058                 {
2059                         detach_mode = GDB_DETACH_RESUME;
2060                         return ERROR_OK;
2061                 }
2062                 else if (strcmp(args[0], "reset") == 0)
2063                 {
2064                         detach_mode = GDB_DETACH_RESET;
2065                         return ERROR_OK;
2066                 }
2067                 else if (strcmp(args[0], "halt") == 0)
2068                 {
2069                         detach_mode = GDB_DETACH_HALT;
2070                         return ERROR_OK;
2071                 }
2072                 else if (strcmp(args[0], "nothing") == 0)
2073                 {
2074                         detach_mode = GDB_DETACH_NOTHING;
2075                         return ERROR_OK;
2076                 }
2077         }
2078
2079         LOG_WARNING("invalid gdb_detach configuration directive: %s", args[0]);
2080         return ERROR_OK;
2081 }
2082
2083 int handle_gdb_memory_map_command(struct command_context_s *cmd_ctx, char *cmd, char **args, int argc)
2084 {
2085         if (argc == 1)
2086         {
2087                 if (strcmp(args[0], "enable") == 0)
2088                 {
2089                         gdb_use_memory_map = 1;
2090                         return ERROR_OK;
2091                 }
2092                 else if (strcmp(args[0], "disable") == 0)
2093                 {
2094                         gdb_use_memory_map = 0;
2095                         return ERROR_OK;
2096                 }
2097         }
2098
2099         LOG_WARNING("invalid gdb_memory_map configuration directive: %s", args[0]);
2100         return ERROR_OK;
2101 }
2102
2103 int handle_gdb_flash_program_command(struct command_context_s *cmd_ctx, char *cmd, char **args, int argc)
2104 {
2105         if (argc == 1)
2106         {
2107                 if (strcmp(args[0], "enable") == 0)
2108                 {
2109                         gdb_flash_program = 1;
2110                         return ERROR_OK;
2111                 }
2112                 else if (strcmp(args[0], "disable") == 0)
2113                 {
2114                         gdb_flash_program = 0;
2115                         return ERROR_OK;
2116                 }
2117         }
2118
2119         LOG_WARNING("invalid gdb_memory_map configuration directive: %s", args[0]);
2120         return ERROR_OK;
2121 }
2122
2123 int handle_gdb_report_data_abort_command(struct command_context_s *cmd_ctx, char *cmd, char **args, int argc)
2124 {
2125         if (argc == 1)
2126         {
2127                 if (strcmp(args[0], "enable") == 0)
2128                 {
2129                         gdb_report_data_abort = 1;
2130                         return ERROR_OK;
2131                 }
2132                 else if (strcmp(args[0], "disable") == 0)
2133                 {
2134                         gdb_report_data_abort = 0;
2135                         return ERROR_OK;
2136                 }
2137         }
2138
2139         LOG_WARNING("invalid gdb_report_data_abort configuration directive: %s", args[0]);
2140         return ERROR_OK;
2141 }
2142
2143 int gdb_register_commands(command_context_t *command_context)
2144 {
2145         register_command(command_context, NULL, "gdb_port", handle_gdb_port_command,
2146                         COMMAND_CONFIG, "");
2147         register_command(command_context, NULL, "gdb_detach", handle_gdb_detach_command,
2148                         COMMAND_CONFIG, "");
2149         register_command(command_context, NULL, "gdb_memory_map", handle_gdb_memory_map_command,
2150                         COMMAND_CONFIG, "");
2151         register_command(command_context, NULL, "gdb_flash_program", handle_gdb_flash_program_command,
2152                         COMMAND_CONFIG, "");
2153         register_command(command_context, NULL, "gdb_report_data_abort", handle_gdb_report_data_abort_command,
2154                         COMMAND_CONFIG, "");
2155         return ERROR_OK;
2156 }