usb: dev-mtp: fix memory leak in error path
[qemu/ar7.git] / gdbstub.c
blobc4e4f9f08219ddfd6be5dfe28d50d171bff987d4
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 "trace-root.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 TaskState *ts = (TaskState *) cpu->opaque;
68 return ts->ts_tid;
69 #else
70 return cpu->cpu_index + 1;
71 #endif
74 enum {
75 GDB_SIGNAL_0 = 0,
76 GDB_SIGNAL_INT = 2,
77 GDB_SIGNAL_QUIT = 3,
78 GDB_SIGNAL_TRAP = 5,
79 GDB_SIGNAL_ABRT = 6,
80 GDB_SIGNAL_ALRM = 14,
81 GDB_SIGNAL_IO = 23,
82 GDB_SIGNAL_XCPU = 24,
83 GDB_SIGNAL_UNKNOWN = 143
86 #ifdef CONFIG_USER_ONLY
88 /* Map target signal numbers to GDB protocol signal numbers and vice
89 * versa. For user emulation's currently supported systems, we can
90 * assume most signals are defined.
93 static int gdb_signal_table[] = {
95 TARGET_SIGHUP,
96 TARGET_SIGINT,
97 TARGET_SIGQUIT,
98 TARGET_SIGILL,
99 TARGET_SIGTRAP,
100 TARGET_SIGABRT,
101 -1, /* SIGEMT */
102 TARGET_SIGFPE,
103 TARGET_SIGKILL,
104 TARGET_SIGBUS,
105 TARGET_SIGSEGV,
106 TARGET_SIGSYS,
107 TARGET_SIGPIPE,
108 TARGET_SIGALRM,
109 TARGET_SIGTERM,
110 TARGET_SIGURG,
111 TARGET_SIGSTOP,
112 TARGET_SIGTSTP,
113 TARGET_SIGCONT,
114 TARGET_SIGCHLD,
115 TARGET_SIGTTIN,
116 TARGET_SIGTTOU,
117 TARGET_SIGIO,
118 TARGET_SIGXCPU,
119 TARGET_SIGXFSZ,
120 TARGET_SIGVTALRM,
121 TARGET_SIGPROF,
122 TARGET_SIGWINCH,
123 -1, /* SIGLOST */
124 TARGET_SIGUSR1,
125 TARGET_SIGUSR2,
126 #ifdef TARGET_SIGPWR
127 TARGET_SIGPWR,
128 #else
130 #endif
131 -1, /* SIGPOLL */
143 #ifdef __SIGRTMIN
144 __SIGRTMIN + 1,
145 __SIGRTMIN + 2,
146 __SIGRTMIN + 3,
147 __SIGRTMIN + 4,
148 __SIGRTMIN + 5,
149 __SIGRTMIN + 6,
150 __SIGRTMIN + 7,
151 __SIGRTMIN + 8,
152 __SIGRTMIN + 9,
153 __SIGRTMIN + 10,
154 __SIGRTMIN + 11,
155 __SIGRTMIN + 12,
156 __SIGRTMIN + 13,
157 __SIGRTMIN + 14,
158 __SIGRTMIN + 15,
159 __SIGRTMIN + 16,
160 __SIGRTMIN + 17,
161 __SIGRTMIN + 18,
162 __SIGRTMIN + 19,
163 __SIGRTMIN + 20,
164 __SIGRTMIN + 21,
165 __SIGRTMIN + 22,
166 __SIGRTMIN + 23,
167 __SIGRTMIN + 24,
168 __SIGRTMIN + 25,
169 __SIGRTMIN + 26,
170 __SIGRTMIN + 27,
171 __SIGRTMIN + 28,
172 __SIGRTMIN + 29,
173 __SIGRTMIN + 30,
174 __SIGRTMIN + 31,
175 -1, /* SIGCANCEL */
176 __SIGRTMIN,
177 __SIGRTMIN + 32,
178 __SIGRTMIN + 33,
179 __SIGRTMIN + 34,
180 __SIGRTMIN + 35,
181 __SIGRTMIN + 36,
182 __SIGRTMIN + 37,
183 __SIGRTMIN + 38,
184 __SIGRTMIN + 39,
185 __SIGRTMIN + 40,
186 __SIGRTMIN + 41,
187 __SIGRTMIN + 42,
188 __SIGRTMIN + 43,
189 __SIGRTMIN + 44,
190 __SIGRTMIN + 45,
191 __SIGRTMIN + 46,
192 __SIGRTMIN + 47,
193 __SIGRTMIN + 48,
194 __SIGRTMIN + 49,
195 __SIGRTMIN + 50,
196 __SIGRTMIN + 51,
197 __SIGRTMIN + 52,
198 __SIGRTMIN + 53,
199 __SIGRTMIN + 54,
200 __SIGRTMIN + 55,
201 __SIGRTMIN + 56,
202 __SIGRTMIN + 57,
203 __SIGRTMIN + 58,
204 __SIGRTMIN + 59,
205 __SIGRTMIN + 60,
206 __SIGRTMIN + 61,
207 __SIGRTMIN + 62,
208 __SIGRTMIN + 63,
209 __SIGRTMIN + 64,
210 __SIGRTMIN + 65,
211 __SIGRTMIN + 66,
212 __SIGRTMIN + 67,
213 __SIGRTMIN + 68,
214 __SIGRTMIN + 69,
215 __SIGRTMIN + 70,
216 __SIGRTMIN + 71,
217 __SIGRTMIN + 72,
218 __SIGRTMIN + 73,
219 __SIGRTMIN + 74,
220 __SIGRTMIN + 75,
221 __SIGRTMIN + 76,
222 __SIGRTMIN + 77,
223 __SIGRTMIN + 78,
224 __SIGRTMIN + 79,
225 __SIGRTMIN + 80,
226 __SIGRTMIN + 81,
227 __SIGRTMIN + 82,
228 __SIGRTMIN + 83,
229 __SIGRTMIN + 84,
230 __SIGRTMIN + 85,
231 __SIGRTMIN + 86,
232 __SIGRTMIN + 87,
233 __SIGRTMIN + 88,
234 __SIGRTMIN + 89,
235 __SIGRTMIN + 90,
236 __SIGRTMIN + 91,
237 __SIGRTMIN + 92,
238 __SIGRTMIN + 93,
239 __SIGRTMIN + 94,
240 __SIGRTMIN + 95,
241 -1, /* SIGINFO */
242 -1, /* UNKNOWN */
243 -1, /* DEFAULT */
250 #endif
252 #else
253 /* In system mode we only need SIGINT and SIGTRAP; other signals
254 are not yet supported. */
256 enum {
257 TARGET_SIGINT = 2,
258 TARGET_SIGTRAP = 5
261 static int gdb_signal_table[] = {
264 TARGET_SIGINT,
267 TARGET_SIGTRAP
269 #endif
271 #ifdef CONFIG_USER_ONLY
272 static int target_signal_to_gdb (int sig)
274 int i;
275 for (i = 0; i < ARRAY_SIZE (gdb_signal_table); i++)
276 if (gdb_signal_table[i] == sig)
277 return i;
278 return GDB_SIGNAL_UNKNOWN;
280 #endif
282 static int gdb_signal_to_target (int sig)
284 if (sig < ARRAY_SIZE (gdb_signal_table))
285 return gdb_signal_table[sig];
286 else
287 return -1;
290 typedef struct GDBRegisterState {
291 int base_reg;
292 int num_regs;
293 gdb_reg_cb get_reg;
294 gdb_reg_cb set_reg;
295 const char *xml;
296 struct GDBRegisterState *next;
297 } GDBRegisterState;
299 enum RSState {
300 RS_INACTIVE,
301 RS_IDLE,
302 RS_GETLINE,
303 RS_GETLINE_ESC,
304 RS_GETLINE_RLE,
305 RS_CHKSUM1,
306 RS_CHKSUM2,
308 typedef struct GDBState {
309 CPUState *c_cpu; /* current CPU for step/continue ops */
310 CPUState *g_cpu; /* current CPU for other ops */
311 CPUState *query_cpu; /* for q{f|s}ThreadInfo */
312 enum RSState state; /* parsing state */
313 char line_buf[MAX_PACKET_LENGTH];
314 int line_buf_index;
315 int line_sum; /* running checksum */
316 int line_csum; /* checksum at the end of the packet */
317 uint8_t last_packet[MAX_PACKET_LENGTH + 4];
318 int last_packet_len;
319 int signal;
320 #ifdef CONFIG_USER_ONLY
321 int fd;
322 int running_state;
323 #else
324 CharBackend chr;
325 Chardev *mon_chr;
326 #endif
327 char syscall_buf[256];
328 gdb_syscall_complete_cb current_syscall_cb;
329 } GDBState;
331 /* By default use no IRQs and no timers while single stepping so as to
332 * make single stepping like an ICE HW step.
334 static int sstep_flags = SSTEP_ENABLE|SSTEP_NOIRQ|SSTEP_NOTIMER;
336 static GDBState *gdbserver_state;
338 bool gdb_has_xml;
340 #ifdef CONFIG_USER_ONLY
341 /* XXX: This is not thread safe. Do we care? */
342 static int gdbserver_fd = -1;
344 static int get_char(GDBState *s)
346 uint8_t ch;
347 int ret;
349 for(;;) {
350 ret = qemu_recv(s->fd, &ch, 1, 0);
351 if (ret < 0) {
352 if (errno == ECONNRESET)
353 s->fd = -1;
354 if (errno != EINTR)
355 return -1;
356 } else if (ret == 0) {
357 close(s->fd);
358 s->fd = -1;
359 return -1;
360 } else {
361 break;
364 return ch;
366 #endif
368 static enum {
369 GDB_SYS_UNKNOWN,
370 GDB_SYS_ENABLED,
371 GDB_SYS_DISABLED,
372 } gdb_syscall_mode;
374 /* Decide if either remote gdb syscalls or native file IO should be used. */
375 int use_gdb_syscalls(void)
377 SemihostingTarget target = semihosting_get_target();
378 if (target == SEMIHOSTING_TARGET_NATIVE) {
379 /* -semihosting-config target=native */
380 return false;
381 } else if (target == SEMIHOSTING_TARGET_GDB) {
382 /* -semihosting-config target=gdb */
383 return true;
386 /* -semihosting-config target=auto */
387 /* On the first call check if gdb is connected and remember. */
388 if (gdb_syscall_mode == GDB_SYS_UNKNOWN) {
389 gdb_syscall_mode = (gdbserver_state ? GDB_SYS_ENABLED
390 : GDB_SYS_DISABLED);
392 return gdb_syscall_mode == GDB_SYS_ENABLED;
395 /* Resume execution. */
396 static inline void gdb_continue(GDBState *s)
399 #ifdef CONFIG_USER_ONLY
400 s->running_state = 1;
401 trace_gdbstub_op_continue();
402 #else
403 if (!runstate_needs_reset()) {
404 trace_gdbstub_op_continue();
405 vm_start();
407 #endif
411 * Resume execution, per CPU actions. For user-mode emulation it's
412 * equivalent to gdb_continue.
414 static int gdb_continue_partial(GDBState *s, char *newstates)
416 CPUState *cpu;
417 int res = 0;
418 #ifdef CONFIG_USER_ONLY
420 * This is not exactly accurate, but it's an improvement compared to the
421 * previous situation, where only one CPU would be single-stepped.
423 CPU_FOREACH(cpu) {
424 if (newstates[cpu->cpu_index] == 's') {
425 trace_gdbstub_op_stepping(cpu->cpu_index);
426 cpu_single_step(cpu, sstep_flags);
429 s->running_state = 1;
430 #else
431 int flag = 0;
433 if (!runstate_needs_reset()) {
434 if (vm_prepare_start()) {
435 return 0;
438 CPU_FOREACH(cpu) {
439 switch (newstates[cpu->cpu_index]) {
440 case 0:
441 case 1:
442 break; /* nothing to do here */
443 case 's':
444 trace_gdbstub_op_stepping(cpu->cpu_index);
445 cpu_single_step(cpu, sstep_flags);
446 cpu_resume(cpu);
447 flag = 1;
448 break;
449 case 'c':
450 trace_gdbstub_op_continue_cpu(cpu->cpu_index);
451 cpu_resume(cpu);
452 flag = 1;
453 break;
454 default:
455 res = -1;
456 break;
460 if (flag) {
461 qemu_clock_enable(QEMU_CLOCK_VIRTUAL, true);
463 #endif
464 return res;
467 static void put_buffer(GDBState *s, const uint8_t *buf, int len)
469 #ifdef CONFIG_USER_ONLY
470 int ret;
472 while (len > 0) {
473 ret = send(s->fd, buf, len, 0);
474 if (ret < 0) {
475 if (errno != EINTR)
476 return;
477 } else {
478 buf += ret;
479 len -= ret;
482 #else
483 /* XXX this blocks entire thread. Rewrite to use
484 * qemu_chr_fe_write and background I/O callbacks */
485 qemu_chr_fe_write_all(&s->chr, buf, len);
486 #endif
489 static inline int fromhex(int v)
491 if (v >= '0' && v <= '9')
492 return v - '0';
493 else if (v >= 'A' && v <= 'F')
494 return v - 'A' + 10;
495 else if (v >= 'a' && v <= 'f')
496 return v - 'a' + 10;
497 else
498 return 0;
501 static inline int tohex(int v)
503 if (v < 10)
504 return v + '0';
505 else
506 return v - 10 + 'a';
509 /* writes 2*len+1 bytes in buf */
510 static void memtohex(char *buf, const uint8_t *mem, int len)
512 int i, c;
513 char *q;
514 q = buf;
515 for(i = 0; i < len; i++) {
516 c = mem[i];
517 *q++ = tohex(c >> 4);
518 *q++ = tohex(c & 0xf);
520 *q = '\0';
523 static void hextomem(uint8_t *mem, const char *buf, int len)
525 int i;
527 for(i = 0; i < len; i++) {
528 mem[i] = (fromhex(buf[0]) << 4) | fromhex(buf[1]);
529 buf += 2;
533 static void hexdump(const char *buf, int len,
534 void (*trace_fn)(size_t ofs, char const *text))
536 char line_buffer[3 * 16 + 4 + 16 + 1];
538 size_t i;
539 for (i = 0; i < len || (i & 0xF); ++i) {
540 size_t byte_ofs = i & 15;
542 if (byte_ofs == 0) {
543 memset(line_buffer, ' ', 3 * 16 + 4 + 16);
544 line_buffer[3 * 16 + 4 + 16] = 0;
547 size_t col_group = (i >> 2) & 3;
548 size_t hex_col = byte_ofs * 3 + col_group;
549 size_t txt_col = 3 * 16 + 4 + byte_ofs;
551 if (i < len) {
552 char value = buf[i];
554 line_buffer[hex_col + 0] = tohex((value >> 4) & 0xF);
555 line_buffer[hex_col + 1] = tohex((value >> 0) & 0xF);
556 line_buffer[txt_col + 0] = (value >= ' ' && value < 127)
557 ? value
558 : '.';
561 if (byte_ofs == 0xF)
562 trace_fn(i & -16, line_buffer);
566 /* return -1 if error, 0 if OK */
567 static int put_packet_binary(GDBState *s, const char *buf, int len, bool dump)
569 int csum, i;
570 uint8_t *p;
572 if (dump && trace_event_get_state_backends(TRACE_GDBSTUB_IO_BINARYREPLY)) {
573 hexdump(buf, len, trace_gdbstub_io_binaryreply);
576 for(;;) {
577 p = s->last_packet;
578 *(p++) = '$';
579 memcpy(p, buf, len);
580 p += len;
581 csum = 0;
582 for(i = 0; i < len; i++) {
583 csum += buf[i];
585 *(p++) = '#';
586 *(p++) = tohex((csum >> 4) & 0xf);
587 *(p++) = tohex((csum) & 0xf);
589 s->last_packet_len = p - s->last_packet;
590 put_buffer(s, (uint8_t *)s->last_packet, s->last_packet_len);
592 #ifdef CONFIG_USER_ONLY
593 i = get_char(s);
594 if (i < 0)
595 return -1;
596 if (i == '+')
597 break;
598 #else
599 break;
600 #endif
602 return 0;
605 /* return -1 if error, 0 if OK */
606 static int put_packet(GDBState *s, const char *buf)
608 trace_gdbstub_io_reply(buf);
610 return put_packet_binary(s, buf, strlen(buf), false);
613 /* Encode data using the encoding for 'x' packets. */
614 static int memtox(char *buf, const char *mem, int len)
616 char *p = buf;
617 char c;
619 while (len--) {
620 c = *(mem++);
621 switch (c) {
622 case '#': case '$': case '*': case '}':
623 *(p++) = '}';
624 *(p++) = c ^ 0x20;
625 break;
626 default:
627 *(p++) = c;
628 break;
631 return p - buf;
634 static const char *get_feature_xml(const char *p, const char **newp,
635 CPUClass *cc)
637 size_t len;
638 int i;
639 const char *name;
640 static char target_xml[1024];
642 len = 0;
643 while (p[len] && p[len] != ':')
644 len++;
645 *newp = p + len;
647 name = NULL;
648 if (strncmp(p, "target.xml", len) == 0) {
649 /* Generate the XML description for this CPU. */
650 if (!target_xml[0]) {
651 GDBRegisterState *r;
652 CPUState *cpu = first_cpu;
654 pstrcat(target_xml, sizeof(target_xml),
655 "<?xml version=\"1.0\"?>"
656 "<!DOCTYPE target SYSTEM \"gdb-target.dtd\">"
657 "<target>");
658 if (cc->gdb_arch_name) {
659 gchar *arch = cc->gdb_arch_name(cpu);
660 pstrcat(target_xml, sizeof(target_xml), "<architecture>");
661 pstrcat(target_xml, sizeof(target_xml), arch);
662 pstrcat(target_xml, sizeof(target_xml), "</architecture>");
663 g_free(arch);
665 pstrcat(target_xml, sizeof(target_xml), "<xi:include href=\"");
666 pstrcat(target_xml, sizeof(target_xml), cc->gdb_core_xml_file);
667 pstrcat(target_xml, sizeof(target_xml), "\"/>");
668 for (r = cpu->gdb_regs; r; r = r->next) {
669 pstrcat(target_xml, sizeof(target_xml), "<xi:include href=\"");
670 pstrcat(target_xml, sizeof(target_xml), r->xml);
671 pstrcat(target_xml, sizeof(target_xml), "\"/>");
673 pstrcat(target_xml, sizeof(target_xml), "</target>");
675 return target_xml;
677 if (cc->gdb_get_dynamic_xml) {
678 CPUState *cpu = first_cpu;
679 char *xmlname = g_strndup(p, len);
680 const char *xml = cc->gdb_get_dynamic_xml(cpu, xmlname);
682 g_free(xmlname);
683 if (xml) {
684 return xml;
687 for (i = 0; ; i++) {
688 name = xml_builtin[i][0];
689 if (!name || (strncmp(name, p, len) == 0 && strlen(name) == len))
690 break;
692 return name ? xml_builtin[i][1] : NULL;
695 static int gdb_read_register(CPUState *cpu, uint8_t *mem_buf, int reg)
697 CPUClass *cc = CPU_GET_CLASS(cpu);
698 CPUArchState *env = cpu->env_ptr;
699 GDBRegisterState *r;
701 if (reg < cc->gdb_num_core_regs) {
702 return cc->gdb_read_register(cpu, mem_buf, reg);
705 for (r = cpu->gdb_regs; r; r = r->next) {
706 if (r->base_reg <= reg && reg < r->base_reg + r->num_regs) {
707 return r->get_reg(env, mem_buf, reg - r->base_reg);
710 return 0;
713 static int gdb_write_register(CPUState *cpu, uint8_t *mem_buf, int reg)
715 CPUClass *cc = CPU_GET_CLASS(cpu);
716 CPUArchState *env = cpu->env_ptr;
717 GDBRegisterState *r;
719 if (reg < cc->gdb_num_core_regs) {
720 return cc->gdb_write_register(cpu, mem_buf, reg);
723 for (r = cpu->gdb_regs; r; r = r->next) {
724 if (r->base_reg <= reg && reg < r->base_reg + r->num_regs) {
725 return r->set_reg(env, mem_buf, reg - r->base_reg);
728 return 0;
731 /* Register a supplemental set of CPU registers. If g_pos is nonzero it
732 specifies the first register number and these registers are included in
733 a standard "g" packet. Direction is relative to gdb, i.e. get_reg is
734 gdb reading a CPU register, and set_reg is gdb modifying a CPU register.
737 void gdb_register_coprocessor(CPUState *cpu,
738 gdb_reg_cb get_reg, gdb_reg_cb set_reg,
739 int num_regs, const char *xml, int g_pos)
741 GDBRegisterState *s;
742 GDBRegisterState **p;
744 p = &cpu->gdb_regs;
745 while (*p) {
746 /* Check for duplicates. */
747 if (strcmp((*p)->xml, xml) == 0)
748 return;
749 p = &(*p)->next;
752 s = g_new0(GDBRegisterState, 1);
753 s->base_reg = cpu->gdb_num_regs;
754 s->num_regs = num_regs;
755 s->get_reg = get_reg;
756 s->set_reg = set_reg;
757 s->xml = xml;
759 /* Add to end of list. */
760 cpu->gdb_num_regs += num_regs;
761 *p = s;
762 if (g_pos) {
763 if (g_pos != s->base_reg) {
764 error_report("Error: Bad gdb register numbering for '%s', "
765 "expected %d got %d", xml, g_pos, s->base_reg);
766 } else {
767 cpu->gdb_num_g_regs = cpu->gdb_num_regs;
772 #ifndef CONFIG_USER_ONLY
773 /* Translate GDB watchpoint type to a flags value for cpu_watchpoint_* */
774 static inline int xlat_gdb_type(CPUState *cpu, int gdbtype)
776 static const int xlat[] = {
777 [GDB_WATCHPOINT_WRITE] = BP_GDB | BP_MEM_WRITE,
778 [GDB_WATCHPOINT_READ] = BP_GDB | BP_MEM_READ,
779 [GDB_WATCHPOINT_ACCESS] = BP_GDB | BP_MEM_ACCESS,
782 CPUClass *cc = CPU_GET_CLASS(cpu);
783 int cputype = xlat[gdbtype];
785 if (cc->gdb_stop_before_watchpoint) {
786 cputype |= BP_STOP_BEFORE_ACCESS;
788 return cputype;
790 #endif
792 static int gdb_breakpoint_insert(target_ulong addr, target_ulong len, int type)
794 CPUState *cpu;
795 int err = 0;
797 if (kvm_enabled()) {
798 return kvm_insert_breakpoint(gdbserver_state->c_cpu, addr, len, type);
801 switch (type) {
802 case GDB_BREAKPOINT_SW:
803 case GDB_BREAKPOINT_HW:
804 CPU_FOREACH(cpu) {
805 err = cpu_breakpoint_insert(cpu, addr, BP_GDB, NULL);
806 if (err) {
807 break;
810 return err;
811 #ifndef CONFIG_USER_ONLY
812 case GDB_WATCHPOINT_WRITE:
813 case GDB_WATCHPOINT_READ:
814 case GDB_WATCHPOINT_ACCESS:
815 CPU_FOREACH(cpu) {
816 err = cpu_watchpoint_insert(cpu, addr, len,
817 xlat_gdb_type(cpu, type), NULL);
818 if (err) {
819 break;
822 return err;
823 #endif
824 default:
825 return -ENOSYS;
829 static int gdb_breakpoint_remove(target_ulong addr, target_ulong len, int type)
831 CPUState *cpu;
832 int err = 0;
834 if (kvm_enabled()) {
835 return kvm_remove_breakpoint(gdbserver_state->c_cpu, addr, len, type);
838 switch (type) {
839 case GDB_BREAKPOINT_SW:
840 case GDB_BREAKPOINT_HW:
841 CPU_FOREACH(cpu) {
842 err = cpu_breakpoint_remove(cpu, addr, BP_GDB);
843 if (err) {
844 break;
847 return err;
848 #ifndef CONFIG_USER_ONLY
849 case GDB_WATCHPOINT_WRITE:
850 case GDB_WATCHPOINT_READ:
851 case GDB_WATCHPOINT_ACCESS:
852 CPU_FOREACH(cpu) {
853 err = cpu_watchpoint_remove(cpu, addr, len,
854 xlat_gdb_type(cpu, type));
855 if (err)
856 break;
858 return err;
859 #endif
860 default:
861 return -ENOSYS;
865 static void gdb_breakpoint_remove_all(void)
867 CPUState *cpu;
869 if (kvm_enabled()) {
870 kvm_remove_all_breakpoints(gdbserver_state->c_cpu);
871 return;
874 CPU_FOREACH(cpu) {
875 cpu_breakpoint_remove_all(cpu, BP_GDB);
876 #ifndef CONFIG_USER_ONLY
877 cpu_watchpoint_remove_all(cpu, BP_GDB);
878 #endif
882 static void gdb_set_cpu_pc(GDBState *s, target_ulong pc)
884 CPUState *cpu = s->c_cpu;
886 cpu_synchronize_state(cpu);
887 cpu_set_pc(cpu, pc);
890 static CPUState *find_cpu(uint32_t thread_id)
892 CPUState *cpu;
894 CPU_FOREACH(cpu) {
895 if (cpu_gdb_index(cpu) == thread_id) {
896 return cpu;
900 return NULL;
903 static int is_query_packet(const char *p, const char *query, char separator)
905 unsigned int query_len = strlen(query);
907 return strncmp(p, query, query_len) == 0 &&
908 (p[query_len] == '\0' || p[query_len] == separator);
912 * gdb_handle_vcont - Parses and handles a vCont packet.
913 * returns -ENOTSUP if a command is unsupported, -EINVAL or -ERANGE if there is
914 * a format error, 0 on success.
916 static int gdb_handle_vcont(GDBState *s, const char *p)
918 int res, idx, signal = 0;
919 char cur_action;
920 char *newstates;
921 unsigned long tmp;
922 CPUState *cpu;
923 #ifdef CONFIG_USER_ONLY
924 int max_cpus = 1; /* global variable max_cpus exists only in system mode */
926 CPU_FOREACH(cpu) {
927 max_cpus = max_cpus <= cpu->cpu_index ? cpu->cpu_index + 1 : max_cpus;
929 #endif
930 /* uninitialised CPUs stay 0 */
931 newstates = g_new0(char, max_cpus);
933 /* mark valid CPUs with 1 */
934 CPU_FOREACH(cpu) {
935 newstates[cpu->cpu_index] = 1;
939 * res keeps track of what error we are returning, with -ENOTSUP meaning
940 * that the command is unknown or unsupported, thus returning an empty
941 * packet, while -EINVAL and -ERANGE cause an E22 packet, due to invalid,
942 * or incorrect parameters passed.
944 res = 0;
945 while (*p) {
946 if (*p++ != ';') {
947 res = -ENOTSUP;
948 goto out;
951 cur_action = *p++;
952 if (cur_action == 'C' || cur_action == 'S') {
953 cur_action = qemu_tolower(cur_action);
954 res = qemu_strtoul(p + 1, &p, 16, &tmp);
955 if (res) {
956 goto out;
958 signal = gdb_signal_to_target(tmp);
959 } else if (cur_action != 'c' && cur_action != 's') {
960 /* unknown/invalid/unsupported command */
961 res = -ENOTSUP;
962 goto out;
964 /* thread specification. special values: (none), -1 = all; 0 = any */
965 if ((p[0] == ':' && p[1] == '-' && p[2] == '1') || (p[0] != ':')) {
966 if (*p == ':') {
967 p += 3;
969 for (idx = 0; idx < max_cpus; idx++) {
970 if (newstates[idx] == 1) {
971 newstates[idx] = cur_action;
974 } else if (*p == ':') {
975 p++;
976 res = qemu_strtoul(p, &p, 16, &tmp);
977 if (res) {
978 goto out;
981 /* 0 means any thread, so we pick the first valid CPU */
982 cpu = tmp ? find_cpu(tmp) : first_cpu;
984 /* invalid CPU/thread specified */
985 if (!cpu) {
986 res = -EINVAL;
987 goto out;
990 /* only use if no previous match occourred */
991 if (newstates[cpu->cpu_index] == 1) {
992 newstates[cpu->cpu_index] = cur_action;
996 s->signal = signal;
997 gdb_continue_partial(s, newstates);
999 out:
1000 g_free(newstates);
1002 return res;
1005 static int gdb_handle_packet(GDBState *s, const char *line_buf)
1007 CPUState *cpu;
1008 CPUClass *cc;
1009 const char *p;
1010 uint32_t thread;
1011 int ch, reg_size, type, res;
1012 uint8_t mem_buf[MAX_PACKET_LENGTH];
1013 char buf[sizeof(mem_buf) + 1 /* trailing NUL */];
1014 uint8_t *registers;
1015 target_ulong addr, len;
1017 trace_gdbstub_io_command(line_buf);
1019 p = line_buf;
1020 ch = *p++;
1021 switch(ch) {
1022 case '?':
1023 /* TODO: Make this return the correct value for user-mode. */
1024 snprintf(buf, sizeof(buf), "T%02xthread:%02x;", GDB_SIGNAL_TRAP,
1025 cpu_gdb_index(s->c_cpu));
1026 put_packet(s, buf);
1027 /* Remove all the breakpoints when this query is issued,
1028 * because gdb is doing and initial connect and the state
1029 * should be cleaned up.
1031 gdb_breakpoint_remove_all();
1032 break;
1033 case 'c':
1034 if (*p != '\0') {
1035 addr = strtoull(p, (char **)&p, 16);
1036 gdb_set_cpu_pc(s, addr);
1038 s->signal = 0;
1039 gdb_continue(s);
1040 return RS_IDLE;
1041 case 'C':
1042 s->signal = gdb_signal_to_target (strtoul(p, (char **)&p, 16));
1043 if (s->signal == -1)
1044 s->signal = 0;
1045 gdb_continue(s);
1046 return RS_IDLE;
1047 case 'v':
1048 if (strncmp(p, "Cont", 4) == 0) {
1049 p += 4;
1050 if (*p == '?') {
1051 put_packet(s, "vCont;c;C;s;S");
1052 break;
1055 res = gdb_handle_vcont(s, p);
1057 if (res) {
1058 if ((res == -EINVAL) || (res == -ERANGE)) {
1059 put_packet(s, "E22");
1060 break;
1062 goto unknown_command;
1064 break;
1065 } else {
1066 goto unknown_command;
1068 case 'k':
1069 /* Kill the target */
1070 error_report("QEMU: Terminated via GDBstub");
1071 exit(0);
1072 case 'D':
1073 /* Detach packet */
1074 gdb_breakpoint_remove_all();
1075 gdb_syscall_mode = GDB_SYS_DISABLED;
1076 gdb_continue(s);
1077 put_packet(s, "OK");
1078 break;
1079 case 's':
1080 if (*p != '\0') {
1081 addr = strtoull(p, (char **)&p, 16);
1082 gdb_set_cpu_pc(s, addr);
1084 cpu_single_step(s->c_cpu, sstep_flags);
1085 gdb_continue(s);
1086 return RS_IDLE;
1087 case 'F':
1089 target_ulong ret;
1090 target_ulong err;
1092 ret = strtoull(p, (char **)&p, 16);
1093 if (*p == ',') {
1094 p++;
1095 err = strtoull(p, (char **)&p, 16);
1096 } else {
1097 err = 0;
1099 if (*p == ',')
1100 p++;
1101 type = *p;
1102 if (s->current_syscall_cb) {
1103 s->current_syscall_cb(s->c_cpu, ret, err);
1104 s->current_syscall_cb = NULL;
1106 if (type == 'C') {
1107 put_packet(s, "T02");
1108 } else {
1109 gdb_continue(s);
1112 break;
1113 case 'g':
1114 cpu_synchronize_state(s->g_cpu);
1115 len = 0;
1116 for (addr = 0; addr < s->g_cpu->gdb_num_g_regs; addr++) {
1117 reg_size = gdb_read_register(s->g_cpu, mem_buf + len, addr);
1118 len += reg_size;
1120 memtohex(buf, mem_buf, len);
1121 put_packet(s, buf);
1122 break;
1123 case 'G':
1124 cpu_synchronize_state(s->g_cpu);
1125 registers = mem_buf;
1126 len = strlen(p) / 2;
1127 hextomem((uint8_t *)registers, p, len);
1128 for (addr = 0; addr < s->g_cpu->gdb_num_g_regs && len > 0; addr++) {
1129 reg_size = gdb_write_register(s->g_cpu, registers, addr);
1130 len -= reg_size;
1131 registers += reg_size;
1133 put_packet(s, "OK");
1134 break;
1135 case 'm':
1136 addr = strtoull(p, (char **)&p, 16);
1137 if (*p == ',')
1138 p++;
1139 len = strtoull(p, NULL, 16);
1141 /* memtohex() doubles the required space */
1142 if (len > MAX_PACKET_LENGTH / 2) {
1143 put_packet (s, "E22");
1144 break;
1147 if (target_memory_rw_debug(s->g_cpu, addr, mem_buf, len, false) != 0) {
1148 put_packet (s, "E14");
1149 } else {
1150 memtohex(buf, mem_buf, len);
1151 put_packet(s, buf);
1153 break;
1154 case 'M':
1155 addr = strtoull(p, (char **)&p, 16);
1156 if (*p == ',')
1157 p++;
1158 len = strtoull(p, (char **)&p, 16);
1159 if (*p == ':')
1160 p++;
1162 /* hextomem() reads 2*len bytes */
1163 if (len > strlen(p) / 2) {
1164 put_packet (s, "E22");
1165 break;
1167 hextomem(mem_buf, p, len);
1168 if (target_memory_rw_debug(s->g_cpu, addr, mem_buf, len,
1169 true) != 0) {
1170 put_packet(s, "E14");
1171 } else {
1172 put_packet(s, "OK");
1174 break;
1175 case 'p':
1176 /* Older gdb are really dumb, and don't use 'g' if 'p' is avaialable.
1177 This works, but can be very slow. Anything new enough to
1178 understand XML also knows how to use this properly. */
1179 if (!gdb_has_xml)
1180 goto unknown_command;
1181 addr = strtoull(p, (char **)&p, 16);
1182 reg_size = gdb_read_register(s->g_cpu, mem_buf, addr);
1183 if (reg_size) {
1184 memtohex(buf, mem_buf, reg_size);
1185 put_packet(s, buf);
1186 } else {
1187 put_packet(s, "E14");
1189 break;
1190 case 'P':
1191 if (!gdb_has_xml)
1192 goto unknown_command;
1193 addr = strtoull(p, (char **)&p, 16);
1194 if (*p == '=')
1195 p++;
1196 reg_size = strlen(p) / 2;
1197 hextomem(mem_buf, p, reg_size);
1198 gdb_write_register(s->g_cpu, mem_buf, addr);
1199 put_packet(s, "OK");
1200 break;
1201 case 'Z':
1202 case 'z':
1203 type = strtoul(p, (char **)&p, 16);
1204 if (*p == ',')
1205 p++;
1206 addr = strtoull(p, (char **)&p, 16);
1207 if (*p == ',')
1208 p++;
1209 len = strtoull(p, (char **)&p, 16);
1210 if (ch == 'Z')
1211 res = gdb_breakpoint_insert(addr, len, type);
1212 else
1213 res = gdb_breakpoint_remove(addr, len, type);
1214 if (res >= 0)
1215 put_packet(s, "OK");
1216 else if (res == -ENOSYS)
1217 put_packet(s, "");
1218 else
1219 put_packet(s, "E22");
1220 break;
1221 case 'H':
1222 type = *p++;
1223 thread = strtoull(p, (char **)&p, 16);
1224 if (thread == -1 || thread == 0) {
1225 put_packet(s, "OK");
1226 break;
1228 cpu = find_cpu(thread);
1229 if (cpu == NULL) {
1230 put_packet(s, "E22");
1231 break;
1233 switch (type) {
1234 case 'c':
1235 s->c_cpu = cpu;
1236 put_packet(s, "OK");
1237 break;
1238 case 'g':
1239 s->g_cpu = cpu;
1240 put_packet(s, "OK");
1241 break;
1242 default:
1243 put_packet(s, "E22");
1244 break;
1246 break;
1247 case 'T':
1248 thread = strtoull(p, (char **)&p, 16);
1249 cpu = find_cpu(thread);
1251 if (cpu != NULL) {
1252 put_packet(s, "OK");
1253 } else {
1254 put_packet(s, "E22");
1256 break;
1257 case 'q':
1258 case 'Q':
1259 /* parse any 'q' packets here */
1260 if (!strcmp(p,"qemu.sstepbits")) {
1261 /* Query Breakpoint bit definitions */
1262 snprintf(buf, sizeof(buf), "ENABLE=%x,NOIRQ=%x,NOTIMER=%x",
1263 SSTEP_ENABLE,
1264 SSTEP_NOIRQ,
1265 SSTEP_NOTIMER);
1266 put_packet(s, buf);
1267 break;
1268 } else if (is_query_packet(p, "qemu.sstep", '=')) {
1269 /* Display or change the sstep_flags */
1270 p += 10;
1271 if (*p != '=') {
1272 /* Display current setting */
1273 snprintf(buf, sizeof(buf), "0x%x", sstep_flags);
1274 put_packet(s, buf);
1275 break;
1277 p++;
1278 type = strtoul(p, (char **)&p, 16);
1279 sstep_flags = type;
1280 put_packet(s, "OK");
1281 break;
1282 } else if (strcmp(p,"C") == 0) {
1283 /* "Current thread" remains vague in the spec, so always return
1284 * the first CPU (gdb returns the first thread). */
1285 put_packet(s, "QC1");
1286 break;
1287 } else if (strcmp(p,"fThreadInfo") == 0) {
1288 s->query_cpu = first_cpu;
1289 goto report_cpuinfo;
1290 } else if (strcmp(p,"sThreadInfo") == 0) {
1291 report_cpuinfo:
1292 if (s->query_cpu) {
1293 snprintf(buf, sizeof(buf), "m%x", cpu_gdb_index(s->query_cpu));
1294 put_packet(s, buf);
1295 s->query_cpu = CPU_NEXT(s->query_cpu);
1296 } else
1297 put_packet(s, "l");
1298 break;
1299 } else if (strncmp(p,"ThreadExtraInfo,", 16) == 0) {
1300 thread = strtoull(p+16, (char **)&p, 16);
1301 cpu = find_cpu(thread);
1302 if (cpu != NULL) {
1303 cpu_synchronize_state(cpu);
1304 /* memtohex() doubles the required space */
1305 len = snprintf((char *)mem_buf, sizeof(buf) / 2,
1306 "CPU#%d [%s]", cpu->cpu_index,
1307 cpu->halted ? "halted " : "running");
1308 trace_gdbstub_op_extra_info((char *)mem_buf);
1309 memtohex(buf, mem_buf, len);
1310 put_packet(s, buf);
1312 break;
1314 #ifdef CONFIG_USER_ONLY
1315 else if (strcmp(p, "Offsets") == 0) {
1316 TaskState *ts = s->c_cpu->opaque;
1318 snprintf(buf, sizeof(buf),
1319 "Text=" TARGET_ABI_FMT_lx ";Data=" TARGET_ABI_FMT_lx
1320 ";Bss=" TARGET_ABI_FMT_lx,
1321 ts->info->code_offset,
1322 ts->info->data_offset,
1323 ts->info->data_offset);
1324 put_packet(s, buf);
1325 break;
1327 #else /* !CONFIG_USER_ONLY */
1328 else if (strncmp(p, "Rcmd,", 5) == 0) {
1329 int len = strlen(p + 5);
1331 if ((len % 2) != 0) {
1332 put_packet(s, "E01");
1333 break;
1335 len = len / 2;
1336 hextomem(mem_buf, p + 5, len);
1337 mem_buf[len++] = 0;
1338 qemu_chr_be_write(s->mon_chr, mem_buf, len);
1339 put_packet(s, "OK");
1340 break;
1342 #endif /* !CONFIG_USER_ONLY */
1343 if (is_query_packet(p, "Supported", ':')) {
1344 snprintf(buf, sizeof(buf), "PacketSize=%x", MAX_PACKET_LENGTH);
1345 cc = CPU_GET_CLASS(first_cpu);
1346 if (cc->gdb_core_xml_file != NULL) {
1347 pstrcat(buf, sizeof(buf), ";qXfer:features:read+");
1349 put_packet(s, buf);
1350 break;
1352 if (strncmp(p, "Xfer:features:read:", 19) == 0) {
1353 const char *xml;
1354 target_ulong total_len;
1356 cc = CPU_GET_CLASS(first_cpu);
1357 if (cc->gdb_core_xml_file == NULL) {
1358 goto unknown_command;
1361 gdb_has_xml = true;
1362 p += 19;
1363 xml = get_feature_xml(p, &p, cc);
1364 if (!xml) {
1365 snprintf(buf, sizeof(buf), "E00");
1366 put_packet(s, buf);
1367 break;
1370 if (*p == ':')
1371 p++;
1372 addr = strtoul(p, (char **)&p, 16);
1373 if (*p == ',')
1374 p++;
1375 len = strtoul(p, (char **)&p, 16);
1377 total_len = strlen(xml);
1378 if (addr > total_len) {
1379 snprintf(buf, sizeof(buf), "E00");
1380 put_packet(s, buf);
1381 break;
1383 if (len > (MAX_PACKET_LENGTH - 5) / 2)
1384 len = (MAX_PACKET_LENGTH - 5) / 2;
1385 if (len < total_len - addr) {
1386 buf[0] = 'm';
1387 len = memtox(buf + 1, xml + addr, len);
1388 } else {
1389 buf[0] = 'l';
1390 len = memtox(buf + 1, xml + addr, total_len - addr);
1392 put_packet_binary(s, buf, len + 1, true);
1393 break;
1395 if (is_query_packet(p, "Attached", ':')) {
1396 put_packet(s, GDB_ATTACHED);
1397 break;
1399 /* Unrecognised 'q' command. */
1400 goto unknown_command;
1402 default:
1403 unknown_command:
1404 /* put empty packet */
1405 buf[0] = '\0';
1406 put_packet(s, buf);
1407 break;
1409 return RS_IDLE;
1412 void gdb_set_stop_cpu(CPUState *cpu)
1414 gdbserver_state->c_cpu = cpu;
1415 gdbserver_state->g_cpu = cpu;
1418 #ifndef CONFIG_USER_ONLY
1419 static void gdb_vm_state_change(void *opaque, int running, RunState state)
1421 GDBState *s = gdbserver_state;
1422 CPUState *cpu = s->c_cpu;
1423 char buf[256];
1424 const char *type;
1425 int ret;
1427 if (running || s->state == RS_INACTIVE) {
1428 return;
1430 /* Is there a GDB syscall waiting to be sent? */
1431 if (s->current_syscall_cb) {
1432 put_packet(s, s->syscall_buf);
1433 return;
1435 switch (state) {
1436 case RUN_STATE_DEBUG:
1437 if (cpu->watchpoint_hit) {
1438 switch (cpu->watchpoint_hit->flags & BP_MEM_ACCESS) {
1439 case BP_MEM_READ:
1440 type = "r";
1441 break;
1442 case BP_MEM_ACCESS:
1443 type = "a";
1444 break;
1445 default:
1446 type = "";
1447 break;
1449 trace_gdbstub_hit_watchpoint(type, cpu_gdb_index(cpu),
1450 (target_ulong)cpu->watchpoint_hit->vaddr);
1451 snprintf(buf, sizeof(buf),
1452 "T%02xthread:%02x;%swatch:" TARGET_FMT_lx ";",
1453 GDB_SIGNAL_TRAP, cpu_gdb_index(cpu), type,
1454 (target_ulong)cpu->watchpoint_hit->vaddr);
1455 cpu->watchpoint_hit = NULL;
1456 goto send_packet;
1457 } else {
1458 trace_gdbstub_hit_break();
1460 tb_flush(cpu);
1461 ret = GDB_SIGNAL_TRAP;
1462 break;
1463 case RUN_STATE_PAUSED:
1464 trace_gdbstub_hit_paused();
1465 ret = GDB_SIGNAL_INT;
1466 break;
1467 case RUN_STATE_SHUTDOWN:
1468 trace_gdbstub_hit_shutdown();
1469 ret = GDB_SIGNAL_QUIT;
1470 break;
1471 case RUN_STATE_IO_ERROR:
1472 trace_gdbstub_hit_io_error();
1473 ret = GDB_SIGNAL_IO;
1474 break;
1475 case RUN_STATE_WATCHDOG:
1476 trace_gdbstub_hit_watchdog();
1477 ret = GDB_SIGNAL_ALRM;
1478 break;
1479 case RUN_STATE_INTERNAL_ERROR:
1480 trace_gdbstub_hit_internal_error();
1481 ret = GDB_SIGNAL_ABRT;
1482 break;
1483 case RUN_STATE_SAVE_VM:
1484 case RUN_STATE_RESTORE_VM:
1485 return;
1486 case RUN_STATE_FINISH_MIGRATE:
1487 ret = GDB_SIGNAL_XCPU;
1488 break;
1489 default:
1490 trace_gdbstub_hit_unknown(state);
1491 ret = GDB_SIGNAL_UNKNOWN;
1492 break;
1494 gdb_set_stop_cpu(cpu);
1495 snprintf(buf, sizeof(buf), "T%02xthread:%02x;", ret, cpu_gdb_index(cpu));
1497 send_packet:
1498 put_packet(s, buf);
1500 /* disable single step if it was enabled */
1501 cpu_single_step(cpu, 0);
1503 #endif
1505 /* Send a gdb syscall request.
1506 This accepts limited printf-style format specifiers, specifically:
1507 %x - target_ulong argument printed in hex.
1508 %lx - 64-bit argument printed in hex.
1509 %s - string pointer (target_ulong) and length (int) pair. */
1510 void gdb_do_syscallv(gdb_syscall_complete_cb cb, const char *fmt, va_list va)
1512 char *p;
1513 char *p_end;
1514 target_ulong addr;
1515 uint64_t i64;
1516 GDBState *s;
1518 s = gdbserver_state;
1519 if (!s)
1520 return;
1521 s->current_syscall_cb = cb;
1522 #ifndef CONFIG_USER_ONLY
1523 vm_stop(RUN_STATE_DEBUG);
1524 #endif
1525 p = s->syscall_buf;
1526 p_end = &s->syscall_buf[sizeof(s->syscall_buf)];
1527 *(p++) = 'F';
1528 while (*fmt) {
1529 if (*fmt == '%') {
1530 fmt++;
1531 switch (*fmt++) {
1532 case 'x':
1533 addr = va_arg(va, target_ulong);
1534 p += snprintf(p, p_end - p, TARGET_FMT_lx, addr);
1535 break;
1536 case 'l':
1537 if (*(fmt++) != 'x')
1538 goto bad_format;
1539 i64 = va_arg(va, uint64_t);
1540 p += snprintf(p, p_end - p, "%" PRIx64, i64);
1541 break;
1542 case 's':
1543 addr = va_arg(va, target_ulong);
1544 p += snprintf(p, p_end - p, TARGET_FMT_lx "/%x",
1545 addr, va_arg(va, int));
1546 break;
1547 default:
1548 bad_format:
1549 error_report("gdbstub: Bad syscall format string '%s'",
1550 fmt - 1);
1551 break;
1553 } else {
1554 *(p++) = *(fmt++);
1557 *p = 0;
1558 #ifdef CONFIG_USER_ONLY
1559 put_packet(s, s->syscall_buf);
1560 /* Return control to gdb for it to process the syscall request.
1561 * Since the protocol requires that gdb hands control back to us
1562 * using a "here are the results" F packet, we don't need to check
1563 * gdb_handlesig's return value (which is the signal to deliver if
1564 * execution was resumed via a continue packet).
1566 gdb_handlesig(s->c_cpu, 0);
1567 #else
1568 /* In this case wait to send the syscall packet until notification that
1569 the CPU has stopped. This must be done because if the packet is sent
1570 now the reply from the syscall request could be received while the CPU
1571 is still in the running state, which can cause packets to be dropped
1572 and state transition 'T' packets to be sent while the syscall is still
1573 being processed. */
1574 qemu_cpu_kick(s->c_cpu);
1575 #endif
1578 void gdb_do_syscall(gdb_syscall_complete_cb cb, const char *fmt, ...)
1580 va_list va;
1582 va_start(va, fmt);
1583 gdb_do_syscallv(cb, fmt, va);
1584 va_end(va);
1587 static void gdb_read_byte(GDBState *s, int ch)
1589 uint8_t reply;
1591 #ifndef CONFIG_USER_ONLY
1592 if (s->last_packet_len) {
1593 /* Waiting for a response to the last packet. If we see the start
1594 of a new command then abandon the previous response. */
1595 if (ch == '-') {
1596 trace_gdbstub_err_got_nack();
1597 put_buffer(s, (uint8_t *)s->last_packet, s->last_packet_len);
1598 } else if (ch == '+') {
1599 trace_gdbstub_io_got_ack();
1600 } else {
1601 trace_gdbstub_io_got_unexpected((uint8_t)ch);
1604 if (ch == '+' || ch == '$')
1605 s->last_packet_len = 0;
1606 if (ch != '$')
1607 return;
1609 if (runstate_is_running()) {
1610 /* when the CPU is running, we cannot do anything except stop
1611 it when receiving a char */
1612 vm_stop(RUN_STATE_PAUSED);
1613 } else
1614 #endif
1616 switch(s->state) {
1617 case RS_IDLE:
1618 if (ch == '$') {
1619 /* start of command packet */
1620 s->line_buf_index = 0;
1621 s->line_sum = 0;
1622 s->state = RS_GETLINE;
1623 } else {
1624 trace_gdbstub_err_garbage((uint8_t)ch);
1626 break;
1627 case RS_GETLINE:
1628 if (ch == '}') {
1629 /* start escape sequence */
1630 s->state = RS_GETLINE_ESC;
1631 s->line_sum += ch;
1632 } else if (ch == '*') {
1633 /* start run length encoding sequence */
1634 s->state = RS_GETLINE_RLE;
1635 s->line_sum += ch;
1636 } else if (ch == '#') {
1637 /* end of command, start of checksum*/
1638 s->state = RS_CHKSUM1;
1639 } else if (s->line_buf_index >= sizeof(s->line_buf) - 1) {
1640 trace_gdbstub_err_overrun();
1641 s->state = RS_IDLE;
1642 } else {
1643 /* unescaped command character */
1644 s->line_buf[s->line_buf_index++] = ch;
1645 s->line_sum += ch;
1647 break;
1648 case RS_GETLINE_ESC:
1649 if (ch == '#') {
1650 /* unexpected end of command in escape sequence */
1651 s->state = RS_CHKSUM1;
1652 } else if (s->line_buf_index >= sizeof(s->line_buf) - 1) {
1653 /* command buffer overrun */
1654 trace_gdbstub_err_overrun();
1655 s->state = RS_IDLE;
1656 } else {
1657 /* parse escaped character and leave escape state */
1658 s->line_buf[s->line_buf_index++] = ch ^ 0x20;
1659 s->line_sum += ch;
1660 s->state = RS_GETLINE;
1662 break;
1663 case RS_GETLINE_RLE:
1664 if (ch < ' ') {
1665 /* invalid RLE count encoding */
1666 trace_gdbstub_err_invalid_repeat((uint8_t)ch);
1667 s->state = RS_GETLINE;
1668 } else {
1669 /* decode repeat length */
1670 int repeat = (unsigned char)ch - ' ' + 3;
1671 if (s->line_buf_index + repeat >= sizeof(s->line_buf) - 1) {
1672 /* that many repeats would overrun the command buffer */
1673 trace_gdbstub_err_overrun();
1674 s->state = RS_IDLE;
1675 } else if (s->line_buf_index < 1) {
1676 /* got a repeat but we have nothing to repeat */
1677 trace_gdbstub_err_invalid_rle();
1678 s->state = RS_GETLINE;
1679 } else {
1680 /* repeat the last character */
1681 memset(s->line_buf + s->line_buf_index,
1682 s->line_buf[s->line_buf_index - 1], repeat);
1683 s->line_buf_index += repeat;
1684 s->line_sum += ch;
1685 s->state = RS_GETLINE;
1688 break;
1689 case RS_CHKSUM1:
1690 /* get high hex digit of checksum */
1691 if (!isxdigit(ch)) {
1692 trace_gdbstub_err_checksum_invalid((uint8_t)ch);
1693 s->state = RS_GETLINE;
1694 break;
1696 s->line_buf[s->line_buf_index] = '\0';
1697 s->line_csum = fromhex(ch) << 4;
1698 s->state = RS_CHKSUM2;
1699 break;
1700 case RS_CHKSUM2:
1701 /* get low hex digit of checksum */
1702 if (!isxdigit(ch)) {
1703 trace_gdbstub_err_checksum_invalid((uint8_t)ch);
1704 s->state = RS_GETLINE;
1705 break;
1707 s->line_csum |= fromhex(ch);
1709 if (s->line_csum != (s->line_sum & 0xff)) {
1710 trace_gdbstub_err_checksum_incorrect(s->line_sum, s->line_csum);
1711 /* send NAK reply */
1712 reply = '-';
1713 put_buffer(s, &reply, 1);
1714 s->state = RS_IDLE;
1715 } else {
1716 /* send ACK reply */
1717 reply = '+';
1718 put_buffer(s, &reply, 1);
1719 s->state = gdb_handle_packet(s, s->line_buf);
1721 break;
1722 default:
1723 abort();
1728 /* Tell the remote gdb that the process has exited. */
1729 void gdb_exit(CPUArchState *env, int code)
1731 GDBState *s;
1732 char buf[4];
1734 s = gdbserver_state;
1735 if (!s) {
1736 return;
1738 #ifdef CONFIG_USER_ONLY
1739 if (gdbserver_fd < 0 || s->fd < 0) {
1740 return;
1742 #endif
1744 trace_gdbstub_op_exiting((uint8_t)code);
1746 snprintf(buf, sizeof(buf), "W%02x", (uint8_t)code);
1747 put_packet(s, buf);
1749 #ifndef CONFIG_USER_ONLY
1750 qemu_chr_fe_deinit(&s->chr, true);
1751 #endif
1754 #ifdef CONFIG_USER_ONLY
1756 gdb_handlesig(CPUState *cpu, int sig)
1758 GDBState *s;
1759 char buf[256];
1760 int n;
1762 s = gdbserver_state;
1763 if (gdbserver_fd < 0 || s->fd < 0) {
1764 return sig;
1767 /* disable single step if it was enabled */
1768 cpu_single_step(cpu, 0);
1769 tb_flush(cpu);
1771 if (sig != 0) {
1772 snprintf(buf, sizeof(buf), "S%02x", target_signal_to_gdb(sig));
1773 put_packet(s, buf);
1775 /* put_packet() might have detected that the peer terminated the
1776 connection. */
1777 if (s->fd < 0) {
1778 return sig;
1781 sig = 0;
1782 s->state = RS_IDLE;
1783 s->running_state = 0;
1784 while (s->running_state == 0) {
1785 n = read(s->fd, buf, 256);
1786 if (n > 0) {
1787 int i;
1789 for (i = 0; i < n; i++) {
1790 gdb_read_byte(s, buf[i]);
1792 } else {
1793 /* XXX: Connection closed. Should probably wait for another
1794 connection before continuing. */
1795 if (n == 0) {
1796 close(s->fd);
1798 s->fd = -1;
1799 return sig;
1802 sig = s->signal;
1803 s->signal = 0;
1804 return sig;
1807 /* Tell the remote gdb that the process has exited due to SIG. */
1808 void gdb_signalled(CPUArchState *env, int sig)
1810 GDBState *s;
1811 char buf[4];
1813 s = gdbserver_state;
1814 if (gdbserver_fd < 0 || s->fd < 0) {
1815 return;
1818 snprintf(buf, sizeof(buf), "X%02x", target_signal_to_gdb(sig));
1819 put_packet(s, buf);
1822 static bool gdb_accept(void)
1824 GDBState *s;
1825 struct sockaddr_in sockaddr;
1826 socklen_t len;
1827 int fd;
1829 for(;;) {
1830 len = sizeof(sockaddr);
1831 fd = accept(gdbserver_fd, (struct sockaddr *)&sockaddr, &len);
1832 if (fd < 0 && errno != EINTR) {
1833 perror("accept");
1834 return false;
1835 } else if (fd >= 0) {
1836 qemu_set_cloexec(fd);
1837 break;
1841 /* set short latency */
1842 if (socket_set_nodelay(fd)) {
1843 perror("setsockopt");
1844 close(fd);
1845 return false;
1848 s = g_malloc0(sizeof(GDBState));
1849 s->c_cpu = first_cpu;
1850 s->g_cpu = first_cpu;
1851 s->fd = fd;
1852 gdb_has_xml = false;
1854 gdbserver_state = s;
1855 return true;
1858 static int gdbserver_open(int port)
1860 struct sockaddr_in sockaddr;
1861 int fd, ret;
1863 fd = socket(PF_INET, SOCK_STREAM, 0);
1864 if (fd < 0) {
1865 perror("socket");
1866 return -1;
1868 qemu_set_cloexec(fd);
1870 socket_set_fast_reuse(fd);
1872 sockaddr.sin_family = AF_INET;
1873 sockaddr.sin_port = htons(port);
1874 sockaddr.sin_addr.s_addr = 0;
1875 ret = bind(fd, (struct sockaddr *)&sockaddr, sizeof(sockaddr));
1876 if (ret < 0) {
1877 perror("bind");
1878 close(fd);
1879 return -1;
1881 ret = listen(fd, 1);
1882 if (ret < 0) {
1883 perror("listen");
1884 close(fd);
1885 return -1;
1887 return fd;
1890 int gdbserver_start(int port)
1892 gdbserver_fd = gdbserver_open(port);
1893 if (gdbserver_fd < 0)
1894 return -1;
1895 /* accept connections */
1896 if (!gdb_accept()) {
1897 close(gdbserver_fd);
1898 gdbserver_fd = -1;
1899 return -1;
1901 return 0;
1904 /* Disable gdb stub for child processes. */
1905 void gdbserver_fork(CPUState *cpu)
1907 GDBState *s = gdbserver_state;
1909 if (gdbserver_fd < 0 || s->fd < 0) {
1910 return;
1912 close(s->fd);
1913 s->fd = -1;
1914 cpu_breakpoint_remove_all(cpu, BP_GDB);
1915 cpu_watchpoint_remove_all(cpu, BP_GDB);
1917 #else
1918 static int gdb_chr_can_receive(void *opaque)
1920 /* We can handle an arbitrarily large amount of data.
1921 Pick the maximum packet size, which is as good as anything. */
1922 return MAX_PACKET_LENGTH;
1925 static void gdb_chr_receive(void *opaque, const uint8_t *buf, int size)
1927 int i;
1929 for (i = 0; i < size; i++) {
1930 gdb_read_byte(gdbserver_state, buf[i]);
1934 static void gdb_chr_event(void *opaque, int event)
1936 switch (event) {
1937 case CHR_EVENT_OPENED:
1938 vm_stop(RUN_STATE_PAUSED);
1939 gdb_has_xml = false;
1940 break;
1941 default:
1942 break;
1946 static void gdb_monitor_output(GDBState *s, const char *msg, int len)
1948 char buf[MAX_PACKET_LENGTH];
1950 buf[0] = 'O';
1951 if (len > (MAX_PACKET_LENGTH/2) - 1)
1952 len = (MAX_PACKET_LENGTH/2) - 1;
1953 memtohex(buf + 1, (uint8_t *)msg, len);
1954 put_packet(s, buf);
1957 static int gdb_monitor_write(Chardev *chr, const uint8_t *buf, int len)
1959 const char *p = (const char *)buf;
1960 int max_sz;
1962 max_sz = (sizeof(gdbserver_state->last_packet) - 2) / 2;
1963 for (;;) {
1964 if (len <= max_sz) {
1965 gdb_monitor_output(gdbserver_state, p, len);
1966 break;
1968 gdb_monitor_output(gdbserver_state, p, max_sz);
1969 p += max_sz;
1970 len -= max_sz;
1972 return len;
1975 #ifndef _WIN32
1976 static void gdb_sigterm_handler(int signal)
1978 if (runstate_is_running()) {
1979 vm_stop(RUN_STATE_PAUSED);
1982 #endif
1984 static void gdb_monitor_open(Chardev *chr, ChardevBackend *backend,
1985 bool *be_opened, Error **errp)
1987 *be_opened = false;
1990 static void char_gdb_class_init(ObjectClass *oc, void *data)
1992 ChardevClass *cc = CHARDEV_CLASS(oc);
1994 cc->internal = true;
1995 cc->open = gdb_monitor_open;
1996 cc->chr_write = gdb_monitor_write;
1999 #define TYPE_CHARDEV_GDB "chardev-gdb"
2001 static const TypeInfo char_gdb_type_info = {
2002 .name = TYPE_CHARDEV_GDB,
2003 .parent = TYPE_CHARDEV,
2004 .class_init = char_gdb_class_init,
2007 int gdbserver_start(const char *device)
2009 trace_gdbstub_op_start(device);
2011 GDBState *s;
2012 char gdbstub_device_name[128];
2013 Chardev *chr = NULL;
2014 Chardev *mon_chr;
2016 if (!first_cpu) {
2017 error_report("gdbstub: meaningless to attach gdb to a "
2018 "machine without any CPU.");
2019 return -1;
2022 if (!device)
2023 return -1;
2024 if (strcmp(device, "none") != 0) {
2025 if (strstart(device, "tcp:", NULL)) {
2026 /* enforce required TCP attributes */
2027 snprintf(gdbstub_device_name, sizeof(gdbstub_device_name),
2028 "%s,nowait,nodelay,server", device);
2029 device = gdbstub_device_name;
2031 #ifndef _WIN32
2032 else if (strcmp(device, "stdio") == 0) {
2033 struct sigaction act;
2035 memset(&act, 0, sizeof(act));
2036 act.sa_handler = gdb_sigterm_handler;
2037 sigaction(SIGINT, &act, NULL);
2039 #endif
2041 * FIXME: it's a bit weird to allow using a mux chardev here
2042 * and implicitly setup a monitor. We may want to break this.
2044 chr = qemu_chr_new_noreplay("gdb", device, true);
2045 if (!chr)
2046 return -1;
2049 s = gdbserver_state;
2050 if (!s) {
2051 s = g_malloc0(sizeof(GDBState));
2052 gdbserver_state = s;
2054 qemu_add_vm_change_state_handler(gdb_vm_state_change, NULL);
2056 /* Initialize a monitor terminal for gdb */
2057 mon_chr = qemu_chardev_new(NULL, TYPE_CHARDEV_GDB,
2058 NULL, &error_abort);
2059 monitor_init(mon_chr, 0);
2060 } else {
2061 qemu_chr_fe_deinit(&s->chr, true);
2062 mon_chr = s->mon_chr;
2063 memset(s, 0, sizeof(GDBState));
2064 s->mon_chr = mon_chr;
2066 s->c_cpu = first_cpu;
2067 s->g_cpu = first_cpu;
2068 if (chr) {
2069 qemu_chr_fe_init(&s->chr, chr, &error_abort);
2070 qemu_chr_fe_set_handlers(&s->chr, gdb_chr_can_receive, gdb_chr_receive,
2071 gdb_chr_event, NULL, NULL, NULL, true);
2073 s->state = chr ? RS_IDLE : RS_INACTIVE;
2074 s->mon_chr = mon_chr;
2075 s->current_syscall_cb = NULL;
2077 return 0;
2080 void gdbserver_cleanup(void)
2082 if (gdbserver_state) {
2083 put_packet(gdbserver_state, "W00");
2087 static void register_types(void)
2089 type_register_static(&char_gdb_type_info);
2092 type_init(register_types);
2093 #endif