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