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