gdbstub: modernise DEBUG_GDB
[qemu/kevin.git] / gdbstub.c
blob39659802ad54a05ac6b48e0c435819f05263268a
1 /*
2 * gdb server stub
4 * Copyright (c) 2003-2005 Fabrice Bellard
6 * This library is free software; you can redistribute it and/or
7 * modify it under the terms of the GNU Lesser General Public
8 * License as published by the Free Software Foundation; either
9 * version 2 of the License, or (at your option) any later version.
11 * This library is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14 * Lesser General Public License for more details.
16 * You should have received a copy of the GNU Lesser General Public
17 * License along with this library; if not, see <http://www.gnu.org/licenses/>.
19 #include "qemu/osdep.h"
20 #include "qapi/error.h"
21 #include "qemu/error-report.h"
22 #include "qemu/cutils.h"
23 #include "cpu.h"
24 #ifdef CONFIG_USER_ONLY
25 #include "qemu.h"
26 #else
27 #include "monitor/monitor.h"
28 #include "chardev/char.h"
29 #include "chardev/char-fe.h"
30 #include "sysemu/sysemu.h"
31 #include "exec/gdbstub.h"
32 #endif
34 #define MAX_PACKET_LENGTH 4096
36 #include "qemu/sockets.h"
37 #include "sysemu/hw_accel.h"
38 #include "sysemu/kvm.h"
39 #include "exec/semihost.h"
40 #include "exec/exec-all.h"
42 #ifdef CONFIG_USER_ONLY
43 #define GDB_ATTACHED "0"
44 #else
45 #define GDB_ATTACHED "1"
46 #endif
48 static inline int target_memory_rw_debug(CPUState *cpu, target_ulong addr,
49 uint8_t *buf, int len, bool is_write)
51 CPUClass *cc = CPU_GET_CLASS(cpu);
53 if (cc->memory_rw_debug) {
54 return cc->memory_rw_debug(cpu, addr, buf, len, is_write);
56 return cpu_memory_rw_debug(cpu, addr, buf, len, is_write);
59 enum {
60 GDB_SIGNAL_0 = 0,
61 GDB_SIGNAL_INT = 2,
62 GDB_SIGNAL_QUIT = 3,
63 GDB_SIGNAL_TRAP = 5,
64 GDB_SIGNAL_ABRT = 6,
65 GDB_SIGNAL_ALRM = 14,
66 GDB_SIGNAL_IO = 23,
67 GDB_SIGNAL_XCPU = 24,
68 GDB_SIGNAL_UNKNOWN = 143
71 #ifdef CONFIG_USER_ONLY
73 /* Map target signal numbers to GDB protocol signal numbers and vice
74 * versa. For user emulation's currently supported systems, we can
75 * assume most signals are defined.
78 static int gdb_signal_table[] = {
80 TARGET_SIGHUP,
81 TARGET_SIGINT,
82 TARGET_SIGQUIT,
83 TARGET_SIGILL,
84 TARGET_SIGTRAP,
85 TARGET_SIGABRT,
86 -1, /* SIGEMT */
87 TARGET_SIGFPE,
88 TARGET_SIGKILL,
89 TARGET_SIGBUS,
90 TARGET_SIGSEGV,
91 TARGET_SIGSYS,
92 TARGET_SIGPIPE,
93 TARGET_SIGALRM,
94 TARGET_SIGTERM,
95 TARGET_SIGURG,
96 TARGET_SIGSTOP,
97 TARGET_SIGTSTP,
98 TARGET_SIGCONT,
99 TARGET_SIGCHLD,
100 TARGET_SIGTTIN,
101 TARGET_SIGTTOU,
102 TARGET_SIGIO,
103 TARGET_SIGXCPU,
104 TARGET_SIGXFSZ,
105 TARGET_SIGVTALRM,
106 TARGET_SIGPROF,
107 TARGET_SIGWINCH,
108 -1, /* SIGLOST */
109 TARGET_SIGUSR1,
110 TARGET_SIGUSR2,
111 #ifdef TARGET_SIGPWR
112 TARGET_SIGPWR,
113 #else
115 #endif
116 -1, /* SIGPOLL */
128 #ifdef __SIGRTMIN
129 __SIGRTMIN + 1,
130 __SIGRTMIN + 2,
131 __SIGRTMIN + 3,
132 __SIGRTMIN + 4,
133 __SIGRTMIN + 5,
134 __SIGRTMIN + 6,
135 __SIGRTMIN + 7,
136 __SIGRTMIN + 8,
137 __SIGRTMIN + 9,
138 __SIGRTMIN + 10,
139 __SIGRTMIN + 11,
140 __SIGRTMIN + 12,
141 __SIGRTMIN + 13,
142 __SIGRTMIN + 14,
143 __SIGRTMIN + 15,
144 __SIGRTMIN + 16,
145 __SIGRTMIN + 17,
146 __SIGRTMIN + 18,
147 __SIGRTMIN + 19,
148 __SIGRTMIN + 20,
149 __SIGRTMIN + 21,
150 __SIGRTMIN + 22,
151 __SIGRTMIN + 23,
152 __SIGRTMIN + 24,
153 __SIGRTMIN + 25,
154 __SIGRTMIN + 26,
155 __SIGRTMIN + 27,
156 __SIGRTMIN + 28,
157 __SIGRTMIN + 29,
158 __SIGRTMIN + 30,
159 __SIGRTMIN + 31,
160 -1, /* SIGCANCEL */
161 __SIGRTMIN,
162 __SIGRTMIN + 32,
163 __SIGRTMIN + 33,
164 __SIGRTMIN + 34,
165 __SIGRTMIN + 35,
166 __SIGRTMIN + 36,
167 __SIGRTMIN + 37,
168 __SIGRTMIN + 38,
169 __SIGRTMIN + 39,
170 __SIGRTMIN + 40,
171 __SIGRTMIN + 41,
172 __SIGRTMIN + 42,
173 __SIGRTMIN + 43,
174 __SIGRTMIN + 44,
175 __SIGRTMIN + 45,
176 __SIGRTMIN + 46,
177 __SIGRTMIN + 47,
178 __SIGRTMIN + 48,
179 __SIGRTMIN + 49,
180 __SIGRTMIN + 50,
181 __SIGRTMIN + 51,
182 __SIGRTMIN + 52,
183 __SIGRTMIN + 53,
184 __SIGRTMIN + 54,
185 __SIGRTMIN + 55,
186 __SIGRTMIN + 56,
187 __SIGRTMIN + 57,
188 __SIGRTMIN + 58,
189 __SIGRTMIN + 59,
190 __SIGRTMIN + 60,
191 __SIGRTMIN + 61,
192 __SIGRTMIN + 62,
193 __SIGRTMIN + 63,
194 __SIGRTMIN + 64,
195 __SIGRTMIN + 65,
196 __SIGRTMIN + 66,
197 __SIGRTMIN + 67,
198 __SIGRTMIN + 68,
199 __SIGRTMIN + 69,
200 __SIGRTMIN + 70,
201 __SIGRTMIN + 71,
202 __SIGRTMIN + 72,
203 __SIGRTMIN + 73,
204 __SIGRTMIN + 74,
205 __SIGRTMIN + 75,
206 __SIGRTMIN + 76,
207 __SIGRTMIN + 77,
208 __SIGRTMIN + 78,
209 __SIGRTMIN + 79,
210 __SIGRTMIN + 80,
211 __SIGRTMIN + 81,
212 __SIGRTMIN + 82,
213 __SIGRTMIN + 83,
214 __SIGRTMIN + 84,
215 __SIGRTMIN + 85,
216 __SIGRTMIN + 86,
217 __SIGRTMIN + 87,
218 __SIGRTMIN + 88,
219 __SIGRTMIN + 89,
220 __SIGRTMIN + 90,
221 __SIGRTMIN + 91,
222 __SIGRTMIN + 92,
223 __SIGRTMIN + 93,
224 __SIGRTMIN + 94,
225 __SIGRTMIN + 95,
226 -1, /* SIGINFO */
227 -1, /* UNKNOWN */
228 -1, /* DEFAULT */
235 #endif
237 #else
238 /* In system mode we only need SIGINT and SIGTRAP; other signals
239 are not yet supported. */
241 enum {
242 TARGET_SIGINT = 2,
243 TARGET_SIGTRAP = 5
246 static int gdb_signal_table[] = {
249 TARGET_SIGINT,
252 TARGET_SIGTRAP
254 #endif
256 #ifdef CONFIG_USER_ONLY
257 static int target_signal_to_gdb (int sig)
259 int i;
260 for (i = 0; i < ARRAY_SIZE (gdb_signal_table); i++)
261 if (gdb_signal_table[i] == sig)
262 return i;
263 return GDB_SIGNAL_UNKNOWN;
265 #endif
267 static int gdb_signal_to_target (int sig)
269 if (sig < ARRAY_SIZE (gdb_signal_table))
270 return gdb_signal_table[sig];
271 else
272 return -1;
275 /* #define DEBUG_GDB */
277 #ifdef DEBUG_GDB
278 # define DEBUG_GDB_GATE 1
279 #else
280 # define DEBUG_GDB_GATE 0
281 #endif
283 #define gdb_debug(fmt, ...) do { \
284 if (DEBUG_GDB_GATE) { \
285 fprintf(stderr, "%s: " fmt, __func__, ## __VA_ARGS__); \
287 } while (0)
290 typedef struct GDBRegisterState {
291 int base_reg;
292 int num_regs;
293 gdb_reg_cb get_reg;
294 gdb_reg_cb set_reg;
295 const char *xml;
296 struct GDBRegisterState *next;
297 } GDBRegisterState;
299 enum RSState {
300 RS_INACTIVE,
301 RS_IDLE,
302 RS_GETLINE,
303 RS_GETLINE_ESC,
304 RS_GETLINE_RLE,
305 RS_CHKSUM1,
306 RS_CHKSUM2,
308 typedef struct GDBState {
309 CPUState *c_cpu; /* current CPU for step/continue ops */
310 CPUState *g_cpu; /* current CPU for other ops */
311 CPUState *query_cpu; /* for q{f|s}ThreadInfo */
312 enum RSState state; /* parsing state */
313 char line_buf[MAX_PACKET_LENGTH];
314 int line_buf_index;
315 int line_sum; /* running checksum */
316 int line_csum; /* checksum at the end of the packet */
317 uint8_t last_packet[MAX_PACKET_LENGTH + 4];
318 int last_packet_len;
319 int signal;
320 #ifdef CONFIG_USER_ONLY
321 int fd;
322 int running_state;
323 #else
324 CharBackend chr;
325 Chardev *mon_chr;
326 #endif
327 char syscall_buf[256];
328 gdb_syscall_complete_cb current_syscall_cb;
329 } GDBState;
331 /* By default use no IRQs and no timers while single stepping so as to
332 * make single stepping like an ICE HW step.
334 static int sstep_flags = SSTEP_ENABLE|SSTEP_NOIRQ|SSTEP_NOTIMER;
336 static GDBState *gdbserver_state;
338 bool gdb_has_xml;
340 #ifdef CONFIG_USER_ONLY
341 /* XXX: This is not thread safe. Do we care? */
342 static int gdbserver_fd = -1;
344 static int get_char(GDBState *s)
346 uint8_t ch;
347 int ret;
349 for(;;) {
350 ret = qemu_recv(s->fd, &ch, 1, 0);
351 if (ret < 0) {
352 if (errno == ECONNRESET)
353 s->fd = -1;
354 if (errno != EINTR)
355 return -1;
356 } else if (ret == 0) {
357 close(s->fd);
358 s->fd = -1;
359 return -1;
360 } else {
361 break;
364 return ch;
366 #endif
368 static enum {
369 GDB_SYS_UNKNOWN,
370 GDB_SYS_ENABLED,
371 GDB_SYS_DISABLED,
372 } gdb_syscall_mode;
374 /* Decide if either remote gdb syscalls or native file IO should be used. */
375 int use_gdb_syscalls(void)
377 SemihostingTarget target = semihosting_get_target();
378 if (target == SEMIHOSTING_TARGET_NATIVE) {
379 /* -semihosting-config target=native */
380 return false;
381 } else if (target == SEMIHOSTING_TARGET_GDB) {
382 /* -semihosting-config target=gdb */
383 return true;
386 /* -semihosting-config target=auto */
387 /* On the first call check if gdb is connected and remember. */
388 if (gdb_syscall_mode == GDB_SYS_UNKNOWN) {
389 gdb_syscall_mode = (gdbserver_state ? GDB_SYS_ENABLED
390 : GDB_SYS_DISABLED);
392 return gdb_syscall_mode == GDB_SYS_ENABLED;
395 /* Resume execution. */
396 static inline void gdb_continue(GDBState *s)
398 #ifdef CONFIG_USER_ONLY
399 s->running_state = 1;
400 #else
401 if (!runstate_needs_reset()) {
402 vm_start();
404 #endif
408 * Resume execution, per CPU actions. For user-mode emulation it's
409 * equivalent to gdb_continue.
411 static int gdb_continue_partial(GDBState *s, char *newstates)
413 CPUState *cpu;
414 int res = 0;
415 #ifdef CONFIG_USER_ONLY
417 * This is not exactly accurate, but it's an improvement compared to the
418 * previous situation, where only one CPU would be single-stepped.
420 CPU_FOREACH(cpu) {
421 if (newstates[cpu->cpu_index] == 's') {
422 cpu_single_step(cpu, sstep_flags);
425 s->running_state = 1;
426 #else
427 int flag = 0;
429 if (!runstate_needs_reset()) {
430 if (vm_prepare_start()) {
431 return 0;
434 CPU_FOREACH(cpu) {
435 switch (newstates[cpu->cpu_index]) {
436 case 0:
437 case 1:
438 break; /* nothing to do here */
439 case 's':
440 cpu_single_step(cpu, sstep_flags);
441 cpu_resume(cpu);
442 flag = 1;
443 break;
444 case 'c':
445 cpu_resume(cpu);
446 flag = 1;
447 break;
448 default:
449 res = -1;
450 break;
454 if (flag) {
455 qemu_clock_enable(QEMU_CLOCK_VIRTUAL, true);
457 #endif
458 return res;
461 static void put_buffer(GDBState *s, const uint8_t *buf, int len)
463 #ifdef CONFIG_USER_ONLY
464 int ret;
466 while (len > 0) {
467 ret = send(s->fd, buf, len, 0);
468 if (ret < 0) {
469 if (errno != EINTR)
470 return;
471 } else {
472 buf += ret;
473 len -= ret;
476 #else
477 /* XXX this blocks entire thread. Rewrite to use
478 * qemu_chr_fe_write and background I/O callbacks */
479 qemu_chr_fe_write_all(&s->chr, buf, len);
480 #endif
483 static inline int fromhex(int v)
485 if (v >= '0' && v <= '9')
486 return v - '0';
487 else if (v >= 'A' && v <= 'F')
488 return v - 'A' + 10;
489 else if (v >= 'a' && v <= 'f')
490 return v - 'a' + 10;
491 else
492 return 0;
495 static inline int tohex(int v)
497 if (v < 10)
498 return v + '0';
499 else
500 return v - 10 + 'a';
503 static void memtohex(char *buf, const uint8_t *mem, int len)
505 int i, c;
506 char *q;
507 q = buf;
508 for(i = 0; i < len; i++) {
509 c = mem[i];
510 *q++ = tohex(c >> 4);
511 *q++ = tohex(c & 0xf);
513 *q = '\0';
516 static void hextomem(uint8_t *mem, const char *buf, int len)
518 int i;
520 for(i = 0; i < len; i++) {
521 mem[i] = (fromhex(buf[0]) << 4) | fromhex(buf[1]);
522 buf += 2;
526 /* return -1 if error, 0 if OK */
527 static int put_packet_binary(GDBState *s, const char *buf, int len)
529 int csum, i;
530 uint8_t *p;
532 for(;;) {
533 p = s->last_packet;
534 *(p++) = '$';
535 memcpy(p, buf, len);
536 p += len;
537 csum = 0;
538 for(i = 0; i < len; i++) {
539 csum += buf[i];
541 *(p++) = '#';
542 *(p++) = tohex((csum >> 4) & 0xf);
543 *(p++) = tohex((csum) & 0xf);
545 s->last_packet_len = p - s->last_packet;
546 put_buffer(s, (uint8_t *)s->last_packet, s->last_packet_len);
548 #ifdef CONFIG_USER_ONLY
549 i = get_char(s);
550 if (i < 0)
551 return -1;
552 if (i == '+')
553 break;
554 #else
555 break;
556 #endif
558 return 0;
561 /* return -1 if error, 0 if OK */
562 static int put_packet(GDBState *s, const char *buf)
564 gdb_debug("reply='%s'\n", buf);
566 return put_packet_binary(s, buf, strlen(buf));
569 /* Encode data using the encoding for 'x' packets. */
570 static int memtox(char *buf, const char *mem, int len)
572 char *p = buf;
573 char c;
575 while (len--) {
576 c = *(mem++);
577 switch (c) {
578 case '#': case '$': case '*': case '}':
579 *(p++) = '}';
580 *(p++) = c ^ 0x20;
581 break;
582 default:
583 *(p++) = c;
584 break;
587 return p - buf;
590 static const char *get_feature_xml(const char *p, const char **newp,
591 CPUClass *cc)
593 size_t len;
594 int i;
595 const char *name;
596 static char target_xml[1024];
598 len = 0;
599 while (p[len] && p[len] != ':')
600 len++;
601 *newp = p + len;
603 name = NULL;
604 if (strncmp(p, "target.xml", len) == 0) {
605 /* Generate the XML description for this CPU. */
606 if (!target_xml[0]) {
607 GDBRegisterState *r;
608 CPUState *cpu = first_cpu;
610 pstrcat(target_xml, sizeof(target_xml),
611 "<?xml version=\"1.0\"?>"
612 "<!DOCTYPE target SYSTEM \"gdb-target.dtd\">"
613 "<target>");
614 if (cc->gdb_arch_name) {
615 gchar *arch = cc->gdb_arch_name(cpu);
616 pstrcat(target_xml, sizeof(target_xml), "<architecture>");
617 pstrcat(target_xml, sizeof(target_xml), arch);
618 pstrcat(target_xml, sizeof(target_xml), "</architecture>");
619 g_free(arch);
621 pstrcat(target_xml, sizeof(target_xml), "<xi:include href=\"");
622 pstrcat(target_xml, sizeof(target_xml), cc->gdb_core_xml_file);
623 pstrcat(target_xml, sizeof(target_xml), "\"/>");
624 for (r = cpu->gdb_regs; r; r = r->next) {
625 pstrcat(target_xml, sizeof(target_xml), "<xi:include href=\"");
626 pstrcat(target_xml, sizeof(target_xml), r->xml);
627 pstrcat(target_xml, sizeof(target_xml), "\"/>");
629 pstrcat(target_xml, sizeof(target_xml), "</target>");
631 return target_xml;
633 for (i = 0; ; i++) {
634 name = xml_builtin[i][0];
635 if (!name || (strncmp(name, p, len) == 0 && strlen(name) == len))
636 break;
638 return name ? xml_builtin[i][1] : NULL;
641 static int gdb_read_register(CPUState *cpu, uint8_t *mem_buf, int reg)
643 CPUClass *cc = CPU_GET_CLASS(cpu);
644 CPUArchState *env = cpu->env_ptr;
645 GDBRegisterState *r;
647 if (reg < cc->gdb_num_core_regs) {
648 return cc->gdb_read_register(cpu, mem_buf, reg);
651 for (r = cpu->gdb_regs; r; r = r->next) {
652 if (r->base_reg <= reg && reg < r->base_reg + r->num_regs) {
653 return r->get_reg(env, mem_buf, reg - r->base_reg);
656 return 0;
659 static int gdb_write_register(CPUState *cpu, uint8_t *mem_buf, int reg)
661 CPUClass *cc = CPU_GET_CLASS(cpu);
662 CPUArchState *env = cpu->env_ptr;
663 GDBRegisterState *r;
665 if (reg < cc->gdb_num_core_regs) {
666 return cc->gdb_write_register(cpu, mem_buf, reg);
669 for (r = cpu->gdb_regs; r; r = r->next) {
670 if (r->base_reg <= reg && reg < r->base_reg + r->num_regs) {
671 return r->set_reg(env, mem_buf, reg - r->base_reg);
674 return 0;
677 /* Register a supplemental set of CPU registers. If g_pos is nonzero it
678 specifies the first register number and these registers are included in
679 a standard "g" packet. Direction is relative to gdb, i.e. get_reg is
680 gdb reading a CPU register, and set_reg is gdb modifying a CPU register.
683 void gdb_register_coprocessor(CPUState *cpu,
684 gdb_reg_cb get_reg, gdb_reg_cb set_reg,
685 int num_regs, const char *xml, int g_pos)
687 GDBRegisterState *s;
688 GDBRegisterState **p;
690 p = &cpu->gdb_regs;
691 while (*p) {
692 /* Check for duplicates. */
693 if (strcmp((*p)->xml, xml) == 0)
694 return;
695 p = &(*p)->next;
698 s = g_new0(GDBRegisterState, 1);
699 s->base_reg = cpu->gdb_num_regs;
700 s->num_regs = num_regs;
701 s->get_reg = get_reg;
702 s->set_reg = set_reg;
703 s->xml = xml;
705 /* Add to end of list. */
706 cpu->gdb_num_regs += num_regs;
707 *p = s;
708 if (g_pos) {
709 if (g_pos != s->base_reg) {
710 error_report("Error: Bad gdb register numbering for '%s', "
711 "expected %d got %d", xml, g_pos, s->base_reg);
712 } else {
713 cpu->gdb_num_g_regs = cpu->gdb_num_regs;
718 #ifndef CONFIG_USER_ONLY
719 /* Translate GDB watchpoint type to a flags value for cpu_watchpoint_* */
720 static inline int xlat_gdb_type(CPUState *cpu, int gdbtype)
722 static const int xlat[] = {
723 [GDB_WATCHPOINT_WRITE] = BP_GDB | BP_MEM_WRITE,
724 [GDB_WATCHPOINT_READ] = BP_GDB | BP_MEM_READ,
725 [GDB_WATCHPOINT_ACCESS] = BP_GDB | BP_MEM_ACCESS,
728 CPUClass *cc = CPU_GET_CLASS(cpu);
729 int cputype = xlat[gdbtype];
731 if (cc->gdb_stop_before_watchpoint) {
732 cputype |= BP_STOP_BEFORE_ACCESS;
734 return cputype;
736 #endif
738 static int gdb_breakpoint_insert(target_ulong addr, target_ulong len, int type)
740 CPUState *cpu;
741 int err = 0;
743 if (kvm_enabled()) {
744 return kvm_insert_breakpoint(gdbserver_state->c_cpu, addr, len, type);
747 switch (type) {
748 case GDB_BREAKPOINT_SW:
749 case GDB_BREAKPOINT_HW:
750 CPU_FOREACH(cpu) {
751 err = cpu_breakpoint_insert(cpu, addr, BP_GDB, NULL);
752 if (err) {
753 break;
756 return err;
757 #ifndef CONFIG_USER_ONLY
758 case GDB_WATCHPOINT_WRITE:
759 case GDB_WATCHPOINT_READ:
760 case GDB_WATCHPOINT_ACCESS:
761 CPU_FOREACH(cpu) {
762 err = cpu_watchpoint_insert(cpu, addr, len,
763 xlat_gdb_type(cpu, type), NULL);
764 if (err) {
765 break;
768 return err;
769 #endif
770 default:
771 return -ENOSYS;
775 static int gdb_breakpoint_remove(target_ulong addr, target_ulong len, int type)
777 CPUState *cpu;
778 int err = 0;
780 if (kvm_enabled()) {
781 return kvm_remove_breakpoint(gdbserver_state->c_cpu, addr, len, type);
784 switch (type) {
785 case GDB_BREAKPOINT_SW:
786 case GDB_BREAKPOINT_HW:
787 CPU_FOREACH(cpu) {
788 err = cpu_breakpoint_remove(cpu, addr, BP_GDB);
789 if (err) {
790 break;
793 return err;
794 #ifndef CONFIG_USER_ONLY
795 case GDB_WATCHPOINT_WRITE:
796 case GDB_WATCHPOINT_READ:
797 case GDB_WATCHPOINT_ACCESS:
798 CPU_FOREACH(cpu) {
799 err = cpu_watchpoint_remove(cpu, addr, len,
800 xlat_gdb_type(cpu, type));
801 if (err)
802 break;
804 return err;
805 #endif
806 default:
807 return -ENOSYS;
811 static void gdb_breakpoint_remove_all(void)
813 CPUState *cpu;
815 if (kvm_enabled()) {
816 kvm_remove_all_breakpoints(gdbserver_state->c_cpu);
817 return;
820 CPU_FOREACH(cpu) {
821 cpu_breakpoint_remove_all(cpu, BP_GDB);
822 #ifndef CONFIG_USER_ONLY
823 cpu_watchpoint_remove_all(cpu, BP_GDB);
824 #endif
828 static void gdb_set_cpu_pc(GDBState *s, target_ulong pc)
830 CPUState *cpu = s->c_cpu;
832 cpu_synchronize_state(cpu);
833 cpu_set_pc(cpu, pc);
836 static CPUState *find_cpu(uint32_t thread_id)
838 CPUState *cpu;
840 CPU_FOREACH(cpu) {
841 if (cpu_index(cpu) == thread_id) {
842 return cpu;
846 return NULL;
849 static int is_query_packet(const char *p, const char *query, char separator)
851 unsigned int query_len = strlen(query);
853 return strncmp(p, query, query_len) == 0 &&
854 (p[query_len] == '\0' || p[query_len] == separator);
858 * gdb_handle_vcont - Parses and handles a vCont packet.
859 * returns -ENOTSUP if a command is unsupported, -EINVAL or -ERANGE if there is
860 * a format error, 0 on success.
862 static int gdb_handle_vcont(GDBState *s, const char *p)
864 int res, idx, signal = 0;
865 char cur_action;
866 char *newstates;
867 unsigned long tmp;
868 CPUState *cpu;
869 #ifdef CONFIG_USER_ONLY
870 int max_cpus = 1; /* global variable max_cpus exists only in system mode */
872 CPU_FOREACH(cpu) {
873 max_cpus = max_cpus <= cpu->cpu_index ? cpu->cpu_index + 1 : max_cpus;
875 #endif
876 /* uninitialised CPUs stay 0 */
877 newstates = g_new0(char, max_cpus);
879 /* mark valid CPUs with 1 */
880 CPU_FOREACH(cpu) {
881 newstates[cpu->cpu_index] = 1;
885 * res keeps track of what error we are returning, with -ENOTSUP meaning
886 * that the command is unknown or unsupported, thus returning an empty
887 * packet, while -EINVAL and -ERANGE cause an E22 packet, due to invalid,
888 * or incorrect parameters passed.
890 res = 0;
891 while (*p) {
892 if (*p++ != ';') {
893 res = -ENOTSUP;
894 goto out;
897 cur_action = *p++;
898 if (cur_action == 'C' || cur_action == 'S') {
899 cur_action = tolower(cur_action);
900 res = qemu_strtoul(p + 1, &p, 16, &tmp);
901 if (res) {
902 goto out;
904 signal = gdb_signal_to_target(tmp);
905 } else if (cur_action != 'c' && cur_action != 's') {
906 /* unknown/invalid/unsupported command */
907 res = -ENOTSUP;
908 goto out;
910 /* thread specification. special values: (none), -1 = all; 0 = any */
911 if ((p[0] == ':' && p[1] == '-' && p[2] == '1') || (p[0] != ':')) {
912 if (*p == ':') {
913 p += 3;
915 for (idx = 0; idx < max_cpus; idx++) {
916 if (newstates[idx] == 1) {
917 newstates[idx] = cur_action;
920 } else if (*p == ':') {
921 p++;
922 res = qemu_strtoul(p, &p, 16, &tmp);
923 if (res) {
924 goto out;
926 idx = tmp;
927 /* 0 means any thread, so we pick the first valid CPU */
928 if (!idx) {
929 idx = cpu_index(first_cpu);
933 * If we are in user mode, the thread specified is actually a
934 * thread id, and not an index. We need to find the actual
935 * CPU first, and only then we can use its index.
937 cpu = find_cpu(idx);
938 /* invalid CPU/thread specified */
939 if (!idx || !cpu) {
940 res = -EINVAL;
941 goto out;
943 /* only use if no previous match occourred */
944 if (newstates[cpu->cpu_index] == 1) {
945 newstates[cpu->cpu_index] = cur_action;
949 s->signal = signal;
950 gdb_continue_partial(s, newstates);
952 out:
953 g_free(newstates);
955 return res;
958 static int gdb_handle_packet(GDBState *s, const char *line_buf)
960 CPUState *cpu;
961 CPUClass *cc;
962 const char *p;
963 uint32_t thread;
964 int ch, reg_size, type, res;
965 char buf[MAX_PACKET_LENGTH];
966 uint8_t mem_buf[MAX_PACKET_LENGTH];
967 uint8_t *registers;
968 target_ulong addr, len;
971 gdb_debug("command='%s'\n", line_buf);
973 p = line_buf;
974 ch = *p++;
975 switch(ch) {
976 case '?':
977 /* TODO: Make this return the correct value for user-mode. */
978 snprintf(buf, sizeof(buf), "T%02xthread:%02x;", GDB_SIGNAL_TRAP,
979 cpu_index(s->c_cpu));
980 put_packet(s, buf);
981 /* Remove all the breakpoints when this query is issued,
982 * because gdb is doing and initial connect and the state
983 * should be cleaned up.
985 gdb_breakpoint_remove_all();
986 break;
987 case 'c':
988 if (*p != '\0') {
989 addr = strtoull(p, (char **)&p, 16);
990 gdb_set_cpu_pc(s, addr);
992 s->signal = 0;
993 gdb_continue(s);
994 return RS_IDLE;
995 case 'C':
996 s->signal = gdb_signal_to_target (strtoul(p, (char **)&p, 16));
997 if (s->signal == -1)
998 s->signal = 0;
999 gdb_continue(s);
1000 return RS_IDLE;
1001 case 'v':
1002 if (strncmp(p, "Cont", 4) == 0) {
1003 p += 4;
1004 if (*p == '?') {
1005 put_packet(s, "vCont;c;C;s;S");
1006 break;
1009 res = gdb_handle_vcont(s, p);
1011 if (res) {
1012 if ((res == -EINVAL) || (res == -ERANGE)) {
1013 put_packet(s, "E22");
1014 break;
1016 goto unknown_command;
1018 break;
1019 } else {
1020 goto unknown_command;
1022 case 'k':
1023 /* Kill the target */
1024 error_report("QEMU: Terminated via GDBstub");
1025 exit(0);
1026 case 'D':
1027 /* Detach packet */
1028 gdb_breakpoint_remove_all();
1029 gdb_syscall_mode = GDB_SYS_DISABLED;
1030 gdb_continue(s);
1031 put_packet(s, "OK");
1032 break;
1033 case 's':
1034 if (*p != '\0') {
1035 addr = strtoull(p, (char **)&p, 16);
1036 gdb_set_cpu_pc(s, addr);
1038 cpu_single_step(s->c_cpu, sstep_flags);
1039 gdb_continue(s);
1040 return RS_IDLE;
1041 case 'F':
1043 target_ulong ret;
1044 target_ulong err;
1046 ret = strtoull(p, (char **)&p, 16);
1047 if (*p == ',') {
1048 p++;
1049 err = strtoull(p, (char **)&p, 16);
1050 } else {
1051 err = 0;
1053 if (*p == ',')
1054 p++;
1055 type = *p;
1056 if (s->current_syscall_cb) {
1057 s->current_syscall_cb(s->c_cpu, ret, err);
1058 s->current_syscall_cb = NULL;
1060 if (type == 'C') {
1061 put_packet(s, "T02");
1062 } else {
1063 gdb_continue(s);
1066 break;
1067 case 'g':
1068 cpu_synchronize_state(s->g_cpu);
1069 len = 0;
1070 for (addr = 0; addr < s->g_cpu->gdb_num_g_regs; addr++) {
1071 reg_size = gdb_read_register(s->g_cpu, mem_buf + len, addr);
1072 len += reg_size;
1074 memtohex(buf, mem_buf, len);
1075 put_packet(s, buf);
1076 break;
1077 case 'G':
1078 cpu_synchronize_state(s->g_cpu);
1079 registers = mem_buf;
1080 len = strlen(p) / 2;
1081 hextomem((uint8_t *)registers, p, len);
1082 for (addr = 0; addr < s->g_cpu->gdb_num_g_regs && len > 0; addr++) {
1083 reg_size = gdb_write_register(s->g_cpu, registers, addr);
1084 len -= reg_size;
1085 registers += reg_size;
1087 put_packet(s, "OK");
1088 break;
1089 case 'm':
1090 addr = strtoull(p, (char **)&p, 16);
1091 if (*p == ',')
1092 p++;
1093 len = strtoull(p, NULL, 16);
1095 /* memtohex() doubles the required space */
1096 if (len > MAX_PACKET_LENGTH / 2) {
1097 put_packet (s, "E22");
1098 break;
1101 if (target_memory_rw_debug(s->g_cpu, addr, mem_buf, len, false) != 0) {
1102 put_packet (s, "E14");
1103 } else {
1104 memtohex(buf, mem_buf, len);
1105 put_packet(s, buf);
1107 break;
1108 case 'M':
1109 addr = strtoull(p, (char **)&p, 16);
1110 if (*p == ',')
1111 p++;
1112 len = strtoull(p, (char **)&p, 16);
1113 if (*p == ':')
1114 p++;
1116 /* hextomem() reads 2*len bytes */
1117 if (len > strlen(p) / 2) {
1118 put_packet (s, "E22");
1119 break;
1121 hextomem(mem_buf, p, len);
1122 if (target_memory_rw_debug(s->g_cpu, addr, mem_buf, len,
1123 true) != 0) {
1124 put_packet(s, "E14");
1125 } else {
1126 put_packet(s, "OK");
1128 break;
1129 case 'p':
1130 /* Older gdb are really dumb, and don't use 'g' if 'p' is avaialable.
1131 This works, but can be very slow. Anything new enough to
1132 understand XML also knows how to use this properly. */
1133 if (!gdb_has_xml)
1134 goto unknown_command;
1135 addr = strtoull(p, (char **)&p, 16);
1136 reg_size = gdb_read_register(s->g_cpu, mem_buf, addr);
1137 if (reg_size) {
1138 memtohex(buf, mem_buf, reg_size);
1139 put_packet(s, buf);
1140 } else {
1141 put_packet(s, "E14");
1143 break;
1144 case 'P':
1145 if (!gdb_has_xml)
1146 goto unknown_command;
1147 addr = strtoull(p, (char **)&p, 16);
1148 if (*p == '=')
1149 p++;
1150 reg_size = strlen(p) / 2;
1151 hextomem(mem_buf, p, reg_size);
1152 gdb_write_register(s->g_cpu, mem_buf, addr);
1153 put_packet(s, "OK");
1154 break;
1155 case 'Z':
1156 case 'z':
1157 type = strtoul(p, (char **)&p, 16);
1158 if (*p == ',')
1159 p++;
1160 addr = strtoull(p, (char **)&p, 16);
1161 if (*p == ',')
1162 p++;
1163 len = strtoull(p, (char **)&p, 16);
1164 if (ch == 'Z')
1165 res = gdb_breakpoint_insert(addr, len, type);
1166 else
1167 res = gdb_breakpoint_remove(addr, len, type);
1168 if (res >= 0)
1169 put_packet(s, "OK");
1170 else if (res == -ENOSYS)
1171 put_packet(s, "");
1172 else
1173 put_packet(s, "E22");
1174 break;
1175 case 'H':
1176 type = *p++;
1177 thread = strtoull(p, (char **)&p, 16);
1178 if (thread == -1 || thread == 0) {
1179 put_packet(s, "OK");
1180 break;
1182 cpu = find_cpu(thread);
1183 if (cpu == NULL) {
1184 put_packet(s, "E22");
1185 break;
1187 switch (type) {
1188 case 'c':
1189 s->c_cpu = cpu;
1190 put_packet(s, "OK");
1191 break;
1192 case 'g':
1193 s->g_cpu = cpu;
1194 put_packet(s, "OK");
1195 break;
1196 default:
1197 put_packet(s, "E22");
1198 break;
1200 break;
1201 case 'T':
1202 thread = strtoull(p, (char **)&p, 16);
1203 cpu = find_cpu(thread);
1205 if (cpu != NULL) {
1206 put_packet(s, "OK");
1207 } else {
1208 put_packet(s, "E22");
1210 break;
1211 case 'q':
1212 case 'Q':
1213 /* parse any 'q' packets here */
1214 if (!strcmp(p,"qemu.sstepbits")) {
1215 /* Query Breakpoint bit definitions */
1216 snprintf(buf, sizeof(buf), "ENABLE=%x,NOIRQ=%x,NOTIMER=%x",
1217 SSTEP_ENABLE,
1218 SSTEP_NOIRQ,
1219 SSTEP_NOTIMER);
1220 put_packet(s, buf);
1221 break;
1222 } else if (is_query_packet(p, "qemu.sstep", '=')) {
1223 /* Display or change the sstep_flags */
1224 p += 10;
1225 if (*p != '=') {
1226 /* Display current setting */
1227 snprintf(buf, sizeof(buf), "0x%x", sstep_flags);
1228 put_packet(s, buf);
1229 break;
1231 p++;
1232 type = strtoul(p, (char **)&p, 16);
1233 sstep_flags = type;
1234 put_packet(s, "OK");
1235 break;
1236 } else if (strcmp(p,"C") == 0) {
1237 /* "Current thread" remains vague in the spec, so always return
1238 * the first CPU (gdb returns the first thread). */
1239 put_packet(s, "QC1");
1240 break;
1241 } else if (strcmp(p,"fThreadInfo") == 0) {
1242 s->query_cpu = first_cpu;
1243 goto report_cpuinfo;
1244 } else if (strcmp(p,"sThreadInfo") == 0) {
1245 report_cpuinfo:
1246 if (s->query_cpu) {
1247 snprintf(buf, sizeof(buf), "m%x", cpu_index(s->query_cpu));
1248 put_packet(s, buf);
1249 s->query_cpu = CPU_NEXT(s->query_cpu);
1250 } else
1251 put_packet(s, "l");
1252 break;
1253 } else if (strncmp(p,"ThreadExtraInfo,", 16) == 0) {
1254 thread = strtoull(p+16, (char **)&p, 16);
1255 cpu = find_cpu(thread);
1256 if (cpu != NULL) {
1257 cpu_synchronize_state(cpu);
1258 /* memtohex() doubles the required space */
1259 len = snprintf((char *)mem_buf, sizeof(buf) / 2,
1260 "CPU#%d [%s]", cpu->cpu_index,
1261 cpu->halted ? "halted " : "running");
1262 memtohex(buf, mem_buf, len);
1263 put_packet(s, buf);
1265 break;
1267 #ifdef CONFIG_USER_ONLY
1268 else if (strcmp(p, "Offsets") == 0) {
1269 TaskState *ts = s->c_cpu->opaque;
1271 snprintf(buf, sizeof(buf),
1272 "Text=" TARGET_ABI_FMT_lx ";Data=" TARGET_ABI_FMT_lx
1273 ";Bss=" TARGET_ABI_FMT_lx,
1274 ts->info->code_offset,
1275 ts->info->data_offset,
1276 ts->info->data_offset);
1277 put_packet(s, buf);
1278 break;
1280 #else /* !CONFIG_USER_ONLY */
1281 else if (strncmp(p, "Rcmd,", 5) == 0) {
1282 int len = strlen(p + 5);
1284 if ((len % 2) != 0) {
1285 put_packet(s, "E01");
1286 break;
1288 len = len / 2;
1289 hextomem(mem_buf, p + 5, len);
1290 mem_buf[len++] = 0;
1291 qemu_chr_be_write(s->mon_chr, mem_buf, len);
1292 put_packet(s, "OK");
1293 break;
1295 #endif /* !CONFIG_USER_ONLY */
1296 if (is_query_packet(p, "Supported", ':')) {
1297 snprintf(buf, sizeof(buf), "PacketSize=%x", MAX_PACKET_LENGTH);
1298 cc = CPU_GET_CLASS(first_cpu);
1299 if (cc->gdb_core_xml_file != NULL) {
1300 pstrcat(buf, sizeof(buf), ";qXfer:features:read+");
1302 put_packet(s, buf);
1303 break;
1305 if (strncmp(p, "Xfer:features:read:", 19) == 0) {
1306 const char *xml;
1307 target_ulong total_len;
1309 cc = CPU_GET_CLASS(first_cpu);
1310 if (cc->gdb_core_xml_file == NULL) {
1311 goto unknown_command;
1314 gdb_has_xml = true;
1315 p += 19;
1316 xml = get_feature_xml(p, &p, cc);
1317 if (!xml) {
1318 snprintf(buf, sizeof(buf), "E00");
1319 put_packet(s, buf);
1320 break;
1323 if (*p == ':')
1324 p++;
1325 addr = strtoul(p, (char **)&p, 16);
1326 if (*p == ',')
1327 p++;
1328 len = strtoul(p, (char **)&p, 16);
1330 total_len = strlen(xml);
1331 if (addr > total_len) {
1332 snprintf(buf, sizeof(buf), "E00");
1333 put_packet(s, buf);
1334 break;
1336 if (len > (MAX_PACKET_LENGTH - 5) / 2)
1337 len = (MAX_PACKET_LENGTH - 5) / 2;
1338 if (len < total_len - addr) {
1339 buf[0] = 'm';
1340 len = memtox(buf + 1, xml + addr, len);
1341 } else {
1342 buf[0] = 'l';
1343 len = memtox(buf + 1, xml + addr, total_len - addr);
1345 put_packet_binary(s, buf, len + 1);
1346 break;
1348 if (is_query_packet(p, "Attached", ':')) {
1349 put_packet(s, GDB_ATTACHED);
1350 break;
1352 /* Unrecognised 'q' command. */
1353 goto unknown_command;
1355 default:
1356 unknown_command:
1357 /* put empty packet */
1358 buf[0] = '\0';
1359 put_packet(s, buf);
1360 break;
1362 return RS_IDLE;
1365 void gdb_set_stop_cpu(CPUState *cpu)
1367 gdbserver_state->c_cpu = cpu;
1368 gdbserver_state->g_cpu = cpu;
1371 #ifndef CONFIG_USER_ONLY
1372 static void gdb_vm_state_change(void *opaque, int running, RunState state)
1374 GDBState *s = gdbserver_state;
1375 CPUState *cpu = s->c_cpu;
1376 char buf[256];
1377 const char *type;
1378 int ret;
1380 if (running || s->state == RS_INACTIVE) {
1381 return;
1383 /* Is there a GDB syscall waiting to be sent? */
1384 if (s->current_syscall_cb) {
1385 put_packet(s, s->syscall_buf);
1386 return;
1388 switch (state) {
1389 case RUN_STATE_DEBUG:
1390 if (cpu->watchpoint_hit) {
1391 switch (cpu->watchpoint_hit->flags & BP_MEM_ACCESS) {
1392 case BP_MEM_READ:
1393 type = "r";
1394 break;
1395 case BP_MEM_ACCESS:
1396 type = "a";
1397 break;
1398 default:
1399 type = "";
1400 break;
1402 snprintf(buf, sizeof(buf),
1403 "T%02xthread:%02x;%swatch:" TARGET_FMT_lx ";",
1404 GDB_SIGNAL_TRAP, cpu_index(cpu), type,
1405 (target_ulong)cpu->watchpoint_hit->vaddr);
1406 cpu->watchpoint_hit = NULL;
1407 goto send_packet;
1409 tb_flush(cpu);
1410 ret = GDB_SIGNAL_TRAP;
1411 break;
1412 case RUN_STATE_PAUSED:
1413 ret = GDB_SIGNAL_INT;
1414 break;
1415 case RUN_STATE_SHUTDOWN:
1416 ret = GDB_SIGNAL_QUIT;
1417 break;
1418 case RUN_STATE_IO_ERROR:
1419 ret = GDB_SIGNAL_IO;
1420 break;
1421 case RUN_STATE_WATCHDOG:
1422 ret = GDB_SIGNAL_ALRM;
1423 break;
1424 case RUN_STATE_INTERNAL_ERROR:
1425 ret = GDB_SIGNAL_ABRT;
1426 break;
1427 case RUN_STATE_SAVE_VM:
1428 case RUN_STATE_RESTORE_VM:
1429 return;
1430 case RUN_STATE_FINISH_MIGRATE:
1431 ret = GDB_SIGNAL_XCPU;
1432 break;
1433 default:
1434 ret = GDB_SIGNAL_UNKNOWN;
1435 break;
1437 gdb_set_stop_cpu(cpu);
1438 snprintf(buf, sizeof(buf), "T%02xthread:%02x;", ret, cpu_index(cpu));
1440 send_packet:
1441 put_packet(s, buf);
1443 /* disable single step if it was enabled */
1444 cpu_single_step(cpu, 0);
1446 #endif
1448 /* Send a gdb syscall request.
1449 This accepts limited printf-style format specifiers, specifically:
1450 %x - target_ulong argument printed in hex.
1451 %lx - 64-bit argument printed in hex.
1452 %s - string pointer (target_ulong) and length (int) pair. */
1453 void gdb_do_syscallv(gdb_syscall_complete_cb cb, const char *fmt, va_list va)
1455 char *p;
1456 char *p_end;
1457 target_ulong addr;
1458 uint64_t i64;
1459 GDBState *s;
1461 s = gdbserver_state;
1462 if (!s)
1463 return;
1464 s->current_syscall_cb = cb;
1465 #ifndef CONFIG_USER_ONLY
1466 vm_stop(RUN_STATE_DEBUG);
1467 #endif
1468 p = s->syscall_buf;
1469 p_end = &s->syscall_buf[sizeof(s->syscall_buf)];
1470 *(p++) = 'F';
1471 while (*fmt) {
1472 if (*fmt == '%') {
1473 fmt++;
1474 switch (*fmt++) {
1475 case 'x':
1476 addr = va_arg(va, target_ulong);
1477 p += snprintf(p, p_end - p, TARGET_FMT_lx, addr);
1478 break;
1479 case 'l':
1480 if (*(fmt++) != 'x')
1481 goto bad_format;
1482 i64 = va_arg(va, uint64_t);
1483 p += snprintf(p, p_end - p, "%" PRIx64, i64);
1484 break;
1485 case 's':
1486 addr = va_arg(va, target_ulong);
1487 p += snprintf(p, p_end - p, TARGET_FMT_lx "/%x",
1488 addr, va_arg(va, int));
1489 break;
1490 default:
1491 bad_format:
1492 error_report("gdbstub: Bad syscall format string '%s'",
1493 fmt - 1);
1494 break;
1496 } else {
1497 *(p++) = *(fmt++);
1500 *p = 0;
1501 #ifdef CONFIG_USER_ONLY
1502 put_packet(s, s->syscall_buf);
1503 gdb_handlesig(s->c_cpu, 0);
1504 #else
1505 /* In this case wait to send the syscall packet until notification that
1506 the CPU has stopped. This must be done because if the packet is sent
1507 now the reply from the syscall request could be received while the CPU
1508 is still in the running state, which can cause packets to be dropped
1509 and state transition 'T' packets to be sent while the syscall is still
1510 being processed. */
1511 qemu_cpu_kick(s->c_cpu);
1512 #endif
1515 void gdb_do_syscall(gdb_syscall_complete_cb cb, const char *fmt, ...)
1517 va_list va;
1519 va_start(va, fmt);
1520 gdb_do_syscallv(cb, fmt, va);
1521 va_end(va);
1524 static void gdb_read_byte(GDBState *s, int ch)
1526 uint8_t reply;
1528 #ifndef CONFIG_USER_ONLY
1529 if (s->last_packet_len) {
1530 /* Waiting for a response to the last packet. If we see the start
1531 of a new command then abandon the previous response. */
1532 if (ch == '-') {
1533 gdb_debug("Got NACK, retransmitting\n");
1534 put_buffer(s, (uint8_t *)s->last_packet, s->last_packet_len);
1535 } else if (ch == '+') {
1536 gdb_debug("Got ACK\n");
1537 } else {
1538 gdb_debug("Got '%c' when expecting ACK/NACK\n", ch);
1541 if (ch == '+' || ch == '$')
1542 s->last_packet_len = 0;
1543 if (ch != '$')
1544 return;
1546 if (runstate_is_running()) {
1547 /* when the CPU is running, we cannot do anything except stop
1548 it when receiving a char */
1549 vm_stop(RUN_STATE_PAUSED);
1550 } else
1551 #endif
1553 switch(s->state) {
1554 case RS_IDLE:
1555 if (ch == '$') {
1556 /* start of command packet */
1557 s->line_buf_index = 0;
1558 s->line_sum = 0;
1559 s->state = RS_GETLINE;
1560 } else {
1561 gdb_debug("received garbage between packets: 0x%x\n", ch);
1563 break;
1564 case RS_GETLINE:
1565 if (ch == '}') {
1566 /* start escape sequence */
1567 s->state = RS_GETLINE_ESC;
1568 s->line_sum += ch;
1569 } else if (ch == '*') {
1570 /* start run length encoding sequence */
1571 s->state = RS_GETLINE_RLE;
1572 s->line_sum += ch;
1573 } else if (ch == '#') {
1574 /* end of command, start of checksum*/
1575 s->state = RS_CHKSUM1;
1576 } else if (s->line_buf_index >= sizeof(s->line_buf) - 1) {
1577 gdb_debug("command buffer overrun, dropping command\n");
1578 s->state = RS_IDLE;
1579 } else {
1580 /* unescaped command character */
1581 s->line_buf[s->line_buf_index++] = ch;
1582 s->line_sum += ch;
1584 break;
1585 case RS_GETLINE_ESC:
1586 if (ch == '#') {
1587 /* unexpected end of command in escape sequence */
1588 s->state = RS_CHKSUM1;
1589 } else if (s->line_buf_index >= sizeof(s->line_buf) - 1) {
1590 /* command buffer overrun */
1591 gdb_debug("command buffer overrun, dropping command\n");
1592 s->state = RS_IDLE;
1593 } else {
1594 /* parse escaped character and leave escape state */
1595 s->line_buf[s->line_buf_index++] = ch ^ 0x20;
1596 s->line_sum += ch;
1597 s->state = RS_GETLINE;
1599 break;
1600 case RS_GETLINE_RLE:
1601 if (ch < ' ') {
1602 /* invalid RLE count encoding */
1603 gdb_debug("got invalid RLE count: 0x%x\n", ch);
1604 s->state = RS_GETLINE;
1605 } else {
1606 /* decode repeat length */
1607 int repeat = (unsigned char)ch - ' ' + 3;
1608 if (s->line_buf_index + repeat >= sizeof(s->line_buf) - 1) {
1609 /* that many repeats would overrun the command buffer */
1610 gdb_debug("command buffer overrun, dropping command\n");
1611 s->state = RS_IDLE;
1612 } else if (s->line_buf_index < 1) {
1613 /* got a repeat but we have nothing to repeat */
1614 gdb_debug("got invalid RLE sequence\n");
1615 s->state = RS_GETLINE;
1616 } else {
1617 /* repeat the last character */
1618 memset(s->line_buf + s->line_buf_index,
1619 s->line_buf[s->line_buf_index - 1], repeat);
1620 s->line_buf_index += repeat;
1621 s->line_sum += ch;
1622 s->state = RS_GETLINE;
1625 break;
1626 case RS_CHKSUM1:
1627 /* get high hex digit of checksum */
1628 if (!isxdigit(ch)) {
1629 gdb_debug("got invalid command checksum digit\n");
1630 s->state = RS_GETLINE;
1631 break;
1633 s->line_buf[s->line_buf_index] = '\0';
1634 s->line_csum = fromhex(ch) << 4;
1635 s->state = RS_CHKSUM2;
1636 break;
1637 case RS_CHKSUM2:
1638 /* get low hex digit of checksum */
1639 if (!isxdigit(ch)) {
1640 gdb_debug("got invalid command checksum digit\n");
1641 s->state = RS_GETLINE;
1642 break;
1644 s->line_csum |= fromhex(ch);
1646 if (s->line_csum != (s->line_sum & 0xff)) {
1647 gdb_debug("got command packet with incorrect checksum\n");
1648 /* send NAK reply */
1649 reply = '-';
1650 put_buffer(s, &reply, 1);
1651 s->state = RS_IDLE;
1652 } else {
1653 /* send ACK reply */
1654 reply = '+';
1655 put_buffer(s, &reply, 1);
1656 s->state = gdb_handle_packet(s, s->line_buf);
1658 break;
1659 default:
1660 abort();
1665 /* Tell the remote gdb that the process has exited. */
1666 void gdb_exit(CPUArchState *env, int code)
1668 GDBState *s;
1669 char buf[4];
1671 s = gdbserver_state;
1672 if (!s) {
1673 return;
1675 #ifdef CONFIG_USER_ONLY
1676 if (gdbserver_fd < 0 || s->fd < 0) {
1677 return;
1679 #endif
1681 snprintf(buf, sizeof(buf), "W%02x", (uint8_t)code);
1682 put_packet(s, buf);
1684 #ifndef CONFIG_USER_ONLY
1685 qemu_chr_fe_deinit(&s->chr, true);
1686 #endif
1689 #ifdef CONFIG_USER_ONLY
1691 gdb_handlesig(CPUState *cpu, int sig)
1693 GDBState *s;
1694 char buf[256];
1695 int n;
1697 s = gdbserver_state;
1698 if (gdbserver_fd < 0 || s->fd < 0) {
1699 return sig;
1702 /* disable single step if it was enabled */
1703 cpu_single_step(cpu, 0);
1704 tb_flush(cpu);
1706 if (sig != 0) {
1707 snprintf(buf, sizeof(buf), "S%02x", target_signal_to_gdb(sig));
1708 put_packet(s, buf);
1710 /* put_packet() might have detected that the peer terminated the
1711 connection. */
1712 if (s->fd < 0) {
1713 return sig;
1716 sig = 0;
1717 s->state = RS_IDLE;
1718 s->running_state = 0;
1719 while (s->running_state == 0) {
1720 n = read(s->fd, buf, 256);
1721 if (n > 0) {
1722 int i;
1724 for (i = 0; i < n; i++) {
1725 gdb_read_byte(s, buf[i]);
1727 } else {
1728 /* XXX: Connection closed. Should probably wait for another
1729 connection before continuing. */
1730 if (n == 0) {
1731 close(s->fd);
1733 s->fd = -1;
1734 return sig;
1737 sig = s->signal;
1738 s->signal = 0;
1739 return sig;
1742 /* Tell the remote gdb that the process has exited due to SIG. */
1743 void gdb_signalled(CPUArchState *env, int sig)
1745 GDBState *s;
1746 char buf[4];
1748 s = gdbserver_state;
1749 if (gdbserver_fd < 0 || s->fd < 0) {
1750 return;
1753 snprintf(buf, sizeof(buf), "X%02x", target_signal_to_gdb(sig));
1754 put_packet(s, buf);
1757 static void gdb_accept(void)
1759 GDBState *s;
1760 struct sockaddr_in sockaddr;
1761 socklen_t len;
1762 int fd;
1764 for(;;) {
1765 len = sizeof(sockaddr);
1766 fd = accept(gdbserver_fd, (struct sockaddr *)&sockaddr, &len);
1767 if (fd < 0 && errno != EINTR) {
1768 perror("accept");
1769 return;
1770 } else if (fd >= 0) {
1771 #ifndef _WIN32
1772 fcntl(fd, F_SETFD, FD_CLOEXEC);
1773 #endif
1774 break;
1778 /* set short latency */
1779 socket_set_nodelay(fd);
1781 s = g_malloc0(sizeof(GDBState));
1782 s->c_cpu = first_cpu;
1783 s->g_cpu = first_cpu;
1784 s->fd = fd;
1785 gdb_has_xml = false;
1787 gdbserver_state = s;
1790 static int gdbserver_open(int port)
1792 struct sockaddr_in sockaddr;
1793 int fd, ret;
1795 fd = socket(PF_INET, SOCK_STREAM, 0);
1796 if (fd < 0) {
1797 perror("socket");
1798 return -1;
1800 #ifndef _WIN32
1801 fcntl(fd, F_SETFD, FD_CLOEXEC);
1802 #endif
1804 socket_set_fast_reuse(fd);
1806 sockaddr.sin_family = AF_INET;
1807 sockaddr.sin_port = htons(port);
1808 sockaddr.sin_addr.s_addr = 0;
1809 ret = bind(fd, (struct sockaddr *)&sockaddr, sizeof(sockaddr));
1810 if (ret < 0) {
1811 perror("bind");
1812 close(fd);
1813 return -1;
1815 ret = listen(fd, 1);
1816 if (ret < 0) {
1817 perror("listen");
1818 close(fd);
1819 return -1;
1821 return fd;
1824 int gdbserver_start(int port)
1826 gdbserver_fd = gdbserver_open(port);
1827 if (gdbserver_fd < 0)
1828 return -1;
1829 /* accept connections */
1830 gdb_accept();
1831 return 0;
1834 /* Disable gdb stub for child processes. */
1835 void gdbserver_fork(CPUState *cpu)
1837 GDBState *s = gdbserver_state;
1839 if (gdbserver_fd < 0 || s->fd < 0) {
1840 return;
1842 close(s->fd);
1843 s->fd = -1;
1844 cpu_breakpoint_remove_all(cpu, BP_GDB);
1845 cpu_watchpoint_remove_all(cpu, BP_GDB);
1847 #else
1848 static int gdb_chr_can_receive(void *opaque)
1850 /* We can handle an arbitrarily large amount of data.
1851 Pick the maximum packet size, which is as good as anything. */
1852 return MAX_PACKET_LENGTH;
1855 static void gdb_chr_receive(void *opaque, const uint8_t *buf, int size)
1857 int i;
1859 for (i = 0; i < size; i++) {
1860 gdb_read_byte(gdbserver_state, buf[i]);
1864 static void gdb_chr_event(void *opaque, int event)
1866 switch (event) {
1867 case CHR_EVENT_OPENED:
1868 vm_stop(RUN_STATE_PAUSED);
1869 gdb_has_xml = false;
1870 break;
1871 default:
1872 break;
1876 static void gdb_monitor_output(GDBState *s, const char *msg, int len)
1878 char buf[MAX_PACKET_LENGTH];
1880 buf[0] = 'O';
1881 if (len > (MAX_PACKET_LENGTH/2) - 1)
1882 len = (MAX_PACKET_LENGTH/2) - 1;
1883 memtohex(buf + 1, (uint8_t *)msg, len);
1884 put_packet(s, buf);
1887 static int gdb_monitor_write(Chardev *chr, const uint8_t *buf, int len)
1889 const char *p = (const char *)buf;
1890 int max_sz;
1892 max_sz = (sizeof(gdbserver_state->last_packet) - 2) / 2;
1893 for (;;) {
1894 if (len <= max_sz) {
1895 gdb_monitor_output(gdbserver_state, p, len);
1896 break;
1898 gdb_monitor_output(gdbserver_state, p, max_sz);
1899 p += max_sz;
1900 len -= max_sz;
1902 return len;
1905 #ifndef _WIN32
1906 static void gdb_sigterm_handler(int signal)
1908 if (runstate_is_running()) {
1909 vm_stop(RUN_STATE_PAUSED);
1912 #endif
1914 static void gdb_monitor_open(Chardev *chr, ChardevBackend *backend,
1915 bool *be_opened, Error **errp)
1917 *be_opened = false;
1920 static void char_gdb_class_init(ObjectClass *oc, void *data)
1922 ChardevClass *cc = CHARDEV_CLASS(oc);
1924 cc->internal = true;
1925 cc->open = gdb_monitor_open;
1926 cc->chr_write = gdb_monitor_write;
1929 #define TYPE_CHARDEV_GDB "chardev-gdb"
1931 static const TypeInfo char_gdb_type_info = {
1932 .name = TYPE_CHARDEV_GDB,
1933 .parent = TYPE_CHARDEV,
1934 .class_init = char_gdb_class_init,
1937 int gdbserver_start(const char *device)
1939 GDBState *s;
1940 char gdbstub_device_name[128];
1941 Chardev *chr = NULL;
1942 Chardev *mon_chr;
1944 if (!first_cpu) {
1945 error_report("gdbstub: meaningless to attach gdb to a "
1946 "machine without any CPU.");
1947 return -1;
1950 if (!device)
1951 return -1;
1952 if (strcmp(device, "none") != 0) {
1953 if (strstart(device, "tcp:", NULL)) {
1954 /* enforce required TCP attributes */
1955 snprintf(gdbstub_device_name, sizeof(gdbstub_device_name),
1956 "%s,nowait,nodelay,server", device);
1957 device = gdbstub_device_name;
1959 #ifndef _WIN32
1960 else if (strcmp(device, "stdio") == 0) {
1961 struct sigaction act;
1963 memset(&act, 0, sizeof(act));
1964 act.sa_handler = gdb_sigterm_handler;
1965 sigaction(SIGINT, &act, NULL);
1967 #endif
1968 chr = qemu_chr_new_noreplay("gdb", device);
1969 if (!chr)
1970 return -1;
1973 s = gdbserver_state;
1974 if (!s) {
1975 s = g_malloc0(sizeof(GDBState));
1976 gdbserver_state = s;
1978 qemu_add_vm_change_state_handler(gdb_vm_state_change, NULL);
1980 /* Initialize a monitor terminal for gdb */
1981 mon_chr = qemu_chardev_new(NULL, TYPE_CHARDEV_GDB,
1982 NULL, &error_abort);
1983 monitor_init(mon_chr, 0);
1984 } else {
1985 qemu_chr_fe_deinit(&s->chr, true);
1986 mon_chr = s->mon_chr;
1987 memset(s, 0, sizeof(GDBState));
1988 s->mon_chr = mon_chr;
1990 s->c_cpu = first_cpu;
1991 s->g_cpu = first_cpu;
1992 if (chr) {
1993 qemu_chr_fe_init(&s->chr, chr, &error_abort);
1994 qemu_chr_fe_set_handlers(&s->chr, gdb_chr_can_receive, gdb_chr_receive,
1995 gdb_chr_event, NULL, NULL, NULL, true);
1997 s->state = chr ? RS_IDLE : RS_INACTIVE;
1998 s->mon_chr = mon_chr;
1999 s->current_syscall_cb = NULL;
2001 return 0;
2004 static void register_types(void)
2006 type_register_static(&char_gdb_type_info);
2009 type_init(register_types);
2010 #endif