gdb_server: simplify logic to enable/disable gdb_log_callback()
[openocd.git] / src / server / gdb_server.c
1 /***************************************************************************
2 * Copyright (C) 2005 by Dominic Rath *
3 * Dominic.Rath@gmx.de *
4 * *
5 * Copyright (C) 2007-2010 Øyvind Harboe *
6 * oyvind.harboe@zylin.com *
7 * *
8 * Copyright (C) 2008 by Spencer Oliver *
9 * spen@spen-soft.co.uk *
10 * *
11 * Copyright (C) 2011 by Broadcom Corporation *
12 * Evan Hunter - ehunter@broadcom.com *
13 * *
14 * Copyright (C) ST-Ericsson SA 2011 *
15 * michel.jaouen@stericsson.com : smp minimum support *
16 * *
17 * Copyright (C) 2013 Andes Technology *
18 * Hsiangkai Wang <hkwang@andestech.com> *
19 * *
20 * Copyright (C) 2013 Franck Jullien *
21 * elec4fun@gmail.com *
22 * *
23 * This program is free software; you can redistribute it and/or modify *
24 * it under the terms of the GNU General Public License as published by *
25 * the Free Software Foundation; either version 2 of the License, or *
26 * (at your option) any later version. *
27 * *
28 * This program is distributed in the hope that it will be useful, *
29 * but WITHOUT ANY WARRANTY; without even the implied warranty of *
30 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
31 * GNU General Public License for more details. *
32 * *
33 * You should have received a copy of the GNU General Public License *
34 * along with this program. If not, see <http://www.gnu.org/licenses/>. *
35 ***************************************************************************/
36
37 #ifdef HAVE_CONFIG_H
38 #include "config.h"
39 #endif
40
41 #include <target/breakpoints.h>
42 #include <target/target_request.h>
43 #include <target/register.h>
44 #include <target/target.h>
45 #include <target/target_type.h>
46 #include <target/semihosting_common.h>
47 #include "server.h"
48 #include <flash/nor/core.h>
49 #include "gdb_server.h"
50 #include <target/image.h>
51 #include <jtag/jtag.h>
52 #include "rtos/rtos.h"
53 #include "target/smp.h"
54
55 /**
56 * @file
57 * GDB server implementation.
58 *
59 * This implements the GDB Remote Serial Protocol, over TCP connections,
60 * giving GDB access to the JTAG or other hardware debugging facilities
61 * found in most modern embedded processors.
62 */
63
64 enum gdb_output_flag {
65 /* GDB doesn't accept 'O' packets */
66 GDB_OUTPUT_NO,
67 /* GDB accepts 'O' packets */
68 GDB_OUTPUT_ALL,
69 };
70
71 struct target_desc_format {
72 char *tdesc;
73 uint32_t tdesc_length;
74 };
75
76 /* private connection data for GDB */
77 struct gdb_connection {
78 char buffer[GDB_BUFFER_SIZE + 1]; /* Extra byte for null-termination */
79 char *buf_p;
80 int buf_cnt;
81 bool ctrl_c;
82 enum target_state frontend_state;
83 struct image *vflash_image;
84 bool closed;
85 bool busy;
86 int noack_mode;
87 /* set flag to true if you want the next stepi to return immediately.
88 * allowing GDB to pick up a fresh set of register values from the target
89 * without modifying the target state. */
90 bool sync;
91 /* We delay reporting memory write errors until next step/continue or memory
92 * write. This improves performance of gdb load significantly as the GDB packet
93 * can be replied immediately and a new GDB packet will be ready without delay
94 * (ca. 10% or so...). */
95 bool mem_write_error;
96 /* with extended-remote it seems we need to better emulate attach/detach.
97 * what this means is we reply with a W stop reply after a kill packet,
98 * normally we reply with a S reply via gdb_last_signal_packet.
99 * as a side note this behaviour only effects gdb > 6.8 */
100 bool attached;
101 /* set when extended protocol is used */
102 bool extended_protocol;
103 /* temporarily used for target description support */
104 struct target_desc_format target_desc;
105 /* temporarily used for thread list support */
106 char *thread_list;
107 /* flag to mask the output from gdb_log_callback() */
108 enum gdb_output_flag output_flag;
109 };
110
111 #if 0
112 #define _DEBUG_GDB_IO_
113 #endif
114
115 static struct gdb_connection *current_gdb_connection;
116
117 static int gdb_breakpoint_override;
118 static enum breakpoint_type gdb_breakpoint_override_type;
119
120 static int gdb_error(struct connection *connection, int retval);
121 static char *gdb_port;
122 static char *gdb_port_next;
123
124 static void gdb_log_callback(void *priv, const char *file, unsigned line,
125 const char *function, const char *string);
126
127 static void gdb_sig_halted(struct connection *connection);
128
129 /* number of gdb connections, mainly to suppress gdb related debugging spam
130 * in helper/log.c when no gdb connections are actually active */
131 int gdb_actual_connections;
132
133 /* set if we are sending a memory map to gdb
134 * via qXfer:memory-map:read packet */
135 /* enabled by default*/
136 static int gdb_use_memory_map = 1;
137 /* enabled by default*/
138 static int gdb_flash_program = 1;
139
140 /* if set, data aborts cause an error to be reported in memory read packets
141 * see the code in gdb_read_memory_packet() for further explanations.
142 * Disabled by default.
143 */
144 static int gdb_report_data_abort;
145 /* If set, errors when accessing registers are reported to gdb. Disabled by
146 * default. */
147 static int gdb_report_register_access_error;
148
149 /* set if we are sending target descriptions to gdb
150 * via qXfer:features:read packet */
151 /* enabled by default */
152 static int gdb_use_target_description = 1;
153
154 /* current processing free-run type, used by file-I/O */
155 static char gdb_running_type;
156
157 static int gdb_last_signal(struct target *target)
158 {
159 switch (target->debug_reason) {
160 case DBG_REASON_DBGRQ:
161 return 0x2; /* SIGINT */
162 case DBG_REASON_BREAKPOINT:
163 case DBG_REASON_WATCHPOINT:
164 case DBG_REASON_WPTANDBKPT:
165 return 0x05; /* SIGTRAP */
166 case DBG_REASON_SINGLESTEP:
167 return 0x05; /* SIGTRAP */
168 case DBG_REASON_EXC_CATCH:
169 return 0x05;
170 case DBG_REASON_NOTHALTED:
171 return 0x0; /* no signal... shouldn't happen */
172 default:
173 LOG_USER("undefined debug reason %d - target needs reset",
174 target->debug_reason);
175 return 0x0;
176 }
177 }
178
179 static int check_pending(struct connection *connection,
180 int timeout_s, int *got_data)
181 {
182 /* a non-blocking socket will block if there is 0 bytes available on the socket,
183 * but return with as many bytes as are available immediately
184 */
185 struct timeval tv;
186 fd_set read_fds;
187 struct gdb_connection *gdb_con = connection->priv;
188 int t;
189 if (!got_data)
190 got_data = &t;
191 *got_data = 0;
192
193 if (gdb_con->buf_cnt > 0) {
194 *got_data = 1;
195 return ERROR_OK;
196 }
197
198 FD_ZERO(&read_fds);
199 FD_SET(connection->fd, &read_fds);
200
201 tv.tv_sec = timeout_s;
202 tv.tv_usec = 0;
203 if (socket_select(connection->fd + 1, &read_fds, NULL, NULL, &tv) == 0) {
204 /* This can typically be because a "monitor" command took too long
205 * before printing any progress messages
206 */
207 if (timeout_s > 0)
208 return ERROR_GDB_TIMEOUT;
209 else
210 return ERROR_OK;
211 }
212 *got_data = FD_ISSET(connection->fd, &read_fds) != 0;
213 return ERROR_OK;
214 }
215
216 static int gdb_get_char_inner(struct connection *connection, int *next_char)
217 {
218 struct gdb_connection *gdb_con = connection->priv;
219 int retval = ERROR_OK;
220
221 #ifdef _DEBUG_GDB_IO_
222 char *debug_buffer;
223 #endif
224 for (;; ) {
225 if (connection->service->type != CONNECTION_TCP)
226 gdb_con->buf_cnt = read(connection->fd, gdb_con->buffer, GDB_BUFFER_SIZE);
227 else {
228 retval = check_pending(connection, 1, NULL);
229 if (retval != ERROR_OK)
230 return retval;
231 gdb_con->buf_cnt = read_socket(connection->fd,
232 gdb_con->buffer,
233 GDB_BUFFER_SIZE);
234 }
235
236 if (gdb_con->buf_cnt > 0)
237 break;
238 if (gdb_con->buf_cnt == 0) {
239 LOG_DEBUG("GDB connection closed by the remote client");
240 gdb_con->closed = true;
241 return ERROR_SERVER_REMOTE_CLOSED;
242 }
243
244 #ifdef _WIN32
245 errno = WSAGetLastError();
246
247 switch (errno) {
248 case WSAEWOULDBLOCK:
249 usleep(1000);
250 break;
251 case WSAECONNABORTED:
252 gdb_con->closed = true;
253 return ERROR_SERVER_REMOTE_CLOSED;
254 case WSAECONNRESET:
255 gdb_con->closed = true;
256 return ERROR_SERVER_REMOTE_CLOSED;
257 default:
258 LOG_ERROR("read: %d", errno);
259 exit(-1);
260 }
261 #else
262 switch (errno) {
263 case EAGAIN:
264 usleep(1000);
265 break;
266 case ECONNABORTED:
267 gdb_con->closed = true;
268 return ERROR_SERVER_REMOTE_CLOSED;
269 case ECONNRESET:
270 gdb_con->closed = true;
271 return ERROR_SERVER_REMOTE_CLOSED;
272 default:
273 LOG_ERROR("read: %s", strerror(errno));
274 gdb_con->closed = true;
275 return ERROR_SERVER_REMOTE_CLOSED;
276 }
277 #endif
278 }
279
280 #ifdef _DEBUG_GDB_IO_
281 debug_buffer = strndup(gdb_con->buffer, gdb_con->buf_cnt);
282 LOG_DEBUG("received '%s'", debug_buffer);
283 free(debug_buffer);
284 #endif
285
286 gdb_con->buf_p = gdb_con->buffer;
287 gdb_con->buf_cnt--;
288 *next_char = *(gdb_con->buf_p++);
289 if (gdb_con->buf_cnt > 0)
290 connection->input_pending = true;
291 else
292 connection->input_pending = false;
293 #ifdef _DEBUG_GDB_IO_
294 LOG_DEBUG("returned char '%c' (0x%2.2x)", *next_char, *next_char);
295 #endif
296
297 return retval;
298 }
299
300 /**
301 * The cool thing about this fn is that it allows buf_p and buf_cnt to be
302 * held in registers in the inner loop.
303 *
304 * For small caches and embedded systems this is important!
305 */
306 static inline int gdb_get_char_fast(struct connection *connection,
307 int *next_char, char **buf_p, int *buf_cnt)
308 {
309 int retval = ERROR_OK;
310
311 if ((*buf_cnt)-- > 0) {
312 *next_char = **buf_p;
313 (*buf_p)++;
314 if (*buf_cnt > 0)
315 connection->input_pending = true;
316 else
317 connection->input_pending = false;
318
319 #ifdef _DEBUG_GDB_IO_
320 LOG_DEBUG("returned char '%c' (0x%2.2x)", *next_char, *next_char);
321 #endif
322
323 return ERROR_OK;
324 }
325
326 struct gdb_connection *gdb_con = connection->priv;
327 gdb_con->buf_p = *buf_p;
328 gdb_con->buf_cnt = *buf_cnt;
329 retval = gdb_get_char_inner(connection, next_char);
330 *buf_p = gdb_con->buf_p;
331 *buf_cnt = gdb_con->buf_cnt;
332
333 return retval;
334 }
335
336 static int gdb_get_char(struct connection *connection, int *next_char)
337 {
338 struct gdb_connection *gdb_con = connection->priv;
339 return gdb_get_char_fast(connection, next_char, &gdb_con->buf_p, &gdb_con->buf_cnt);
340 }
341
342 static int gdb_putback_char(struct connection *connection, int last_char)
343 {
344 struct gdb_connection *gdb_con = connection->priv;
345
346 if (gdb_con->buf_p > gdb_con->buffer) {
347 *(--gdb_con->buf_p) = last_char;
348 gdb_con->buf_cnt++;
349 } else
350 LOG_ERROR("BUG: couldn't put character back");
351
352 return ERROR_OK;
353 }
354
355 /* The only way we can detect that the socket is closed is the first time
356 * we write to it, we will fail. Subsequent write operations will
357 * succeed. Shudder! */
358 static int gdb_write(struct connection *connection, void *data, int len)
359 {
360 struct gdb_connection *gdb_con = connection->priv;
361 if (gdb_con->closed) {
362 LOG_DEBUG("GDB socket marked as closed, cannot write to it.");
363 return ERROR_SERVER_REMOTE_CLOSED;
364 }
365
366 if (connection_write(connection, data, len) == len)
367 return ERROR_OK;
368
369 LOG_WARNING("Error writing to GDB socket. Dropping the connection.");
370 gdb_con->closed = true;
371 return ERROR_SERVER_REMOTE_CLOSED;
372 }
373
374 static void gdb_log_incoming_packet(char *packet)
375 {
376 if (!LOG_LEVEL_IS(LOG_LVL_DEBUG))
377 return;
378
379 /* Avoid dumping non-printable characters to the terminal */
380 const unsigned packet_len = strlen(packet);
381 const char *nonprint = find_nonprint_char(packet, packet_len);
382 if (nonprint) {
383 /* Does packet at least have a prefix that is printable?
384 * Look within the first 50 chars of the packet. */
385 const char *colon = memchr(packet, ':', MIN(50, packet_len));
386 const bool packet_has_prefix = (colon);
387 const bool packet_prefix_printable = (packet_has_prefix && nonprint > colon);
388
389 if (packet_prefix_printable) {
390 const unsigned int prefix_len = colon - packet + 1; /* + 1 to include the ':' */
391 const unsigned int payload_len = packet_len - prefix_len;
392 LOG_DEBUG("received packet: %.*s<binary-data-%u-bytes>", prefix_len, packet, payload_len);
393 } else {
394 LOG_DEBUG("received packet: <binary-data-%u-bytes>", packet_len);
395 }
396 } else {
397 /* All chars printable, dump the packet as is */
398 LOG_DEBUG("received packet: %s", packet);
399 }
400 }
401
402 static void gdb_log_outgoing_packet(char *packet_buf, unsigned int packet_len, unsigned char checksum)
403 {
404 if (!LOG_LEVEL_IS(LOG_LVL_DEBUG))
405 return;
406
407 if (find_nonprint_char(packet_buf, packet_len))
408 LOG_DEBUG("sending packet: $<binary-data-%u-bytes>#%2.2x", packet_len, checksum);
409 else
410 LOG_DEBUG("sending packet: $%.*s#%2.2x'", packet_len, packet_buf, checksum);
411 }
412
413 static int gdb_put_packet_inner(struct connection *connection,
414 char *buffer, int len)
415 {
416 int i;
417 unsigned char my_checksum = 0;
418 int reply;
419 int retval;
420 struct gdb_connection *gdb_con = connection->priv;
421
422 for (i = 0; i < len; i++)
423 my_checksum += buffer[i];
424
425 #ifdef _DEBUG_GDB_IO_
426 /*
427 * At this point we should have nothing in the input queue from GDB,
428 * however sometimes '-' is sent even though we've already received
429 * an ACK (+) for everything we've sent off.
430 */
431 int gotdata;
432 for (;; ) {
433 retval = check_pending(connection, 0, &gotdata);
434 if (retval != ERROR_OK)
435 return retval;
436 if (!gotdata)
437 break;
438 retval = gdb_get_char(connection, &reply);
439 if (retval != ERROR_OK)
440 return retval;
441 if (reply == '$') {
442 /* fix a problem with some IAR tools */
443 gdb_putback_char(connection, reply);
444 LOG_DEBUG("Unexpected start of new packet");
445 break;
446 }
447
448 LOG_WARNING("Discard unexpected char %c", reply);
449 }
450 #endif
451
452 while (1) {
453 gdb_log_outgoing_packet(buffer, len, my_checksum);
454
455 char local_buffer[1024];
456 local_buffer[0] = '$';
457 if ((size_t)len + 4 <= sizeof(local_buffer)) {
458 /* performance gain on smaller packets by only a single call to gdb_write() */
459 memcpy(local_buffer + 1, buffer, len++);
460 len += snprintf(local_buffer + len, sizeof(local_buffer) - len, "#%02x", my_checksum);
461 retval = gdb_write(connection, local_buffer, len);
462 if (retval != ERROR_OK)
463 return retval;
464 } else {
465 /* larger packets are transmitted directly from caller supplied buffer
466 * by several calls to gdb_write() to avoid dynamic allocation */
467 snprintf(local_buffer + 1, sizeof(local_buffer) - 1, "#%02x", my_checksum);
468 retval = gdb_write(connection, local_buffer, 1);
469 if (retval != ERROR_OK)
470 return retval;
471 retval = gdb_write(connection, buffer, len);
472 if (retval != ERROR_OK)
473 return retval;
474 retval = gdb_write(connection, local_buffer + 1, 3);
475 if (retval != ERROR_OK)
476 return retval;
477 }
478
479 if (gdb_con->noack_mode)
480 break;
481
482 retval = gdb_get_char(connection, &reply);
483 if (retval != ERROR_OK)
484 return retval;
485
486 if (reply == '+')
487 break;
488 else if (reply == '-') {
489 /* Stop sending output packets for now */
490 gdb_con->output_flag = GDB_OUTPUT_NO;
491 LOG_WARNING("negative reply, retrying");
492 } else if (reply == 0x3) {
493 gdb_con->ctrl_c = true;
494 retval = gdb_get_char(connection, &reply);
495 if (retval != ERROR_OK)
496 return retval;
497 if (reply == '+')
498 break;
499 else if (reply == '-') {
500 /* Stop sending output packets for now */
501 gdb_con->output_flag = GDB_OUTPUT_NO;
502 LOG_WARNING("negative reply, retrying");
503 } else if (reply == '$') {
504 LOG_ERROR("GDB missing ack(1) - assumed good");
505 gdb_putback_char(connection, reply);
506 return ERROR_OK;
507 } else {
508 LOG_ERROR("unknown character(1) 0x%2.2x in reply, dropping connection", reply);
509 gdb_con->closed = true;
510 return ERROR_SERVER_REMOTE_CLOSED;
511 }
512 } else if (reply == '$') {
513 LOG_ERROR("GDB missing ack(2) - assumed good");
514 gdb_putback_char(connection, reply);
515 return ERROR_OK;
516 } else {
517 LOG_ERROR("unknown character(2) 0x%2.2x in reply, dropping connection",
518 reply);
519 gdb_con->closed = true;
520 return ERROR_SERVER_REMOTE_CLOSED;
521 }
522 }
523 if (gdb_con->closed)
524 return ERROR_SERVER_REMOTE_CLOSED;
525
526 return ERROR_OK;
527 }
528
529 int gdb_put_packet(struct connection *connection, char *buffer, int len)
530 {
531 struct gdb_connection *gdb_con = connection->priv;
532 gdb_con->busy = true;
533 int retval = gdb_put_packet_inner(connection, buffer, len);
534 gdb_con->busy = false;
535
536 /* we sent some data, reset timer for keep alive messages */
537 kept_alive();
538
539 return retval;
540 }
541
542 static inline int fetch_packet(struct connection *connection,
543 int *checksum_ok, int noack, int *len, char *buffer)
544 {
545 unsigned char my_checksum = 0;
546 char checksum[3];
547 int character;
548 int retval = ERROR_OK;
549
550 struct gdb_connection *gdb_con = connection->priv;
551 my_checksum = 0;
552 int count = 0;
553 count = 0;
554
555 /* move this over into local variables to use registers and give the
556 * more freedom to optimize */
557 char *buf_p = gdb_con->buf_p;
558 int buf_cnt = gdb_con->buf_cnt;
559
560 for (;; ) {
561 /* The common case is that we have an entire packet with no escape chars.
562 * We need to leave at least 2 bytes in the buffer to have
563 * gdb_get_char() update various bits and bobs correctly.
564 */
565 if ((buf_cnt > 2) && ((buf_cnt + count) < *len)) {
566 /* The compiler will struggle a bit with constant propagation and
567 * aliasing, so we help it by showing that these values do not
568 * change inside the loop
569 */
570 int i;
571 char *buf = buf_p;
572 int run = buf_cnt - 2;
573 i = 0;
574 int done = 0;
575 while (i < run) {
576 character = *buf++;
577 i++;
578 if (character == '#') {
579 /* Danger! character can be '#' when esc is
580 * used so we need an explicit boolean for done here. */
581 done = 1;
582 break;
583 }
584
585 if (character == '}') {
586 /* data transmitted in binary mode (X packet)
587 * uses 0x7d as escape character */
588 my_checksum += character & 0xff;
589 character = *buf++;
590 i++;
591 my_checksum += character & 0xff;
592 buffer[count++] = (character ^ 0x20) & 0xff;
593 } else {
594 my_checksum += character & 0xff;
595 buffer[count++] = character & 0xff;
596 }
597 }
598 buf_p += i;
599 buf_cnt -= i;
600 if (done)
601 break;
602 }
603 if (count > *len) {
604 LOG_ERROR("packet buffer too small");
605 retval = ERROR_GDB_BUFFER_TOO_SMALL;
606 break;
607 }
608
609 retval = gdb_get_char_fast(connection, &character, &buf_p, &buf_cnt);
610 if (retval != ERROR_OK)
611 break;
612
613 if (character == '#')
614 break;
615
616 if (character == '}') {
617 /* data transmitted in binary mode (X packet)
618 * uses 0x7d as escape character */
619 my_checksum += character & 0xff;
620
621 retval = gdb_get_char_fast(connection, &character, &buf_p, &buf_cnt);
622 if (retval != ERROR_OK)
623 break;
624
625 my_checksum += character & 0xff;
626 buffer[count++] = (character ^ 0x20) & 0xff;
627 } else {
628 my_checksum += character & 0xff;
629 buffer[count++] = character & 0xff;
630 }
631 }
632
633 gdb_con->buf_p = buf_p;
634 gdb_con->buf_cnt = buf_cnt;
635
636 if (retval != ERROR_OK)
637 return retval;
638
639 *len = count;
640
641 retval = gdb_get_char(connection, &character);
642 if (retval != ERROR_OK)
643 return retval;
644 checksum[0] = character;
645 retval = gdb_get_char(connection, &character);
646 if (retval != ERROR_OK)
647 return retval;
648 checksum[1] = character;
649 checksum[2] = 0;
650
651 if (!noack)
652 *checksum_ok = (my_checksum == strtoul(checksum, NULL, 16));
653
654 return ERROR_OK;
655 }
656
657 static int gdb_get_packet_inner(struct connection *connection,
658 char *buffer, int *len)
659 {
660 int character;
661 int retval;
662 struct gdb_connection *gdb_con = connection->priv;
663
664 while (1) {
665 do {
666 retval = gdb_get_char(connection, &character);
667 if (retval != ERROR_OK)
668 return retval;
669
670 #ifdef _DEBUG_GDB_IO_
671 LOG_DEBUG("character: '%c'", character);
672 #endif
673
674 switch (character) {
675 case '$':
676 break;
677 case '+':
678 /* According to the GDB documentation
679 * (https://sourceware.org/gdb/onlinedocs/gdb/Packet-Acknowledgment.html):
680 * "gdb sends a final `+` acknowledgment of the stub's `OK`
681 * response, which can be safely ignored by the stub."
682 * However OpenOCD server already is in noack mode at this
683 * point and instead of ignoring this it was emitting a
684 * warning. This code makes server ignore the first ACK
685 * that will be received after going into noack mode,
686 * warning only about subsequent ACK's. */
687 if (gdb_con->noack_mode > 1) {
688 LOG_WARNING("acknowledgment received, but no packet pending");
689 } else if (gdb_con->noack_mode) {
690 LOG_DEBUG("Received first acknowledgment after entering noack mode. Ignoring it.");
691 gdb_con->noack_mode = 2;
692 }
693 break;
694 case '-':
695 LOG_WARNING("negative acknowledgment, but no packet pending");
696 break;
697 case 0x3:
698 gdb_con->ctrl_c = true;
699 *len = 0;
700 return ERROR_OK;
701 default:
702 LOG_WARNING("ignoring character 0x%x", character);
703 break;
704 }
705 } while (character != '$');
706
707 int checksum_ok = 0;
708 /* explicit code expansion here to get faster inlined code in -O3 by not
709 * calculating checksum */
710 if (gdb_con->noack_mode) {
711 retval = fetch_packet(connection, &checksum_ok, 1, len, buffer);
712 if (retval != ERROR_OK)
713 return retval;
714 } else {
715 retval = fetch_packet(connection, &checksum_ok, 0, len, buffer);
716 if (retval != ERROR_OK)
717 return retval;
718 }
719
720 if (gdb_con->noack_mode) {
721 /* checksum is not checked in noack mode */
722 break;
723 }
724 if (checksum_ok) {
725 retval = gdb_write(connection, "+", 1);
726 if (retval != ERROR_OK)
727 return retval;
728 break;
729 }
730 }
731 if (gdb_con->closed)
732 return ERROR_SERVER_REMOTE_CLOSED;
733
734 return ERROR_OK;
735 }
736
737 static int gdb_get_packet(struct connection *connection, char *buffer, int *len)
738 {
739 struct gdb_connection *gdb_con = connection->priv;
740 gdb_con->busy = true;
741 int retval = gdb_get_packet_inner(connection, buffer, len);
742 gdb_con->busy = false;
743 return retval;
744 }
745
746 static int gdb_output_con(struct connection *connection, const char *line)
747 {
748 char *hex_buffer;
749 int bin_size;
750
751 bin_size = strlen(line);
752
753 hex_buffer = malloc(bin_size * 2 + 2);
754 if (!hex_buffer)
755 return ERROR_GDB_BUFFER_TOO_SMALL;
756
757 hex_buffer[0] = 'O';
758 size_t pkt_len = hexify(hex_buffer + 1, (const uint8_t *)line, bin_size,
759 bin_size * 2 + 1);
760 int retval = gdb_put_packet(connection, hex_buffer, pkt_len + 1);
761
762 free(hex_buffer);
763 return retval;
764 }
765
766 static int gdb_output(struct command_context *context, const char *line)
767 {
768 /* this will be dumped to the log and also sent as an O packet if possible */
769 LOG_USER_N("%s", line);
770 return ERROR_OK;
771 }
772
773 static void gdb_signal_reply(struct target *target, struct connection *connection)
774 {
775 struct gdb_connection *gdb_connection = connection->priv;
776 char sig_reply[65];
777 char stop_reason[32];
778 char current_thread[25];
779 int sig_reply_len;
780 int signal_var;
781
782 rtos_update_threads(target);
783
784 if (target->debug_reason == DBG_REASON_EXIT) {
785 sig_reply_len = snprintf(sig_reply, sizeof(sig_reply), "W00");
786 } else {
787 struct target *ct;
788 if (target->rtos) {
789 target->rtos->current_threadid = target->rtos->current_thread;
790 target->rtos->gdb_target_for_threadid(connection, target->rtos->current_threadid, &ct);
791 } else {
792 ct = target;
793 }
794
795 if (gdb_connection->ctrl_c) {
796 signal_var = 0x2;
797 } else
798 signal_var = gdb_last_signal(ct);
799
800 stop_reason[0] = '\0';
801 if (ct->debug_reason == DBG_REASON_WATCHPOINT) {
802 enum watchpoint_rw hit_wp_type;
803 target_addr_t hit_wp_address;
804
805 if (watchpoint_hit(ct, &hit_wp_type, &hit_wp_address) == ERROR_OK) {
806
807 switch (hit_wp_type) {
808 case WPT_WRITE:
809 snprintf(stop_reason, sizeof(stop_reason),
810 "watch:%08" TARGET_PRIxADDR ";", hit_wp_address);
811 break;
812 case WPT_READ:
813 snprintf(stop_reason, sizeof(stop_reason),
814 "rwatch:%08" TARGET_PRIxADDR ";", hit_wp_address);
815 break;
816 case WPT_ACCESS:
817 snprintf(stop_reason, sizeof(stop_reason),
818 "awatch:%08" TARGET_PRIxADDR ";", hit_wp_address);
819 break;
820 default:
821 break;
822 }
823 }
824 }
825
826 current_thread[0] = '\0';
827 if (target->rtos)
828 snprintf(current_thread, sizeof(current_thread), "thread:%" PRIx64 ";",
829 target->rtos->current_thread);
830
831 sig_reply_len = snprintf(sig_reply, sizeof(sig_reply), "T%2.2x%s%s",
832 signal_var, stop_reason, current_thread);
833
834 gdb_connection->ctrl_c = false;
835 }
836
837 gdb_put_packet(connection, sig_reply, sig_reply_len);
838 gdb_connection->frontend_state = TARGET_HALTED;
839 }
840
841 static void gdb_fileio_reply(struct target *target, struct connection *connection)
842 {
843 struct gdb_connection *gdb_connection = connection->priv;
844 char fileio_command[256];
845 int command_len;
846 bool program_exited = false;
847
848 if (strcmp(target->fileio_info->identifier, "open") == 0)
849 sprintf(fileio_command, "F%s,%" PRIx64 "/%" PRIx64 ",%" PRIx64 ",%" PRIx64, target->fileio_info->identifier,
850 target->fileio_info->param_1,
851 target->fileio_info->param_2 + 1, /* len + trailing zero */
852 target->fileio_info->param_3,
853 target->fileio_info->param_4);
854 else if (strcmp(target->fileio_info->identifier, "close") == 0)
855 sprintf(fileio_command, "F%s,%" PRIx64, target->fileio_info->identifier,
856 target->fileio_info->param_1);
857 else if (strcmp(target->fileio_info->identifier, "read") == 0)
858 sprintf(fileio_command, "F%s,%" PRIx64 ",%" PRIx64 ",%" PRIx64, target->fileio_info->identifier,
859 target->fileio_info->param_1,
860 target->fileio_info->param_2,
861 target->fileio_info->param_3);
862 else if (strcmp(target->fileio_info->identifier, "write") == 0)
863 sprintf(fileio_command, "F%s,%" PRIx64 ",%" PRIx64 ",%" PRIx64, target->fileio_info->identifier,
864 target->fileio_info->param_1,
865 target->fileio_info->param_2,
866 target->fileio_info->param_3);
867 else if (strcmp(target->fileio_info->identifier, "lseek") == 0)
868 sprintf(fileio_command, "F%s,%" PRIx64 ",%" PRIx64 ",%" PRIx64, target->fileio_info->identifier,
869 target->fileio_info->param_1,
870 target->fileio_info->param_2,
871 target->fileio_info->param_3);
872 else if (strcmp(target->fileio_info->identifier, "rename") == 0)
873 sprintf(fileio_command, "F%s,%" PRIx64 "/%" PRIx64 ",%" PRIx64 "/%" PRIx64, target->fileio_info->identifier,
874 target->fileio_info->param_1,
875 target->fileio_info->param_2 + 1, /* len + trailing zero */
876 target->fileio_info->param_3,
877 target->fileio_info->param_4 + 1); /* len + trailing zero */
878 else if (strcmp(target->fileio_info->identifier, "unlink") == 0)
879 sprintf(fileio_command, "F%s,%" PRIx64 "/%" PRIx64, target->fileio_info->identifier,
880 target->fileio_info->param_1,
881 target->fileio_info->param_2 + 1); /* len + trailing zero */
882 else if (strcmp(target->fileio_info->identifier, "stat") == 0)
883 sprintf(fileio_command, "F%s,%" PRIx64 "/%" PRIx64 ",%" PRIx64, target->fileio_info->identifier,
884 target->fileio_info->param_1,
885 target->fileio_info->param_2,
886 target->fileio_info->param_3);
887 else if (strcmp(target->fileio_info->identifier, "fstat") == 0)
888 sprintf(fileio_command, "F%s,%" PRIx64 ",%" PRIx64, target->fileio_info->identifier,
889 target->fileio_info->param_1,
890 target->fileio_info->param_2);
891 else if (strcmp(target->fileio_info->identifier, "gettimeofday") == 0)
892 sprintf(fileio_command, "F%s,%" PRIx64 ",%" PRIx64, target->fileio_info->identifier,
893 target->fileio_info->param_1,
894 target->fileio_info->param_2);
895 else if (strcmp(target->fileio_info->identifier, "isatty") == 0)
896 sprintf(fileio_command, "F%s,%" PRIx64, target->fileio_info->identifier,
897 target->fileio_info->param_1);
898 else if (strcmp(target->fileio_info->identifier, "system") == 0)
899 sprintf(fileio_command, "F%s,%" PRIx64 "/%" PRIx64, target->fileio_info->identifier,
900 target->fileio_info->param_1,
901 target->fileio_info->param_2 + 1); /* len + trailing zero */
902 else if (strcmp(target->fileio_info->identifier, "exit") == 0) {
903 /* If target hits exit syscall, report to GDB the program is terminated.
904 * In addition, let target run its own exit syscall handler. */
905 program_exited = true;
906 sprintf(fileio_command, "W%02" PRIx64, target->fileio_info->param_1);
907 } else {
908 LOG_DEBUG("Unknown syscall: %s", target->fileio_info->identifier);
909
910 /* encounter unknown syscall, continue */
911 gdb_connection->frontend_state = TARGET_RUNNING;
912 target_resume(target, 1, 0x0, 0, 0);
913 return;
914 }
915
916 command_len = strlen(fileio_command);
917 gdb_put_packet(connection, fileio_command, command_len);
918
919 if (program_exited) {
920 /* Use target_resume() to let target run its own exit syscall handler. */
921 gdb_connection->frontend_state = TARGET_RUNNING;
922 target_resume(target, 1, 0x0, 0, 0);
923 } else {
924 gdb_connection->frontend_state = TARGET_HALTED;
925 rtos_update_threads(target);
926 }
927 }
928
929 static void gdb_frontend_halted(struct target *target, struct connection *connection)
930 {
931 struct gdb_connection *gdb_connection = connection->priv;
932
933 /* In the GDB protocol when we are stepping or continuing execution,
934 * we have a lingering reply. Upon receiving a halted event
935 * when we have that lingering packet, we reply to the original
936 * step or continue packet.
937 *
938 * Executing monitor commands can bring the target in and
939 * out of the running state so we'll see lots of TARGET_EVENT_XXX
940 * that are to be ignored.
941 */
942 if (gdb_connection->frontend_state == TARGET_RUNNING) {
943 /* stop forwarding log packets! */
944 gdb_connection->output_flag = GDB_OUTPUT_NO;
945
946 /* check fileio first */
947 if (target_get_gdb_fileio_info(target, target->fileio_info) == ERROR_OK)
948 gdb_fileio_reply(target, connection);
949 else
950 gdb_signal_reply(target, connection);
951 }
952 }
953
954 static int gdb_target_callback_event_handler(struct target *target,
955 enum target_event event, void *priv)
956 {
957 struct connection *connection = priv;
958 struct gdb_service *gdb_service = connection->service->priv;
959
960 if (gdb_service->target != target)
961 return ERROR_OK;
962
963 switch (event) {
964 case TARGET_EVENT_GDB_HALT:
965 gdb_frontend_halted(target, connection);
966 break;
967 case TARGET_EVENT_HALTED:
968 target_call_event_callbacks(target, TARGET_EVENT_GDB_END);
969 break;
970 default:
971 break;
972 }
973
974 return ERROR_OK;
975 }
976
977 static int gdb_new_connection(struct connection *connection)
978 {
979 struct gdb_connection *gdb_connection = malloc(sizeof(struct gdb_connection));
980 struct target *target;
981 int retval;
982 int initial_ack;
983
984 target = get_target_from_connection(connection);
985 connection->priv = gdb_connection;
986 connection->cmd_ctx->current_target = target;
987
988 /* initialize gdb connection information */
989 gdb_connection->buf_p = gdb_connection->buffer;
990 gdb_connection->buf_cnt = 0;
991 gdb_connection->ctrl_c = false;
992 gdb_connection->frontend_state = TARGET_HALTED;
993 gdb_connection->vflash_image = NULL;
994 gdb_connection->closed = false;
995 gdb_connection->busy = false;
996 gdb_connection->noack_mode = 0;
997 gdb_connection->sync = false;
998 gdb_connection->mem_write_error = false;
999 gdb_connection->attached = true;
1000 gdb_connection->extended_protocol = false;
1001 gdb_connection->target_desc.tdesc = NULL;
1002 gdb_connection->target_desc.tdesc_length = 0;
1003 gdb_connection->thread_list = NULL;
1004 gdb_connection->output_flag = GDB_OUTPUT_NO;
1005
1006 /* send ACK to GDB for debug request */
1007 gdb_write(connection, "+", 1);
1008
1009 /* output goes through gdb connection */
1010 command_set_output_handler(connection->cmd_ctx, gdb_output, connection);
1011
1012 /* we must remove all breakpoints registered to the target as a previous
1013 * GDB session could leave dangling breakpoints if e.g. communication
1014 * timed out.
1015 */
1016 breakpoint_clear_target(target);
1017 watchpoint_clear_target(target);
1018
1019 /* Since version 3.95 (gdb-19990504), with the exclusion of 6.5~6.8, GDB
1020 * sends an ACK at connection with the following comment in its source code:
1021 * "Ack any packet which the remote side has already sent."
1022 * LLDB does the same since the first gdb-remote implementation.
1023 * Remove the initial ACK from the incoming buffer.
1024 */
1025 retval = gdb_get_char(connection, &initial_ack);
1026 if (retval != ERROR_OK)
1027 return retval;
1028
1029 if (initial_ack != '+')
1030 gdb_putback_char(connection, initial_ack);
1031
1032 target_call_event_callbacks(target, TARGET_EVENT_GDB_ATTACH);
1033
1034 if (target->rtos) {
1035 /* clean previous rtos session if supported*/
1036 if (target->rtos->type->clean)
1037 target->rtos->type->clean(target);
1038
1039 /* update threads */
1040 rtos_update_threads(target);
1041 }
1042
1043 if (gdb_use_memory_map) {
1044 /* Connect must fail if the memory map can't be set up correctly.
1045 *
1046 * This will cause an auto_probe to be invoked, which is either
1047 * a no-op or it will fail when the target isn't ready(e.g. not halted).
1048 */
1049 for (unsigned int i = 0; i < flash_get_bank_count(); i++) {
1050 struct flash_bank *p;
1051 p = get_flash_bank_by_num_noprobe(i);
1052 if (p->target != target)
1053 continue;
1054 retval = get_flash_bank_by_num(i, &p);
1055 if (retval != ERROR_OK) {
1056 LOG_ERROR("Connect failed. Consider setting up a gdb-attach event for the target "
1057 "to prepare target for GDB connect, or use 'gdb_memory_map disable'.");
1058 return retval;
1059 }
1060 }
1061 }
1062
1063 gdb_actual_connections++;
1064 log_printf_lf(all_targets->next ? LOG_LVL_INFO : LOG_LVL_DEBUG,
1065 __FILE__, __LINE__, __func__,
1066 "New GDB Connection: %d, Target %s, state: %s",
1067 gdb_actual_connections,
1068 target_name(target),
1069 target_state_name(target));
1070
1071 if (!target_was_examined(target)) {
1072 LOG_ERROR("Target %s not examined yet, refuse gdb connection %d!",
1073 target_name(target), gdb_actual_connections);
1074 gdb_actual_connections--;
1075 return ERROR_TARGET_NOT_EXAMINED;
1076 }
1077
1078 if (target->state != TARGET_HALTED)
1079 LOG_WARNING("GDB connection %d on target %s not halted",
1080 gdb_actual_connections, target_name(target));
1081
1082 /* DANGER! If we fail subsequently, we must remove this handler,
1083 * otherwise we occasionally see crashes as the timer can invoke the
1084 * callback fn.
1085 *
1086 * register callback to be informed about target events */
1087 target_register_event_callback(gdb_target_callback_event_handler, connection);
1088
1089 log_add_callback(gdb_log_callback, connection);
1090
1091 return ERROR_OK;
1092 }
1093
1094 static int gdb_connection_closed(struct connection *connection)
1095 {
1096 struct target *target;
1097 struct gdb_connection *gdb_connection = connection->priv;
1098
1099 target = get_target_from_connection(connection);
1100
1101 /* we're done forwarding messages. Tear down callback before
1102 * cleaning up connection.
1103 */
1104 log_remove_callback(gdb_log_callback, connection);
1105
1106 gdb_actual_connections--;
1107 LOG_DEBUG("GDB Close, Target: %s, state: %s, gdb_actual_connections=%d",
1108 target_name(target),
1109 target_state_name(target),
1110 gdb_actual_connections);
1111
1112 /* see if an image built with vFlash commands is left */
1113 if (gdb_connection->vflash_image) {
1114 image_close(gdb_connection->vflash_image);
1115 free(gdb_connection->vflash_image);
1116 gdb_connection->vflash_image = NULL;
1117 }
1118
1119 /* if this connection registered a debug-message receiver delete it */
1120 delete_debug_msg_receiver(connection->cmd_ctx, target);
1121
1122 free(connection->priv);
1123 connection->priv = NULL;
1124
1125 target_unregister_event_callback(gdb_target_callback_event_handler, connection);
1126
1127 target_call_event_callbacks(target, TARGET_EVENT_GDB_END);
1128
1129 target_call_event_callbacks(target, TARGET_EVENT_GDB_DETACH);
1130
1131 return ERROR_OK;
1132 }
1133
1134 static void gdb_send_error(struct connection *connection, uint8_t the_error)
1135 {
1136 char err[4];
1137 snprintf(err, 4, "E%2.2X", the_error);
1138 gdb_put_packet(connection, err, 3);
1139 }
1140
1141 static int gdb_last_signal_packet(struct connection *connection,
1142 char const *packet, int packet_size)
1143 {
1144 struct target *target = get_target_from_connection(connection);
1145 struct gdb_connection *gdb_con = connection->priv;
1146 char sig_reply[4];
1147 int signal_var;
1148
1149 if (!gdb_con->attached) {
1150 /* if we are here we have received a kill packet
1151 * reply W stop reply otherwise gdb gets very unhappy */
1152 gdb_put_packet(connection, "W00", 3);
1153 return ERROR_OK;
1154 }
1155
1156 signal_var = gdb_last_signal(target);
1157
1158 snprintf(sig_reply, 4, "S%2.2x", signal_var);
1159 gdb_put_packet(connection, sig_reply, 3);
1160
1161 return ERROR_OK;
1162 }
1163
1164 static inline int gdb_reg_pos(struct target *target, int pos, int len)
1165 {
1166 if (target->endianness == TARGET_LITTLE_ENDIAN)
1167 return pos;
1168 else
1169 return len - 1 - pos;
1170 }
1171
1172 /* Convert register to string of bytes. NB! The # of bits in the
1173 * register might be non-divisible by 8(a byte), in which
1174 * case an entire byte is shown.
1175 *
1176 * NB! the format on the wire is the target endianness
1177 *
1178 * The format of reg->value is little endian
1179 *
1180 */
1181 static void gdb_str_to_target(struct target *target,
1182 char *tstr, struct reg *reg)
1183 {
1184 int i;
1185
1186 uint8_t *buf;
1187 int buf_len;
1188 buf = reg->value;
1189 buf_len = DIV_ROUND_UP(reg->size, 8);
1190
1191 for (i = 0; i < buf_len; i++) {
1192 int j = gdb_reg_pos(target, i, buf_len);
1193 tstr += sprintf(tstr, "%02x", buf[j]);
1194 }
1195 }
1196
1197 /* copy over in register buffer */
1198 static void gdb_target_to_reg(struct target *target,
1199 char const *tstr, int str_len, uint8_t *bin)
1200 {
1201 if (str_len % 2) {
1202 LOG_ERROR("BUG: gdb value with uneven number of characters encountered");
1203 exit(-1);
1204 }
1205
1206 int i;
1207 for (i = 0; i < str_len; i += 2) {
1208 unsigned t;
1209 if (sscanf(tstr + i, "%02x", &t) != 1) {
1210 LOG_ERROR("BUG: unable to convert register value");
1211 exit(-1);
1212 }
1213
1214 int j = gdb_reg_pos(target, i/2, str_len/2);
1215 bin[j] = t;
1216 }
1217 }
1218
1219 static int gdb_get_registers_packet(struct connection *connection,
1220 char const *packet, int packet_size)
1221 {
1222 struct target *target = get_target_from_connection(connection);
1223 struct reg **reg_list;
1224 int reg_list_size;
1225 int retval;
1226 int reg_packet_size = 0;
1227 char *reg_packet;
1228 char *reg_packet_p;
1229 int i;
1230
1231 #ifdef _DEBUG_GDB_IO_
1232 LOG_DEBUG("-");
1233 #endif
1234
1235 if ((target->rtos) && (rtos_get_gdb_reg_list(connection) == ERROR_OK))
1236 return ERROR_OK;
1237
1238 retval = target_get_gdb_reg_list(target, &reg_list, &reg_list_size,
1239 REG_CLASS_GENERAL);
1240 if (retval != ERROR_OK)
1241 return gdb_error(connection, retval);
1242
1243 for (i = 0; i < reg_list_size; i++) {
1244 if (!reg_list[i] || reg_list[i]->exist == false || reg_list[i]->hidden)
1245 continue;
1246 reg_packet_size += DIV_ROUND_UP(reg_list[i]->size, 8) * 2;
1247 }
1248
1249 assert(reg_packet_size > 0);
1250
1251 reg_packet = malloc(reg_packet_size + 1); /* plus one for string termination null */
1252 if (!reg_packet)
1253 return ERROR_FAIL;
1254
1255 reg_packet_p = reg_packet;
1256
1257 for (i = 0; i < reg_list_size; i++) {
1258 if (!reg_list[i] || reg_list[i]->exist == false || reg_list[i]->hidden)
1259 continue;
1260 if (!reg_list[i]->valid) {
1261 retval = reg_list[i]->type->get(reg_list[i]);
1262 if (retval != ERROR_OK && gdb_report_register_access_error) {
1263 LOG_DEBUG("Couldn't get register %s.", reg_list[i]->name);
1264 free(reg_packet);
1265 free(reg_list);
1266 return gdb_error(connection, retval);
1267 }
1268 }
1269 gdb_str_to_target(target, reg_packet_p, reg_list[i]);
1270 reg_packet_p += DIV_ROUND_UP(reg_list[i]->size, 8) * 2;
1271 }
1272
1273 #ifdef _DEBUG_GDB_IO_
1274 {
1275 char *reg_packet_p_debug;
1276 reg_packet_p_debug = strndup(reg_packet, reg_packet_size);
1277 LOG_DEBUG("reg_packet: %s", reg_packet_p_debug);
1278 free(reg_packet_p_debug);
1279 }
1280 #endif
1281
1282 gdb_put_packet(connection, reg_packet, reg_packet_size);
1283 free(reg_packet);
1284
1285 free(reg_list);
1286
1287 return ERROR_OK;
1288 }
1289
1290 static int gdb_set_registers_packet(struct connection *connection,
1291 char const *packet, int packet_size)
1292 {
1293 struct target *target = get_target_from_connection(connection);
1294 int i;
1295 struct reg **reg_list;
1296 int reg_list_size;
1297 int retval;
1298 char const *packet_p;
1299
1300 #ifdef _DEBUG_GDB_IO_
1301 LOG_DEBUG("-");
1302 #endif
1303
1304 /* skip command character */
1305 packet++;
1306 packet_size--;
1307
1308 if (packet_size % 2) {
1309 LOG_WARNING("GDB set_registers packet with uneven characters received, dropping connection");
1310 return ERROR_SERVER_REMOTE_CLOSED;
1311 }
1312
1313 retval = target_get_gdb_reg_list(target, &reg_list, &reg_list_size,
1314 REG_CLASS_GENERAL);
1315 if (retval != ERROR_OK)
1316 return gdb_error(connection, retval);
1317
1318 packet_p = packet;
1319 for (i = 0; i < reg_list_size; i++) {
1320 uint8_t *bin_buf;
1321 int chars = (DIV_ROUND_UP(reg_list[i]->size, 8) * 2);
1322
1323 if (packet_p + chars > packet + packet_size)
1324 LOG_ERROR("BUG: register packet is too small for registers");
1325
1326 bin_buf = malloc(DIV_ROUND_UP(reg_list[i]->size, 8));
1327 gdb_target_to_reg(target, packet_p, chars, bin_buf);
1328
1329 retval = reg_list[i]->type->set(reg_list[i], bin_buf);
1330 if (retval != ERROR_OK && gdb_report_register_access_error) {
1331 LOG_DEBUG("Couldn't set register %s.", reg_list[i]->name);
1332 free(reg_list);
1333 free(bin_buf);
1334 return gdb_error(connection, retval);
1335 }
1336
1337 /* advance packet pointer */
1338 packet_p += chars;
1339
1340 free(bin_buf);
1341 }
1342
1343 /* free struct reg *reg_list[] array allocated by get_gdb_reg_list */
1344 free(reg_list);
1345
1346 gdb_put_packet(connection, "OK", 2);
1347
1348 return ERROR_OK;
1349 }
1350
1351 static int gdb_get_register_packet(struct connection *connection,
1352 char const *packet, int packet_size)
1353 {
1354 struct target *target = get_target_from_connection(connection);
1355 char *reg_packet;
1356 int reg_num = strtoul(packet + 1, NULL, 16);
1357 struct reg **reg_list;
1358 int reg_list_size;
1359 int retval;
1360
1361 #ifdef _DEBUG_GDB_IO_
1362 LOG_DEBUG("-");
1363 #endif
1364
1365 if ((target->rtos) && (rtos_get_gdb_reg(connection, reg_num) == ERROR_OK))
1366 return ERROR_OK;
1367
1368 retval = target_get_gdb_reg_list_noread(target, &reg_list, &reg_list_size,
1369 REG_CLASS_ALL);
1370 if (retval != ERROR_OK)
1371 return gdb_error(connection, retval);
1372
1373 if (reg_list_size <= reg_num) {
1374 LOG_ERROR("gdb requested a non-existing register (reg_num=%d)", reg_num);
1375 return ERROR_SERVER_REMOTE_CLOSED;
1376 }
1377
1378 if (!reg_list[reg_num]->valid) {
1379 retval = reg_list[reg_num]->type->get(reg_list[reg_num]);
1380 if (retval != ERROR_OK && gdb_report_register_access_error) {
1381 LOG_DEBUG("Couldn't get register %s.", reg_list[reg_num]->name);
1382 free(reg_list);
1383 return gdb_error(connection, retval);
1384 }
1385 }
1386
1387 reg_packet = calloc(DIV_ROUND_UP(reg_list[reg_num]->size, 8) * 2 + 1, 1); /* plus one for string termination null */
1388
1389 gdb_str_to_target(target, reg_packet, reg_list[reg_num]);
1390
1391 gdb_put_packet(connection, reg_packet, DIV_ROUND_UP(reg_list[reg_num]->size, 8) * 2);
1392
1393 free(reg_list);
1394 free(reg_packet);
1395
1396 return ERROR_OK;
1397 }
1398
1399 static int gdb_set_register_packet(struct connection *connection,
1400 char const *packet, int packet_size)
1401 {
1402 struct target *target = get_target_from_connection(connection);
1403 char *separator;
1404 int reg_num = strtoul(packet + 1, &separator, 16);
1405 struct reg **reg_list;
1406 int reg_list_size;
1407 int retval;
1408
1409 #ifdef _DEBUG_GDB_IO_
1410 LOG_DEBUG("-");
1411 #endif
1412
1413 if (*separator != '=') {
1414 LOG_ERROR("GDB 'set register packet', but no '=' following the register number");
1415 return ERROR_SERVER_REMOTE_CLOSED;
1416 }
1417 size_t chars = strlen(separator + 1);
1418 uint8_t *bin_buf = malloc(chars / 2);
1419 gdb_target_to_reg(target, separator + 1, chars, bin_buf);
1420
1421 if ((target->rtos) &&
1422 (rtos_set_reg(connection, reg_num, bin_buf) == ERROR_OK)) {
1423 free(bin_buf);
1424 gdb_put_packet(connection, "OK", 2);
1425 return ERROR_OK;
1426 }
1427
1428 retval = target_get_gdb_reg_list_noread(target, &reg_list, &reg_list_size,
1429 REG_CLASS_ALL);
1430 if (retval != ERROR_OK) {
1431 free(bin_buf);
1432 return gdb_error(connection, retval);
1433 }
1434
1435 if (reg_list_size <= reg_num) {
1436 LOG_ERROR("gdb requested a non-existing register (reg_num=%d)", reg_num);
1437 free(bin_buf);
1438 free(reg_list);
1439 return ERROR_SERVER_REMOTE_CLOSED;
1440 }
1441
1442 if (chars != (DIV_ROUND_UP(reg_list[reg_num]->size, 8) * 2)) {
1443 LOG_ERROR("gdb sent %zu bits for a %" PRIu32 "-bit register (%s)",
1444 chars * 4, reg_list[reg_num]->size, reg_list[reg_num]->name);
1445 free(bin_buf);
1446 free(reg_list);
1447 return ERROR_SERVER_REMOTE_CLOSED;
1448 }
1449
1450 gdb_target_to_reg(target, separator + 1, chars, bin_buf);
1451
1452 retval = reg_list[reg_num]->type->set(reg_list[reg_num], bin_buf);
1453 if (retval != ERROR_OK && gdb_report_register_access_error) {
1454 LOG_DEBUG("Couldn't set register %s.", reg_list[reg_num]->name);
1455 free(bin_buf);
1456 free(reg_list);
1457 return gdb_error(connection, retval);
1458 }
1459
1460 gdb_put_packet(connection, "OK", 2);
1461
1462 free(bin_buf);
1463 free(reg_list);
1464
1465 return ERROR_OK;
1466 }
1467
1468 /* No attempt is made to translate the "retval" to
1469 * GDB speak. This has to be done at the calling
1470 * site as no mapping really exists.
1471 */
1472 static int gdb_error(struct connection *connection, int retval)
1473 {
1474 LOG_DEBUG("Reporting %i to GDB as generic error", retval);
1475 gdb_send_error(connection, EFAULT);
1476 return ERROR_OK;
1477 }
1478
1479 /* We don't have to worry about the default 2 second timeout for GDB packets,
1480 * because GDB breaks up large memory reads into smaller reads.
1481 */
1482 static int gdb_read_memory_packet(struct connection *connection,
1483 char const *packet, int packet_size)
1484 {
1485 struct target *target = get_target_from_connection(connection);
1486 char *separator;
1487 uint64_t addr = 0;
1488 uint32_t len = 0;
1489
1490 uint8_t *buffer;
1491 char *hex_buffer;
1492
1493 int retval = ERROR_OK;
1494
1495 /* skip command character */
1496 packet++;
1497
1498 addr = strtoull(packet, &separator, 16);
1499
1500 if (*separator != ',') {
1501 LOG_ERROR("incomplete read memory packet received, dropping connection");
1502 return ERROR_SERVER_REMOTE_CLOSED;
1503 }
1504
1505 len = strtoul(separator + 1, NULL, 16);
1506
1507 if (!len) {
1508 LOG_WARNING("invalid read memory packet received (len == 0)");
1509 gdb_put_packet(connection, "", 0);
1510 return ERROR_OK;
1511 }
1512
1513 buffer = malloc(len);
1514
1515 LOG_DEBUG("addr: 0x%16.16" PRIx64 ", len: 0x%8.8" PRIx32 "", addr, len);
1516
1517 retval = ERROR_NOT_IMPLEMENTED;
1518 if (target->rtos)
1519 retval = rtos_read_buffer(target, addr, len, buffer);
1520 if (retval == ERROR_NOT_IMPLEMENTED)
1521 retval = target_read_buffer(target, addr, len, buffer);
1522
1523 if ((retval != ERROR_OK) && !gdb_report_data_abort) {
1524 /* TODO : Here we have to lie and send back all zero's lest stack traces won't work.
1525 * At some point this might be fixed in GDB, in which case this code can be removed.
1526 *
1527 * OpenOCD developers are acutely aware of this problem, but there is nothing
1528 * gained by involving the user in this problem that hopefully will get resolved
1529 * eventually
1530 *
1531 * http://sourceware.org/cgi-bin/gnatsweb.pl? \
1532 * cmd = view%20audit-trail&database = gdb&pr = 2395
1533 *
1534 * For now, the default is to fix up things to make current GDB versions work.
1535 * This can be overwritten using the gdb_report_data_abort <'enable'|'disable'> command.
1536 */
1537 memset(buffer, 0, len);
1538 retval = ERROR_OK;
1539 }
1540
1541 if (retval == ERROR_OK) {
1542 hex_buffer = malloc(len * 2 + 1);
1543
1544 size_t pkt_len = hexify(hex_buffer, buffer, len, len * 2 + 1);
1545
1546 gdb_put_packet(connection, hex_buffer, pkt_len);
1547
1548 free(hex_buffer);
1549 } else
1550 retval = gdb_error(connection, retval);
1551
1552 free(buffer);
1553
1554 return retval;
1555 }
1556
1557 static int gdb_write_memory_packet(struct connection *connection,
1558 char const *packet, int packet_size)
1559 {
1560 struct target *target = get_target_from_connection(connection);
1561 char *separator;
1562 uint64_t addr = 0;
1563 uint32_t len = 0;
1564
1565 uint8_t *buffer;
1566 int retval;
1567
1568 /* skip command character */
1569 packet++;
1570
1571 addr = strtoull(packet, &separator, 16);
1572
1573 if (*separator != ',') {
1574 LOG_ERROR("incomplete write memory packet received, dropping connection");
1575 return ERROR_SERVER_REMOTE_CLOSED;
1576 }
1577
1578 len = strtoul(separator + 1, &separator, 16);
1579
1580 if (*(separator++) != ':') {
1581 LOG_ERROR("incomplete write memory packet received, dropping connection");
1582 return ERROR_SERVER_REMOTE_CLOSED;
1583 }
1584
1585 buffer = malloc(len);
1586
1587 LOG_DEBUG("addr: 0x%" PRIx64 ", len: 0x%8.8" PRIx32 "", addr, len);
1588
1589 if (unhexify(buffer, separator, len) != len)
1590 LOG_ERROR("unable to decode memory packet");
1591
1592 retval = ERROR_NOT_IMPLEMENTED;
1593 if (target->rtos)
1594 retval = rtos_write_buffer(target, addr, len, buffer);
1595 if (retval == ERROR_NOT_IMPLEMENTED)
1596 retval = target_write_buffer(target, addr, len, buffer);
1597
1598 if (retval == ERROR_OK)
1599 gdb_put_packet(connection, "OK", 2);
1600 else
1601 retval = gdb_error(connection, retval);
1602
1603 free(buffer);
1604
1605 return retval;
1606 }
1607
1608 static int gdb_write_memory_binary_packet(struct connection *connection,
1609 char const *packet, int packet_size)
1610 {
1611 struct target *target = get_target_from_connection(connection);
1612 char *separator;
1613 uint64_t addr = 0;
1614 uint32_t len = 0;
1615
1616 int retval = ERROR_OK;
1617 /* Packets larger than fast_limit bytes will be acknowledged instantly on
1618 * the assumption that we're in a download and it's important to go as fast
1619 * as possible. */
1620 uint32_t fast_limit = 8;
1621
1622 /* skip command character */
1623 packet++;
1624
1625 addr = strtoull(packet, &separator, 16);
1626
1627 if (*separator != ',') {
1628 LOG_ERROR("incomplete write memory binary packet received, dropping connection");
1629 return ERROR_SERVER_REMOTE_CLOSED;
1630 }
1631
1632 len = strtoul(separator + 1, &separator, 16);
1633
1634 if (*(separator++) != ':') {
1635 LOG_ERROR("incomplete write memory binary packet received, dropping connection");
1636 return ERROR_SERVER_REMOTE_CLOSED;
1637 }
1638
1639 struct gdb_connection *gdb_connection = connection->priv;
1640
1641 if (gdb_connection->mem_write_error)
1642 retval = ERROR_FAIL;
1643
1644 if (retval == ERROR_OK) {
1645 if (len >= fast_limit) {
1646 /* By replying the packet *immediately* GDB will send us a new packet
1647 * while we write the last one to the target.
1648 * We only do this for larger writes, so that users who do something like:
1649 * p *((int*)0xdeadbeef)=8675309
1650 * will get immediate feedback that that write failed.
1651 */
1652 gdb_put_packet(connection, "OK", 2);
1653 }
1654 } else {
1655 retval = gdb_error(connection, retval);
1656 /* now that we have reported the memory write error, we can clear the condition */
1657 gdb_connection->mem_write_error = false;
1658 if (retval != ERROR_OK)
1659 return retval;
1660 }
1661
1662 if (len) {
1663 LOG_DEBUG("addr: 0x%" PRIx64 ", len: 0x%8.8" PRIx32 "", addr, len);
1664
1665 retval = ERROR_NOT_IMPLEMENTED;
1666 if (target->rtos)
1667 retval = rtos_write_buffer(target, addr, len, (uint8_t *)separator);
1668 if (retval == ERROR_NOT_IMPLEMENTED)
1669 retval = target_write_buffer(target, addr, len, (uint8_t *)separator);
1670
1671 if (retval != ERROR_OK)
1672 gdb_connection->mem_write_error = true;
1673 }
1674
1675 if (len < fast_limit) {
1676 if (retval != ERROR_OK) {
1677 gdb_error(connection, retval);
1678 gdb_connection->mem_write_error = false;
1679 } else {
1680 gdb_put_packet(connection, "OK", 2);
1681 }
1682 }
1683
1684 return ERROR_OK;
1685 }
1686
1687 static int gdb_step_continue_packet(struct connection *connection,
1688 char const *packet, int packet_size)
1689 {
1690 struct target *target = get_target_from_connection(connection);
1691 int current = 0;
1692 uint64_t address = 0x0;
1693 int retval = ERROR_OK;
1694
1695 LOG_DEBUG("-");
1696
1697 if (packet_size > 1)
1698 address = strtoull(packet + 1, NULL, 16);
1699 else
1700 current = 1;
1701
1702 gdb_running_type = packet[0];
1703 if (packet[0] == 'c') {
1704 LOG_DEBUG("continue");
1705 /* resume at current address, don't handle breakpoints, not debugging */
1706 retval = target_resume(target, current, address, 0, 0);
1707 } else if (packet[0] == 's') {
1708 LOG_DEBUG("step");
1709 /* step at current or address, don't handle breakpoints */
1710 retval = target_step(target, current, address, 0);
1711 }
1712 return retval;
1713 }
1714
1715 static int gdb_breakpoint_watchpoint_packet(struct connection *connection,
1716 char const *packet, int packet_size)
1717 {
1718 struct target *target = get_target_from_connection(connection);
1719 int type;
1720 enum breakpoint_type bp_type = BKPT_SOFT /* dummy init to avoid warning */;
1721 enum watchpoint_rw wp_type = WPT_READ /* dummy init to avoid warning */;
1722 uint64_t address;
1723 uint32_t size;
1724 char *separator;
1725 int retval;
1726
1727 LOG_DEBUG("[%s]", target_name(target));
1728
1729 type = strtoul(packet + 1, &separator, 16);
1730
1731 if (type == 0) /* memory breakpoint */
1732 bp_type = BKPT_SOFT;
1733 else if (type == 1) /* hardware breakpoint */
1734 bp_type = BKPT_HARD;
1735 else if (type == 2) /* write watchpoint */
1736 wp_type = WPT_WRITE;
1737 else if (type == 3) /* read watchpoint */
1738 wp_type = WPT_READ;
1739 else if (type == 4) /* access watchpoint */
1740 wp_type = WPT_ACCESS;
1741 else {
1742 LOG_ERROR("invalid gdb watch/breakpoint type(%d), dropping connection", type);
1743 return ERROR_SERVER_REMOTE_CLOSED;
1744 }
1745
1746 if (gdb_breakpoint_override && ((bp_type == BKPT_SOFT) || (bp_type == BKPT_HARD)))
1747 bp_type = gdb_breakpoint_override_type;
1748
1749 if (*separator != ',') {
1750 LOG_ERROR("incomplete breakpoint/watchpoint packet received, dropping connection");
1751 return ERROR_SERVER_REMOTE_CLOSED;
1752 }
1753
1754 address = strtoull(separator + 1, &separator, 16);
1755
1756 if (*separator != ',') {
1757 LOG_ERROR("incomplete breakpoint/watchpoint packet received, dropping connection");
1758 return ERROR_SERVER_REMOTE_CLOSED;
1759 }
1760
1761 size = strtoul(separator + 1, &separator, 16);
1762
1763 switch (type) {
1764 case 0:
1765 case 1:
1766 if (packet[0] == 'Z') {
1767 retval = breakpoint_add(target, address, size, bp_type);
1768 if (retval != ERROR_OK) {
1769 retval = gdb_error(connection, retval);
1770 if (retval != ERROR_OK)
1771 return retval;
1772 } else
1773 gdb_put_packet(connection, "OK", 2);
1774 } else {
1775 breakpoint_remove(target, address);
1776 gdb_put_packet(connection, "OK", 2);
1777 }
1778 break;
1779 case 2:
1780 case 3:
1781 case 4:
1782 {
1783 if (packet[0] == 'Z') {
1784 retval = watchpoint_add(target, address, size, wp_type, 0, 0xffffffffu);
1785 if (retval != ERROR_OK) {
1786 retval = gdb_error(connection, retval);
1787 if (retval != ERROR_OK)
1788 return retval;
1789 } else
1790 gdb_put_packet(connection, "OK", 2);
1791 } else {
1792 watchpoint_remove(target, address);
1793 gdb_put_packet(connection, "OK", 2);
1794 }
1795 break;
1796 }
1797 default:
1798 break;
1799 }
1800
1801 return ERROR_OK;
1802 }
1803
1804 /* print out a string and allocate more space as needed,
1805 * mainly used for XML at this point
1806 */
1807 static __attribute__ ((format (PRINTF_ATTRIBUTE_FORMAT, 5, 6))) void xml_printf(int *retval,
1808 char **xml, int *pos, int *size, const char *fmt, ...)
1809 {
1810 if (*retval != ERROR_OK)
1811 return;
1812 int first = 1;
1813
1814 for (;; ) {
1815 if ((!*xml) || (!first)) {
1816 /* start by 0 to exercise all the code paths.
1817 * Need minimum 2 bytes to fit 1 char and 0 terminator. */
1818
1819 *size = *size * 2 + 2;
1820 char *t = *xml;
1821 *xml = realloc(*xml, *size);
1822 if (!*xml) {
1823 free(t);
1824 *retval = ERROR_SERVER_REMOTE_CLOSED;
1825 return;
1826 }
1827 }
1828
1829 va_list ap;
1830 int ret;
1831 va_start(ap, fmt);
1832 ret = vsnprintf(*xml + *pos, *size - *pos, fmt, ap);
1833 va_end(ap);
1834 if ((ret > 0) && ((ret + 1) < *size - *pos)) {
1835 *pos += ret;
1836 return;
1837 }
1838 /* there was just enough or not enough space, allocate more. */
1839 first = 0;
1840 }
1841 }
1842
1843 static int decode_xfer_read(char const *buf, char **annex, int *ofs, unsigned int *len)
1844 {
1845 /* Locate the annex. */
1846 const char *annex_end = strchr(buf, ':');
1847 if (!annex_end)
1848 return ERROR_FAIL;
1849
1850 /* After the read marker and annex, qXfer looks like a
1851 * traditional 'm' packet. */
1852 char *separator;
1853 *ofs = strtoul(annex_end + 1, &separator, 16);
1854
1855 if (*separator != ',')
1856 return ERROR_FAIL;
1857
1858 *len = strtoul(separator + 1, NULL, 16);
1859
1860 /* Extract the annex if needed */
1861 if (annex) {
1862 *annex = strndup(buf, annex_end - buf);
1863 if (!*annex)
1864 return ERROR_FAIL;
1865 }
1866
1867 return ERROR_OK;
1868 }
1869
1870 static int compare_bank(const void *a, const void *b)
1871 {
1872 struct flash_bank *b1, *b2;
1873 b1 = *((struct flash_bank **)a);
1874 b2 = *((struct flash_bank **)b);
1875
1876 if (b1->base == b2->base)
1877 return 0;
1878 else if (b1->base > b2->base)
1879 return 1;
1880 else
1881 return -1;
1882 }
1883
1884 static int gdb_memory_map(struct connection *connection,
1885 char const *packet, int packet_size)
1886 {
1887 /* We get away with only specifying flash here. Regions that are not
1888 * specified are treated as if we provided no memory map(if not we
1889 * could detect the holes and mark them as RAM).
1890 * Normally we only execute this code once, but no big deal if we
1891 * have to regenerate it a couple of times.
1892 */
1893
1894 struct target *target = get_target_from_connection(connection);
1895 struct flash_bank *p;
1896 char *xml = NULL;
1897 int size = 0;
1898 int pos = 0;
1899 int retval = ERROR_OK;
1900 struct flash_bank **banks;
1901 int offset;
1902 int length;
1903 char *separator;
1904 target_addr_t ram_start = 0;
1905 unsigned int target_flash_banks = 0;
1906
1907 /* skip command character */
1908 packet += 23;
1909
1910 offset = strtoul(packet, &separator, 16);
1911 length = strtoul(separator + 1, &separator, 16);
1912
1913 xml_printf(&retval, &xml, &pos, &size, "<memory-map>\n");
1914
1915 /* Sort banks in ascending order. We need to report non-flash
1916 * memory as ram (or rather read/write) by default for GDB, since
1917 * it has no concept of non-cacheable read/write memory (i/o etc).
1918 */
1919 banks = malloc(sizeof(struct flash_bank *)*flash_get_bank_count());
1920
1921 for (unsigned int i = 0; i < flash_get_bank_count(); i++) {
1922 p = get_flash_bank_by_num_noprobe(i);
1923 if (p->target != target)
1924 continue;
1925 retval = get_flash_bank_by_num(i, &p);
1926 if (retval != ERROR_OK) {
1927 free(banks);
1928 gdb_error(connection, retval);
1929 return retval;
1930 }
1931 banks[target_flash_banks++] = p;
1932 }
1933
1934 qsort(banks, target_flash_banks, sizeof(struct flash_bank *),
1935 compare_bank);
1936
1937 for (unsigned int i = 0; i < target_flash_banks; i++) {
1938 unsigned sector_size = 0;
1939 unsigned group_len = 0;
1940
1941 p = banks[i];
1942
1943 if (ram_start < p->base)
1944 xml_printf(&retval, &xml, &pos, &size,
1945 "<memory type=\"ram\" start=\"" TARGET_ADDR_FMT "\" "
1946 "length=\"" TARGET_ADDR_FMT "\"/>\n",
1947 ram_start, p->base - ram_start);
1948
1949 /* Report adjacent groups of same-size sectors. So for
1950 * example top boot CFI flash will list an initial region
1951 * with several large sectors (maybe 128KB) and several
1952 * smaller ones at the end (maybe 32KB). STR7 will have
1953 * regions with 8KB, 32KB, and 64KB sectors; etc.
1954 */
1955 for (unsigned int j = 0; j < p->num_sectors; j++) {
1956
1957 /* Maybe start a new group of sectors. */
1958 if (sector_size == 0) {
1959 if (p->sectors[j].offset + p->sectors[j].size > p->size) {
1960 LOG_WARNING("The flash sector at offset 0x%08" PRIx32
1961 " overflows the end of %s bank.",
1962 p->sectors[j].offset, p->name);
1963 LOG_WARNING("The rest of bank will not show in gdb memory map.");
1964 break;
1965 }
1966 target_addr_t start;
1967 start = p->base + p->sectors[j].offset;
1968 xml_printf(&retval, &xml, &pos, &size,
1969 "<memory type=\"flash\" "
1970 "start=\"" TARGET_ADDR_FMT "\" ",
1971 start);
1972 sector_size = p->sectors[j].size;
1973 group_len = sector_size;
1974 } else {
1975 group_len += sector_size; /* equal to p->sectors[j].size */
1976 }
1977
1978 /* Does this finish a group of sectors?
1979 * If not, continue an already-started group.
1980 */
1981 if (j < p->num_sectors - 1
1982 && p->sectors[j + 1].size == sector_size
1983 && p->sectors[j + 1].offset == p->sectors[j].offset + sector_size
1984 && p->sectors[j + 1].offset + p->sectors[j + 1].size <= p->size)
1985 continue;
1986
1987 xml_printf(&retval, &xml, &pos, &size,
1988 "length=\"0x%x\">\n"
1989 "<property name=\"blocksize\">"
1990 "0x%x</property>\n"
1991 "</memory>\n",
1992 group_len,
1993 sector_size);
1994 sector_size = 0;
1995 }
1996
1997 ram_start = p->base + p->size;
1998 }
1999
2000 if (ram_start != 0)
2001 xml_printf(&retval, &xml, &pos, &size,
2002 "<memory type=\"ram\" start=\"" TARGET_ADDR_FMT "\" "
2003 "length=\"" TARGET_ADDR_FMT "\"/>\n",
2004 ram_start, target_address_max(target) - ram_start + 1);
2005 /* ELSE a flash chip could be at the very end of the address space, in
2006 * which case ram_start will be precisely 0 */
2007
2008 free(banks);
2009
2010 xml_printf(&retval, &xml, &pos, &size, "</memory-map>\n");
2011
2012 if (retval != ERROR_OK) {
2013 free(xml);
2014 gdb_error(connection, retval);
2015 return retval;
2016 }
2017
2018 if (offset + length > pos)
2019 length = pos - offset;
2020
2021 char *t = malloc(length + 1);
2022 t[0] = 'l';
2023 memcpy(t + 1, xml + offset, length);
2024 gdb_put_packet(connection, t, length + 1);
2025
2026 free(t);
2027 free(xml);
2028 return ERROR_OK;
2029 }
2030
2031 static const char *gdb_get_reg_type_name(enum reg_type type)
2032 {
2033 switch (type) {
2034 case REG_TYPE_BOOL:
2035 return "bool";
2036 case REG_TYPE_INT:
2037 return "int";
2038 case REG_TYPE_INT8:
2039 return "int8";
2040 case REG_TYPE_INT16:
2041 return "int16";
2042 case REG_TYPE_INT32:
2043 return "int32";
2044 case REG_TYPE_INT64:
2045 return "int64";
2046 case REG_TYPE_INT128:
2047 return "int128";
2048 case REG_TYPE_UINT:
2049 return "uint";
2050 case REG_TYPE_UINT8:
2051 return "uint8";
2052 case REG_TYPE_UINT16:
2053 return "uint16";
2054 case REG_TYPE_UINT32:
2055 return "uint32";
2056 case REG_TYPE_UINT64:
2057 return "uint64";
2058 case REG_TYPE_UINT128:
2059 return "uint128";
2060 case REG_TYPE_CODE_PTR:
2061 return "code_ptr";
2062 case REG_TYPE_DATA_PTR:
2063 return "data_ptr";
2064 case REG_TYPE_FLOAT:
2065 return "float";
2066 case REG_TYPE_IEEE_SINGLE:
2067 return "ieee_single";
2068 case REG_TYPE_IEEE_DOUBLE:
2069 return "ieee_double";
2070 case REG_TYPE_ARCH_DEFINED:
2071 return "int"; /* return arbitrary string to avoid compile warning. */
2072 }
2073
2074 return "int"; /* "int" as default value */
2075 }
2076
2077 static int lookup_add_arch_defined_types(char const **arch_defined_types_list[], const char *type_id,
2078 int *num_arch_defined_types)
2079 {
2080 int tbl_sz = *num_arch_defined_types;
2081
2082 if (type_id && (strcmp(type_id, ""))) {
2083 for (int j = 0; j < (tbl_sz + 1); j++) {
2084 if (!((*arch_defined_types_list)[j])) {
2085 (*arch_defined_types_list)[tbl_sz++] = type_id;
2086 *arch_defined_types_list = realloc(*arch_defined_types_list,
2087 sizeof(char *) * (tbl_sz + 1));
2088 (*arch_defined_types_list)[tbl_sz] = NULL;
2089 *num_arch_defined_types = tbl_sz;
2090 return 1;
2091 } else {
2092 if (!strcmp((*arch_defined_types_list)[j], type_id))
2093 return 0;
2094 }
2095 }
2096 }
2097
2098 return -1;
2099 }
2100
2101 static int gdb_generate_reg_type_description(struct target *target,
2102 char **tdesc, int *pos, int *size, struct reg_data_type *type,
2103 char const **arch_defined_types_list[], int *num_arch_defined_types)
2104 {
2105 int retval = ERROR_OK;
2106
2107 if (type->type_class == REG_TYPE_CLASS_VECTOR) {
2108 struct reg_data_type *data_type = type->reg_type_vector->type;
2109 if (data_type->type == REG_TYPE_ARCH_DEFINED) {
2110 if (lookup_add_arch_defined_types(arch_defined_types_list, data_type->id,
2111 num_arch_defined_types))
2112 gdb_generate_reg_type_description(target, tdesc, pos, size, data_type,
2113 arch_defined_types_list,
2114 num_arch_defined_types);
2115 }
2116 /* <vector id="id" type="type" count="count"/> */
2117 xml_printf(&retval, tdesc, pos, size,
2118 "<vector id=\"%s\" type=\"%s\" count=\"%" PRIu32 "\"/>\n",
2119 type->id, type->reg_type_vector->type->id,
2120 type->reg_type_vector->count);
2121
2122 } else if (type->type_class == REG_TYPE_CLASS_UNION) {
2123 struct reg_data_type_union_field *field;
2124 field = type->reg_type_union->fields;
2125 while (field) {
2126 struct reg_data_type *data_type = field->type;
2127 if (data_type->type == REG_TYPE_ARCH_DEFINED) {
2128 if (lookup_add_arch_defined_types(arch_defined_types_list, data_type->id,
2129 num_arch_defined_types))
2130 gdb_generate_reg_type_description(target, tdesc, pos, size, data_type,
2131 arch_defined_types_list,
2132 num_arch_defined_types);
2133 }
2134
2135 field = field->next;
2136 }
2137 /* <union id="id">
2138 * <field name="name" type="type"/> ...
2139 * </union> */
2140 xml_printf(&retval, tdesc, pos, size,
2141 "<union id=\"%s\">\n",
2142 type->id);
2143
2144 field = type->reg_type_union->fields;
2145 while (field) {
2146 xml_printf(&retval, tdesc, pos, size,
2147 "<field name=\"%s\" type=\"%s\"/>\n",
2148 field->name, field->type->id);
2149
2150 field = field->next;
2151 }
2152
2153 xml_printf(&retval, tdesc, pos, size,
2154 "</union>\n");
2155
2156 } else if (type->type_class == REG_TYPE_CLASS_STRUCT) {
2157 struct reg_data_type_struct_field *field;
2158 field = type->reg_type_struct->fields;
2159
2160 if (field->use_bitfields) {
2161 /* <struct id="id" size="size">
2162 * <field name="name" start="start" end="end"/> ...
2163 * </struct> */
2164 xml_printf(&retval, tdesc, pos, size,
2165 "<struct id=\"%s\" size=\"%" PRIu32 "\">\n",
2166 type->id, type->reg_type_struct->size);
2167 while (field) {
2168 xml_printf(&retval, tdesc, pos, size,
2169 "<field name=\"%s\" start=\"%" PRIu32 "\" end=\"%" PRIu32 "\" type=\"%s\" />\n",
2170 field->name, field->bitfield->start, field->bitfield->end,
2171 gdb_get_reg_type_name(field->bitfield->type));
2172
2173 field = field->next;
2174 }
2175 } else {
2176 while (field) {
2177 struct reg_data_type *data_type = field->type;
2178 if (data_type->type == REG_TYPE_ARCH_DEFINED) {
2179 if (lookup_add_arch_defined_types(arch_defined_types_list, data_type->id,
2180 num_arch_defined_types))
2181 gdb_generate_reg_type_description(target, tdesc, pos, size, data_type,
2182 arch_defined_types_list,
2183 num_arch_defined_types);
2184 }
2185 }
2186
2187 /* <struct id="id">
2188 * <field name="name" type="type"/> ...
2189 * </struct> */
2190 xml_printf(&retval, tdesc, pos, size,
2191 "<struct id=\"%s\">\n",
2192 type->id);
2193 while (field) {
2194 xml_printf(&retval, tdesc, pos, size,
2195 "<field name=\"%s\" type=\"%s\"/>\n",
2196 field->name, field->type->id);
2197
2198 field = field->next;
2199 }
2200 }
2201
2202 xml_printf(&retval, tdesc, pos, size,
2203 "</struct>\n");
2204
2205 } else if (type->type_class == REG_TYPE_CLASS_FLAGS) {
2206 /* <flags id="id" size="size">
2207 * <field name="name" start="start" end="end"/> ...
2208 * </flags> */
2209 xml_printf(&retval, tdesc, pos, size,
2210 "<flags id=\"%s\" size=\"%" PRIu32 "\">\n",
2211 type->id, type->reg_type_flags->size);
2212
2213 struct reg_data_type_flags_field *field;
2214 field = type->reg_type_flags->fields;
2215 while (field) {
2216 xml_printf(&retval, tdesc, pos, size,
2217 "<field name=\"%s\" start=\"%" PRIu32 "\" end=\"%" PRIu32 "\" type=\"%s\" />\n",
2218 field->name, field->bitfield->start, field->bitfield->end,
2219 gdb_get_reg_type_name(field->bitfield->type));
2220
2221 field = field->next;
2222 }
2223
2224 xml_printf(&retval, tdesc, pos, size,
2225 "</flags>\n");
2226
2227 }
2228
2229 return ERROR_OK;
2230 }
2231
2232 /* Get a list of available target registers features. feature_list must
2233 * be freed by caller.
2234 */
2235 static int get_reg_features_list(struct target *target, char const **feature_list[], int *feature_list_size,
2236 struct reg **reg_list, int reg_list_size)
2237 {
2238 int tbl_sz = 0;
2239
2240 /* Start with only one element */
2241 *feature_list = calloc(1, sizeof(char *));
2242
2243 for (int i = 0; i < reg_list_size; i++) {
2244 if (reg_list[i]->exist == false || reg_list[i]->hidden)
2245 continue;
2246
2247 if (reg_list[i]->feature
2248 && reg_list[i]->feature->name
2249 && (strcmp(reg_list[i]->feature->name, ""))) {
2250 /* We found a feature, check if the feature is already in the
2251 * table. If not, allocate a new entry for the table and
2252 * put the new feature in it.
2253 */
2254 for (int j = 0; j < (tbl_sz + 1); j++) {
2255 if (!((*feature_list)[j])) {
2256 (*feature_list)[tbl_sz++] = reg_list[i]->feature->name;
2257 *feature_list = realloc(*feature_list, sizeof(char *) * (tbl_sz + 1));
2258 (*feature_list)[tbl_sz] = NULL;
2259 break;
2260 } else {
2261 if (!strcmp((*feature_list)[j], reg_list[i]->feature->name))
2262 break;
2263 }
2264 }
2265 }
2266 }
2267
2268 if (feature_list_size)
2269 *feature_list_size = tbl_sz;
2270
2271 return ERROR_OK;
2272 }
2273
2274 /* Create a register list that's the union of all the registers of the SMP
2275 * group this target is in. If the target is not part of an SMP group, this
2276 * returns the same as target_get_gdb_reg_list_noread().
2277 */
2278 static int smp_reg_list_noread(struct target *target,
2279 struct reg **combined_list[], int *combined_list_size,
2280 enum target_register_class reg_class)
2281 {
2282 if (!target->smp)
2283 return target_get_gdb_reg_list_noread(target, combined_list,
2284 combined_list_size, REG_CLASS_ALL);
2285
2286 unsigned int combined_allocated = 256;
2287 struct reg **local_list = malloc(combined_allocated * sizeof(struct reg *));
2288 if (!local_list) {
2289 LOG_ERROR("malloc(%zu) failed", combined_allocated * sizeof(struct reg *));
2290 return ERROR_FAIL;
2291 }
2292 unsigned int local_list_size = 0;
2293
2294 struct target_list *head;
2295 foreach_smp_target(head, target->smp_targets) {
2296 if (!target_was_examined(head->target))
2297 continue;
2298
2299 struct reg **reg_list = NULL;
2300 int reg_list_size;
2301 int result = target_get_gdb_reg_list_noread(head->target, &reg_list,
2302 &reg_list_size, reg_class);
2303 if (result != ERROR_OK) {
2304 free(local_list);
2305 return result;
2306 }
2307 for (int i = 0; i < reg_list_size; i++) {
2308 bool found = false;
2309 struct reg *a = reg_list[i];
2310 if (a->exist) {
2311 /* Nested loop makes this O(n^2), but this entire function with
2312 * 5 RISC-V targets takes just 2ms on my computer. Fast enough
2313 * for me. */
2314 for (unsigned int j = 0; j < local_list_size; j++) {
2315 struct reg *b = local_list[j];
2316 if (!strcmp(a->name, b->name)) {
2317 found = true;
2318 if (a->size != b->size) {
2319 LOG_ERROR("SMP register %s is %d bits on one "
2320 "target, but %d bits on another target.",
2321 a->name, a->size, b->size);
2322 free(reg_list);
2323 free(local_list);
2324 return ERROR_FAIL;
2325 }
2326 break;
2327 }
2328 }
2329 if (!found) {
2330 LOG_DEBUG("[%s] %s not found in combined list", target_name(target), a->name);
2331 if (local_list_size >= combined_allocated) {
2332 combined_allocated *= 2;
2333 local_list = realloc(local_list, combined_allocated * sizeof(struct reg *));
2334 if (!local_list) {
2335 LOG_ERROR("realloc(%zu) failed", combined_allocated * sizeof(struct reg *));
2336 return ERROR_FAIL;
2337 }
2338 }
2339 local_list[local_list_size] = a;
2340 local_list_size++;
2341 }
2342 }
2343 }
2344 free(reg_list);
2345 }
2346
2347 if (local_list_size == 0) {
2348 LOG_ERROR("Unable to get register list");
2349 free(local_list);
2350 return ERROR_FAIL;
2351 }
2352
2353 /* Now warn the user about any registers that weren't found in every target. */
2354 foreach_smp_target(head, target->smp_targets) {
2355 if (!target_was_examined(head->target))
2356 continue;
2357
2358 struct reg **reg_list = NULL;
2359 int reg_list_size;
2360 int result = target_get_gdb_reg_list_noread(head->target, &reg_list,
2361 &reg_list_size, reg_class);
2362 if (result != ERROR_OK) {
2363 free(local_list);
2364 return result;
2365 }
2366 for (unsigned int i = 0; i < local_list_size; i++) {
2367 bool found = false;
2368 struct reg *a = local_list[i];
2369 for (int j = 0; j < reg_list_size; j++) {
2370 struct reg *b = reg_list[j];
2371 if (b->exist && !strcmp(a->name, b->name)) {
2372 found = true;
2373 break;
2374 }
2375 }
2376 if (!found) {
2377 LOG_WARNING("Register %s does not exist in %s, which is part of an SMP group where "
2378 "this register does exist.",
2379 a->name, target_name(head->target));
2380 }
2381 }
2382 free(reg_list);
2383 }
2384
2385 *combined_list = local_list;
2386 *combined_list_size = local_list_size;
2387 return ERROR_OK;
2388 }
2389
2390 static int gdb_generate_target_description(struct target *target, char **tdesc_out)
2391 {
2392 int retval = ERROR_OK;
2393 struct reg **reg_list = NULL;
2394 int reg_list_size;
2395 char const *architecture;
2396 char const **features = NULL;
2397 int feature_list_size = 0;
2398 char *tdesc = NULL;
2399 int pos = 0;
2400 int size = 0;
2401
2402
2403 retval = smp_reg_list_noread(target, &reg_list, &reg_list_size,
2404 REG_CLASS_ALL);
2405
2406 if (retval != ERROR_OK) {
2407 LOG_ERROR("get register list failed");
2408 retval = ERROR_FAIL;
2409 goto error;
2410 }
2411
2412 if (reg_list_size <= 0) {
2413 LOG_ERROR("get register list failed");
2414 retval = ERROR_FAIL;
2415 goto error;
2416 }
2417
2418 /* Get a list of available target registers features */
2419 retval = get_reg_features_list(target, &features, &feature_list_size, reg_list, reg_list_size);
2420 if (retval != ERROR_OK) {
2421 LOG_ERROR("Can't get the registers feature list");
2422 retval = ERROR_FAIL;
2423 goto error;
2424 }
2425
2426 /* If we found some features associated with registers, create sections */
2427 int current_feature = 0;
2428
2429 xml_printf(&retval, &tdesc, &pos, &size,
2430 "<?xml version=\"1.0\"?>\n"
2431 "<!DOCTYPE target SYSTEM \"gdb-target.dtd\">\n"
2432 "<target version=\"1.0\">\n");
2433
2434 /* generate architecture element if supported by target */
2435 architecture = target_get_gdb_arch(target);
2436 if (architecture)
2437 xml_printf(&retval, &tdesc, &pos, &size,
2438 "<architecture>%s</architecture>\n", architecture);
2439
2440 /* generate target description according to register list */
2441 if (features) {
2442 while (features[current_feature]) {
2443 char const **arch_defined_types = NULL;
2444 int num_arch_defined_types = 0;
2445
2446 arch_defined_types = calloc(1, sizeof(char *));
2447 xml_printf(&retval, &tdesc, &pos, &size,
2448 "<feature name=\"%s\">\n",
2449 features[current_feature]);
2450
2451 int i;
2452 for (i = 0; i < reg_list_size; i++) {
2453
2454 if (reg_list[i]->exist == false || reg_list[i]->hidden)
2455 continue;
2456
2457 if (strcmp(reg_list[i]->feature->name, features[current_feature]))
2458 continue;
2459
2460 const char *type_str;
2461 if (reg_list[i]->reg_data_type) {
2462 if (reg_list[i]->reg_data_type->type == REG_TYPE_ARCH_DEFINED) {
2463 /* generate <type... first, if there are architecture-defined types. */
2464 if (lookup_add_arch_defined_types(&arch_defined_types,
2465 reg_list[i]->reg_data_type->id,
2466 &num_arch_defined_types))
2467 gdb_generate_reg_type_description(target, &tdesc, &pos, &size,
2468 reg_list[i]->reg_data_type,
2469 &arch_defined_types,
2470 &num_arch_defined_types);
2471
2472 type_str = reg_list[i]->reg_data_type->id;
2473 } else {
2474 /* predefined type */
2475 type_str = gdb_get_reg_type_name(
2476 reg_list[i]->reg_data_type->type);
2477 }
2478 } else {
2479 /* Default type is "int" */
2480 type_str = "int";
2481 }
2482
2483 xml_printf(&retval, &tdesc, &pos, &size,
2484 "<reg name=\"%s\"", reg_list[i]->name);
2485 xml_printf(&retval, &tdesc, &pos, &size,
2486 " bitsize=\"%" PRIu32 "\"", reg_list[i]->size);
2487 xml_printf(&retval, &tdesc, &pos, &size,
2488 " regnum=\"%" PRIu32 "\"", reg_list[i]->number);
2489 if (reg_list[i]->caller_save)
2490 xml_printf(&retval, &tdesc, &pos, &size,
2491 " save-restore=\"yes\"");
2492 else
2493 xml_printf(&retval, &tdesc, &pos, &size,
2494 " save-restore=\"no\"");
2495
2496 xml_printf(&retval, &tdesc, &pos, &size,
2497 " type=\"%s\"", type_str);
2498
2499 if (reg_list[i]->group)
2500 xml_printf(&retval, &tdesc, &pos, &size,
2501 " group=\"%s\"", reg_list[i]->group);
2502
2503 xml_printf(&retval, &tdesc, &pos, &size,
2504 "/>\n");
2505 }
2506
2507 xml_printf(&retval, &tdesc, &pos, &size,
2508 "</feature>\n");
2509
2510 current_feature++;
2511 free(arch_defined_types);
2512 }
2513 }
2514
2515 xml_printf(&retval, &tdesc, &pos, &size,
2516 "</target>\n");
2517
2518 error:
2519 free(features);
2520 free(reg_list);
2521
2522 if (retval == ERROR_OK)
2523 *tdesc_out = tdesc;
2524 else
2525 free(tdesc);
2526
2527 return retval;
2528 }
2529
2530 static int gdb_get_target_description_chunk(struct target *target, struct target_desc_format *target_desc,
2531 char **chunk, int32_t offset, uint32_t length)
2532 {
2533 if (!target_desc) {
2534 LOG_ERROR("Unable to Generate Target Description");
2535 return ERROR_FAIL;
2536 }
2537
2538 char *tdesc = target_desc->tdesc;
2539 uint32_t tdesc_length = target_desc->tdesc_length;
2540
2541 if (!tdesc) {
2542 int retval = gdb_generate_target_description(target, &tdesc);
2543 if (retval != ERROR_OK) {
2544 LOG_ERROR("Unable to Generate Target Description");
2545 return ERROR_FAIL;
2546 }
2547
2548 tdesc_length = strlen(tdesc);
2549 }
2550
2551 char transfer_type;
2552
2553 if (length < (tdesc_length - offset))
2554 transfer_type = 'm';
2555 else
2556 transfer_type = 'l';
2557
2558 *chunk = malloc(length + 2);
2559 if (!*chunk) {
2560 LOG_ERROR("Unable to allocate memory");
2561 return ERROR_FAIL;
2562 }
2563
2564 (*chunk)[0] = transfer_type;
2565 if (transfer_type == 'm') {
2566 strncpy((*chunk) + 1, tdesc + offset, length);
2567 (*chunk)[1 + length] = '\0';
2568 } else {
2569 strncpy((*chunk) + 1, tdesc + offset, tdesc_length - offset);
2570 (*chunk)[1 + (tdesc_length - offset)] = '\0';
2571
2572 /* After gdb-server sends out last chunk, invalidate tdesc. */
2573 free(tdesc);
2574 tdesc = NULL;
2575 tdesc_length = 0;
2576 }
2577
2578 target_desc->tdesc = tdesc;
2579 target_desc->tdesc_length = tdesc_length;
2580
2581 return ERROR_OK;
2582 }
2583
2584 static int gdb_target_description_supported(struct target *target, int *supported)
2585 {
2586 int retval = ERROR_OK;
2587 struct reg **reg_list = NULL;
2588 int reg_list_size = 0;
2589 char const **features = NULL;
2590 int feature_list_size = 0;
2591
2592 char const *architecture = target_get_gdb_arch(target);
2593
2594 retval = target_get_gdb_reg_list_noread(target, &reg_list,
2595 &reg_list_size, REG_CLASS_ALL);
2596 if (retval != ERROR_OK) {
2597 LOG_ERROR("get register list failed");
2598 goto error;
2599 }
2600
2601 if (reg_list_size <= 0) {
2602 LOG_ERROR("get register list failed");
2603 retval = ERROR_FAIL;
2604 goto error;
2605 }
2606
2607 /* Get a list of available target registers features */
2608 retval = get_reg_features_list(target, &features, &feature_list_size, reg_list, reg_list_size);
2609 if (retval != ERROR_OK) {
2610 LOG_ERROR("Can't get the registers feature list");
2611 goto error;
2612 }
2613
2614 if (supported) {
2615 if (architecture || feature_list_size)
2616 *supported = 1;
2617 else
2618 *supported = 0;
2619 }
2620
2621 error:
2622 free(features);
2623
2624 free(reg_list);
2625
2626 return retval;
2627 }
2628
2629 static int gdb_generate_thread_list(struct target *target, char **thread_list_out)
2630 {
2631 struct rtos *rtos = target->rtos;
2632 int retval = ERROR_OK;
2633 char *thread_list = NULL;
2634 int pos = 0;
2635 int size = 0;
2636
2637 xml_printf(&retval, &thread_list, &pos, &size,
2638 "<?xml version=\"1.0\"?>\n"
2639 "<threads>\n");
2640
2641 if (rtos) {
2642 for (int i = 0; i < rtos->thread_count; i++) {
2643 struct thread_detail *thread_detail = &rtos->thread_details[i];
2644
2645 if (!thread_detail->exists)
2646 continue;
2647
2648 if (thread_detail->thread_name_str)
2649 xml_printf(&retval, &thread_list, &pos, &size,
2650 "<thread id=\"%" PRIx64 "\" name=\"%s\">",
2651 thread_detail->threadid,
2652 thread_detail->thread_name_str);
2653 else
2654 xml_printf(&retval, &thread_list, &pos, &size,
2655 "<thread id=\"%" PRIx64 "\">", thread_detail->threadid);
2656
2657 if (thread_detail->thread_name_str)
2658 xml_printf(&retval, &thread_list, &pos, &size,
2659 "Name: %s", thread_detail->thread_name_str);
2660
2661 if (thread_detail->extra_info_str) {
2662 if (thread_detail->thread_name_str)
2663 xml_printf(&retval, &thread_list, &pos, &size,
2664 ", ");
2665 xml_printf(&retval, &thread_list, &pos, &size,
2666 "%s", thread_detail->extra_info_str);
2667 }
2668
2669 xml_printf(&retval, &thread_list, &pos, &size,
2670 "</thread>\n");
2671 }
2672 }
2673
2674 xml_printf(&retval, &thread_list, &pos, &size,
2675 "</threads>\n");
2676
2677 if (retval == ERROR_OK)
2678 *thread_list_out = thread_list;
2679 else
2680 free(thread_list);
2681
2682 return retval;
2683 }
2684
2685 static int gdb_get_thread_list_chunk(struct target *target, char **thread_list,
2686 char **chunk, int32_t offset, uint32_t length)
2687 {
2688 if (!*thread_list) {
2689 int retval = gdb_generate_thread_list(target, thread_list);
2690 if (retval != ERROR_OK) {
2691 LOG_ERROR("Unable to Generate Thread List");
2692 return ERROR_FAIL;
2693 }
2694 }
2695
2696 size_t thread_list_length = strlen(*thread_list);
2697 char transfer_type;
2698
2699 length = MIN(length, thread_list_length - offset);
2700 if (length < (thread_list_length - offset))
2701 transfer_type = 'm';
2702 else
2703 transfer_type = 'l';
2704
2705 *chunk = malloc(length + 2 + 3);
2706 /* Allocating extra 3 bytes prevents false positive valgrind report
2707 * of strlen(chunk) word access:
2708 * Invalid read of size 4
2709 * Address 0x4479934 is 44 bytes inside a block of size 45 alloc'd */
2710 if (!*chunk) {
2711 LOG_ERROR("Unable to allocate memory");
2712 return ERROR_FAIL;
2713 }
2714
2715 (*chunk)[0] = transfer_type;
2716 strncpy((*chunk) + 1, (*thread_list) + offset, length);
2717 (*chunk)[1 + length] = '\0';
2718
2719 /* After gdb-server sends out last chunk, invalidate thread list. */
2720 if (transfer_type == 'l') {
2721 free(*thread_list);
2722 *thread_list = NULL;
2723 }
2724
2725 return ERROR_OK;
2726 }
2727
2728 static int gdb_query_packet(struct connection *connection,
2729 char const *packet, int packet_size)
2730 {
2731 struct command_context *cmd_ctx = connection->cmd_ctx;
2732 struct gdb_connection *gdb_connection = connection->priv;
2733 struct target *target = get_target_from_connection(connection);
2734
2735 if (strncmp(packet, "qRcmd,", 6) == 0) {
2736 if (packet_size > 6) {
2737 char *cmd;
2738 cmd = malloc((packet_size - 6) / 2 + 1);
2739 size_t len = unhexify((uint8_t *)cmd, packet + 6, (packet_size - 6) / 2);
2740 cmd[len] = 0;
2741
2742 /* We want to print all debug output to GDB connection */
2743 gdb_connection->output_flag = GDB_OUTPUT_ALL;
2744 target_call_timer_callbacks_now();
2745 /* some commands need to know the GDB connection, make note of current
2746 * GDB connection. */
2747 current_gdb_connection = gdb_connection;
2748 command_run_line(cmd_ctx, cmd);
2749 current_gdb_connection = NULL;
2750 target_call_timer_callbacks_now();
2751 gdb_connection->output_flag = GDB_OUTPUT_NO;
2752 free(cmd);
2753 }
2754 gdb_put_packet(connection, "OK", 2);
2755 return ERROR_OK;
2756 } else if (strncmp(packet, "qCRC:", 5) == 0) {
2757 if (packet_size > 5) {
2758 int retval;
2759 char gdb_reply[10];
2760 char *separator;
2761 uint32_t checksum;
2762 target_addr_t addr = 0;
2763 uint32_t len = 0;
2764
2765 /* skip command character */
2766 packet += 5;
2767
2768 addr = strtoull(packet, &separator, 16);
2769
2770 if (*separator != ',') {
2771 LOG_ERROR("incomplete read memory packet received, dropping connection");
2772 return ERROR_SERVER_REMOTE_CLOSED;
2773 }
2774
2775 len = strtoul(separator + 1, NULL, 16);
2776
2777 retval = target_checksum_memory(target, addr, len, &checksum);
2778
2779 if (retval == ERROR_OK) {
2780 snprintf(gdb_reply, 10, "C%8.8" PRIx32 "", checksum);
2781 gdb_put_packet(connection, gdb_reply, 9);
2782 } else {
2783 retval = gdb_error(connection, retval);
2784 if (retval != ERROR_OK)
2785 return retval;
2786 }
2787
2788 return ERROR_OK;
2789 }
2790 } else if (strncmp(packet, "qSupported", 10) == 0) {
2791 /* we currently support packet size and qXfer:memory-map:read (if enabled)
2792 * qXfer:features:read is supported for some targets */
2793 int retval = ERROR_OK;
2794 char *buffer = NULL;
2795 int pos = 0;
2796 int size = 0;
2797 int gdb_target_desc_supported = 0;
2798
2799 /* we need to test that the target supports target descriptions */
2800 retval = gdb_target_description_supported(target, &gdb_target_desc_supported);
2801 if (retval != ERROR_OK) {
2802 LOG_INFO("Failed detecting Target Description Support, disabling");
2803 gdb_target_desc_supported = 0;
2804 }
2805
2806 /* support may be disabled globally */
2807 if (gdb_use_target_description == 0) {
2808 if (gdb_target_desc_supported)
2809 LOG_WARNING("Target Descriptions Supported, but disabled");
2810 gdb_target_desc_supported = 0;
2811 }
2812
2813 xml_printf(&retval,
2814 &buffer,
2815 &pos,
2816 &size,
2817 "PacketSize=%x;qXfer:memory-map:read%c;qXfer:features:read%c;qXfer:threads:read+;QStartNoAckMode+;vContSupported+",
2818 GDB_BUFFER_SIZE,
2819 ((gdb_use_memory_map == 1) && (flash_get_bank_count() > 0)) ? '+' : '-',
2820 (gdb_target_desc_supported == 1) ? '+' : '-');
2821
2822 if (retval != ERROR_OK) {
2823 gdb_send_error(connection, 01);
2824 return ERROR_OK;
2825 }
2826
2827 gdb_put_packet(connection, buffer, strlen(buffer));
2828 free(buffer);
2829
2830 return ERROR_OK;
2831 } else if ((strncmp(packet, "qXfer:memory-map:read::", 23) == 0)
2832 && (flash_get_bank_count() > 0))
2833 return gdb_memory_map(connection, packet, packet_size);
2834 else if (strncmp(packet, "qXfer:features:read:", 20) == 0) {
2835 char *xml = NULL;
2836 int retval = ERROR_OK;
2837
2838 int offset;
2839 unsigned int length;
2840
2841 /* skip command character */
2842 packet += 20;
2843
2844 if (decode_xfer_read(packet, NULL, &offset, &length) < 0) {
2845 gdb_send_error(connection, 01);
2846 return ERROR_OK;
2847 }
2848
2849 /* Target should prepare correct target description for annex.
2850 * The first character of returned xml is 'm' or 'l'. 'm' for
2851 * there are *more* chunks to transfer. 'l' for it is the *last*
2852 * chunk of target description.
2853 */
2854 retval = gdb_get_target_description_chunk(target, &gdb_connection->target_desc,
2855 &xml, offset, length);
2856 if (retval != ERROR_OK) {
2857 gdb_error(connection, retval);
2858 return retval;
2859 }
2860
2861 gdb_put_packet(connection, xml, strlen(xml));
2862
2863 free(xml);
2864 return ERROR_OK;
2865 } else if (strncmp(packet, "qXfer:threads:read:", 19) == 0) {
2866 char *xml = NULL;
2867 int retval = ERROR_OK;
2868
2869 int offset;
2870 unsigned int length;
2871
2872 /* skip command character */
2873 packet += 19;
2874
2875 if (decode_xfer_read(packet, NULL, &offset, &length) < 0) {
2876 gdb_send_error(connection, 01);
2877 return ERROR_OK;
2878 }
2879
2880 /* Target should prepare correct thread list for annex.
2881 * The first character of returned xml is 'm' or 'l'. 'm' for
2882 * there are *more* chunks to transfer. 'l' for it is the *last*
2883 * chunk of target description.
2884 */
2885 retval = gdb_get_thread_list_chunk(target, &gdb_connection->thread_list,
2886 &xml, offset, length);
2887 if (retval != ERROR_OK) {
2888 gdb_error(connection, retval);
2889 return retval;
2890 }
2891
2892 gdb_put_packet(connection, xml, strlen(xml));
2893
2894 free(xml);
2895 return ERROR_OK;
2896 } else if (strncmp(packet, "QStartNoAckMode", 15) == 0) {
2897 gdb_connection->noack_mode = 1;
2898 gdb_put_packet(connection, "OK", 2);
2899 return ERROR_OK;
2900 }
2901
2902 gdb_put_packet(connection, "", 0);
2903 return ERROR_OK;
2904 }
2905
2906 static bool gdb_handle_vcont_packet(struct connection *connection, const char *packet, int packet_size)
2907 {
2908 struct gdb_connection *gdb_connection = connection->priv;
2909 struct target *target = get_target_from_connection(connection);
2910 const char *parse = packet;
2911 int retval;
2912
2913 /* query for vCont supported */
2914 if (parse[0] == '?') {
2915 if (target->type->step) {
2916 /* gdb doesn't accept c without C and s without S */
2917 gdb_put_packet(connection, "vCont;c;C;s;S", 13);
2918 return true;
2919 }
2920 return false;
2921 }
2922
2923 if (parse[0] == ';') {
2924 ++parse;
2925 --packet_size;
2926 }
2927
2928 /* simple case, a continue packet */
2929 if (parse[0] == 'c') {
2930 gdb_running_type = 'c';
2931 LOG_DEBUG("target %s continue", target_name(target));
2932 gdb_connection->output_flag = GDB_OUTPUT_ALL;
2933 retval = target_resume(target, 1, 0, 0, 0);
2934 if (retval == ERROR_TARGET_NOT_HALTED)
2935 LOG_INFO("target %s was not halted when resume was requested", target_name(target));
2936
2937 /* poll target in an attempt to make its internal state consistent */
2938 if (retval != ERROR_OK) {
2939 retval = target_poll(target);
2940 if (retval != ERROR_OK)
2941 LOG_DEBUG("error polling target %s after failed resume", target_name(target));
2942 }
2943
2944 /*
2945 * We don't report errors to gdb here, move frontend_state to
2946 * TARGET_RUNNING to stay in sync with gdb's expectation of the
2947 * target state
2948 */
2949 gdb_connection->frontend_state = TARGET_RUNNING;
2950 target_call_event_callbacks(target, TARGET_EVENT_GDB_START);
2951
2952 return true;
2953 }
2954
2955 /* single-step or step-over-breakpoint */
2956 if (parse[0] == 's') {
2957 gdb_running_type = 's';
2958 bool fake_step = false;
2959
2960 if (strncmp(parse, "s:", 2) == 0) {
2961 struct target *ct = target;
2962 int current_pc = 1;
2963 int64_t thread_id;
2964 char *endp;
2965
2966 parse += 2;
2967 packet_size -= 2;
2968
2969 thread_id = strtoll(parse, &endp, 16);
2970 if (endp) {
2971 packet_size -= endp - parse;
2972 parse = endp;
2973 }
2974
2975 if (target->rtos) {
2976 /* FIXME: why is this necessary? rtos state should be up-to-date here already! */
2977 rtos_update_threads(target);
2978
2979 target->rtos->gdb_target_for_threadid(connection, thread_id, &ct);
2980
2981 /*
2982 * check if the thread to be stepped is the current rtos thread
2983 * if not, we must fake the step
2984 */
2985 if (target->rtos->current_thread != thread_id)
2986 fake_step = true;
2987 }
2988
2989 if (parse[0] == ';') {
2990 ++parse;
2991 --packet_size;
2992
2993 if (parse[0] == 'c') {
2994 parse += 1;
2995
2996 /* check if thread-id follows */
2997 if (parse[0] == ':') {
2998 int64_t tid;
2999 parse += 1;
3000
3001 tid = strtoll(parse, &endp, 16);
3002 if (tid == thread_id) {
3003 /*
3004 * Special case: only step a single thread (core),
3005 * keep the other threads halted. Currently, only
3006 * aarch64 target understands it. Other target types don't
3007 * care (nobody checks the actual value of 'current')
3008 * and it doesn't really matter. This deserves
3009 * a symbolic constant and a formal interface documentation
3010 * at a later time.
3011 */
3012 LOG_DEBUG("request to step current core only");
3013 /* uncomment after checking that indeed other targets are safe */
3014 /*current_pc = 2;*/
3015 }
3016 }
3017 }
3018 }
3019
3020 LOG_DEBUG("target %s single-step thread %"PRIx64, target_name(ct), thread_id);
3021 gdb_connection->output_flag = GDB_OUTPUT_ALL;
3022 target_call_event_callbacks(ct, TARGET_EVENT_GDB_START);
3023
3024 /*
3025 * work around an annoying gdb behaviour: when the current thread
3026 * is changed in gdb, it assumes that the target can follow and also
3027 * make the thread current. This is an assumption that cannot hold
3028 * for a real target running a multi-threading OS. We just fake
3029 * the step to not trigger an internal error in gdb. See
3030 * https://sourceware.org/bugzilla/show_bug.cgi?id=22925 for details
3031 */
3032 if (fake_step) {
3033 int sig_reply_len;
3034 char sig_reply[128];
3035
3036 LOG_DEBUG("fake step thread %"PRIx64, thread_id);
3037
3038 sig_reply_len = snprintf(sig_reply, sizeof(sig_reply),
3039 "T05thread:%016"PRIx64";", thread_id);
3040
3041 gdb_put_packet(connection, sig_reply, sig_reply_len);
3042 gdb_connection->output_flag = GDB_OUTPUT_NO;
3043
3044 return true;
3045 }
3046
3047 /* support for gdb_sync command */
3048 if (gdb_connection->sync) {
3049 gdb_connection->sync = false;
3050 if (ct->state == TARGET_HALTED) {
3051 LOG_DEBUG("stepi ignored. GDB will now fetch the register state "
3052 "from the target.");
3053 gdb_sig_halted(connection);
3054 gdb_connection->output_flag = GDB_OUTPUT_NO;
3055 } else
3056 gdb_connection->frontend_state = TARGET_RUNNING;
3057 return true;
3058 }
3059
3060 retval = target_step(ct, current_pc, 0, 0);
3061 if (retval == ERROR_TARGET_NOT_HALTED)
3062 LOG_INFO("target %s was not halted when step was requested", target_name(ct));
3063
3064 /* if step was successful send a reply back to gdb */
3065 if (retval == ERROR_OK) {
3066 retval = target_poll(ct);
3067 if (retval != ERROR_OK)
3068 LOG_DEBUG("error polling target %s after successful step", target_name(ct));
3069 /* send back signal information */
3070 gdb_signal_reply(ct, connection);
3071 /* stop forwarding log packets! */
3072 gdb_connection->output_flag = GDB_OUTPUT_NO;
3073 } else
3074 gdb_connection->frontend_state = TARGET_RUNNING;
3075 } else {
3076 LOG_ERROR("Unknown vCont packet");
3077 return false;
3078 }
3079 return true;
3080 }
3081
3082 return false;
3083 }
3084
3085 static char *next_hex_encoded_field(const char **str, char sep)
3086 {
3087 size_t hexlen;
3088 const char *hex = *str;
3089 if (hex[0] == '\0')
3090 return NULL;
3091
3092 const char *end = strchr(hex, sep);
3093 if (!end)
3094 hexlen = strlen(hex);
3095 else
3096 hexlen = end - hex;
3097 *str = hex + hexlen + 1;
3098
3099 if (hexlen % 2 != 0) {
3100 /* Malformed hex data */
3101 return NULL;
3102 }
3103
3104 size_t count = hexlen / 2;
3105 char *decoded = malloc(count + 1);
3106 if (!decoded)
3107 return NULL;
3108
3109 size_t converted = unhexify((void *)decoded, hex, count);
3110 if (converted != count) {
3111 free(decoded);
3112 return NULL;
3113 }
3114
3115 decoded[count] = '\0';
3116 return decoded;
3117 }
3118
3119 /* handle extended restart packet */
3120 static void gdb_restart_inferior(struct connection *connection, const char *packet, int packet_size)
3121 {
3122 struct gdb_connection *gdb_con = connection->priv;
3123 struct target *target = get_target_from_connection(connection);
3124
3125 breakpoint_clear_target(target);
3126 watchpoint_clear_target(target);
3127 command_run_linef(connection->cmd_ctx, "ocd_gdb_restart %s",
3128 target_name(target));
3129 /* set connection as attached after reset */
3130 gdb_con->attached = true;
3131 /* info rtos parts */
3132 gdb_thread_packet(connection, packet, packet_size);
3133 }
3134
3135 static bool gdb_handle_vrun_packet(struct connection *connection, const char *packet, int packet_size)
3136 {
3137 struct target *target = get_target_from_connection(connection);
3138 const char *parse = packet;
3139
3140 /* Skip "vRun" */
3141 parse += 4;
3142
3143 if (parse[0] != ';')
3144 return false;
3145 parse++;
3146
3147 /* Skip first field "filename"; don't know what to do with it. */
3148 free(next_hex_encoded_field(&parse, ';'));
3149
3150 char *cmdline = next_hex_encoded_field(&parse, ';');
3151 while (cmdline) {
3152 char *arg = next_hex_encoded_field(&parse, ';');
3153 if (!arg)
3154 break;
3155 char *new_cmdline = alloc_printf("%s %s", cmdline, arg);
3156 free(cmdline);
3157 free(arg);
3158 cmdline = new_cmdline;
3159 }
3160
3161 if (cmdline) {
3162 if (target->semihosting) {
3163 LOG_INFO("GDB set inferior command line to '%s'", cmdline);
3164 free(target->semihosting->cmdline);
3165 target->semihosting->cmdline = cmdline;
3166 } else {
3167 LOG_INFO("GDB set inferior command line to '%s' but semihosting is unavailable", cmdline);
3168 free(cmdline);
3169 }
3170 }
3171
3172 gdb_restart_inferior(connection, packet, packet_size);
3173 gdb_put_packet(connection, "S00", 3);
3174 return true;
3175 }
3176
3177 static int gdb_v_packet(struct connection *connection,
3178 char const *packet, int packet_size)
3179 {
3180 struct gdb_connection *gdb_connection = connection->priv;
3181 int result;
3182
3183 struct target *target = get_target_from_connection(connection);
3184
3185 if (strncmp(packet, "vCont", 5) == 0) {
3186 bool handled;
3187
3188 packet += 5;
3189 packet_size -= 5;
3190
3191 handled = gdb_handle_vcont_packet(connection, packet, packet_size);
3192 if (!handled)
3193 gdb_put_packet(connection, "", 0);
3194
3195 return ERROR_OK;
3196 }
3197
3198 if (strncmp(packet, "vRun", 4) == 0) {
3199 bool handled;
3200
3201 handled = gdb_handle_vrun_packet(connection, packet, packet_size);
3202 if (!handled)
3203 gdb_put_packet(connection, "", 0);
3204
3205 return ERROR_OK;
3206 }
3207
3208 /* if flash programming disabled - send a empty reply */
3209
3210 if (gdb_flash_program == 0) {
3211 gdb_put_packet(connection, "", 0);
3212 return ERROR_OK;
3213 }
3214
3215 if (strncmp(packet, "vFlashErase:", 12) == 0) {
3216 unsigned long addr;
3217 unsigned long length;
3218
3219 char const *parse = packet + 12;
3220 if (*parse == '\0') {
3221 LOG_ERROR("incomplete vFlashErase packet received, dropping connection");
3222 return ERROR_SERVER_REMOTE_CLOSED;
3223 }
3224
3225 addr = strtoul(parse, (char **)&parse, 16);
3226
3227 if (*(parse++) != ',' || *parse == '\0') {
3228 LOG_ERROR("incomplete vFlashErase packet received, dropping connection");
3229 return ERROR_SERVER_REMOTE_CLOSED;
3230 }
3231
3232 length = strtoul(parse, (char **)&parse, 16);
3233
3234 if (*parse != '\0') {
3235 LOG_ERROR("incomplete vFlashErase packet received, dropping connection");
3236 return ERROR_SERVER_REMOTE_CLOSED;
3237 }
3238
3239 /* assume all sectors need erasing - stops any problems
3240 * when flash_write is called multiple times */
3241 flash_set_dirty();
3242
3243 /* perform any target specific operations before the erase */
3244 target_call_event_callbacks(target,
3245 TARGET_EVENT_GDB_FLASH_ERASE_START);
3246
3247 /* vFlashErase:addr,length messages require region start and
3248 * end to be "block" aligned ... if padding is ever needed,
3249 * GDB will have become dangerously confused.
3250 */
3251 result = flash_erase_address_range(target, false, addr,
3252 length);
3253
3254 /* perform any target specific operations after the erase */
3255 target_call_event_callbacks(target,
3256 TARGET_EVENT_GDB_FLASH_ERASE_END);
3257
3258 /* perform erase */
3259 if (result != ERROR_OK) {
3260 /* GDB doesn't evaluate the actual error number returned,
3261 * treat a failed erase as an I/O error
3262 */
3263 gdb_send_error(connection, EIO);
3264 LOG_ERROR("flash_erase returned %i", result);
3265 } else
3266 gdb_put_packet(connection, "OK", 2);
3267
3268 return ERROR_OK;
3269 }
3270
3271 if (strncmp(packet, "vFlashWrite:", 12) == 0) {
3272 int retval;
3273 unsigned long addr;
3274 unsigned long length;
3275 char const *parse = packet + 12;
3276
3277 if (*parse == '\0') {
3278 LOG_ERROR("incomplete vFlashErase packet received, dropping connection");
3279 return ERROR_SERVER_REMOTE_CLOSED;
3280 }
3281 addr = strtoul(parse, (char **)&parse, 16);
3282 if (*(parse++) != ':') {
3283 LOG_ERROR("incomplete vFlashErase packet received, dropping connection");
3284 return ERROR_SERVER_REMOTE_CLOSED;
3285 }
3286 length = packet_size - (parse - packet);
3287
3288 /* create a new image if there isn't already one */
3289 if (!gdb_connection->vflash_image) {
3290 gdb_connection->vflash_image = malloc(sizeof(struct image));
3291 image_open(gdb_connection->vflash_image, "", "build");
3292 }
3293
3294 /* create new section with content from packet buffer */
3295 retval = image_add_section(gdb_connection->vflash_image,
3296 addr, length, 0x0, (uint8_t const *)parse);
3297 if (retval != ERROR_OK)
3298 return retval;
3299
3300 gdb_put_packet(connection, "OK", 2);
3301
3302 return ERROR_OK;
3303 }
3304
3305 if (strncmp(packet, "vFlashDone", 10) == 0) {
3306 uint32_t written;
3307
3308 /* process the flashing buffer. No need to erase as GDB
3309 * always issues a vFlashErase first. */
3310 target_call_event_callbacks(target,
3311 TARGET_EVENT_GDB_FLASH_WRITE_START);
3312 result = flash_write(target, gdb_connection->vflash_image,
3313 &written, false);
3314 target_call_event_callbacks(target,
3315 TARGET_EVENT_GDB_FLASH_WRITE_END);
3316 if (result != ERROR_OK) {
3317 if (result == ERROR_FLASH_DST_OUT_OF_BANK)
3318 gdb_put_packet(connection, "E.memtype", 9);
3319 else
3320 gdb_send_error(connection, EIO);
3321 } else {
3322 LOG_DEBUG("wrote %u bytes from vFlash image to flash", (unsigned)written);
3323 gdb_put_packet(connection, "OK", 2);
3324 }
3325
3326 image_close(gdb_connection->vflash_image);
3327 free(gdb_connection->vflash_image);
3328 gdb_connection->vflash_image = NULL;
3329
3330 return ERROR_OK;
3331 }
3332
3333 gdb_put_packet(connection, "", 0);
3334 return ERROR_OK;
3335 }
3336
3337 static int gdb_detach(struct connection *connection)
3338 {
3339 /*
3340 * Only reply "OK" to GDB
3341 * it will close the connection and this will trigger a call to
3342 * gdb_connection_closed() that will in turn trigger the event
3343 * TARGET_EVENT_GDB_DETACH
3344 */
3345 return gdb_put_packet(connection, "OK", 2);
3346 }
3347
3348 /* The format of 'F' response packet is
3349 * Fretcode,errno,Ctrl-C flag;call-specific attachment
3350 */
3351 static int gdb_fileio_response_packet(struct connection *connection,
3352 char const *packet, int packet_size)
3353 {
3354 struct target *target = get_target_from_connection(connection);
3355 char *separator;
3356 char *parsing_point;
3357 int fileio_retcode = strtoul(packet + 1, &separator, 16);
3358 int fileio_errno = 0;
3359 bool fileio_ctrl_c = false;
3360 int retval;
3361
3362 LOG_DEBUG("-");
3363
3364 if (*separator == ',') {
3365 parsing_point = separator + 1;
3366 fileio_errno = strtoul(parsing_point, &separator, 16);
3367 if (*separator == ',') {
3368 if (*(separator + 1) == 'C') {
3369 /* TODO: process ctrl-c */
3370 fileio_ctrl_c = true;
3371 }
3372 }
3373 }
3374
3375 LOG_DEBUG("File-I/O response, retcode: 0x%x, errno: 0x%x, ctrl-c: %s",
3376 fileio_retcode, fileio_errno, fileio_ctrl_c ? "true" : "false");
3377
3378 retval = target_gdb_fileio_end(target, fileio_retcode, fileio_errno, fileio_ctrl_c);
3379 if (retval != ERROR_OK)
3380 return ERROR_FAIL;
3381
3382 /* After File-I/O ends, keep continue or step */
3383 if (gdb_running_type == 'c')
3384 retval = target_resume(target, 1, 0x0, 0, 0);
3385 else if (gdb_running_type == 's')
3386 retval = target_step(target, 1, 0x0, 0);
3387 else
3388 retval = ERROR_FAIL;
3389
3390 if (retval != ERROR_OK)
3391 return ERROR_FAIL;
3392
3393 return ERROR_OK;
3394 }
3395
3396 static void gdb_log_callback(void *priv, const char *file, unsigned line,
3397 const char *function, const char *string)
3398 {
3399 struct connection *connection = priv;
3400 struct gdb_connection *gdb_con = connection->priv;
3401
3402 if (gdb_con->output_flag == GDB_OUTPUT_NO)
3403 /* No out allowed */
3404 return;
3405
3406 if (gdb_con->busy) {
3407 /* do not reply this using the O packet */
3408 return;
3409 }
3410
3411 gdb_output_con(connection, string);
3412 }
3413
3414 static void gdb_sig_halted(struct connection *connection)
3415 {
3416 char sig_reply[4];
3417 snprintf(sig_reply, 4, "T%2.2x", 2);
3418 gdb_put_packet(connection, sig_reply, 3);
3419 }
3420
3421 static int gdb_input_inner(struct connection *connection)
3422 {
3423 /* Do not allocate this on the stack */
3424 static char gdb_packet_buffer[GDB_BUFFER_SIZE + 1]; /* Extra byte for null-termination */
3425
3426 struct target *target;
3427 char const *packet = gdb_packet_buffer;
3428 int packet_size;
3429 int retval;
3430 struct gdb_connection *gdb_con = connection->priv;
3431 static bool warn_use_ext;
3432
3433 target = get_target_from_connection(connection);
3434
3435 /* drain input buffer. If one of the packets fail, then an error
3436 * packet is replied, if applicable.
3437 *
3438 * This loop will terminate and the error code is returned.
3439 *
3440 * The calling fn will check if this error is something that
3441 * can be recovered from, or if the connection must be closed.
3442 *
3443 * If the error is recoverable, this fn is called again to
3444 * drain the rest of the buffer.
3445 */
3446 do {
3447 packet_size = GDB_BUFFER_SIZE;
3448 retval = gdb_get_packet(connection, gdb_packet_buffer, &packet_size);
3449 if (retval != ERROR_OK)
3450 return retval;
3451
3452 /* terminate with zero */
3453 gdb_packet_buffer[packet_size] = '\0';
3454
3455 gdb_log_incoming_packet(gdb_packet_buffer);
3456
3457 if (packet_size > 0) {
3458 retval = ERROR_OK;
3459 switch (packet[0]) {
3460 case 'T': /* Is thread alive? */
3461 gdb_thread_packet(connection, packet, packet_size);
3462 break;
3463 case 'H': /* Set current thread ( 'c' for step and continue,
3464 * 'g' for all other operations ) */
3465 gdb_thread_packet(connection, packet, packet_size);
3466 break;
3467 case 'q':
3468 case 'Q':
3469 retval = gdb_thread_packet(connection, packet, packet_size);
3470 if (retval == GDB_THREAD_PACKET_NOT_CONSUMED)
3471 retval = gdb_query_packet(connection, packet, packet_size);
3472 break;
3473 case 'g':
3474 retval = gdb_get_registers_packet(connection, packet, packet_size);
3475 break;
3476 case 'G':
3477 retval = gdb_set_registers_packet(connection, packet, packet_size);
3478 break;
3479 case 'p':
3480 retval = gdb_get_register_packet(connection, packet, packet_size);
3481 break;
3482 case 'P':
3483 retval = gdb_set_register_packet(connection, packet, packet_size);
3484 break;
3485 case 'm':
3486 retval = gdb_read_memory_packet(connection, packet, packet_size);
3487 break;
3488 case 'M':
3489 retval = gdb_write_memory_packet(connection, packet, packet_size);
3490 break;
3491 case 'z':
3492 case 'Z':
3493 retval = gdb_breakpoint_watchpoint_packet(connection, packet, packet_size);
3494 break;
3495 case '?':
3496 gdb_last_signal_packet(connection, packet, packet_size);
3497 /* '?' is sent after the eventual '!' */
3498 if (!warn_use_ext && !gdb_con->extended_protocol) {
3499 warn_use_ext = true;
3500 LOG_WARNING("Prefer GDB command \"target extended-remote :%s\" instead of \"target remote :%s\"",
3501 connection->service->port, connection->service->port);
3502 }
3503 break;
3504 case 'c':
3505 case 's':
3506 {
3507 gdb_thread_packet(connection, packet, packet_size);
3508 gdb_con->output_flag = GDB_OUTPUT_ALL;
3509
3510 if (gdb_con->mem_write_error) {
3511 LOG_ERROR("Memory write failure!");
3512
3513 /* now that we have reported the memory write error,
3514 * we can clear the condition */
3515 gdb_con->mem_write_error = false;
3516 }
3517
3518 bool nostep = false;
3519 bool already_running = false;
3520 if (target->state == TARGET_RUNNING) {
3521 LOG_WARNING("WARNING! The target is already running. "
3522 "All changes GDB did to registers will be discarded! "
3523 "Waiting for target to halt.");
3524 already_running = true;
3525 } else if (target->state != TARGET_HALTED) {
3526 LOG_WARNING("The target is not in the halted nor running stated, "
3527 "stepi/continue ignored.");
3528 nostep = true;
3529 } else if ((packet[0] == 's') && gdb_con->sync) {
3530 /* Hmm..... when you issue a continue in GDB, then a "stepi" is
3531 * sent by GDB first to OpenOCD, thus defeating the check to
3532 * make only the single stepping have the sync feature...
3533 */
3534 nostep = true;
3535 LOG_DEBUG("stepi ignored. GDB will now fetch the register state "
3536 "from the target.");
3537 }
3538 gdb_con->sync = false;
3539
3540 if (!already_running && nostep) {
3541 /* Either the target isn't in the halted state, then we can't
3542 * step/continue. This might be early setup, etc.
3543 *
3544 * Or we want to allow GDB to pick up a fresh set of
3545 * register values without modifying the target state.
3546 *
3547 */
3548 gdb_sig_halted(connection);
3549
3550 /* stop forwarding log packets! */
3551 gdb_con->output_flag = GDB_OUTPUT_NO;
3552 } else {
3553 /* We're running/stepping, in which case we can
3554 * forward log output until the target is halted
3555 */
3556 gdb_con->frontend_state = TARGET_RUNNING;
3557 target_call_event_callbacks(target, TARGET_EVENT_GDB_START);
3558
3559 if (!already_running) {
3560 /* Here we don't want packet processing to stop even if this fails,
3561 * so we use a local variable instead of retval. */
3562 retval = gdb_step_continue_packet(connection, packet, packet_size);
3563 if (retval != ERROR_OK) {
3564 /* we'll never receive a halted
3565 * condition... issue a false one..
3566 */
3567 gdb_frontend_halted(target, connection);
3568 }
3569 }
3570 }
3571 }
3572 break;
3573 case 'v':
3574 retval = gdb_v_packet(connection, packet, packet_size);
3575 break;
3576 case 'D':
3577 retval = gdb_detach(connection);
3578 break;
3579 case 'X':
3580 retval = gdb_write_memory_binary_packet(connection, packet, packet_size);
3581 if (retval != ERROR_OK)
3582 return retval;
3583 break;
3584 case 'k':
3585 if (gdb_con->extended_protocol) {
3586 gdb_con->attached = false;
3587 break;
3588 }
3589 gdb_put_packet(connection, "OK", 2);
3590 return ERROR_SERVER_REMOTE_CLOSED;
3591 case '!':
3592 /* handle extended remote protocol */
3593 gdb_con->extended_protocol = true;
3594 gdb_put_packet(connection, "OK", 2);
3595 break;
3596 case 'R':
3597 /* handle extended restart packet */
3598 gdb_restart_inferior(connection, packet, packet_size);
3599 break;
3600
3601 case 'j':
3602 /* packet supported only by smp target i.e cortex_a.c*/
3603 /* handle smp packet replying coreid played to gbd */
3604 gdb_read_smp_packet(connection, packet, packet_size);
3605 break;
3606
3607 case 'J':
3608 /* packet supported only by smp target i.e cortex_a.c */
3609 /* handle smp packet setting coreid to be played at next
3610 * resume to gdb */
3611 gdb_write_smp_packet(connection, packet, packet_size);
3612 break;
3613
3614 case 'F':
3615 /* File-I/O extension */
3616 /* After gdb uses host-side syscall to complete target file
3617 * I/O, gdb sends host-side syscall return value to target
3618 * by 'F' packet.
3619 * The format of 'F' response packet is
3620 * Fretcode,errno,Ctrl-C flag;call-specific attachment
3621 */
3622 gdb_con->frontend_state = TARGET_RUNNING;
3623 gdb_con->output_flag = GDB_OUTPUT_ALL;
3624 gdb_fileio_response_packet(connection, packet, packet_size);
3625 break;
3626
3627 default:
3628 /* ignore unknown packets */
3629 LOG_DEBUG("ignoring 0x%2.2x packet", packet[0]);
3630 gdb_put_packet(connection, "", 0);
3631 break;
3632 }
3633
3634 /* if a packet handler returned an error, exit input loop */
3635 if (retval != ERROR_OK)
3636 return retval;
3637 }
3638
3639 if (gdb_con->ctrl_c) {
3640 if (target->state == TARGET_RUNNING) {
3641 struct target *t = target;
3642 if (target->rtos)
3643 target->rtos->gdb_target_for_threadid(connection, target->rtos->current_threadid, &t);
3644 retval = target_halt(t);
3645 if (retval == ERROR_OK)
3646 retval = target_poll(t);
3647 if (retval != ERROR_OK)
3648 target_call_event_callbacks(target, TARGET_EVENT_GDB_HALT);
3649 gdb_con->ctrl_c = false;
3650 } else {
3651 LOG_INFO("The target is not running when halt was requested, stopping GDB.");
3652 target_call_event_callbacks(target, TARGET_EVENT_GDB_HALT);
3653 }
3654 }
3655
3656 } while (gdb_con->buf_cnt > 0);
3657
3658 return ERROR_OK;
3659 }
3660
3661 static int gdb_input(struct connection *connection)
3662 {
3663 int retval = gdb_input_inner(connection);
3664 struct gdb_connection *gdb_con = connection->priv;
3665 if (retval == ERROR_SERVER_REMOTE_CLOSED)
3666 return retval;
3667
3668 /* logging does not propagate the error, yet can set the gdb_con->closed flag */
3669 if (gdb_con->closed)
3670 return ERROR_SERVER_REMOTE_CLOSED;
3671
3672 /* we'll recover from any other errors(e.g. temporary timeouts, etc.) */
3673 return ERROR_OK;
3674 }
3675
3676 static const struct service_driver gdb_service_driver = {
3677 .name = "gdb",
3678 .new_connection_during_keep_alive_handler = NULL,
3679 .new_connection_handler = gdb_new_connection,
3680 .input_handler = gdb_input,
3681 .connection_closed_handler = gdb_connection_closed,
3682 .keep_client_alive_handler = NULL,
3683 };
3684
3685 static int gdb_target_start(struct target *target, const char *port)
3686 {
3687 struct gdb_service *gdb_service;
3688 int ret;
3689 gdb_service = malloc(sizeof(struct gdb_service));
3690
3691 if (!gdb_service)
3692 return -ENOMEM;
3693
3694 LOG_INFO("starting gdb server for %s on %s", target_name(target), port);
3695
3696 gdb_service->target = target;
3697 gdb_service->core[0] = -1;
3698 gdb_service->core[1] = -1;
3699 target->gdb_service = gdb_service;
3700
3701 ret = add_service(&gdb_service_driver, port, target->gdb_max_connections, gdb_service);
3702 /* initialize all targets gdb service with the same pointer */
3703 {
3704 struct target_list *head;
3705 foreach_smp_target(head, target->smp_targets) {
3706 struct target *curr = head->target;
3707 if (curr != target)
3708 curr->gdb_service = gdb_service;
3709 }
3710 }
3711 return ret;
3712 }
3713
3714 static int gdb_target_add_one(struct target *target)
3715 {
3716 /* one gdb instance per smp list */
3717 if ((target->smp) && (target->gdb_service))
3718 return ERROR_OK;
3719
3720 /* skip targets that cannot handle a gdb connections (e.g. mem_ap) */
3721 if (!target_supports_gdb_connection(target)) {
3722 LOG_DEBUG("skip gdb server for target %s", target_name(target));
3723 return ERROR_OK;
3724 }
3725
3726 if (target->gdb_port_override) {
3727 if (strcmp(target->gdb_port_override, "disabled") == 0) {
3728 LOG_INFO("gdb port disabled");
3729 return ERROR_OK;
3730 }
3731 return gdb_target_start(target, target->gdb_port_override);
3732 }
3733
3734 if (strcmp(gdb_port, "disabled") == 0) {
3735 LOG_INFO("gdb port disabled");
3736 return ERROR_OK;
3737 }
3738
3739 int retval = gdb_target_start(target, gdb_port_next);
3740 if (retval == ERROR_OK) {
3741 /* save the port number so can be queried with
3742 * $target_name cget -gdb-port
3743 */
3744 target->gdb_port_override = strdup(gdb_port_next);
3745
3746 long portnumber;
3747 /* If we can parse the port number
3748 * then we increment the port number for the next target.
3749 */
3750 char *end;
3751 portnumber = strtol(gdb_port_next, &end, 0);
3752 if (!*end) {
3753 if (parse_long(gdb_port_next, &portnumber) == ERROR_OK) {
3754 free(gdb_port_next);
3755 if (portnumber) {
3756 gdb_port_next = alloc_printf("%ld", portnumber+1);
3757 } else {
3758 /* Don't increment if gdb_port is 0, since we're just
3759 * trying to allocate an unused port. */
3760 gdb_port_next = strdup("0");
3761 }
3762 }
3763 }
3764 }
3765 return retval;
3766 }
3767
3768 int gdb_target_add_all(struct target *target)
3769 {
3770 if (!target) {
3771 LOG_WARNING("gdb services need one or more targets defined");
3772 return ERROR_OK;
3773 }
3774
3775 while (target) {
3776 int retval = gdb_target_add_one(target);
3777 if (retval != ERROR_OK)
3778 return retval;
3779
3780 target = target->next;
3781 }
3782
3783 return ERROR_OK;
3784 }
3785
3786 COMMAND_HANDLER(handle_gdb_sync_command)
3787 {
3788 if (CMD_ARGC != 0)
3789 return ERROR_COMMAND_SYNTAX_ERROR;
3790
3791 if (!current_gdb_connection) {
3792 command_print(CMD,
3793 "gdb_sync command can only be run from within gdb using \"monitor gdb_sync\"");
3794 return ERROR_FAIL;
3795 }
3796
3797 current_gdb_connection->sync = true;
3798
3799 return ERROR_OK;
3800 }
3801
3802 /* daemon configuration command gdb_port */
3803 COMMAND_HANDLER(handle_gdb_port_command)
3804 {
3805 int retval = CALL_COMMAND_HANDLER(server_pipe_command, &gdb_port);
3806 if (retval == ERROR_OK) {
3807 free(gdb_port_next);
3808 gdb_port_next = strdup(gdb_port);
3809 }
3810 return retval;
3811 }
3812
3813 COMMAND_HANDLER(handle_gdb_memory_map_command)
3814 {
3815 if (CMD_ARGC != 1)
3816 return ERROR_COMMAND_SYNTAX_ERROR;
3817
3818 COMMAND_PARSE_ENABLE(CMD_ARGV[0], gdb_use_memory_map);
3819 return ERROR_OK;
3820 }
3821
3822 COMMAND_HANDLER(handle_gdb_flash_program_command)
3823 {
3824 if (CMD_ARGC != 1)
3825 return ERROR_COMMAND_SYNTAX_ERROR;
3826
3827 COMMAND_PARSE_ENABLE(CMD_ARGV[0], gdb_flash_program);
3828 return ERROR_OK;
3829 }
3830
3831 COMMAND_HANDLER(handle_gdb_report_data_abort_command)
3832 {
3833 if (CMD_ARGC != 1)
3834 return ERROR_COMMAND_SYNTAX_ERROR;
3835
3836 COMMAND_PARSE_ENABLE(CMD_ARGV[0], gdb_report_data_abort);
3837 return ERROR_OK;
3838 }
3839
3840 COMMAND_HANDLER(handle_gdb_report_register_access_error)
3841 {
3842 if (CMD_ARGC != 1)
3843 return ERROR_COMMAND_SYNTAX_ERROR;
3844
3845 COMMAND_PARSE_ENABLE(CMD_ARGV[0], gdb_report_register_access_error);
3846 return ERROR_OK;
3847 }
3848
3849 /* gdb_breakpoint_override */
3850 COMMAND_HANDLER(handle_gdb_breakpoint_override_command)
3851 {
3852 if (CMD_ARGC == 0) {
3853 /* nothing */
3854 } else if (CMD_ARGC == 1) {
3855 gdb_breakpoint_override = 1;
3856 if (strcmp(CMD_ARGV[0], "hard") == 0)
3857 gdb_breakpoint_override_type = BKPT_HARD;
3858 else if (strcmp(CMD_ARGV[0], "soft") == 0)
3859 gdb_breakpoint_override_type = BKPT_SOFT;
3860 else if (strcmp(CMD_ARGV[0], "disable") == 0)
3861 gdb_breakpoint_override = 0;
3862 } else
3863 return ERROR_COMMAND_SYNTAX_ERROR;
3864 if (gdb_breakpoint_override)
3865 LOG_USER("force %s breakpoints",
3866 (gdb_breakpoint_override_type == BKPT_HARD) ? "hard" : "soft");
3867 else
3868 LOG_USER("breakpoint type is not overridden");
3869
3870 return ERROR_OK;
3871 }
3872
3873 COMMAND_HANDLER(handle_gdb_target_description_command)
3874 {
3875 if (CMD_ARGC != 1)
3876 return ERROR_COMMAND_SYNTAX_ERROR;
3877
3878 COMMAND_PARSE_ENABLE(CMD_ARGV[0], gdb_use_target_description);
3879 return ERROR_OK;
3880 }
3881
3882 COMMAND_HANDLER(handle_gdb_save_tdesc_command)
3883 {
3884 char *tdesc;
3885 uint32_t tdesc_length;
3886 struct target *target = get_current_target(CMD_CTX);
3887
3888 int retval = gdb_generate_target_description(target, &tdesc);
3889 if (retval != ERROR_OK) {
3890 LOG_ERROR("Unable to Generate Target Description");
3891 return ERROR_FAIL;
3892 }
3893
3894 tdesc_length = strlen(tdesc);
3895
3896 struct fileio *fileio;
3897 size_t size_written;
3898
3899 char *tdesc_filename = alloc_printf("%s.xml", target_type_name(target));
3900 if (!tdesc_filename) {
3901 retval = ERROR_FAIL;
3902 goto out;
3903 }
3904
3905 retval = fileio_open(&fileio, tdesc_filename, FILEIO_WRITE, FILEIO_TEXT);
3906
3907 if (retval != ERROR_OK) {
3908 LOG_ERROR("Can't open %s for writing", tdesc_filename);
3909 goto out;
3910 }
3911
3912 retval = fileio_write(fileio, tdesc_length, tdesc, &size_written);
3913
3914 fileio_close(fileio);
3915
3916 if (retval != ERROR_OK)
3917 LOG_ERROR("Error while writing the tdesc file");
3918
3919 out:
3920 free(tdesc_filename);
3921 free(tdesc);
3922
3923 return retval;
3924 }
3925
3926 static const struct command_registration gdb_command_handlers[] = {
3927 {
3928 .name = "gdb_sync",
3929 .handler = handle_gdb_sync_command,
3930 .mode = COMMAND_ANY,
3931 .help = "next stepi will return immediately allowing "
3932 "GDB to fetch register state without affecting "
3933 "target state",
3934 .usage = ""
3935 },
3936 {
3937 .name = "gdb_port",
3938 .handler = handle_gdb_port_command,
3939 .mode = COMMAND_CONFIG,
3940 .help = "Normally gdb listens to a TCP/IP port. Each subsequent GDB "
3941 "server listens for the next port number after the "
3942 "base port number specified. "
3943 "No arguments reports GDB port. \"pipe\" means listen to stdin "
3944 "output to stdout, an integer is base port number, \"disabled\" disables "
3945 "port. Any other string is are interpreted as named pipe to listen to. "
3946 "Output pipe is the same name as input pipe, but with 'o' appended.",
3947 .usage = "[port_num]",
3948 },
3949 {
3950 .name = "gdb_memory_map",
3951 .handler = handle_gdb_memory_map_command,
3952 .mode = COMMAND_CONFIG,
3953 .help = "enable or disable memory map",
3954 .usage = "('enable'|'disable')"
3955 },
3956 {
3957 .name = "gdb_flash_program",
3958 .handler = handle_gdb_flash_program_command,
3959 .mode = COMMAND_CONFIG,
3960 .help = "enable or disable flash program",
3961 .usage = "('enable'|'disable')"
3962 },
3963 {
3964 .name = "gdb_report_data_abort",
3965 .handler = handle_gdb_report_data_abort_command,
3966 .mode = COMMAND_CONFIG,
3967 .help = "enable or disable reporting data aborts",
3968 .usage = "('enable'|'disable')"
3969 },
3970 {
3971 .name = "gdb_report_register_access_error",
3972 .handler = handle_gdb_report_register_access_error,
3973 .mode = COMMAND_CONFIG,
3974 .help = "enable or disable reporting register access errors",
3975 .usage = "('enable'|'disable')"
3976 },
3977 {
3978 .name = "gdb_breakpoint_override",
3979 .handler = handle_gdb_breakpoint_override_command,
3980 .mode = COMMAND_ANY,
3981 .help = "Display or specify type of breakpoint "
3982 "to be used by gdb 'break' commands.",
3983 .usage = "('hard'|'soft'|'disable')"
3984 },
3985 {
3986 .name = "gdb_target_description",
3987 .handler = handle_gdb_target_description_command,
3988 .mode = COMMAND_CONFIG,
3989 .help = "enable or disable target description",
3990 .usage = "('enable'|'disable')"
3991 },
3992 {
3993 .name = "gdb_save_tdesc",
3994 .handler = handle_gdb_save_tdesc_command,
3995 .mode = COMMAND_EXEC,
3996 .help = "Save the target description file",
3997 .usage = "",
3998 },
3999 COMMAND_REGISTRATION_DONE
4000 };
4001
4002 int gdb_register_commands(struct command_context *cmd_ctx)
4003 {
4004 gdb_port = strdup("3333");
4005 gdb_port_next = strdup("3333");
4006 return register_commands(cmd_ctx, NULL, gdb_command_handlers);
4007 }
4008
4009 void gdb_service_free(void)
4010 {
4011 free(gdb_port);
4012 free(gdb_port_next);
4013 }

