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