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