Linking to existing account procedure

If you already have an account and want to add another login method you MUST first sign in with your existing account and then change URL to read https://review.openocd.org/login/?link to get to this page again but this time it'll work for linking. Thank you.

SSH host keys fingerprints

1024 SHA256:YKx8b7u5ZWdcbp7/4AeXNaqElP49m6QrwfXaqQGJAOk gerrit-code-review@openocd.zylin.com (DSA)
384 SHA256:jHIbSQa4REvwCFG4cq5LBlBLxmxSqelQPem/EXIrxjk gerrit-code-review@openocd.org (ECDSA)
521 SHA256:UAOPYkU9Fjtcao0Ul/Rrlnj/OsQvt+pgdYSZ4jOYdgs gerrit-code-review@openocd.org (ECDSA)
256 SHA256:A13M5QlnozFOvTllybRZH6vm7iSt0XLxbA48yfc2yfY gerrit-code-review@openocd.org (ECDSA)
256 SHA256:spYMBqEYoAOtK7yZBrcwE8ZpYt6b68Cfh9yEVetvbXg gerrit-code-review@openocd.org (ED25519)
+--[ED25519 256]--+
|=..              |
|+o..   .         |
|*.o   . .        |
|+B . . .         |
|Bo. = o S        |
|Oo.+ + =         |
|oB=.* = . o      |
| =+=.+   + E     |
|. .=o   . o      |
+----[SHA256]-----+
2048 SHA256:0Onrb7/PHjpo6iVZ7xQX2riKN83FJ3KGU0TvI0TaFG4 gerrit-code-review@openocd.zylin.com (RSA)