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