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