qdev: Replace cannot_instantiate_with_device_add_yet with !user_creatable
[qemu.git] / gdbstub.c
blob86eed4f97c72481798ea5c6579ac6278b44c8976
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 "sysemu/char.h"
29 #include "sysemu/sysemu.h"
30 #include "exec/gdbstub.h"
31 #endif
33 #define MAX_PACKET_LENGTH 4096
35 #include "qemu/sockets.h"
36 #include "sysemu/hw_accel.h"
37 #include "sysemu/kvm.h"
38 #include "exec/semihost.h"
39 #include "exec/exec-all.h"
41 #ifdef CONFIG_USER_ONLY
42 #define GDB_ATTACHED "0"
43 #else
44 #define GDB_ATTACHED "1"
45 #endif
47 static inline int target_memory_rw_debug(CPUState *cpu, target_ulong addr,
48 uint8_t *buf, int len, bool is_write)
50 CPUClass *cc = CPU_GET_CLASS(cpu);
52 if (cc->memory_rw_debug) {
53 return cc->memory_rw_debug(cpu, addr, buf, len, is_write);
55 return cpu_memory_rw_debug(cpu, addr, buf, len, is_write);
58 enum {
59 GDB_SIGNAL_0 = 0,
60 GDB_SIGNAL_INT = 2,
61 GDB_SIGNAL_QUIT = 3,
62 GDB_SIGNAL_TRAP = 5,
63 GDB_SIGNAL_ABRT = 6,
64 GDB_SIGNAL_ALRM = 14,
65 GDB_SIGNAL_IO = 23,
66 GDB_SIGNAL_XCPU = 24,
67 GDB_SIGNAL_UNKNOWN = 143
70 #ifdef CONFIG_USER_ONLY
72 /* Map target signal numbers to GDB protocol signal numbers and vice
73 * versa. For user emulation's currently supported systems, we can
74 * assume most signals are defined.
77 static int gdb_signal_table[] = {
79 TARGET_SIGHUP,
80 TARGET_SIGINT,
81 TARGET_SIGQUIT,
82 TARGET_SIGILL,
83 TARGET_SIGTRAP,
84 TARGET_SIGABRT,
85 -1, /* SIGEMT */
86 TARGET_SIGFPE,
87 TARGET_SIGKILL,
88 TARGET_SIGBUS,
89 TARGET_SIGSEGV,
90 TARGET_SIGSYS,
91 TARGET_SIGPIPE,
92 TARGET_SIGALRM,
93 TARGET_SIGTERM,
94 TARGET_SIGURG,
95 TARGET_SIGSTOP,
96 TARGET_SIGTSTP,
97 TARGET_SIGCONT,
98 TARGET_SIGCHLD,
99 TARGET_SIGTTIN,
100 TARGET_SIGTTOU,
101 TARGET_SIGIO,
102 TARGET_SIGXCPU,
103 TARGET_SIGXFSZ,
104 TARGET_SIGVTALRM,
105 TARGET_SIGPROF,
106 TARGET_SIGWINCH,
107 -1, /* SIGLOST */
108 TARGET_SIGUSR1,
109 TARGET_SIGUSR2,
110 #ifdef TARGET_SIGPWR
111 TARGET_SIGPWR,
112 #else
114 #endif
115 -1, /* SIGPOLL */
127 #ifdef __SIGRTMIN
128 __SIGRTMIN + 1,
129 __SIGRTMIN + 2,
130 __SIGRTMIN + 3,
131 __SIGRTMIN + 4,
132 __SIGRTMIN + 5,
133 __SIGRTMIN + 6,
134 __SIGRTMIN + 7,
135 __SIGRTMIN + 8,
136 __SIGRTMIN + 9,
137 __SIGRTMIN + 10,
138 __SIGRTMIN + 11,
139 __SIGRTMIN + 12,
140 __SIGRTMIN + 13,
141 __SIGRTMIN + 14,
142 __SIGRTMIN + 15,
143 __SIGRTMIN + 16,
144 __SIGRTMIN + 17,
145 __SIGRTMIN + 18,
146 __SIGRTMIN + 19,
147 __SIGRTMIN + 20,
148 __SIGRTMIN + 21,
149 __SIGRTMIN + 22,
150 __SIGRTMIN + 23,
151 __SIGRTMIN + 24,
152 __SIGRTMIN + 25,
153 __SIGRTMIN + 26,
154 __SIGRTMIN + 27,
155 __SIGRTMIN + 28,
156 __SIGRTMIN + 29,
157 __SIGRTMIN + 30,
158 __SIGRTMIN + 31,
159 -1, /* SIGCANCEL */
160 __SIGRTMIN,
161 __SIGRTMIN + 32,
162 __SIGRTMIN + 33,
163 __SIGRTMIN + 34,
164 __SIGRTMIN + 35,
165 __SIGRTMIN + 36,
166 __SIGRTMIN + 37,
167 __SIGRTMIN + 38,
168 __SIGRTMIN + 39,
169 __SIGRTMIN + 40,
170 __SIGRTMIN + 41,
171 __SIGRTMIN + 42,
172 __SIGRTMIN + 43,
173 __SIGRTMIN + 44,
174 __SIGRTMIN + 45,
175 __SIGRTMIN + 46,
176 __SIGRTMIN + 47,
177 __SIGRTMIN + 48,
178 __SIGRTMIN + 49,
179 __SIGRTMIN + 50,
180 __SIGRTMIN + 51,
181 __SIGRTMIN + 52,
182 __SIGRTMIN + 53,
183 __SIGRTMIN + 54,
184 __SIGRTMIN + 55,
185 __SIGRTMIN + 56,
186 __SIGRTMIN + 57,
187 __SIGRTMIN + 58,
188 __SIGRTMIN + 59,
189 __SIGRTMIN + 60,
190 __SIGRTMIN + 61,
191 __SIGRTMIN + 62,
192 __SIGRTMIN + 63,
193 __SIGRTMIN + 64,
194 __SIGRTMIN + 65,
195 __SIGRTMIN + 66,
196 __SIGRTMIN + 67,
197 __SIGRTMIN + 68,
198 __SIGRTMIN + 69,
199 __SIGRTMIN + 70,
200 __SIGRTMIN + 71,
201 __SIGRTMIN + 72,
202 __SIGRTMIN + 73,
203 __SIGRTMIN + 74,
204 __SIGRTMIN + 75,
205 __SIGRTMIN + 76,
206 __SIGRTMIN + 77,
207 __SIGRTMIN + 78,
208 __SIGRTMIN + 79,
209 __SIGRTMIN + 80,
210 __SIGRTMIN + 81,
211 __SIGRTMIN + 82,
212 __SIGRTMIN + 83,
213 __SIGRTMIN + 84,
214 __SIGRTMIN + 85,
215 __SIGRTMIN + 86,
216 __SIGRTMIN + 87,
217 __SIGRTMIN + 88,
218 __SIGRTMIN + 89,
219 __SIGRTMIN + 90,
220 __SIGRTMIN + 91,
221 __SIGRTMIN + 92,
222 __SIGRTMIN + 93,
223 __SIGRTMIN + 94,
224 __SIGRTMIN + 95,
225 -1, /* SIGINFO */
226 -1, /* UNKNOWN */
227 -1, /* DEFAULT */
234 #endif
236 #else
237 /* In system mode we only need SIGINT and SIGTRAP; other signals
238 are not yet supported. */
240 enum {
241 TARGET_SIGINT = 2,
242 TARGET_SIGTRAP = 5
245 static int gdb_signal_table[] = {
248 TARGET_SIGINT,
251 TARGET_SIGTRAP
253 #endif
255 #ifdef CONFIG_USER_ONLY
256 static int target_signal_to_gdb (int sig)
258 int i;
259 for (i = 0; i < ARRAY_SIZE (gdb_signal_table); i++)
260 if (gdb_signal_table[i] == sig)
261 return i;
262 return GDB_SIGNAL_UNKNOWN;
264 #endif
266 static int gdb_signal_to_target (int sig)
268 if (sig < ARRAY_SIZE (gdb_signal_table))
269 return gdb_signal_table[sig];
270 else
271 return -1;
274 //#define DEBUG_GDB
276 typedef struct GDBRegisterState {
277 int base_reg;
278 int num_regs;
279 gdb_reg_cb get_reg;
280 gdb_reg_cb set_reg;
281 const char *xml;
282 struct GDBRegisterState *next;
283 } GDBRegisterState;
285 enum RSState {
286 RS_INACTIVE,
287 RS_IDLE,
288 RS_GETLINE,
289 RS_GETLINE_ESC,
290 RS_GETLINE_RLE,
291 RS_CHKSUM1,
292 RS_CHKSUM2,
294 typedef struct GDBState {
295 CPUState *c_cpu; /* current CPU for step/continue ops */
296 CPUState *g_cpu; /* current CPU for other ops */
297 CPUState *query_cpu; /* for q{f|s}ThreadInfo */
298 enum RSState state; /* parsing state */
299 char line_buf[MAX_PACKET_LENGTH];
300 int line_buf_index;
301 int line_sum; /* running checksum */
302 int line_csum; /* checksum at the end of the packet */
303 uint8_t last_packet[MAX_PACKET_LENGTH + 4];
304 int last_packet_len;
305 int signal;
306 #ifdef CONFIG_USER_ONLY
307 int fd;
308 int running_state;
309 #else
310 CharBackend chr;
311 Chardev *mon_chr;
312 #endif
313 char syscall_buf[256];
314 gdb_syscall_complete_cb current_syscall_cb;
315 } GDBState;
317 /* By default use no IRQs and no timers while single stepping so as to
318 * make single stepping like an ICE HW step.
320 static int sstep_flags = SSTEP_ENABLE|SSTEP_NOIRQ|SSTEP_NOTIMER;
322 static GDBState *gdbserver_state;
324 bool gdb_has_xml;
326 #ifdef CONFIG_USER_ONLY
327 /* XXX: This is not thread safe. Do we care? */
328 static int gdbserver_fd = -1;
330 static int get_char(GDBState *s)
332 uint8_t ch;
333 int ret;
335 for(;;) {
336 ret = qemu_recv(s->fd, &ch, 1, 0);
337 if (ret < 0) {
338 if (errno == ECONNRESET)
339 s->fd = -1;
340 if (errno != EINTR)
341 return -1;
342 } else if (ret == 0) {
343 close(s->fd);
344 s->fd = -1;
345 return -1;
346 } else {
347 break;
350 return ch;
352 #endif
354 static enum {
355 GDB_SYS_UNKNOWN,
356 GDB_SYS_ENABLED,
357 GDB_SYS_DISABLED,
358 } gdb_syscall_mode;
360 /* Decide if either remote gdb syscalls or native file IO should be used. */
361 int use_gdb_syscalls(void)
363 SemihostingTarget target = semihosting_get_target();
364 if (target == SEMIHOSTING_TARGET_NATIVE) {
365 /* -semihosting-config target=native */
366 return false;
367 } else if (target == SEMIHOSTING_TARGET_GDB) {
368 /* -semihosting-config target=gdb */
369 return true;
372 /* -semihosting-config target=auto */
373 /* On the first call check if gdb is connected and remember. */
374 if (gdb_syscall_mode == GDB_SYS_UNKNOWN) {
375 gdb_syscall_mode = (gdbserver_state ? GDB_SYS_ENABLED
376 : GDB_SYS_DISABLED);
378 return gdb_syscall_mode == GDB_SYS_ENABLED;
381 /* Resume execution. */
382 static inline void gdb_continue(GDBState *s)
384 #ifdef CONFIG_USER_ONLY
385 s->running_state = 1;
386 #else
387 if (!runstate_needs_reset()) {
388 vm_start();
390 #endif
394 * Resume execution, per CPU actions. For user-mode emulation it's
395 * equivalent to gdb_continue.
397 static int gdb_continue_partial(GDBState *s, char *newstates)
399 CPUState *cpu;
400 int res = 0;
401 #ifdef CONFIG_USER_ONLY
403 * This is not exactly accurate, but it's an improvement compared to the
404 * previous situation, where only one CPU would be single-stepped.
406 CPU_FOREACH(cpu) {
407 if (newstates[cpu->cpu_index] == 's') {
408 cpu_single_step(cpu, sstep_flags);
411 s->running_state = 1;
412 #else
413 int flag = 0;
415 if (!runstate_needs_reset()) {
416 if (vm_prepare_start()) {
417 return 0;
420 CPU_FOREACH(cpu) {
421 switch (newstates[cpu->cpu_index]) {
422 case 0:
423 case 1:
424 break; /* nothing to do here */
425 case 's':
426 cpu_single_step(cpu, sstep_flags);
427 cpu_resume(cpu);
428 flag = 1;
429 break;
430 case 'c':
431 cpu_resume(cpu);
432 flag = 1;
433 break;
434 default:
435 res = -1;
436 break;
440 if (flag) {
441 qemu_clock_enable(QEMU_CLOCK_VIRTUAL, true);
443 #endif
444 return res;
447 static void put_buffer(GDBState *s, const uint8_t *buf, int len)
449 #ifdef CONFIG_USER_ONLY
450 int ret;
452 while (len > 0) {
453 ret = send(s->fd, buf, len, 0);
454 if (ret < 0) {
455 if (errno != EINTR)
456 return;
457 } else {
458 buf += ret;
459 len -= ret;
462 #else
463 /* XXX this blocks entire thread. Rewrite to use
464 * qemu_chr_fe_write and background I/O callbacks */
465 qemu_chr_fe_write_all(&s->chr, buf, len);
466 #endif
469 static inline int fromhex(int v)
471 if (v >= '0' && v <= '9')
472 return v - '0';
473 else if (v >= 'A' && v <= 'F')
474 return v - 'A' + 10;
475 else if (v >= 'a' && v <= 'f')
476 return v - 'a' + 10;
477 else
478 return 0;
481 static inline int tohex(int v)
483 if (v < 10)
484 return v + '0';
485 else
486 return v - 10 + 'a';
489 static void memtohex(char *buf, const uint8_t *mem, int len)
491 int i, c;
492 char *q;
493 q = buf;
494 for(i = 0; i < len; i++) {
495 c = mem[i];
496 *q++ = tohex(c >> 4);
497 *q++ = tohex(c & 0xf);
499 *q = '\0';
502 static void hextomem(uint8_t *mem, const char *buf, int len)
504 int i;
506 for(i = 0; i < len; i++) {
507 mem[i] = (fromhex(buf[0]) << 4) | fromhex(buf[1]);
508 buf += 2;
512 /* return -1 if error, 0 if OK */
513 static int put_packet_binary(GDBState *s, const char *buf, int len)
515 int csum, i;
516 uint8_t *p;
518 for(;;) {
519 p = s->last_packet;
520 *(p++) = '$';
521 memcpy(p, buf, len);
522 p += len;
523 csum = 0;
524 for(i = 0; i < len; i++) {
525 csum += buf[i];
527 *(p++) = '#';
528 *(p++) = tohex((csum >> 4) & 0xf);
529 *(p++) = tohex((csum) & 0xf);
531 s->last_packet_len = p - s->last_packet;
532 put_buffer(s, (uint8_t *)s->last_packet, s->last_packet_len);
534 #ifdef CONFIG_USER_ONLY
535 i = get_char(s);
536 if (i < 0)
537 return -1;
538 if (i == '+')
539 break;
540 #else
541 break;
542 #endif
544 return 0;
547 /* return -1 if error, 0 if OK */
548 static int put_packet(GDBState *s, const char *buf)
550 #ifdef DEBUG_GDB
551 printf("reply='%s'\n", buf);
552 #endif
554 return put_packet_binary(s, buf, strlen(buf));
557 /* Encode data using the encoding for 'x' packets. */
558 static int memtox(char *buf, const char *mem, int len)
560 char *p = buf;
561 char c;
563 while (len--) {
564 c = *(mem++);
565 switch (c) {
566 case '#': case '$': case '*': case '}':
567 *(p++) = '}';
568 *(p++) = c ^ 0x20;
569 break;
570 default:
571 *(p++) = c;
572 break;
575 return p - buf;
578 static const char *get_feature_xml(const char *p, const char **newp,
579 CPUClass *cc)
581 size_t len;
582 int i;
583 const char *name;
584 static char target_xml[1024];
586 len = 0;
587 while (p[len] && p[len] != ':')
588 len++;
589 *newp = p + len;
591 name = NULL;
592 if (strncmp(p, "target.xml", len) == 0) {
593 /* Generate the XML description for this CPU. */
594 if (!target_xml[0]) {
595 GDBRegisterState *r;
596 CPUState *cpu = first_cpu;
598 pstrcat(target_xml, sizeof(target_xml),
599 "<?xml version=\"1.0\"?>"
600 "<!DOCTYPE target SYSTEM \"gdb-target.dtd\">"
601 "<target>");
602 if (cc->gdb_arch_name) {
603 gchar *arch = cc->gdb_arch_name(cpu);
604 pstrcat(target_xml, sizeof(target_xml), "<architecture>");
605 pstrcat(target_xml, sizeof(target_xml), arch);
606 pstrcat(target_xml, sizeof(target_xml), "</architecture>");
607 g_free(arch);
609 pstrcat(target_xml, sizeof(target_xml), "<xi:include href=\"");
610 pstrcat(target_xml, sizeof(target_xml), cc->gdb_core_xml_file);
611 pstrcat(target_xml, sizeof(target_xml), "\"/>");
612 for (r = cpu->gdb_regs; r; r = r->next) {
613 pstrcat(target_xml, sizeof(target_xml), "<xi:include href=\"");
614 pstrcat(target_xml, sizeof(target_xml), r->xml);
615 pstrcat(target_xml, sizeof(target_xml), "\"/>");
617 pstrcat(target_xml, sizeof(target_xml), "</target>");
619 return target_xml;
621 for (i = 0; ; i++) {
622 name = xml_builtin[i][0];
623 if (!name || (strncmp(name, p, len) == 0 && strlen(name) == len))
624 break;
626 return name ? xml_builtin[i][1] : NULL;
629 static int gdb_read_register(CPUState *cpu, uint8_t *mem_buf, int reg)
631 CPUClass *cc = CPU_GET_CLASS(cpu);
632 CPUArchState *env = cpu->env_ptr;
633 GDBRegisterState *r;
635 if (reg < cc->gdb_num_core_regs) {
636 return cc->gdb_read_register(cpu, mem_buf, reg);
639 for (r = cpu->gdb_regs; r; r = r->next) {
640 if (r->base_reg <= reg && reg < r->base_reg + r->num_regs) {
641 return r->get_reg(env, mem_buf, reg - r->base_reg);
644 return 0;
647 static int gdb_write_register(CPUState *cpu, uint8_t *mem_buf, int reg)
649 CPUClass *cc = CPU_GET_CLASS(cpu);
650 CPUArchState *env = cpu->env_ptr;
651 GDBRegisterState *r;
653 if (reg < cc->gdb_num_core_regs) {
654 return cc->gdb_write_register(cpu, mem_buf, reg);
657 for (r = cpu->gdb_regs; r; r = r->next) {
658 if (r->base_reg <= reg && reg < r->base_reg + r->num_regs) {
659 return r->set_reg(env, mem_buf, reg - r->base_reg);
662 return 0;
665 /* Register a supplemental set of CPU registers. If g_pos is nonzero it
666 specifies the first register number and these registers are included in
667 a standard "g" packet. Direction is relative to gdb, i.e. get_reg is
668 gdb reading a CPU register, and set_reg is gdb modifying a CPU register.
671 void gdb_register_coprocessor(CPUState *cpu,
672 gdb_reg_cb get_reg, gdb_reg_cb set_reg,
673 int num_regs, const char *xml, int g_pos)
675 GDBRegisterState *s;
676 GDBRegisterState **p;
678 p = &cpu->gdb_regs;
679 while (*p) {
680 /* Check for duplicates. */
681 if (strcmp((*p)->xml, xml) == 0)
682 return;
683 p = &(*p)->next;
686 s = g_new0(GDBRegisterState, 1);
687 s->base_reg = cpu->gdb_num_regs;
688 s->num_regs = num_regs;
689 s->get_reg = get_reg;
690 s->set_reg = set_reg;
691 s->xml = xml;
693 /* Add to end of list. */
694 cpu->gdb_num_regs += num_regs;
695 *p = s;
696 if (g_pos) {
697 if (g_pos != s->base_reg) {
698 error_report("Error: Bad gdb register numbering for '%s', "
699 "expected %d got %d", xml, g_pos, s->base_reg);
700 } else {
701 cpu->gdb_num_g_regs = cpu->gdb_num_regs;
706 #ifndef CONFIG_USER_ONLY
707 /* Translate GDB watchpoint type to a flags value for cpu_watchpoint_* */
708 static inline int xlat_gdb_type(CPUState *cpu, int gdbtype)
710 static const int xlat[] = {
711 [GDB_WATCHPOINT_WRITE] = BP_GDB | BP_MEM_WRITE,
712 [GDB_WATCHPOINT_READ] = BP_GDB | BP_MEM_READ,
713 [GDB_WATCHPOINT_ACCESS] = BP_GDB | BP_MEM_ACCESS,
716 CPUClass *cc = CPU_GET_CLASS(cpu);
717 int cputype = xlat[gdbtype];
719 if (cc->gdb_stop_before_watchpoint) {
720 cputype |= BP_STOP_BEFORE_ACCESS;
722 return cputype;
724 #endif
726 static int gdb_breakpoint_insert(target_ulong addr, target_ulong len, int type)
728 CPUState *cpu;
729 int err = 0;
731 if (kvm_enabled()) {
732 return kvm_insert_breakpoint(gdbserver_state->c_cpu, addr, len, type);
735 switch (type) {
736 case GDB_BREAKPOINT_SW:
737 case GDB_BREAKPOINT_HW:
738 CPU_FOREACH(cpu) {
739 err = cpu_breakpoint_insert(cpu, addr, BP_GDB, NULL);
740 if (err) {
741 break;
744 return err;
745 #ifndef CONFIG_USER_ONLY
746 case GDB_WATCHPOINT_WRITE:
747 case GDB_WATCHPOINT_READ:
748 case GDB_WATCHPOINT_ACCESS:
749 CPU_FOREACH(cpu) {
750 err = cpu_watchpoint_insert(cpu, addr, len,
751 xlat_gdb_type(cpu, type), NULL);
752 if (err) {
753 break;
756 return err;
757 #endif
758 default:
759 return -ENOSYS;
763 static int gdb_breakpoint_remove(target_ulong addr, target_ulong len, int type)
765 CPUState *cpu;
766 int err = 0;
768 if (kvm_enabled()) {
769 return kvm_remove_breakpoint(gdbserver_state->c_cpu, addr, len, type);
772 switch (type) {
773 case GDB_BREAKPOINT_SW:
774 case GDB_BREAKPOINT_HW:
775 CPU_FOREACH(cpu) {
776 err = cpu_breakpoint_remove(cpu, addr, BP_GDB);
777 if (err) {
778 break;
781 return err;
782 #ifndef CONFIG_USER_ONLY
783 case GDB_WATCHPOINT_WRITE:
784 case GDB_WATCHPOINT_READ:
785 case GDB_WATCHPOINT_ACCESS:
786 CPU_FOREACH(cpu) {
787 err = cpu_watchpoint_remove(cpu, addr, len,
788 xlat_gdb_type(cpu, type));
789 if (err)
790 break;
792 return err;
793 #endif
794 default:
795 return -ENOSYS;
799 static void gdb_breakpoint_remove_all(void)
801 CPUState *cpu;
803 if (kvm_enabled()) {
804 kvm_remove_all_breakpoints(gdbserver_state->c_cpu);
805 return;
808 CPU_FOREACH(cpu) {
809 cpu_breakpoint_remove_all(cpu, BP_GDB);
810 #ifndef CONFIG_USER_ONLY
811 cpu_watchpoint_remove_all(cpu, BP_GDB);
812 #endif
816 static void gdb_set_cpu_pc(GDBState *s, target_ulong pc)
818 CPUState *cpu = s->c_cpu;
820 cpu_synchronize_state(cpu);
821 cpu_set_pc(cpu, pc);
824 static CPUState *find_cpu(uint32_t thread_id)
826 CPUState *cpu;
828 CPU_FOREACH(cpu) {
829 if (cpu_index(cpu) == thread_id) {
830 return cpu;
834 return NULL;
837 static int is_query_packet(const char *p, const char *query, char separator)
839 unsigned int query_len = strlen(query);
841 return strncmp(p, query, query_len) == 0 &&
842 (p[query_len] == '\0' || p[query_len] == separator);
846 * gdb_handle_vcont - Parses and handles a vCont packet.
847 * returns -ENOTSUP if a command is unsupported, -EINVAL or -ERANGE if there is
848 * a format error, 0 on success.
850 static int gdb_handle_vcont(GDBState *s, const char *p)
852 int res, idx, signal = 0;
853 char cur_action;
854 char *newstates;
855 unsigned long tmp;
856 CPUState *cpu;
857 #ifdef CONFIG_USER_ONLY
858 int max_cpus = 1; /* global variable max_cpus exists only in system mode */
860 CPU_FOREACH(cpu) {
861 max_cpus = max_cpus <= cpu->cpu_index ? cpu->cpu_index + 1 : max_cpus;
863 #endif
864 /* uninitialised CPUs stay 0 */
865 newstates = g_new0(char, max_cpus);
867 /* mark valid CPUs with 1 */
868 CPU_FOREACH(cpu) {
869 newstates[cpu->cpu_index] = 1;
873 * res keeps track of what error we are returning, with -ENOTSUP meaning
874 * that the command is unknown or unsupported, thus returning an empty
875 * packet, while -EINVAL and -ERANGE cause an E22 packet, due to invalid,
876 * or incorrect parameters passed.
878 res = 0;
879 while (*p) {
880 if (*p++ != ';') {
881 res = -ENOTSUP;
882 goto out;
885 cur_action = *p++;
886 if (cur_action == 'C' || cur_action == 'S') {
887 cur_action = tolower(cur_action);
888 res = qemu_strtoul(p + 1, &p, 16, &tmp);
889 if (res) {
890 goto out;
892 signal = gdb_signal_to_target(tmp);
893 } else if (cur_action != 'c' && cur_action != 's') {
894 /* unknown/invalid/unsupported command */
895 res = -ENOTSUP;
896 goto out;
898 /* thread specification. special values: (none), -1 = all; 0 = any */
899 if ((p[0] == ':' && p[1] == '-' && p[2] == '1') || (p[0] != ':')) {
900 if (*p == ':') {
901 p += 3;
903 for (idx = 0; idx < max_cpus; idx++) {
904 if (newstates[idx] == 1) {
905 newstates[idx] = cur_action;
908 } else if (*p == ':') {
909 p++;
910 res = qemu_strtoul(p, &p, 16, &tmp);
911 if (res) {
912 goto out;
914 idx = tmp;
915 /* 0 means any thread, so we pick the first valid CPU */
916 if (!idx) {
917 idx = cpu_index(first_cpu);
921 * If we are in user mode, the thread specified is actually a
922 * thread id, and not an index. We need to find the actual
923 * CPU first, and only then we can use its index.
925 cpu = find_cpu(idx);
926 /* invalid CPU/thread specified */
927 if (!idx || !cpu) {
928 res = -EINVAL;
929 goto out;
931 /* only use if no previous match occourred */
932 if (newstates[cpu->cpu_index] == 1) {
933 newstates[cpu->cpu_index] = cur_action;
937 s->signal = signal;
938 gdb_continue_partial(s, newstates);
940 out:
941 g_free(newstates);
943 return res;
946 static int gdb_handle_packet(GDBState *s, const char *line_buf)
948 CPUState *cpu;
949 CPUClass *cc;
950 const char *p;
951 uint32_t thread;
952 int ch, reg_size, type, res;
953 char buf[MAX_PACKET_LENGTH];
954 uint8_t mem_buf[MAX_PACKET_LENGTH];
955 uint8_t *registers;
956 target_ulong addr, len;
958 #ifdef DEBUG_GDB
959 printf("command='%s'\n", line_buf);
960 #endif
961 p = line_buf;
962 ch = *p++;
963 switch(ch) {
964 case '?':
965 /* TODO: Make this return the correct value for user-mode. */
966 snprintf(buf, sizeof(buf), "T%02xthread:%02x;", GDB_SIGNAL_TRAP,
967 cpu_index(s->c_cpu));
968 put_packet(s, buf);
969 /* Remove all the breakpoints when this query is issued,
970 * because gdb is doing and initial connect and the state
971 * should be cleaned up.
973 gdb_breakpoint_remove_all();
974 break;
975 case 'c':
976 if (*p != '\0') {
977 addr = strtoull(p, (char **)&p, 16);
978 gdb_set_cpu_pc(s, addr);
980 s->signal = 0;
981 gdb_continue(s);
982 return RS_IDLE;
983 case 'C':
984 s->signal = gdb_signal_to_target (strtoul(p, (char **)&p, 16));
985 if (s->signal == -1)
986 s->signal = 0;
987 gdb_continue(s);
988 return RS_IDLE;
989 case 'v':
990 if (strncmp(p, "Cont", 4) == 0) {
991 p += 4;
992 if (*p == '?') {
993 put_packet(s, "vCont;c;C;s;S");
994 break;
997 res = gdb_handle_vcont(s, p);
999 if (res) {
1000 if ((res == -EINVAL) || (res == -ERANGE)) {
1001 put_packet(s, "E22");
1002 break;
1004 goto unknown_command;
1006 break;
1007 } else {
1008 goto unknown_command;
1010 case 'k':
1011 /* Kill the target */
1012 error_report("QEMU: Terminated via GDBstub");
1013 exit(0);
1014 case 'D':
1015 /* Detach packet */
1016 gdb_breakpoint_remove_all();
1017 gdb_syscall_mode = GDB_SYS_DISABLED;
1018 gdb_continue(s);
1019 put_packet(s, "OK");
1020 break;
1021 case 's':
1022 if (*p != '\0') {
1023 addr = strtoull(p, (char **)&p, 16);
1024 gdb_set_cpu_pc(s, addr);
1026 cpu_single_step(s->c_cpu, sstep_flags);
1027 gdb_continue(s);
1028 return RS_IDLE;
1029 case 'F':
1031 target_ulong ret;
1032 target_ulong err;
1034 ret = strtoull(p, (char **)&p, 16);
1035 if (*p == ',') {
1036 p++;
1037 err = strtoull(p, (char **)&p, 16);
1038 } else {
1039 err = 0;
1041 if (*p == ',')
1042 p++;
1043 type = *p;
1044 if (s->current_syscall_cb) {
1045 s->current_syscall_cb(s->c_cpu, ret, err);
1046 s->current_syscall_cb = NULL;
1048 if (type == 'C') {
1049 put_packet(s, "T02");
1050 } else {
1051 gdb_continue(s);
1054 break;
1055 case 'g':
1056 cpu_synchronize_state(s->g_cpu);
1057 len = 0;
1058 for (addr = 0; addr < s->g_cpu->gdb_num_g_regs; addr++) {
1059 reg_size = gdb_read_register(s->g_cpu, mem_buf + len, addr);
1060 len += reg_size;
1062 memtohex(buf, mem_buf, len);
1063 put_packet(s, buf);
1064 break;
1065 case 'G':
1066 cpu_synchronize_state(s->g_cpu);
1067 registers = mem_buf;
1068 len = strlen(p) / 2;
1069 hextomem((uint8_t *)registers, p, len);
1070 for (addr = 0; addr < s->g_cpu->gdb_num_g_regs && len > 0; addr++) {
1071 reg_size = gdb_write_register(s->g_cpu, registers, addr);
1072 len -= reg_size;
1073 registers += reg_size;
1075 put_packet(s, "OK");
1076 break;
1077 case 'm':
1078 addr = strtoull(p, (char **)&p, 16);
1079 if (*p == ',')
1080 p++;
1081 len = strtoull(p, NULL, 16);
1083 /* memtohex() doubles the required space */
1084 if (len > MAX_PACKET_LENGTH / 2) {
1085 put_packet (s, "E22");
1086 break;
1089 if (target_memory_rw_debug(s->g_cpu, addr, mem_buf, len, false) != 0) {
1090 put_packet (s, "E14");
1091 } else {
1092 memtohex(buf, mem_buf, len);
1093 put_packet(s, buf);
1095 break;
1096 case 'M':
1097 addr = strtoull(p, (char **)&p, 16);
1098 if (*p == ',')
1099 p++;
1100 len = strtoull(p, (char **)&p, 16);
1101 if (*p == ':')
1102 p++;
1104 /* hextomem() reads 2*len bytes */
1105 if (len > strlen(p) / 2) {
1106 put_packet (s, "E22");
1107 break;
1109 hextomem(mem_buf, p, len);
1110 if (target_memory_rw_debug(s->g_cpu, addr, mem_buf, len,
1111 true) != 0) {
1112 put_packet(s, "E14");
1113 } else {
1114 put_packet(s, "OK");
1116 break;
1117 case 'p':
1118 /* Older gdb are really dumb, and don't use 'g' if 'p' is avaialable.
1119 This works, but can be very slow. Anything new enough to
1120 understand XML also knows how to use this properly. */
1121 if (!gdb_has_xml)
1122 goto unknown_command;
1123 addr = strtoull(p, (char **)&p, 16);
1124 reg_size = gdb_read_register(s->g_cpu, mem_buf, addr);
1125 if (reg_size) {
1126 memtohex(buf, mem_buf, reg_size);
1127 put_packet(s, buf);
1128 } else {
1129 put_packet(s, "E14");
1131 break;
1132 case 'P':
1133 if (!gdb_has_xml)
1134 goto unknown_command;
1135 addr = strtoull(p, (char **)&p, 16);
1136 if (*p == '=')
1137 p++;
1138 reg_size = strlen(p) / 2;
1139 hextomem(mem_buf, p, reg_size);
1140 gdb_write_register(s->g_cpu, mem_buf, addr);
1141 put_packet(s, "OK");
1142 break;
1143 case 'Z':
1144 case 'z':
1145 type = strtoul(p, (char **)&p, 16);
1146 if (*p == ',')
1147 p++;
1148 addr = strtoull(p, (char **)&p, 16);
1149 if (*p == ',')
1150 p++;
1151 len = strtoull(p, (char **)&p, 16);
1152 if (ch == 'Z')
1153 res = gdb_breakpoint_insert(addr, len, type);
1154 else
1155 res = gdb_breakpoint_remove(addr, len, type);
1156 if (res >= 0)
1157 put_packet(s, "OK");
1158 else if (res == -ENOSYS)
1159 put_packet(s, "");
1160 else
1161 put_packet(s, "E22");
1162 break;
1163 case 'H':
1164 type = *p++;
1165 thread = strtoull(p, (char **)&p, 16);
1166 if (thread == -1 || thread == 0) {
1167 put_packet(s, "OK");
1168 break;
1170 cpu = find_cpu(thread);
1171 if (cpu == NULL) {
1172 put_packet(s, "E22");
1173 break;
1175 switch (type) {
1176 case 'c':
1177 s->c_cpu = cpu;
1178 put_packet(s, "OK");
1179 break;
1180 case 'g':
1181 s->g_cpu = cpu;
1182 put_packet(s, "OK");
1183 break;
1184 default:
1185 put_packet(s, "E22");
1186 break;
1188 break;
1189 case 'T':
1190 thread = strtoull(p, (char **)&p, 16);
1191 cpu = find_cpu(thread);
1193 if (cpu != NULL) {
1194 put_packet(s, "OK");
1195 } else {
1196 put_packet(s, "E22");
1198 break;
1199 case 'q':
1200 case 'Q':
1201 /* parse any 'q' packets here */
1202 if (!strcmp(p,"qemu.sstepbits")) {
1203 /* Query Breakpoint bit definitions */
1204 snprintf(buf, sizeof(buf), "ENABLE=%x,NOIRQ=%x,NOTIMER=%x",
1205 SSTEP_ENABLE,
1206 SSTEP_NOIRQ,
1207 SSTEP_NOTIMER);
1208 put_packet(s, buf);
1209 break;
1210 } else if (is_query_packet(p, "qemu.sstep", '=')) {
1211 /* Display or change the sstep_flags */
1212 p += 10;
1213 if (*p != '=') {
1214 /* Display current setting */
1215 snprintf(buf, sizeof(buf), "0x%x", sstep_flags);
1216 put_packet(s, buf);
1217 break;
1219 p++;
1220 type = strtoul(p, (char **)&p, 16);
1221 sstep_flags = type;
1222 put_packet(s, "OK");
1223 break;
1224 } else if (strcmp(p,"C") == 0) {
1225 /* "Current thread" remains vague in the spec, so always return
1226 * the first CPU (gdb returns the first thread). */
1227 put_packet(s, "QC1");
1228 break;
1229 } else if (strcmp(p,"fThreadInfo") == 0) {
1230 s->query_cpu = first_cpu;
1231 goto report_cpuinfo;
1232 } else if (strcmp(p,"sThreadInfo") == 0) {
1233 report_cpuinfo:
1234 if (s->query_cpu) {
1235 snprintf(buf, sizeof(buf), "m%x", cpu_index(s->query_cpu));
1236 put_packet(s, buf);
1237 s->query_cpu = CPU_NEXT(s->query_cpu);
1238 } else
1239 put_packet(s, "l");
1240 break;
1241 } else if (strncmp(p,"ThreadExtraInfo,", 16) == 0) {
1242 thread = strtoull(p+16, (char **)&p, 16);
1243 cpu = find_cpu(thread);
1244 if (cpu != NULL) {
1245 cpu_synchronize_state(cpu);
1246 /* memtohex() doubles the required space */
1247 len = snprintf((char *)mem_buf, sizeof(buf) / 2,
1248 "CPU#%d [%s]", cpu->cpu_index,
1249 cpu->halted ? "halted " : "running");
1250 memtohex(buf, mem_buf, len);
1251 put_packet(s, buf);
1253 break;
1255 #ifdef CONFIG_USER_ONLY
1256 else if (strcmp(p, "Offsets") == 0) {
1257 TaskState *ts = s->c_cpu->opaque;
1259 snprintf(buf, sizeof(buf),
1260 "Text=" TARGET_ABI_FMT_lx ";Data=" TARGET_ABI_FMT_lx
1261 ";Bss=" TARGET_ABI_FMT_lx,
1262 ts->info->code_offset,
1263 ts->info->data_offset,
1264 ts->info->data_offset);
1265 put_packet(s, buf);
1266 break;
1268 #else /* !CONFIG_USER_ONLY */
1269 else if (strncmp(p, "Rcmd,", 5) == 0) {
1270 int len = strlen(p + 5);
1272 if ((len % 2) != 0) {
1273 put_packet(s, "E01");
1274 break;
1276 len = len / 2;
1277 hextomem(mem_buf, p + 5, len);
1278 mem_buf[len++] = 0;
1279 qemu_chr_be_write(s->mon_chr, mem_buf, len);
1280 put_packet(s, "OK");
1281 break;
1283 #endif /* !CONFIG_USER_ONLY */
1284 if (is_query_packet(p, "Supported", ':')) {
1285 snprintf(buf, sizeof(buf), "PacketSize=%x", MAX_PACKET_LENGTH);
1286 cc = CPU_GET_CLASS(first_cpu);
1287 if (cc->gdb_core_xml_file != NULL) {
1288 pstrcat(buf, sizeof(buf), ";qXfer:features:read+");
1290 put_packet(s, buf);
1291 break;
1293 if (strncmp(p, "Xfer:features:read:", 19) == 0) {
1294 const char *xml;
1295 target_ulong total_len;
1297 cc = CPU_GET_CLASS(first_cpu);
1298 if (cc->gdb_core_xml_file == NULL) {
1299 goto unknown_command;
1302 gdb_has_xml = true;
1303 p += 19;
1304 xml = get_feature_xml(p, &p, cc);
1305 if (!xml) {
1306 snprintf(buf, sizeof(buf), "E00");
1307 put_packet(s, buf);
1308 break;
1311 if (*p == ':')
1312 p++;
1313 addr = strtoul(p, (char **)&p, 16);
1314 if (*p == ',')
1315 p++;
1316 len = strtoul(p, (char **)&p, 16);
1318 total_len = strlen(xml);
1319 if (addr > total_len) {
1320 snprintf(buf, sizeof(buf), "E00");
1321 put_packet(s, buf);
1322 break;
1324 if (len > (MAX_PACKET_LENGTH - 5) / 2)
1325 len = (MAX_PACKET_LENGTH - 5) / 2;
1326 if (len < total_len - addr) {
1327 buf[0] = 'm';
1328 len = memtox(buf + 1, xml + addr, len);
1329 } else {
1330 buf[0] = 'l';
1331 len = memtox(buf + 1, xml + addr, total_len - addr);
1333 put_packet_binary(s, buf, len + 1);
1334 break;
1336 if (is_query_packet(p, "Attached", ':')) {
1337 put_packet(s, GDB_ATTACHED);
1338 break;
1340 /* Unrecognised 'q' command. */
1341 goto unknown_command;
1343 default:
1344 unknown_command:
1345 /* put empty packet */
1346 buf[0] = '\0';
1347 put_packet(s, buf);
1348 break;
1350 return RS_IDLE;
1353 void gdb_set_stop_cpu(CPUState *cpu)
1355 gdbserver_state->c_cpu = cpu;
1356 gdbserver_state->g_cpu = cpu;
1359 #ifndef CONFIG_USER_ONLY
1360 static void gdb_vm_state_change(void *opaque, int running, RunState state)
1362 GDBState *s = gdbserver_state;
1363 CPUState *cpu = s->c_cpu;
1364 char buf[256];
1365 const char *type;
1366 int ret;
1368 if (running || s->state == RS_INACTIVE) {
1369 return;
1371 /* Is there a GDB syscall waiting to be sent? */
1372 if (s->current_syscall_cb) {
1373 put_packet(s, s->syscall_buf);
1374 return;
1376 switch (state) {
1377 case RUN_STATE_DEBUG:
1378 if (cpu->watchpoint_hit) {
1379 switch (cpu->watchpoint_hit->flags & BP_MEM_ACCESS) {
1380 case BP_MEM_READ:
1381 type = "r";
1382 break;
1383 case BP_MEM_ACCESS:
1384 type = "a";
1385 break;
1386 default:
1387 type = "";
1388 break;
1390 snprintf(buf, sizeof(buf),
1391 "T%02xthread:%02x;%swatch:" TARGET_FMT_lx ";",
1392 GDB_SIGNAL_TRAP, cpu_index(cpu), type,
1393 (target_ulong)cpu->watchpoint_hit->vaddr);
1394 cpu->watchpoint_hit = NULL;
1395 goto send_packet;
1397 tb_flush(cpu);
1398 ret = GDB_SIGNAL_TRAP;
1399 break;
1400 case RUN_STATE_PAUSED:
1401 ret = GDB_SIGNAL_INT;
1402 break;
1403 case RUN_STATE_SHUTDOWN:
1404 ret = GDB_SIGNAL_QUIT;
1405 break;
1406 case RUN_STATE_IO_ERROR:
1407 ret = GDB_SIGNAL_IO;
1408 break;
1409 case RUN_STATE_WATCHDOG:
1410 ret = GDB_SIGNAL_ALRM;
1411 break;
1412 case RUN_STATE_INTERNAL_ERROR:
1413 ret = GDB_SIGNAL_ABRT;
1414 break;
1415 case RUN_STATE_SAVE_VM:
1416 case RUN_STATE_RESTORE_VM:
1417 return;
1418 case RUN_STATE_FINISH_MIGRATE:
1419 ret = GDB_SIGNAL_XCPU;
1420 break;
1421 default:
1422 ret = GDB_SIGNAL_UNKNOWN;
1423 break;
1425 gdb_set_stop_cpu(cpu);
1426 snprintf(buf, sizeof(buf), "T%02xthread:%02x;", ret, cpu_index(cpu));
1428 send_packet:
1429 put_packet(s, buf);
1431 /* disable single step if it was enabled */
1432 cpu_single_step(cpu, 0);
1434 #endif
1436 /* Send a gdb syscall request.
1437 This accepts limited printf-style format specifiers, specifically:
1438 %x - target_ulong argument printed in hex.
1439 %lx - 64-bit argument printed in hex.
1440 %s - string pointer (target_ulong) and length (int) pair. */
1441 void gdb_do_syscallv(gdb_syscall_complete_cb cb, const char *fmt, va_list va)
1443 char *p;
1444 char *p_end;
1445 target_ulong addr;
1446 uint64_t i64;
1447 GDBState *s;
1449 s = gdbserver_state;
1450 if (!s)
1451 return;
1452 s->current_syscall_cb = cb;
1453 #ifndef CONFIG_USER_ONLY
1454 vm_stop(RUN_STATE_DEBUG);
1455 #endif
1456 p = s->syscall_buf;
1457 p_end = &s->syscall_buf[sizeof(s->syscall_buf)];
1458 *(p++) = 'F';
1459 while (*fmt) {
1460 if (*fmt == '%') {
1461 fmt++;
1462 switch (*fmt++) {
1463 case 'x':
1464 addr = va_arg(va, target_ulong);
1465 p += snprintf(p, p_end - p, TARGET_FMT_lx, addr);
1466 break;
1467 case 'l':
1468 if (*(fmt++) != 'x')
1469 goto bad_format;
1470 i64 = va_arg(va, uint64_t);
1471 p += snprintf(p, p_end - p, "%" PRIx64, i64);
1472 break;
1473 case 's':
1474 addr = va_arg(va, target_ulong);
1475 p += snprintf(p, p_end - p, TARGET_FMT_lx "/%x",
1476 addr, va_arg(va, int));
1477 break;
1478 default:
1479 bad_format:
1480 error_report("gdbstub: Bad syscall format string '%s'",
1481 fmt - 1);
1482 break;
1484 } else {
1485 *(p++) = *(fmt++);
1488 *p = 0;
1489 #ifdef CONFIG_USER_ONLY
1490 put_packet(s, s->syscall_buf);
1491 gdb_handlesig(s->c_cpu, 0);
1492 #else
1493 /* In this case wait to send the syscall packet until notification that
1494 the CPU has stopped. This must be done because if the packet is sent
1495 now the reply from the syscall request could be received while the CPU
1496 is still in the running state, which can cause packets to be dropped
1497 and state transition 'T' packets to be sent while the syscall is still
1498 being processed. */
1499 qemu_cpu_kick(s->c_cpu);
1500 #endif
1503 void gdb_do_syscall(gdb_syscall_complete_cb cb, const char *fmt, ...)
1505 va_list va;
1507 va_start(va, fmt);
1508 gdb_do_syscallv(cb, fmt, va);
1509 va_end(va);
1512 static void gdb_read_byte(GDBState *s, int ch)
1514 uint8_t reply;
1516 #ifndef CONFIG_USER_ONLY
1517 if (s->last_packet_len) {
1518 /* Waiting for a response to the last packet. If we see the start
1519 of a new command then abandon the previous response. */
1520 if (ch == '-') {
1521 #ifdef DEBUG_GDB
1522 printf("Got NACK, retransmitting\n");
1523 #endif
1524 put_buffer(s, (uint8_t *)s->last_packet, s->last_packet_len);
1526 #ifdef DEBUG_GDB
1527 else if (ch == '+')
1528 printf("Got ACK\n");
1529 else
1530 printf("Got '%c' when expecting ACK/NACK\n", ch);
1531 #endif
1532 if (ch == '+' || ch == '$')
1533 s->last_packet_len = 0;
1534 if (ch != '$')
1535 return;
1537 if (runstate_is_running()) {
1538 /* when the CPU is running, we cannot do anything except stop
1539 it when receiving a char */
1540 vm_stop(RUN_STATE_PAUSED);
1541 } else
1542 #endif
1544 switch(s->state) {
1545 case RS_IDLE:
1546 if (ch == '$') {
1547 /* start of command packet */
1548 s->line_buf_index = 0;
1549 s->line_sum = 0;
1550 s->state = RS_GETLINE;
1551 } else {
1552 #ifdef DEBUG_GDB
1553 printf("gdbstub received garbage between packets: 0x%x\n", ch);
1554 #endif
1556 break;
1557 case RS_GETLINE:
1558 if (ch == '}') {
1559 /* start escape sequence */
1560 s->state = RS_GETLINE_ESC;
1561 s->line_sum += ch;
1562 } else if (ch == '*') {
1563 /* start run length encoding sequence */
1564 s->state = RS_GETLINE_RLE;
1565 s->line_sum += ch;
1566 } else if (ch == '#') {
1567 /* end of command, start of checksum*/
1568 s->state = RS_CHKSUM1;
1569 } else if (s->line_buf_index >= sizeof(s->line_buf) - 1) {
1570 #ifdef DEBUG_GDB
1571 printf("gdbstub command buffer overrun, dropping command\n");
1572 #endif
1573 s->state = RS_IDLE;
1574 } else {
1575 /* unescaped command character */
1576 s->line_buf[s->line_buf_index++] = ch;
1577 s->line_sum += ch;
1579 break;
1580 case RS_GETLINE_ESC:
1581 if (ch == '#') {
1582 /* unexpected end of command in escape sequence */
1583 s->state = RS_CHKSUM1;
1584 } else if (s->line_buf_index >= sizeof(s->line_buf) - 1) {
1585 /* command buffer overrun */
1586 #ifdef DEBUG_GDB
1587 printf("gdbstub command buffer overrun, dropping command\n");
1588 #endif
1589 s->state = RS_IDLE;
1590 } else {
1591 /* parse escaped character and leave escape state */
1592 s->line_buf[s->line_buf_index++] = ch ^ 0x20;
1593 s->line_sum += ch;
1594 s->state = RS_GETLINE;
1596 break;
1597 case RS_GETLINE_RLE:
1598 if (ch < ' ') {
1599 /* invalid RLE count encoding */
1600 #ifdef DEBUG_GDB
1601 printf("gdbstub got invalid RLE count: 0x%x\n", ch);
1602 #endif
1603 s->state = RS_GETLINE;
1604 } else {
1605 /* decode repeat length */
1606 int repeat = (unsigned char)ch - ' ' + 3;
1607 if (s->line_buf_index + repeat >= sizeof(s->line_buf) - 1) {
1608 /* that many repeats would overrun the command buffer */
1609 #ifdef DEBUG_GDB
1610 printf("gdbstub command buffer overrun,"
1611 " dropping command\n");
1612 #endif
1613 s->state = RS_IDLE;
1614 } else if (s->line_buf_index < 1) {
1615 /* got a repeat but we have nothing to repeat */
1616 #ifdef DEBUG_GDB
1617 printf("gdbstub got invalid RLE sequence\n");
1618 #endif
1619 s->state = RS_GETLINE;
1620 } else {
1621 /* repeat the last character */
1622 memset(s->line_buf + s->line_buf_index,
1623 s->line_buf[s->line_buf_index - 1], repeat);
1624 s->line_buf_index += repeat;
1625 s->line_sum += ch;
1626 s->state = RS_GETLINE;
1629 break;
1630 case RS_CHKSUM1:
1631 /* get high hex digit of checksum */
1632 if (!isxdigit(ch)) {
1633 #ifdef DEBUG_GDB
1634 printf("gdbstub got invalid command checksum digit\n");
1635 #endif
1636 s->state = RS_GETLINE;
1637 break;
1639 s->line_buf[s->line_buf_index] = '\0';
1640 s->line_csum = fromhex(ch) << 4;
1641 s->state = RS_CHKSUM2;
1642 break;
1643 case RS_CHKSUM2:
1644 /* get low hex digit of checksum */
1645 if (!isxdigit(ch)) {
1646 #ifdef DEBUG_GDB
1647 printf("gdbstub got invalid command checksum digit\n");
1648 #endif
1649 s->state = RS_GETLINE;
1650 break;
1652 s->line_csum |= fromhex(ch);
1654 if (s->line_csum != (s->line_sum & 0xff)) {
1655 /* send NAK reply */
1656 reply = '-';
1657 put_buffer(s, &reply, 1);
1658 #ifdef DEBUG_GDB
1659 printf("gdbstub got command packet with incorrect checksum\n");
1660 #endif
1661 s->state = RS_IDLE;
1662 } else {
1663 /* send ACK reply */
1664 reply = '+';
1665 put_buffer(s, &reply, 1);
1666 s->state = gdb_handle_packet(s, s->line_buf);
1668 break;
1669 default:
1670 abort();
1675 /* Tell the remote gdb that the process has exited. */
1676 void gdb_exit(CPUArchState *env, int code)
1678 GDBState *s;
1679 char buf[4];
1680 #ifndef CONFIG_USER_ONLY
1681 Chardev *chr;
1682 #endif
1684 s = gdbserver_state;
1685 if (!s) {
1686 return;
1688 #ifdef CONFIG_USER_ONLY
1689 if (gdbserver_fd < 0 || s->fd < 0) {
1690 return;
1692 #else
1693 chr = qemu_chr_fe_get_driver(&s->chr);
1694 if (!chr) {
1695 return;
1697 #endif
1699 snprintf(buf, sizeof(buf), "W%02x", (uint8_t)code);
1700 put_packet(s, buf);
1702 #ifndef CONFIG_USER_ONLY
1703 qemu_chr_fe_deinit(&s->chr);
1704 object_unparent(OBJECT(chr));
1705 #endif
1708 #ifdef CONFIG_USER_ONLY
1710 gdb_handlesig(CPUState *cpu, int sig)
1712 GDBState *s;
1713 char buf[256];
1714 int n;
1716 s = gdbserver_state;
1717 if (gdbserver_fd < 0 || s->fd < 0) {
1718 return sig;
1721 /* disable single step if it was enabled */
1722 cpu_single_step(cpu, 0);
1723 tb_flush(cpu);
1725 if (sig != 0) {
1726 snprintf(buf, sizeof(buf), "S%02x", target_signal_to_gdb(sig));
1727 put_packet(s, buf);
1729 /* put_packet() might have detected that the peer terminated the
1730 connection. */
1731 if (s->fd < 0) {
1732 return sig;
1735 sig = 0;
1736 s->state = RS_IDLE;
1737 s->running_state = 0;
1738 while (s->running_state == 0) {
1739 n = read(s->fd, buf, 256);
1740 if (n > 0) {
1741 int i;
1743 for (i = 0; i < n; i++) {
1744 gdb_read_byte(s, buf[i]);
1746 } else {
1747 /* XXX: Connection closed. Should probably wait for another
1748 connection before continuing. */
1749 if (n == 0) {
1750 close(s->fd);
1752 s->fd = -1;
1753 return sig;
1756 sig = s->signal;
1757 s->signal = 0;
1758 return sig;
1761 /* Tell the remote gdb that the process has exited due to SIG. */
1762 void gdb_signalled(CPUArchState *env, int sig)
1764 GDBState *s;
1765 char buf[4];
1767 s = gdbserver_state;
1768 if (gdbserver_fd < 0 || s->fd < 0) {
1769 return;
1772 snprintf(buf, sizeof(buf), "X%02x", target_signal_to_gdb(sig));
1773 put_packet(s, buf);
1776 static void gdb_accept(void)
1778 GDBState *s;
1779 struct sockaddr_in sockaddr;
1780 socklen_t len;
1781 int fd;
1783 for(;;) {
1784 len = sizeof(sockaddr);
1785 fd = accept(gdbserver_fd, (struct sockaddr *)&sockaddr, &len);
1786 if (fd < 0 && errno != EINTR) {
1787 perror("accept");
1788 return;
1789 } else if (fd >= 0) {
1790 #ifndef _WIN32
1791 fcntl(fd, F_SETFD, FD_CLOEXEC);
1792 #endif
1793 break;
1797 /* set short latency */
1798 socket_set_nodelay(fd);
1800 s = g_malloc0(sizeof(GDBState));
1801 s->c_cpu = first_cpu;
1802 s->g_cpu = first_cpu;
1803 s->fd = fd;
1804 gdb_has_xml = false;
1806 gdbserver_state = s;
1809 static int gdbserver_open(int port)
1811 struct sockaddr_in sockaddr;
1812 int fd, ret;
1814 fd = socket(PF_INET, SOCK_STREAM, 0);
1815 if (fd < 0) {
1816 perror("socket");
1817 return -1;
1819 #ifndef _WIN32
1820 fcntl(fd, F_SETFD, FD_CLOEXEC);
1821 #endif
1823 socket_set_fast_reuse(fd);
1825 sockaddr.sin_family = AF_INET;
1826 sockaddr.sin_port = htons(port);
1827 sockaddr.sin_addr.s_addr = 0;
1828 ret = bind(fd, (struct sockaddr *)&sockaddr, sizeof(sockaddr));
1829 if (ret < 0) {
1830 perror("bind");
1831 close(fd);
1832 return -1;
1834 ret = listen(fd, 1);
1835 if (ret < 0) {
1836 perror("listen");
1837 close(fd);
1838 return -1;
1840 return fd;
1843 int gdbserver_start(int port)
1845 gdbserver_fd = gdbserver_open(port);
1846 if (gdbserver_fd < 0)
1847 return -1;
1848 /* accept connections */
1849 gdb_accept();
1850 return 0;
1853 /* Disable gdb stub for child processes. */
1854 void gdbserver_fork(CPUState *cpu)
1856 GDBState *s = gdbserver_state;
1858 if (gdbserver_fd < 0 || s->fd < 0) {
1859 return;
1861 close(s->fd);
1862 s->fd = -1;
1863 cpu_breakpoint_remove_all(cpu, BP_GDB);
1864 cpu_watchpoint_remove_all(cpu, BP_GDB);
1866 #else
1867 static int gdb_chr_can_receive(void *opaque)
1869 /* We can handle an arbitrarily large amount of data.
1870 Pick the maximum packet size, which is as good as anything. */
1871 return MAX_PACKET_LENGTH;
1874 static void gdb_chr_receive(void *opaque, const uint8_t *buf, int size)
1876 int i;
1878 for (i = 0; i < size; i++) {
1879 gdb_read_byte(gdbserver_state, buf[i]);
1883 static void gdb_chr_event(void *opaque, int event)
1885 switch (event) {
1886 case CHR_EVENT_OPENED:
1887 vm_stop(RUN_STATE_PAUSED);
1888 gdb_has_xml = false;
1889 break;
1890 default:
1891 break;
1895 static void gdb_monitor_output(GDBState *s, const char *msg, int len)
1897 char buf[MAX_PACKET_LENGTH];
1899 buf[0] = 'O';
1900 if (len > (MAX_PACKET_LENGTH/2) - 1)
1901 len = (MAX_PACKET_LENGTH/2) - 1;
1902 memtohex(buf + 1, (uint8_t *)msg, len);
1903 put_packet(s, buf);
1906 static int gdb_monitor_write(Chardev *chr, const uint8_t *buf, int len)
1908 const char *p = (const char *)buf;
1909 int max_sz;
1911 max_sz = (sizeof(gdbserver_state->last_packet) - 2) / 2;
1912 for (;;) {
1913 if (len <= max_sz) {
1914 gdb_monitor_output(gdbserver_state, p, len);
1915 break;
1917 gdb_monitor_output(gdbserver_state, p, max_sz);
1918 p += max_sz;
1919 len -= max_sz;
1921 return len;
1924 #ifndef _WIN32
1925 static void gdb_sigterm_handler(int signal)
1927 if (runstate_is_running()) {
1928 vm_stop(RUN_STATE_PAUSED);
1931 #endif
1933 static void gdb_monitor_open(Chardev *chr, ChardevBackend *backend,
1934 bool *be_opened, Error **errp)
1936 *be_opened = false;
1939 static void char_gdb_class_init(ObjectClass *oc, void *data)
1941 ChardevClass *cc = CHARDEV_CLASS(oc);
1943 cc->internal = true;
1944 cc->open = gdb_monitor_open;
1945 cc->chr_write = gdb_monitor_write;
1948 #define TYPE_CHARDEV_GDB "chardev-gdb"
1950 static const TypeInfo char_gdb_type_info = {
1951 .name = TYPE_CHARDEV_GDB,
1952 .parent = TYPE_CHARDEV,
1953 .class_init = char_gdb_class_init,
1956 int gdbserver_start(const char *device)
1958 GDBState *s;
1959 char gdbstub_device_name[128];
1960 Chardev *chr = NULL;
1961 Chardev *mon_chr;
1963 if (!first_cpu) {
1964 error_report("gdbstub: meaningless to attach gdb to a "
1965 "machine without any CPU.");
1966 return -1;
1969 if (!device)
1970 return -1;
1971 if (strcmp(device, "none") != 0) {
1972 if (strstart(device, "tcp:", NULL)) {
1973 /* enforce required TCP attributes */
1974 snprintf(gdbstub_device_name, sizeof(gdbstub_device_name),
1975 "%s,nowait,nodelay,server", device);
1976 device = gdbstub_device_name;
1978 #ifndef _WIN32
1979 else if (strcmp(device, "stdio") == 0) {
1980 struct sigaction act;
1982 memset(&act, 0, sizeof(act));
1983 act.sa_handler = gdb_sigterm_handler;
1984 sigaction(SIGINT, &act, NULL);
1986 #endif
1987 chr = qemu_chr_new_noreplay("gdb", device);
1988 if (!chr)
1989 return -1;
1992 s = gdbserver_state;
1993 if (!s) {
1994 s = g_malloc0(sizeof(GDBState));
1995 gdbserver_state = s;
1997 qemu_add_vm_change_state_handler(gdb_vm_state_change, NULL);
1999 /* Initialize a monitor terminal for gdb */
2000 mon_chr = qemu_chardev_new(NULL, TYPE_CHARDEV_GDB,
2001 NULL, &error_abort);
2002 monitor_init(mon_chr, 0);
2003 } else {
2004 if (qemu_chr_fe_get_driver(&s->chr)) {
2005 object_unparent(OBJECT(qemu_chr_fe_get_driver(&s->chr)));
2007 mon_chr = s->mon_chr;
2008 memset(s, 0, sizeof(GDBState));
2009 s->mon_chr = mon_chr;
2011 s->c_cpu = first_cpu;
2012 s->g_cpu = first_cpu;
2013 if (chr) {
2014 qemu_chr_fe_init(&s->chr, chr, &error_abort);
2015 qemu_chr_fe_set_handlers(&s->chr, gdb_chr_can_receive, gdb_chr_receive,
2016 gdb_chr_event, NULL, NULL, true);
2018 s->state = chr ? RS_IDLE : RS_INACTIVE;
2019 s->mon_chr = mon_chr;
2020 s->current_syscall_cb = NULL;
2022 return 0;
2025 static void register_types(void)
2027 type_register_static(&char_gdb_type_info);
2030 type_init(register_types);
2031 #endif