gdbstub: rename cpu_index -> cpu_gdb_index
[qemu/kevin.git] / gdbstub.c
blobb1efe0bccb7c28a442419ba52c49d60981ce9e52
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 /* Return the GDB index for a given vCPU state.
61 * For user mode this is simply the thread id. In system mode GDB
62 * numbers CPUs from 1 as 0 is reserved as an "any cpu" index.
64 static inline int cpu_gdb_index(CPUState *cpu)
66 #if defined(CONFIG_USER_ONLY)
67 return cpu->host_tid;
68 #else
69 return cpu->cpu_index + 1;
70 #endif
73 enum {
74 GDB_SIGNAL_0 = 0,
75 GDB_SIGNAL_INT = 2,
76 GDB_SIGNAL_QUIT = 3,
77 GDB_SIGNAL_TRAP = 5,
78 GDB_SIGNAL_ABRT = 6,
79 GDB_SIGNAL_ALRM = 14,
80 GDB_SIGNAL_IO = 23,
81 GDB_SIGNAL_XCPU = 24,
82 GDB_SIGNAL_UNKNOWN = 143
85 #ifdef CONFIG_USER_ONLY
87 /* Map target signal numbers to GDB protocol signal numbers and vice
88 * versa. For user emulation's currently supported systems, we can
89 * assume most signals are defined.
92 static int gdb_signal_table[] = {
94 TARGET_SIGHUP,
95 TARGET_SIGINT,
96 TARGET_SIGQUIT,
97 TARGET_SIGILL,
98 TARGET_SIGTRAP,
99 TARGET_SIGABRT,
100 -1, /* SIGEMT */
101 TARGET_SIGFPE,
102 TARGET_SIGKILL,
103 TARGET_SIGBUS,
104 TARGET_SIGSEGV,
105 TARGET_SIGSYS,
106 TARGET_SIGPIPE,
107 TARGET_SIGALRM,
108 TARGET_SIGTERM,
109 TARGET_SIGURG,
110 TARGET_SIGSTOP,
111 TARGET_SIGTSTP,
112 TARGET_SIGCONT,
113 TARGET_SIGCHLD,
114 TARGET_SIGTTIN,
115 TARGET_SIGTTOU,
116 TARGET_SIGIO,
117 TARGET_SIGXCPU,
118 TARGET_SIGXFSZ,
119 TARGET_SIGVTALRM,
120 TARGET_SIGPROF,
121 TARGET_SIGWINCH,
122 -1, /* SIGLOST */
123 TARGET_SIGUSR1,
124 TARGET_SIGUSR2,
125 #ifdef TARGET_SIGPWR
126 TARGET_SIGPWR,
127 #else
129 #endif
130 -1, /* SIGPOLL */
142 #ifdef __SIGRTMIN
143 __SIGRTMIN + 1,
144 __SIGRTMIN + 2,
145 __SIGRTMIN + 3,
146 __SIGRTMIN + 4,
147 __SIGRTMIN + 5,
148 __SIGRTMIN + 6,
149 __SIGRTMIN + 7,
150 __SIGRTMIN + 8,
151 __SIGRTMIN + 9,
152 __SIGRTMIN + 10,
153 __SIGRTMIN + 11,
154 __SIGRTMIN + 12,
155 __SIGRTMIN + 13,
156 __SIGRTMIN + 14,
157 __SIGRTMIN + 15,
158 __SIGRTMIN + 16,
159 __SIGRTMIN + 17,
160 __SIGRTMIN + 18,
161 __SIGRTMIN + 19,
162 __SIGRTMIN + 20,
163 __SIGRTMIN + 21,
164 __SIGRTMIN + 22,
165 __SIGRTMIN + 23,
166 __SIGRTMIN + 24,
167 __SIGRTMIN + 25,
168 __SIGRTMIN + 26,
169 __SIGRTMIN + 27,
170 __SIGRTMIN + 28,
171 __SIGRTMIN + 29,
172 __SIGRTMIN + 30,
173 __SIGRTMIN + 31,
174 -1, /* SIGCANCEL */
175 __SIGRTMIN,
176 __SIGRTMIN + 32,
177 __SIGRTMIN + 33,
178 __SIGRTMIN + 34,
179 __SIGRTMIN + 35,
180 __SIGRTMIN + 36,
181 __SIGRTMIN + 37,
182 __SIGRTMIN + 38,
183 __SIGRTMIN + 39,
184 __SIGRTMIN + 40,
185 __SIGRTMIN + 41,
186 __SIGRTMIN + 42,
187 __SIGRTMIN + 43,
188 __SIGRTMIN + 44,
189 __SIGRTMIN + 45,
190 __SIGRTMIN + 46,
191 __SIGRTMIN + 47,
192 __SIGRTMIN + 48,
193 __SIGRTMIN + 49,
194 __SIGRTMIN + 50,
195 __SIGRTMIN + 51,
196 __SIGRTMIN + 52,
197 __SIGRTMIN + 53,
198 __SIGRTMIN + 54,
199 __SIGRTMIN + 55,
200 __SIGRTMIN + 56,
201 __SIGRTMIN + 57,
202 __SIGRTMIN + 58,
203 __SIGRTMIN + 59,
204 __SIGRTMIN + 60,
205 __SIGRTMIN + 61,
206 __SIGRTMIN + 62,
207 __SIGRTMIN + 63,
208 __SIGRTMIN + 64,
209 __SIGRTMIN + 65,
210 __SIGRTMIN + 66,
211 __SIGRTMIN + 67,
212 __SIGRTMIN + 68,
213 __SIGRTMIN + 69,
214 __SIGRTMIN + 70,
215 __SIGRTMIN + 71,
216 __SIGRTMIN + 72,
217 __SIGRTMIN + 73,
218 __SIGRTMIN + 74,
219 __SIGRTMIN + 75,
220 __SIGRTMIN + 76,
221 __SIGRTMIN + 77,
222 __SIGRTMIN + 78,
223 __SIGRTMIN + 79,
224 __SIGRTMIN + 80,
225 __SIGRTMIN + 81,
226 __SIGRTMIN + 82,
227 __SIGRTMIN + 83,
228 __SIGRTMIN + 84,
229 __SIGRTMIN + 85,
230 __SIGRTMIN + 86,
231 __SIGRTMIN + 87,
232 __SIGRTMIN + 88,
233 __SIGRTMIN + 89,
234 __SIGRTMIN + 90,
235 __SIGRTMIN + 91,
236 __SIGRTMIN + 92,
237 __SIGRTMIN + 93,
238 __SIGRTMIN + 94,
239 __SIGRTMIN + 95,
240 -1, /* SIGINFO */
241 -1, /* UNKNOWN */
242 -1, /* DEFAULT */
249 #endif
251 #else
252 /* In system mode we only need SIGINT and SIGTRAP; other signals
253 are not yet supported. */
255 enum {
256 TARGET_SIGINT = 2,
257 TARGET_SIGTRAP = 5
260 static int gdb_signal_table[] = {
263 TARGET_SIGINT,
266 TARGET_SIGTRAP
268 #endif
270 #ifdef CONFIG_USER_ONLY
271 static int target_signal_to_gdb (int sig)
273 int i;
274 for (i = 0; i < ARRAY_SIZE (gdb_signal_table); i++)
275 if (gdb_signal_table[i] == sig)
276 return i;
277 return GDB_SIGNAL_UNKNOWN;
279 #endif
281 static int gdb_signal_to_target (int sig)
283 if (sig < ARRAY_SIZE (gdb_signal_table))
284 return gdb_signal_table[sig];
285 else
286 return -1;
289 /* #define DEBUG_GDB */
291 #ifdef DEBUG_GDB
292 # define DEBUG_GDB_GATE 1
293 #else
294 # define DEBUG_GDB_GATE 0
295 #endif
297 #define gdb_debug(fmt, ...) do { \
298 if (DEBUG_GDB_GATE) { \
299 fprintf(stderr, "%s: " fmt, __func__, ## __VA_ARGS__); \
301 } while (0)
304 typedef struct GDBRegisterState {
305 int base_reg;
306 int num_regs;
307 gdb_reg_cb get_reg;
308 gdb_reg_cb set_reg;
309 const char *xml;
310 struct GDBRegisterState *next;
311 } GDBRegisterState;
313 enum RSState {
314 RS_INACTIVE,
315 RS_IDLE,
316 RS_GETLINE,
317 RS_GETLINE_ESC,
318 RS_GETLINE_RLE,
319 RS_CHKSUM1,
320 RS_CHKSUM2,
322 typedef struct GDBState {
323 CPUState *c_cpu; /* current CPU for step/continue ops */
324 CPUState *g_cpu; /* current CPU for other ops */
325 CPUState *query_cpu; /* for q{f|s}ThreadInfo */
326 enum RSState state; /* parsing state */
327 char line_buf[MAX_PACKET_LENGTH];
328 int line_buf_index;
329 int line_sum; /* running checksum */
330 int line_csum; /* checksum at the end of the packet */
331 uint8_t last_packet[MAX_PACKET_LENGTH + 4];
332 int last_packet_len;
333 int signal;
334 #ifdef CONFIG_USER_ONLY
335 int fd;
336 int running_state;
337 #else
338 CharBackend chr;
339 Chardev *mon_chr;
340 #endif
341 char syscall_buf[256];
342 gdb_syscall_complete_cb current_syscall_cb;
343 } GDBState;
345 /* By default use no IRQs and no timers while single stepping so as to
346 * make single stepping like an ICE HW step.
348 static int sstep_flags = SSTEP_ENABLE|SSTEP_NOIRQ|SSTEP_NOTIMER;
350 static GDBState *gdbserver_state;
352 bool gdb_has_xml;
354 #ifdef CONFIG_USER_ONLY
355 /* XXX: This is not thread safe. Do we care? */
356 static int gdbserver_fd = -1;
358 static int get_char(GDBState *s)
360 uint8_t ch;
361 int ret;
363 for(;;) {
364 ret = qemu_recv(s->fd, &ch, 1, 0);
365 if (ret < 0) {
366 if (errno == ECONNRESET)
367 s->fd = -1;
368 if (errno != EINTR)
369 return -1;
370 } else if (ret == 0) {
371 close(s->fd);
372 s->fd = -1;
373 return -1;
374 } else {
375 break;
378 return ch;
380 #endif
382 static enum {
383 GDB_SYS_UNKNOWN,
384 GDB_SYS_ENABLED,
385 GDB_SYS_DISABLED,
386 } gdb_syscall_mode;
388 /* Decide if either remote gdb syscalls or native file IO should be used. */
389 int use_gdb_syscalls(void)
391 SemihostingTarget target = semihosting_get_target();
392 if (target == SEMIHOSTING_TARGET_NATIVE) {
393 /* -semihosting-config target=native */
394 return false;
395 } else if (target == SEMIHOSTING_TARGET_GDB) {
396 /* -semihosting-config target=gdb */
397 return true;
400 /* -semihosting-config target=auto */
401 /* On the first call check if gdb is connected and remember. */
402 if (gdb_syscall_mode == GDB_SYS_UNKNOWN) {
403 gdb_syscall_mode = (gdbserver_state ? GDB_SYS_ENABLED
404 : GDB_SYS_DISABLED);
406 return gdb_syscall_mode == GDB_SYS_ENABLED;
409 /* Resume execution. */
410 static inline void gdb_continue(GDBState *s)
412 #ifdef CONFIG_USER_ONLY
413 s->running_state = 1;
414 #else
415 if (!runstate_needs_reset()) {
416 vm_start();
418 #endif
422 * Resume execution, per CPU actions. For user-mode emulation it's
423 * equivalent to gdb_continue.
425 static int gdb_continue_partial(GDBState *s, char *newstates)
427 CPUState *cpu;
428 int res = 0;
429 #ifdef CONFIG_USER_ONLY
431 * This is not exactly accurate, but it's an improvement compared to the
432 * previous situation, where only one CPU would be single-stepped.
434 CPU_FOREACH(cpu) {
435 if (newstates[cpu->cpu_index] == 's') {
436 cpu_single_step(cpu, sstep_flags);
439 s->running_state = 1;
440 #else
441 int flag = 0;
443 if (!runstate_needs_reset()) {
444 if (vm_prepare_start()) {
445 return 0;
448 CPU_FOREACH(cpu) {
449 switch (newstates[cpu->cpu_index]) {
450 case 0:
451 case 1:
452 break; /* nothing to do here */
453 case 's':
454 cpu_single_step(cpu, sstep_flags);
455 cpu_resume(cpu);
456 flag = 1;
457 break;
458 case 'c':
459 cpu_resume(cpu);
460 flag = 1;
461 break;
462 default:
463 res = -1;
464 break;
468 if (flag) {
469 qemu_clock_enable(QEMU_CLOCK_VIRTUAL, true);
471 #endif
472 return res;
475 static void put_buffer(GDBState *s, const uint8_t *buf, int len)
477 #ifdef CONFIG_USER_ONLY
478 int ret;
480 while (len > 0) {
481 ret = send(s->fd, buf, len, 0);
482 if (ret < 0) {
483 if (errno != EINTR)
484 return;
485 } else {
486 buf += ret;
487 len -= ret;
490 #else
491 /* XXX this blocks entire thread. Rewrite to use
492 * qemu_chr_fe_write and background I/O callbacks */
493 qemu_chr_fe_write_all(&s->chr, buf, len);
494 #endif
497 static inline int fromhex(int v)
499 if (v >= '0' && v <= '9')
500 return v - '0';
501 else if (v >= 'A' && v <= 'F')
502 return v - 'A' + 10;
503 else if (v >= 'a' && v <= 'f')
504 return v - 'a' + 10;
505 else
506 return 0;
509 static inline int tohex(int v)
511 if (v < 10)
512 return v + '0';
513 else
514 return v - 10 + 'a';
517 static void memtohex(char *buf, const uint8_t *mem, int len)
519 int i, c;
520 char *q;
521 q = buf;
522 for(i = 0; i < len; i++) {
523 c = mem[i];
524 *q++ = tohex(c >> 4);
525 *q++ = tohex(c & 0xf);
527 *q = '\0';
530 static void hextomem(uint8_t *mem, const char *buf, int len)
532 int i;
534 for(i = 0; i < len; i++) {
535 mem[i] = (fromhex(buf[0]) << 4) | fromhex(buf[1]);
536 buf += 2;
540 /* return -1 if error, 0 if OK */
541 static int put_packet_binary(GDBState *s, const char *buf, int len)
543 int csum, i;
544 uint8_t *p;
546 for(;;) {
547 p = s->last_packet;
548 *(p++) = '$';
549 memcpy(p, buf, len);
550 p += len;
551 csum = 0;
552 for(i = 0; i < len; i++) {
553 csum += buf[i];
555 *(p++) = '#';
556 *(p++) = tohex((csum >> 4) & 0xf);
557 *(p++) = tohex((csum) & 0xf);
559 s->last_packet_len = p - s->last_packet;
560 put_buffer(s, (uint8_t *)s->last_packet, s->last_packet_len);
562 #ifdef CONFIG_USER_ONLY
563 i = get_char(s);
564 if (i < 0)
565 return -1;
566 if (i == '+')
567 break;
568 #else
569 break;
570 #endif
572 return 0;
575 /* return -1 if error, 0 if OK */
576 static int put_packet(GDBState *s, const char *buf)
578 gdb_debug("reply='%s'\n", buf);
580 return put_packet_binary(s, buf, strlen(buf));
583 /* Encode data using the encoding for 'x' packets. */
584 static int memtox(char *buf, const char *mem, int len)
586 char *p = buf;
587 char c;
589 while (len--) {
590 c = *(mem++);
591 switch (c) {
592 case '#': case '$': case '*': case '}':
593 *(p++) = '}';
594 *(p++) = c ^ 0x20;
595 break;
596 default:
597 *(p++) = c;
598 break;
601 return p - buf;
604 static const char *get_feature_xml(const char *p, const char **newp,
605 CPUClass *cc)
607 size_t len;
608 int i;
609 const char *name;
610 static char target_xml[1024];
612 len = 0;
613 while (p[len] && p[len] != ':')
614 len++;
615 *newp = p + len;
617 name = NULL;
618 if (strncmp(p, "target.xml", len) == 0) {
619 /* Generate the XML description for this CPU. */
620 if (!target_xml[0]) {
621 GDBRegisterState *r;
622 CPUState *cpu = first_cpu;
624 pstrcat(target_xml, sizeof(target_xml),
625 "<?xml version=\"1.0\"?>"
626 "<!DOCTYPE target SYSTEM \"gdb-target.dtd\">"
627 "<target>");
628 if (cc->gdb_arch_name) {
629 gchar *arch = cc->gdb_arch_name(cpu);
630 pstrcat(target_xml, sizeof(target_xml), "<architecture>");
631 pstrcat(target_xml, sizeof(target_xml), arch);
632 pstrcat(target_xml, sizeof(target_xml), "</architecture>");
633 g_free(arch);
635 pstrcat(target_xml, sizeof(target_xml), "<xi:include href=\"");
636 pstrcat(target_xml, sizeof(target_xml), cc->gdb_core_xml_file);
637 pstrcat(target_xml, sizeof(target_xml), "\"/>");
638 for (r = cpu->gdb_regs; r; r = r->next) {
639 pstrcat(target_xml, sizeof(target_xml), "<xi:include href=\"");
640 pstrcat(target_xml, sizeof(target_xml), r->xml);
641 pstrcat(target_xml, sizeof(target_xml), "\"/>");
643 pstrcat(target_xml, sizeof(target_xml), "</target>");
645 return target_xml;
647 for (i = 0; ; i++) {
648 name = xml_builtin[i][0];
649 if (!name || (strncmp(name, p, len) == 0 && strlen(name) == len))
650 break;
652 return name ? xml_builtin[i][1] : NULL;
655 static int gdb_read_register(CPUState *cpu, uint8_t *mem_buf, int reg)
657 CPUClass *cc = CPU_GET_CLASS(cpu);
658 CPUArchState *env = cpu->env_ptr;
659 GDBRegisterState *r;
661 if (reg < cc->gdb_num_core_regs) {
662 return cc->gdb_read_register(cpu, mem_buf, reg);
665 for (r = cpu->gdb_regs; r; r = r->next) {
666 if (r->base_reg <= reg && reg < r->base_reg + r->num_regs) {
667 return r->get_reg(env, mem_buf, reg - r->base_reg);
670 return 0;
673 static int gdb_write_register(CPUState *cpu, uint8_t *mem_buf, int reg)
675 CPUClass *cc = CPU_GET_CLASS(cpu);
676 CPUArchState *env = cpu->env_ptr;
677 GDBRegisterState *r;
679 if (reg < cc->gdb_num_core_regs) {
680 return cc->gdb_write_register(cpu, mem_buf, reg);
683 for (r = cpu->gdb_regs; r; r = r->next) {
684 if (r->base_reg <= reg && reg < r->base_reg + r->num_regs) {
685 return r->set_reg(env, mem_buf, reg - r->base_reg);
688 return 0;
691 /* Register a supplemental set of CPU registers. If g_pos is nonzero it
692 specifies the first register number and these registers are included in
693 a standard "g" packet. Direction is relative to gdb, i.e. get_reg is
694 gdb reading a CPU register, and set_reg is gdb modifying a CPU register.
697 void gdb_register_coprocessor(CPUState *cpu,
698 gdb_reg_cb get_reg, gdb_reg_cb set_reg,
699 int num_regs, const char *xml, int g_pos)
701 GDBRegisterState *s;
702 GDBRegisterState **p;
704 p = &cpu->gdb_regs;
705 while (*p) {
706 /* Check for duplicates. */
707 if (strcmp((*p)->xml, xml) == 0)
708 return;
709 p = &(*p)->next;
712 s = g_new0(GDBRegisterState, 1);
713 s->base_reg = cpu->gdb_num_regs;
714 s->num_regs = num_regs;
715 s->get_reg = get_reg;
716 s->set_reg = set_reg;
717 s->xml = xml;
719 /* Add to end of list. */
720 cpu->gdb_num_regs += num_regs;
721 *p = s;
722 if (g_pos) {
723 if (g_pos != s->base_reg) {
724 error_report("Error: Bad gdb register numbering for '%s', "
725 "expected %d got %d", xml, g_pos, s->base_reg);
726 } else {
727 cpu->gdb_num_g_regs = cpu->gdb_num_regs;
732 #ifndef CONFIG_USER_ONLY
733 /* Translate GDB watchpoint type to a flags value for cpu_watchpoint_* */
734 static inline int xlat_gdb_type(CPUState *cpu, int gdbtype)
736 static const int xlat[] = {
737 [GDB_WATCHPOINT_WRITE] = BP_GDB | BP_MEM_WRITE,
738 [GDB_WATCHPOINT_READ] = BP_GDB | BP_MEM_READ,
739 [GDB_WATCHPOINT_ACCESS] = BP_GDB | BP_MEM_ACCESS,
742 CPUClass *cc = CPU_GET_CLASS(cpu);
743 int cputype = xlat[gdbtype];
745 if (cc->gdb_stop_before_watchpoint) {
746 cputype |= BP_STOP_BEFORE_ACCESS;
748 return cputype;
750 #endif
752 static int gdb_breakpoint_insert(target_ulong addr, target_ulong len, int type)
754 CPUState *cpu;
755 int err = 0;
757 if (kvm_enabled()) {
758 return kvm_insert_breakpoint(gdbserver_state->c_cpu, addr, len, type);
761 switch (type) {
762 case GDB_BREAKPOINT_SW:
763 case GDB_BREAKPOINT_HW:
764 CPU_FOREACH(cpu) {
765 err = cpu_breakpoint_insert(cpu, addr, BP_GDB, NULL);
766 if (err) {
767 break;
770 return err;
771 #ifndef CONFIG_USER_ONLY
772 case GDB_WATCHPOINT_WRITE:
773 case GDB_WATCHPOINT_READ:
774 case GDB_WATCHPOINT_ACCESS:
775 CPU_FOREACH(cpu) {
776 err = cpu_watchpoint_insert(cpu, addr, len,
777 xlat_gdb_type(cpu, type), NULL);
778 if (err) {
779 break;
782 return err;
783 #endif
784 default:
785 return -ENOSYS;
789 static int gdb_breakpoint_remove(target_ulong addr, target_ulong len, int type)
791 CPUState *cpu;
792 int err = 0;
794 if (kvm_enabled()) {
795 return kvm_remove_breakpoint(gdbserver_state->c_cpu, addr, len, type);
798 switch (type) {
799 case GDB_BREAKPOINT_SW:
800 case GDB_BREAKPOINT_HW:
801 CPU_FOREACH(cpu) {
802 err = cpu_breakpoint_remove(cpu, addr, BP_GDB);
803 if (err) {
804 break;
807 return err;
808 #ifndef CONFIG_USER_ONLY
809 case GDB_WATCHPOINT_WRITE:
810 case GDB_WATCHPOINT_READ:
811 case GDB_WATCHPOINT_ACCESS:
812 CPU_FOREACH(cpu) {
813 err = cpu_watchpoint_remove(cpu, addr, len,
814 xlat_gdb_type(cpu, type));
815 if (err)
816 break;
818 return err;
819 #endif
820 default:
821 return -ENOSYS;
825 static void gdb_breakpoint_remove_all(void)
827 CPUState *cpu;
829 if (kvm_enabled()) {
830 kvm_remove_all_breakpoints(gdbserver_state->c_cpu);
831 return;
834 CPU_FOREACH(cpu) {
835 cpu_breakpoint_remove_all(cpu, BP_GDB);
836 #ifndef CONFIG_USER_ONLY
837 cpu_watchpoint_remove_all(cpu, BP_GDB);
838 #endif
842 static void gdb_set_cpu_pc(GDBState *s, target_ulong pc)
844 CPUState *cpu = s->c_cpu;
846 cpu_synchronize_state(cpu);
847 cpu_set_pc(cpu, pc);
850 static CPUState *find_cpu(uint32_t thread_id)
852 CPUState *cpu;
854 CPU_FOREACH(cpu) {
855 if (cpu_gdb_index(cpu) == thread_id) {
856 return cpu;
860 return NULL;
863 static int is_query_packet(const char *p, const char *query, char separator)
865 unsigned int query_len = strlen(query);
867 return strncmp(p, query, query_len) == 0 &&
868 (p[query_len] == '\0' || p[query_len] == separator);
872 * gdb_handle_vcont - Parses and handles a vCont packet.
873 * returns -ENOTSUP if a command is unsupported, -EINVAL or -ERANGE if there is
874 * a format error, 0 on success.
876 static int gdb_handle_vcont(GDBState *s, const char *p)
878 int res, idx, signal = 0;
879 char cur_action;
880 char *newstates;
881 unsigned long tmp;
882 CPUState *cpu;
883 #ifdef CONFIG_USER_ONLY
884 int max_cpus = 1; /* global variable max_cpus exists only in system mode */
886 CPU_FOREACH(cpu) {
887 max_cpus = max_cpus <= cpu->cpu_index ? cpu->cpu_index + 1 : max_cpus;
889 #endif
890 /* uninitialised CPUs stay 0 */
891 newstates = g_new0(char, max_cpus);
893 /* mark valid CPUs with 1 */
894 CPU_FOREACH(cpu) {
895 newstates[cpu->cpu_index] = 1;
899 * res keeps track of what error we are returning, with -ENOTSUP meaning
900 * that the command is unknown or unsupported, thus returning an empty
901 * packet, while -EINVAL and -ERANGE cause an E22 packet, due to invalid,
902 * or incorrect parameters passed.
904 res = 0;
905 while (*p) {
906 if (*p++ != ';') {
907 res = -ENOTSUP;
908 goto out;
911 cur_action = *p++;
912 if (cur_action == 'C' || cur_action == 'S') {
913 cur_action = tolower(cur_action);
914 res = qemu_strtoul(p + 1, &p, 16, &tmp);
915 if (res) {
916 goto out;
918 signal = gdb_signal_to_target(tmp);
919 } else if (cur_action != 'c' && cur_action != 's') {
920 /* unknown/invalid/unsupported command */
921 res = -ENOTSUP;
922 goto out;
924 /* thread specification. special values: (none), -1 = all; 0 = any */
925 if ((p[0] == ':' && p[1] == '-' && p[2] == '1') || (p[0] != ':')) {
926 if (*p == ':') {
927 p += 3;
929 for (idx = 0; idx < max_cpus; idx++) {
930 if (newstates[idx] == 1) {
931 newstates[idx] = cur_action;
934 } else if (*p == ':') {
935 p++;
936 res = qemu_strtoul(p, &p, 16, &tmp);
937 if (res) {
938 goto out;
940 idx = tmp;
941 /* 0 means any thread, so we pick the first valid CPU */
942 if (!idx) {
943 idx = cpu_gdb_index(first_cpu);
947 * If we are in user mode, the thread specified is actually a
948 * thread id, and not an index. We need to find the actual
949 * CPU first, and only then we can use its index.
951 cpu = find_cpu(idx);
952 /* invalid CPU/thread specified */
953 if (!idx || !cpu) {
954 res = -EINVAL;
955 goto out;
957 /* only use if no previous match occourred */
958 if (newstates[cpu->cpu_index] == 1) {
959 newstates[cpu->cpu_index] = cur_action;
963 s->signal = signal;
964 gdb_continue_partial(s, newstates);
966 out:
967 g_free(newstates);
969 return res;
972 static int gdb_handle_packet(GDBState *s, const char *line_buf)
974 CPUState *cpu;
975 CPUClass *cc;
976 const char *p;
977 uint32_t thread;
978 int ch, reg_size, type, res;
979 char buf[MAX_PACKET_LENGTH];
980 uint8_t mem_buf[MAX_PACKET_LENGTH];
981 uint8_t *registers;
982 target_ulong addr, len;
985 gdb_debug("command='%s'\n", line_buf);
987 p = line_buf;
988 ch = *p++;
989 switch(ch) {
990 case '?':
991 /* TODO: Make this return the correct value for user-mode. */
992 snprintf(buf, sizeof(buf), "T%02xthread:%02x;", GDB_SIGNAL_TRAP,
993 cpu_gdb_index(s->c_cpu));
994 put_packet(s, buf);
995 /* Remove all the breakpoints when this query is issued,
996 * because gdb is doing and initial connect and the state
997 * should be cleaned up.
999 gdb_breakpoint_remove_all();
1000 break;
1001 case 'c':
1002 if (*p != '\0') {
1003 addr = strtoull(p, (char **)&p, 16);
1004 gdb_set_cpu_pc(s, addr);
1006 s->signal = 0;
1007 gdb_continue(s);
1008 return RS_IDLE;
1009 case 'C':
1010 s->signal = gdb_signal_to_target (strtoul(p, (char **)&p, 16));
1011 if (s->signal == -1)
1012 s->signal = 0;
1013 gdb_continue(s);
1014 return RS_IDLE;
1015 case 'v':
1016 if (strncmp(p, "Cont", 4) == 0) {
1017 p += 4;
1018 if (*p == '?') {
1019 put_packet(s, "vCont;c;C;s;S");
1020 break;
1023 res = gdb_handle_vcont(s, p);
1025 if (res) {
1026 if ((res == -EINVAL) || (res == -ERANGE)) {
1027 put_packet(s, "E22");
1028 break;
1030 goto unknown_command;
1032 break;
1033 } else {
1034 goto unknown_command;
1036 case 'k':
1037 /* Kill the target */
1038 error_report("QEMU: Terminated via GDBstub");
1039 exit(0);
1040 case 'D':
1041 /* Detach packet */
1042 gdb_breakpoint_remove_all();
1043 gdb_syscall_mode = GDB_SYS_DISABLED;
1044 gdb_continue(s);
1045 put_packet(s, "OK");
1046 break;
1047 case 's':
1048 if (*p != '\0') {
1049 addr = strtoull(p, (char **)&p, 16);
1050 gdb_set_cpu_pc(s, addr);
1052 cpu_single_step(s->c_cpu, sstep_flags);
1053 gdb_continue(s);
1054 return RS_IDLE;
1055 case 'F':
1057 target_ulong ret;
1058 target_ulong err;
1060 ret = strtoull(p, (char **)&p, 16);
1061 if (*p == ',') {
1062 p++;
1063 err = strtoull(p, (char **)&p, 16);
1064 } else {
1065 err = 0;
1067 if (*p == ',')
1068 p++;
1069 type = *p;
1070 if (s->current_syscall_cb) {
1071 s->current_syscall_cb(s->c_cpu, ret, err);
1072 s->current_syscall_cb = NULL;
1074 if (type == 'C') {
1075 put_packet(s, "T02");
1076 } else {
1077 gdb_continue(s);
1080 break;
1081 case 'g':
1082 cpu_synchronize_state(s->g_cpu);
1083 len = 0;
1084 for (addr = 0; addr < s->g_cpu->gdb_num_g_regs; addr++) {
1085 reg_size = gdb_read_register(s->g_cpu, mem_buf + len, addr);
1086 len += reg_size;
1088 memtohex(buf, mem_buf, len);
1089 put_packet(s, buf);
1090 break;
1091 case 'G':
1092 cpu_synchronize_state(s->g_cpu);
1093 registers = mem_buf;
1094 len = strlen(p) / 2;
1095 hextomem((uint8_t *)registers, p, len);
1096 for (addr = 0; addr < s->g_cpu->gdb_num_g_regs && len > 0; addr++) {
1097 reg_size = gdb_write_register(s->g_cpu, registers, addr);
1098 len -= reg_size;
1099 registers += reg_size;
1101 put_packet(s, "OK");
1102 break;
1103 case 'm':
1104 addr = strtoull(p, (char **)&p, 16);
1105 if (*p == ',')
1106 p++;
1107 len = strtoull(p, NULL, 16);
1109 /* memtohex() doubles the required space */
1110 if (len > MAX_PACKET_LENGTH / 2) {
1111 put_packet (s, "E22");
1112 break;
1115 if (target_memory_rw_debug(s->g_cpu, addr, mem_buf, len, false) != 0) {
1116 put_packet (s, "E14");
1117 } else {
1118 memtohex(buf, mem_buf, len);
1119 put_packet(s, buf);
1121 break;
1122 case 'M':
1123 addr = strtoull(p, (char **)&p, 16);
1124 if (*p == ',')
1125 p++;
1126 len = strtoull(p, (char **)&p, 16);
1127 if (*p == ':')
1128 p++;
1130 /* hextomem() reads 2*len bytes */
1131 if (len > strlen(p) / 2) {
1132 put_packet (s, "E22");
1133 break;
1135 hextomem(mem_buf, p, len);
1136 if (target_memory_rw_debug(s->g_cpu, addr, mem_buf, len,
1137 true) != 0) {
1138 put_packet(s, "E14");
1139 } else {
1140 put_packet(s, "OK");
1142 break;
1143 case 'p':
1144 /* Older gdb are really dumb, and don't use 'g' if 'p' is avaialable.
1145 This works, but can be very slow. Anything new enough to
1146 understand XML also knows how to use this properly. */
1147 if (!gdb_has_xml)
1148 goto unknown_command;
1149 addr = strtoull(p, (char **)&p, 16);
1150 reg_size = gdb_read_register(s->g_cpu, mem_buf, addr);
1151 if (reg_size) {
1152 memtohex(buf, mem_buf, reg_size);
1153 put_packet(s, buf);
1154 } else {
1155 put_packet(s, "E14");
1157 break;
1158 case 'P':
1159 if (!gdb_has_xml)
1160 goto unknown_command;
1161 addr = strtoull(p, (char **)&p, 16);
1162 if (*p == '=')
1163 p++;
1164 reg_size = strlen(p) / 2;
1165 hextomem(mem_buf, p, reg_size);
1166 gdb_write_register(s->g_cpu, mem_buf, addr);
1167 put_packet(s, "OK");
1168 break;
1169 case 'Z':
1170 case 'z':
1171 type = strtoul(p, (char **)&p, 16);
1172 if (*p == ',')
1173 p++;
1174 addr = strtoull(p, (char **)&p, 16);
1175 if (*p == ',')
1176 p++;
1177 len = strtoull(p, (char **)&p, 16);
1178 if (ch == 'Z')
1179 res = gdb_breakpoint_insert(addr, len, type);
1180 else
1181 res = gdb_breakpoint_remove(addr, len, type);
1182 if (res >= 0)
1183 put_packet(s, "OK");
1184 else if (res == -ENOSYS)
1185 put_packet(s, "");
1186 else
1187 put_packet(s, "E22");
1188 break;
1189 case 'H':
1190 type = *p++;
1191 thread = strtoull(p, (char **)&p, 16);
1192 if (thread == -1 || thread == 0) {
1193 put_packet(s, "OK");
1194 break;
1196 cpu = find_cpu(thread);
1197 if (cpu == NULL) {
1198 put_packet(s, "E22");
1199 break;
1201 switch (type) {
1202 case 'c':
1203 s->c_cpu = cpu;
1204 put_packet(s, "OK");
1205 break;
1206 case 'g':
1207 s->g_cpu = cpu;
1208 put_packet(s, "OK");
1209 break;
1210 default:
1211 put_packet(s, "E22");
1212 break;
1214 break;
1215 case 'T':
1216 thread = strtoull(p, (char **)&p, 16);
1217 cpu = find_cpu(thread);
1219 if (cpu != NULL) {
1220 put_packet(s, "OK");
1221 } else {
1222 put_packet(s, "E22");
1224 break;
1225 case 'q':
1226 case 'Q':
1227 /* parse any 'q' packets here */
1228 if (!strcmp(p,"qemu.sstepbits")) {
1229 /* Query Breakpoint bit definitions */
1230 snprintf(buf, sizeof(buf), "ENABLE=%x,NOIRQ=%x,NOTIMER=%x",
1231 SSTEP_ENABLE,
1232 SSTEP_NOIRQ,
1233 SSTEP_NOTIMER);
1234 put_packet(s, buf);
1235 break;
1236 } else if (is_query_packet(p, "qemu.sstep", '=')) {
1237 /* Display or change the sstep_flags */
1238 p += 10;
1239 if (*p != '=') {
1240 /* Display current setting */
1241 snprintf(buf, sizeof(buf), "0x%x", sstep_flags);
1242 put_packet(s, buf);
1243 break;
1245 p++;
1246 type = strtoul(p, (char **)&p, 16);
1247 sstep_flags = type;
1248 put_packet(s, "OK");
1249 break;
1250 } else if (strcmp(p,"C") == 0) {
1251 /* "Current thread" remains vague in the spec, so always return
1252 * the first CPU (gdb returns the first thread). */
1253 put_packet(s, "QC1");
1254 break;
1255 } else if (strcmp(p,"fThreadInfo") == 0) {
1256 s->query_cpu = first_cpu;
1257 goto report_cpuinfo;
1258 } else if (strcmp(p,"sThreadInfo") == 0) {
1259 report_cpuinfo:
1260 if (s->query_cpu) {
1261 snprintf(buf, sizeof(buf), "m%x", cpu_gdb_index(s->query_cpu));
1262 put_packet(s, buf);
1263 s->query_cpu = CPU_NEXT(s->query_cpu);
1264 } else
1265 put_packet(s, "l");
1266 break;
1267 } else if (strncmp(p,"ThreadExtraInfo,", 16) == 0) {
1268 thread = strtoull(p+16, (char **)&p, 16);
1269 cpu = find_cpu(thread);
1270 if (cpu != NULL) {
1271 cpu_synchronize_state(cpu);
1272 /* memtohex() doubles the required space */
1273 len = snprintf((char *)mem_buf, sizeof(buf) / 2,
1274 "CPU#%d [%s]", cpu->cpu_index,
1275 cpu->halted ? "halted " : "running");
1276 memtohex(buf, mem_buf, len);
1277 put_packet(s, buf);
1279 break;
1281 #ifdef CONFIG_USER_ONLY
1282 else if (strcmp(p, "Offsets") == 0) {
1283 TaskState *ts = s->c_cpu->opaque;
1285 snprintf(buf, sizeof(buf),
1286 "Text=" TARGET_ABI_FMT_lx ";Data=" TARGET_ABI_FMT_lx
1287 ";Bss=" TARGET_ABI_FMT_lx,
1288 ts->info->code_offset,
1289 ts->info->data_offset,
1290 ts->info->data_offset);
1291 put_packet(s, buf);
1292 break;
1294 #else /* !CONFIG_USER_ONLY */
1295 else if (strncmp(p, "Rcmd,", 5) == 0) {
1296 int len = strlen(p + 5);
1298 if ((len % 2) != 0) {
1299 put_packet(s, "E01");
1300 break;
1302 len = len / 2;
1303 hextomem(mem_buf, p + 5, len);
1304 mem_buf[len++] = 0;
1305 qemu_chr_be_write(s->mon_chr, mem_buf, len);
1306 put_packet(s, "OK");
1307 break;
1309 #endif /* !CONFIG_USER_ONLY */
1310 if (is_query_packet(p, "Supported", ':')) {
1311 snprintf(buf, sizeof(buf), "PacketSize=%x", MAX_PACKET_LENGTH);
1312 cc = CPU_GET_CLASS(first_cpu);
1313 if (cc->gdb_core_xml_file != NULL) {
1314 pstrcat(buf, sizeof(buf), ";qXfer:features:read+");
1316 put_packet(s, buf);
1317 break;
1319 if (strncmp(p, "Xfer:features:read:", 19) == 0) {
1320 const char *xml;
1321 target_ulong total_len;
1323 cc = CPU_GET_CLASS(first_cpu);
1324 if (cc->gdb_core_xml_file == NULL) {
1325 goto unknown_command;
1328 gdb_has_xml = true;
1329 p += 19;
1330 xml = get_feature_xml(p, &p, cc);
1331 if (!xml) {
1332 snprintf(buf, sizeof(buf), "E00");
1333 put_packet(s, buf);
1334 break;
1337 if (*p == ':')
1338 p++;
1339 addr = strtoul(p, (char **)&p, 16);
1340 if (*p == ',')
1341 p++;
1342 len = strtoul(p, (char **)&p, 16);
1344 total_len = strlen(xml);
1345 if (addr > total_len) {
1346 snprintf(buf, sizeof(buf), "E00");
1347 put_packet(s, buf);
1348 break;
1350 if (len > (MAX_PACKET_LENGTH - 5) / 2)
1351 len = (MAX_PACKET_LENGTH - 5) / 2;
1352 if (len < total_len - addr) {
1353 buf[0] = 'm';
1354 len = memtox(buf + 1, xml + addr, len);
1355 } else {
1356 buf[0] = 'l';
1357 len = memtox(buf + 1, xml + addr, total_len - addr);
1359 put_packet_binary(s, buf, len + 1);
1360 break;
1362 if (is_query_packet(p, "Attached", ':')) {
1363 put_packet(s, GDB_ATTACHED);
1364 break;
1366 /* Unrecognised 'q' command. */
1367 goto unknown_command;
1369 default:
1370 unknown_command:
1371 /* put empty packet */
1372 buf[0] = '\0';
1373 put_packet(s, buf);
1374 break;
1376 return RS_IDLE;
1379 void gdb_set_stop_cpu(CPUState *cpu)
1381 gdbserver_state->c_cpu = cpu;
1382 gdbserver_state->g_cpu = cpu;
1385 #ifndef CONFIG_USER_ONLY
1386 static void gdb_vm_state_change(void *opaque, int running, RunState state)
1388 GDBState *s = gdbserver_state;
1389 CPUState *cpu = s->c_cpu;
1390 char buf[256];
1391 const char *type;
1392 int ret;
1394 if (running || s->state == RS_INACTIVE) {
1395 return;
1397 /* Is there a GDB syscall waiting to be sent? */
1398 if (s->current_syscall_cb) {
1399 put_packet(s, s->syscall_buf);
1400 return;
1402 switch (state) {
1403 case RUN_STATE_DEBUG:
1404 if (cpu->watchpoint_hit) {
1405 switch (cpu->watchpoint_hit->flags & BP_MEM_ACCESS) {
1406 case BP_MEM_READ:
1407 type = "r";
1408 break;
1409 case BP_MEM_ACCESS:
1410 type = "a";
1411 break;
1412 default:
1413 type = "";
1414 break;
1416 snprintf(buf, sizeof(buf),
1417 "T%02xthread:%02x;%swatch:" TARGET_FMT_lx ";",
1418 GDB_SIGNAL_TRAP, cpu_gdb_index(cpu), type,
1419 (target_ulong)cpu->watchpoint_hit->vaddr);
1420 cpu->watchpoint_hit = NULL;
1421 goto send_packet;
1423 tb_flush(cpu);
1424 ret = GDB_SIGNAL_TRAP;
1425 break;
1426 case RUN_STATE_PAUSED:
1427 ret = GDB_SIGNAL_INT;
1428 break;
1429 case RUN_STATE_SHUTDOWN:
1430 ret = GDB_SIGNAL_QUIT;
1431 break;
1432 case RUN_STATE_IO_ERROR:
1433 ret = GDB_SIGNAL_IO;
1434 break;
1435 case RUN_STATE_WATCHDOG:
1436 ret = GDB_SIGNAL_ALRM;
1437 break;
1438 case RUN_STATE_INTERNAL_ERROR:
1439 ret = GDB_SIGNAL_ABRT;
1440 break;
1441 case RUN_STATE_SAVE_VM:
1442 case RUN_STATE_RESTORE_VM:
1443 return;
1444 case RUN_STATE_FINISH_MIGRATE:
1445 ret = GDB_SIGNAL_XCPU;
1446 break;
1447 default:
1448 ret = GDB_SIGNAL_UNKNOWN;
1449 break;
1451 gdb_set_stop_cpu(cpu);
1452 snprintf(buf, sizeof(buf), "T%02xthread:%02x;", ret, cpu_gdb_index(cpu));
1454 send_packet:
1455 put_packet(s, buf);
1457 /* disable single step if it was enabled */
1458 cpu_single_step(cpu, 0);
1460 #endif
1462 /* Send a gdb syscall request.
1463 This accepts limited printf-style format specifiers, specifically:
1464 %x - target_ulong argument printed in hex.
1465 %lx - 64-bit argument printed in hex.
1466 %s - string pointer (target_ulong) and length (int) pair. */
1467 void gdb_do_syscallv(gdb_syscall_complete_cb cb, const char *fmt, va_list va)
1469 char *p;
1470 char *p_end;
1471 target_ulong addr;
1472 uint64_t i64;
1473 GDBState *s;
1475 s = gdbserver_state;
1476 if (!s)
1477 return;
1478 s->current_syscall_cb = cb;
1479 #ifndef CONFIG_USER_ONLY
1480 vm_stop(RUN_STATE_DEBUG);
1481 #endif
1482 p = s->syscall_buf;
1483 p_end = &s->syscall_buf[sizeof(s->syscall_buf)];
1484 *(p++) = 'F';
1485 while (*fmt) {
1486 if (*fmt == '%') {
1487 fmt++;
1488 switch (*fmt++) {
1489 case 'x':
1490 addr = va_arg(va, target_ulong);
1491 p += snprintf(p, p_end - p, TARGET_FMT_lx, addr);
1492 break;
1493 case 'l':
1494 if (*(fmt++) != 'x')
1495 goto bad_format;
1496 i64 = va_arg(va, uint64_t);
1497 p += snprintf(p, p_end - p, "%" PRIx64, i64);
1498 break;
1499 case 's':
1500 addr = va_arg(va, target_ulong);
1501 p += snprintf(p, p_end - p, TARGET_FMT_lx "/%x",
1502 addr, va_arg(va, int));
1503 break;
1504 default:
1505 bad_format:
1506 error_report("gdbstub: Bad syscall format string '%s'",
1507 fmt - 1);
1508 break;
1510 } else {
1511 *(p++) = *(fmt++);
1514 *p = 0;
1515 #ifdef CONFIG_USER_ONLY
1516 put_packet(s, s->syscall_buf);
1517 gdb_handlesig(s->c_cpu, 0);
1518 #else
1519 /* In this case wait to send the syscall packet until notification that
1520 the CPU has stopped. This must be done because if the packet is sent
1521 now the reply from the syscall request could be received while the CPU
1522 is still in the running state, which can cause packets to be dropped
1523 and state transition 'T' packets to be sent while the syscall is still
1524 being processed. */
1525 qemu_cpu_kick(s->c_cpu);
1526 #endif
1529 void gdb_do_syscall(gdb_syscall_complete_cb cb, const char *fmt, ...)
1531 va_list va;
1533 va_start(va, fmt);
1534 gdb_do_syscallv(cb, fmt, va);
1535 va_end(va);
1538 static void gdb_read_byte(GDBState *s, int ch)
1540 uint8_t reply;
1542 #ifndef CONFIG_USER_ONLY
1543 if (s->last_packet_len) {
1544 /* Waiting for a response to the last packet. If we see the start
1545 of a new command then abandon the previous response. */
1546 if (ch == '-') {
1547 gdb_debug("Got NACK, retransmitting\n");
1548 put_buffer(s, (uint8_t *)s->last_packet, s->last_packet_len);
1549 } else if (ch == '+') {
1550 gdb_debug("Got ACK\n");
1551 } else {
1552 gdb_debug("Got '%c' when expecting ACK/NACK\n", ch);
1555 if (ch == '+' || ch == '$')
1556 s->last_packet_len = 0;
1557 if (ch != '$')
1558 return;
1560 if (runstate_is_running()) {
1561 /* when the CPU is running, we cannot do anything except stop
1562 it when receiving a char */
1563 vm_stop(RUN_STATE_PAUSED);
1564 } else
1565 #endif
1567 switch(s->state) {
1568 case RS_IDLE:
1569 if (ch == '$') {
1570 /* start of command packet */
1571 s->line_buf_index = 0;
1572 s->line_sum = 0;
1573 s->state = RS_GETLINE;
1574 } else {
1575 gdb_debug("received garbage between packets: 0x%x\n", ch);
1577 break;
1578 case RS_GETLINE:
1579 if (ch == '}') {
1580 /* start escape sequence */
1581 s->state = RS_GETLINE_ESC;
1582 s->line_sum += ch;
1583 } else if (ch == '*') {
1584 /* start run length encoding sequence */
1585 s->state = RS_GETLINE_RLE;
1586 s->line_sum += ch;
1587 } else if (ch == '#') {
1588 /* end of command, start of checksum*/
1589 s->state = RS_CHKSUM1;
1590 } else if (s->line_buf_index >= sizeof(s->line_buf) - 1) {
1591 gdb_debug("command buffer overrun, dropping command\n");
1592 s->state = RS_IDLE;
1593 } else {
1594 /* unescaped command character */
1595 s->line_buf[s->line_buf_index++] = ch;
1596 s->line_sum += ch;
1598 break;
1599 case RS_GETLINE_ESC:
1600 if (ch == '#') {
1601 /* unexpected end of command in escape sequence */
1602 s->state = RS_CHKSUM1;
1603 } else if (s->line_buf_index >= sizeof(s->line_buf) - 1) {
1604 /* command buffer overrun */
1605 gdb_debug("command buffer overrun, dropping command\n");
1606 s->state = RS_IDLE;
1607 } else {
1608 /* parse escaped character and leave escape state */
1609 s->line_buf[s->line_buf_index++] = ch ^ 0x20;
1610 s->line_sum += ch;
1611 s->state = RS_GETLINE;
1613 break;
1614 case RS_GETLINE_RLE:
1615 if (ch < ' ') {
1616 /* invalid RLE count encoding */
1617 gdb_debug("got invalid RLE count: 0x%x\n", ch);
1618 s->state = RS_GETLINE;
1619 } else {
1620 /* decode repeat length */
1621 int repeat = (unsigned char)ch - ' ' + 3;
1622 if (s->line_buf_index + repeat >= sizeof(s->line_buf) - 1) {
1623 /* that many repeats would overrun the command buffer */
1624 gdb_debug("command buffer overrun, dropping command\n");
1625 s->state = RS_IDLE;
1626 } else if (s->line_buf_index < 1) {
1627 /* got a repeat but we have nothing to repeat */
1628 gdb_debug("got invalid RLE sequence\n");
1629 s->state = RS_GETLINE;
1630 } else {
1631 /* repeat the last character */
1632 memset(s->line_buf + s->line_buf_index,
1633 s->line_buf[s->line_buf_index - 1], repeat);
1634 s->line_buf_index += repeat;
1635 s->line_sum += ch;
1636 s->state = RS_GETLINE;
1639 break;
1640 case RS_CHKSUM1:
1641 /* get high hex digit of checksum */
1642 if (!isxdigit(ch)) {
1643 gdb_debug("got invalid command checksum digit\n");
1644 s->state = RS_GETLINE;
1645 break;
1647 s->line_buf[s->line_buf_index] = '\0';
1648 s->line_csum = fromhex(ch) << 4;
1649 s->state = RS_CHKSUM2;
1650 break;
1651 case RS_CHKSUM2:
1652 /* get low hex digit of checksum */
1653 if (!isxdigit(ch)) {
1654 gdb_debug("got invalid command checksum digit\n");
1655 s->state = RS_GETLINE;
1656 break;
1658 s->line_csum |= fromhex(ch);
1660 if (s->line_csum != (s->line_sum & 0xff)) {
1661 gdb_debug("got command packet with incorrect checksum\n");
1662 /* send NAK reply */
1663 reply = '-';
1664 put_buffer(s, &reply, 1);
1665 s->state = RS_IDLE;
1666 } else {
1667 /* send ACK reply */
1668 reply = '+';
1669 put_buffer(s, &reply, 1);
1670 s->state = gdb_handle_packet(s, s->line_buf);
1672 break;
1673 default:
1674 abort();
1679 /* Tell the remote gdb that the process has exited. */
1680 void gdb_exit(CPUArchState *env, int code)
1682 GDBState *s;
1683 char buf[4];
1685 s = gdbserver_state;
1686 if (!s) {
1687 return;
1689 #ifdef CONFIG_USER_ONLY
1690 if (gdbserver_fd < 0 || s->fd < 0) {
1691 return;
1693 #endif
1695 snprintf(buf, sizeof(buf), "W%02x", (uint8_t)code);
1696 put_packet(s, buf);
1698 #ifndef CONFIG_USER_ONLY
1699 qemu_chr_fe_deinit(&s->chr, true);
1700 #endif
1703 #ifdef CONFIG_USER_ONLY
1705 gdb_handlesig(CPUState *cpu, int sig)
1707 GDBState *s;
1708 char buf[256];
1709 int n;
1711 s = gdbserver_state;
1712 if (gdbserver_fd < 0 || s->fd < 0) {
1713 return sig;
1716 /* disable single step if it was enabled */
1717 cpu_single_step(cpu, 0);
1718 tb_flush(cpu);
1720 if (sig != 0) {
1721 snprintf(buf, sizeof(buf), "S%02x", target_signal_to_gdb(sig));
1722 put_packet(s, buf);
1724 /* put_packet() might have detected that the peer terminated the
1725 connection. */
1726 if (s->fd < 0) {
1727 return sig;
1730 sig = 0;
1731 s->state = RS_IDLE;
1732 s->running_state = 0;
1733 while (s->running_state == 0) {
1734 n = read(s->fd, buf, 256);
1735 if (n > 0) {
1736 int i;
1738 for (i = 0; i < n; i++) {
1739 gdb_read_byte(s, buf[i]);
1741 } else {
1742 /* XXX: Connection closed. Should probably wait for another
1743 connection before continuing. */
1744 if (n == 0) {
1745 close(s->fd);
1747 s->fd = -1;
1748 return sig;
1751 sig = s->signal;
1752 s->signal = 0;
1753 return sig;
1756 /* Tell the remote gdb that the process has exited due to SIG. */
1757 void gdb_signalled(CPUArchState *env, int sig)
1759 GDBState *s;
1760 char buf[4];
1762 s = gdbserver_state;
1763 if (gdbserver_fd < 0 || s->fd < 0) {
1764 return;
1767 snprintf(buf, sizeof(buf), "X%02x", target_signal_to_gdb(sig));
1768 put_packet(s, buf);
1771 static void gdb_accept(void)
1773 GDBState *s;
1774 struct sockaddr_in sockaddr;
1775 socklen_t len;
1776 int fd;
1778 for(;;) {
1779 len = sizeof(sockaddr);
1780 fd = accept(gdbserver_fd, (struct sockaddr *)&sockaddr, &len);
1781 if (fd < 0 && errno != EINTR) {
1782 perror("accept");
1783 return;
1784 } else if (fd >= 0) {
1785 #ifndef _WIN32
1786 fcntl(fd, F_SETFD, FD_CLOEXEC);
1787 #endif
1788 break;
1792 /* set short latency */
1793 socket_set_nodelay(fd);
1795 s = g_malloc0(sizeof(GDBState));
1796 s->c_cpu = first_cpu;
1797 s->g_cpu = first_cpu;
1798 s->fd = fd;
1799 gdb_has_xml = false;
1801 gdbserver_state = s;
1804 static int gdbserver_open(int port)
1806 struct sockaddr_in sockaddr;
1807 int fd, ret;
1809 fd = socket(PF_INET, SOCK_STREAM, 0);
1810 if (fd < 0) {
1811 perror("socket");
1812 return -1;
1814 #ifndef _WIN32
1815 fcntl(fd, F_SETFD, FD_CLOEXEC);
1816 #endif
1818 socket_set_fast_reuse(fd);
1820 sockaddr.sin_family = AF_INET;
1821 sockaddr.sin_port = htons(port);
1822 sockaddr.sin_addr.s_addr = 0;
1823 ret = bind(fd, (struct sockaddr *)&sockaddr, sizeof(sockaddr));
1824 if (ret < 0) {
1825 perror("bind");
1826 close(fd);
1827 return -1;
1829 ret = listen(fd, 1);
1830 if (ret < 0) {
1831 perror("listen");
1832 close(fd);
1833 return -1;
1835 return fd;
1838 int gdbserver_start(int port)
1840 gdbserver_fd = gdbserver_open(port);
1841 if (gdbserver_fd < 0)
1842 return -1;
1843 /* accept connections */
1844 gdb_accept();
1845 return 0;
1848 /* Disable gdb stub for child processes. */
1849 void gdbserver_fork(CPUState *cpu)
1851 GDBState *s = gdbserver_state;
1853 if (gdbserver_fd < 0 || s->fd < 0) {
1854 return;
1856 close(s->fd);
1857 s->fd = -1;
1858 cpu_breakpoint_remove_all(cpu, BP_GDB);
1859 cpu_watchpoint_remove_all(cpu, BP_GDB);
1861 #else
1862 static int gdb_chr_can_receive(void *opaque)
1864 /* We can handle an arbitrarily large amount of data.
1865 Pick the maximum packet size, which is as good as anything. */
1866 return MAX_PACKET_LENGTH;
1869 static void gdb_chr_receive(void *opaque, const uint8_t *buf, int size)
1871 int i;
1873 for (i = 0; i < size; i++) {
1874 gdb_read_byte(gdbserver_state, buf[i]);
1878 static void gdb_chr_event(void *opaque, int event)
1880 switch (event) {
1881 case CHR_EVENT_OPENED:
1882 vm_stop(RUN_STATE_PAUSED);
1883 gdb_has_xml = false;
1884 break;
1885 default:
1886 break;
1890 static void gdb_monitor_output(GDBState *s, const char *msg, int len)
1892 char buf[MAX_PACKET_LENGTH];
1894 buf[0] = 'O';
1895 if (len > (MAX_PACKET_LENGTH/2) - 1)
1896 len = (MAX_PACKET_LENGTH/2) - 1;
1897 memtohex(buf + 1, (uint8_t *)msg, len);
1898 put_packet(s, buf);
1901 static int gdb_monitor_write(Chardev *chr, const uint8_t *buf, int len)
1903 const char *p = (const char *)buf;
1904 int max_sz;
1906 max_sz = (sizeof(gdbserver_state->last_packet) - 2) / 2;
1907 for (;;) {
1908 if (len <= max_sz) {
1909 gdb_monitor_output(gdbserver_state, p, len);
1910 break;
1912 gdb_monitor_output(gdbserver_state, p, max_sz);
1913 p += max_sz;
1914 len -= max_sz;
1916 return len;
1919 #ifndef _WIN32
1920 static void gdb_sigterm_handler(int signal)
1922 if (runstate_is_running()) {
1923 vm_stop(RUN_STATE_PAUSED);
1926 #endif
1928 static void gdb_monitor_open(Chardev *chr, ChardevBackend *backend,
1929 bool *be_opened, Error **errp)
1931 *be_opened = false;
1934 static void char_gdb_class_init(ObjectClass *oc, void *data)
1936 ChardevClass *cc = CHARDEV_CLASS(oc);
1938 cc->internal = true;
1939 cc->open = gdb_monitor_open;
1940 cc->chr_write = gdb_monitor_write;
1943 #define TYPE_CHARDEV_GDB "chardev-gdb"
1945 static const TypeInfo char_gdb_type_info = {
1946 .name = TYPE_CHARDEV_GDB,
1947 .parent = TYPE_CHARDEV,
1948 .class_init = char_gdb_class_init,
1951 int gdbserver_start(const char *device)
1953 GDBState *s;
1954 char gdbstub_device_name[128];
1955 Chardev *chr = NULL;
1956 Chardev *mon_chr;
1958 if (!first_cpu) {
1959 error_report("gdbstub: meaningless to attach gdb to a "
1960 "machine without any CPU.");
1961 return -1;
1964 if (!device)
1965 return -1;
1966 if (strcmp(device, "none") != 0) {
1967 if (strstart(device, "tcp:", NULL)) {
1968 /* enforce required TCP attributes */
1969 snprintf(gdbstub_device_name, sizeof(gdbstub_device_name),
1970 "%s,nowait,nodelay,server", device);
1971 device = gdbstub_device_name;
1973 #ifndef _WIN32
1974 else if (strcmp(device, "stdio") == 0) {
1975 struct sigaction act;
1977 memset(&act, 0, sizeof(act));
1978 act.sa_handler = gdb_sigterm_handler;
1979 sigaction(SIGINT, &act, NULL);
1981 #endif
1982 chr = qemu_chr_new_noreplay("gdb", device);
1983 if (!chr)
1984 return -1;
1987 s = gdbserver_state;
1988 if (!s) {
1989 s = g_malloc0(sizeof(GDBState));
1990 gdbserver_state = s;
1992 qemu_add_vm_change_state_handler(gdb_vm_state_change, NULL);
1994 /* Initialize a monitor terminal for gdb */
1995 mon_chr = qemu_chardev_new(NULL, TYPE_CHARDEV_GDB,
1996 NULL, &error_abort);
1997 monitor_init(mon_chr, 0);
1998 } else {
1999 qemu_chr_fe_deinit(&s->chr, true);
2000 mon_chr = s->mon_chr;
2001 memset(s, 0, sizeof(GDBState));
2002 s->mon_chr = mon_chr;
2004 s->c_cpu = first_cpu;
2005 s->g_cpu = first_cpu;
2006 if (chr) {
2007 qemu_chr_fe_init(&s->chr, chr, &error_abort);
2008 qemu_chr_fe_set_handlers(&s->chr, gdb_chr_can_receive, gdb_chr_receive,
2009 gdb_chr_event, NULL, NULL, NULL, true);
2011 s->state = chr ? RS_IDLE : RS_INACTIVE;
2012 s->mon_chr = mon_chr;
2013 s->current_syscall_cb = NULL;
2015 return 0;
2018 static void register_types(void)
2020 type_register_static(&char_gdb_type_info);
2023 type_init(register_types);
2024 #endif