4 * This implements a subset of the remote protocol as described in:
6 * https://sourceware.org/gdb/onlinedocs/gdb/Remote-Protocol.html
8 * Copyright (c) 2003-2005 Fabrice Bellard
10 * This library is free software; you can redistribute it and/or
11 * modify it under the terms of the GNU Lesser General Public
12 * License as published by the Free Software Foundation; either
13 * version 2 of the License, or (at your option) any later version.
15 * This library is distributed in the hope that it will be useful,
16 * but WITHOUT ANY WARRANTY; without even the implied warranty of
17 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
18 * Lesser General Public License for more details.
20 * You should have received a copy of the GNU Lesser General Public
21 * License along with this library; if not, see <http://www.gnu.org/licenses/>.
23 * SPDX-License-Identifier: LGPL-2.0+
26 #include "qemu/osdep.h"
27 #include "qemu-common.h"
28 #include "qapi/error.h"
29 #include "qemu/error-report.h"
30 #include "qemu/ctype.h"
31 #include "qemu/cutils.h"
32 #include "qemu/module.h"
33 #include "trace/trace-root.h"
34 #ifdef CONFIG_USER_ONLY
37 #include "monitor/monitor.h"
38 #include "chardev/char.h"
39 #include "chardev/char-fe.h"
40 #include "exec/gdbstub.h"
41 #include "hw/cpu/cluster.h"
42 #include "hw/boards.h"
45 #define MAX_PACKET_LENGTH 4096
47 #include "qemu/sockets.h"
48 #include "sysemu/hw_accel.h"
49 #include "sysemu/kvm.h"
50 #include "sysemu/runstate.h"
51 #include "semihosting/semihost.h"
52 #include "exec/exec-all.h"
53 #include "sysemu/replay.h"
55 #ifdef CONFIG_USER_ONLY
56 #define GDB_ATTACHED "0"
58 #define GDB_ATTACHED "1"
61 #ifndef CONFIG_USER_ONLY
62 static int phy_memory_mode;
65 static inline int target_memory_rw_debug(CPUState *cpu, target_ulong addr,
66 uint8_t *buf, int len, bool is_write)
70 #ifndef CONFIG_USER_ONLY
71 if (phy_memory_mode) {
73 cpu_physical_memory_write(addr, buf, len);
75 cpu_physical_memory_read(addr, buf, len);
81 cc = CPU_GET_CLASS(cpu);
82 if (cc->memory_rw_debug) {
83 return cc->memory_rw_debug(cpu, addr, buf, len, is_write);
85 return cpu_memory_rw_debug(cpu, addr, buf, len, is_write);
88 /* Return the GDB index for a given vCPU state.
90 * For user mode this is simply the thread id. In system mode GDB
91 * numbers CPUs from 1 as 0 is reserved as an "any cpu" index.
93 static inline int cpu_gdb_index(CPUState *cpu)
95 #if defined(CONFIG_USER_ONLY)
96 TaskState *ts = (TaskState *) cpu->opaque;
99 return cpu->cpu_index + 1;
109 GDB_SIGNAL_ALRM = 14,
111 GDB_SIGNAL_XCPU = 24,
112 GDB_SIGNAL_UNKNOWN = 143
115 #ifdef CONFIG_USER_ONLY
117 /* Map target signal numbers to GDB protocol signal numbers and vice
118 * versa. For user emulation's currently supported systems, we can
119 * assume most signals are defined.
122 static int gdb_signal_table[] = {
282 /* In system mode we only need SIGINT and SIGTRAP; other signals
283 are not yet supported. */
290 static int gdb_signal_table[] = {
300 #ifdef CONFIG_USER_ONLY
301 static int target_signal_to_gdb (int sig)
304 for (i = 0; i < ARRAY_SIZE (gdb_signal_table); i++)
305 if (gdb_signal_table[i] == sig)
307 return GDB_SIGNAL_UNKNOWN;
311 static int gdb_signal_to_target (int sig)
313 if (sig < ARRAY_SIZE (gdb_signal_table))
314 return gdb_signal_table[sig];
319 typedef struct GDBRegisterState {
322 gdb_get_reg_cb get_reg;
323 gdb_set_reg_cb set_reg;
325 struct GDBRegisterState *next;
328 typedef struct GDBProcess {
332 char target_xml[1024];
344 typedef struct GDBState {
345 bool init; /* have we been initialised? */
346 CPUState *c_cpu; /* current CPU for step/continue ops */
347 CPUState *g_cpu; /* current CPU for other ops */
348 CPUState *query_cpu; /* for q{f|s}ThreadInfo */
349 enum RSState state; /* parsing state */
350 char line_buf[MAX_PACKET_LENGTH];
352 int line_sum; /* running checksum */
353 int line_csum; /* checksum at the end of the packet */
354 GByteArray *last_packet;
356 #ifdef CONFIG_USER_ONLY
365 GDBProcess *processes;
367 char syscall_buf[256];
368 gdb_syscall_complete_cb current_syscall_cb;
373 /* By default use no IRQs and no timers while single stepping so as to
374 * make single stepping like an ICE HW step.
376 static int sstep_flags = SSTEP_ENABLE|SSTEP_NOIRQ|SSTEP_NOTIMER;
378 /* Retrieves flags for single step mode. */
379 static int get_sstep_flags(void)
382 * In replay mode all events written into the log should be replayed.
383 * That is why NOIRQ flag is removed in this mode.
385 if (replay_mode != REPLAY_MODE_NONE) {
392 static GDBState gdbserver_state;
394 static void init_gdbserver_state(void)
396 g_assert(!gdbserver_state.init);
397 memset(&gdbserver_state, 0, sizeof(GDBState));
398 gdbserver_state.init = true;
399 gdbserver_state.str_buf = g_string_new(NULL);
400 gdbserver_state.mem_buf = g_byte_array_sized_new(MAX_PACKET_LENGTH);
401 gdbserver_state.last_packet = g_byte_array_sized_new(MAX_PACKET_LENGTH + 4);
404 #ifndef CONFIG_USER_ONLY
405 static void reset_gdbserver_state(void)
407 g_free(gdbserver_state.processes);
408 gdbserver_state.processes = NULL;
409 gdbserver_state.process_num = 0;
415 #ifdef CONFIG_USER_ONLY
417 static int get_char(void)
423 ret = qemu_recv(gdbserver_state.fd, &ch, 1, 0);
425 if (errno == ECONNRESET)
426 gdbserver_state.fd = -1;
429 } else if (ret == 0) {
430 close(gdbserver_state.fd);
431 gdbserver_state.fd = -1;
447 /* Decide if either remote gdb syscalls or native file IO should be used. */
448 int use_gdb_syscalls(void)
450 SemihostingTarget target = semihosting_get_target();
451 if (target == SEMIHOSTING_TARGET_NATIVE) {
452 /* -semihosting-config target=native */
454 } else if (target == SEMIHOSTING_TARGET_GDB) {
455 /* -semihosting-config target=gdb */
459 /* -semihosting-config target=auto */
460 /* On the first call check if gdb is connected and remember. */
461 if (gdb_syscall_mode == GDB_SYS_UNKNOWN) {
462 gdb_syscall_mode = gdbserver_state.init ?
463 GDB_SYS_ENABLED : GDB_SYS_DISABLED;
465 return gdb_syscall_mode == GDB_SYS_ENABLED;
468 /* Resume execution. */
469 static inline void gdb_continue(void)
472 #ifdef CONFIG_USER_ONLY
473 gdbserver_state.running_state = 1;
474 trace_gdbstub_op_continue();
476 if (!runstate_needs_reset()) {
477 trace_gdbstub_op_continue();
484 * Resume execution, per CPU actions. For user-mode emulation it's
485 * equivalent to gdb_continue.
487 static int gdb_continue_partial(char *newstates)
491 #ifdef CONFIG_USER_ONLY
493 * This is not exactly accurate, but it's an improvement compared to the
494 * previous situation, where only one CPU would be single-stepped.
497 if (newstates[cpu->cpu_index] == 's') {
498 trace_gdbstub_op_stepping(cpu->cpu_index);
499 cpu_single_step(cpu, sstep_flags);
502 gdbserver_state.running_state = 1;
506 if (!runstate_needs_reset()) {
507 if (vm_prepare_start()) {
512 switch (newstates[cpu->cpu_index]) {
515 break; /* nothing to do here */
517 trace_gdbstub_op_stepping(cpu->cpu_index);
518 cpu_single_step(cpu, get_sstep_flags());
523 trace_gdbstub_op_continue_cpu(cpu->cpu_index);
534 qemu_clock_enable(QEMU_CLOCK_VIRTUAL, true);
540 static void put_buffer(const uint8_t *buf, int len)
542 #ifdef CONFIG_USER_ONLY
546 ret = send(gdbserver_state.fd, buf, len, 0);
556 /* XXX this blocks entire thread. Rewrite to use
557 * qemu_chr_fe_write and background I/O callbacks */
558 qemu_chr_fe_write_all(&gdbserver_state.chr, buf, len);
562 static inline int fromhex(int v)
564 if (v >= '0' && v <= '9')
566 else if (v >= 'A' && v <= 'F')
568 else if (v >= 'a' && v <= 'f')
574 static inline int tohex(int v)
582 /* writes 2*len+1 bytes in buf */
583 static void memtohex(GString *buf, const uint8_t *mem, int len)
586 for(i = 0; i < len; i++) {
588 g_string_append_c(buf, tohex(c >> 4));
589 g_string_append_c(buf, tohex(c & 0xf));
591 g_string_append_c(buf, '\0');
594 static void hextomem(GByteArray *mem, const char *buf, int len)
598 for(i = 0; i < len; i++) {
599 guint8 byte = fromhex(buf[0]) << 4 | fromhex(buf[1]);
600 g_byte_array_append(mem, &byte, 1);
605 static void hexdump(const char *buf, int len,
606 void (*trace_fn)(size_t ofs, char const *text))
608 char line_buffer[3 * 16 + 4 + 16 + 1];
611 for (i = 0; i < len || (i & 0xF); ++i) {
612 size_t byte_ofs = i & 15;
615 memset(line_buffer, ' ', 3 * 16 + 4 + 16);
616 line_buffer[3 * 16 + 4 + 16] = 0;
619 size_t col_group = (i >> 2) & 3;
620 size_t hex_col = byte_ofs * 3 + col_group;
621 size_t txt_col = 3 * 16 + 4 + byte_ofs;
626 line_buffer[hex_col + 0] = tohex((value >> 4) & 0xF);
627 line_buffer[hex_col + 1] = tohex((value >> 0) & 0xF);
628 line_buffer[txt_col + 0] = (value >= ' ' && value < 127)
634 trace_fn(i & -16, line_buffer);
638 /* return -1 if error, 0 if OK */
639 static int put_packet_binary(const char *buf, int len, bool dump)
644 if (dump && trace_event_get_state_backends(TRACE_GDBSTUB_IO_BINARYREPLY)) {
645 hexdump(buf, len, trace_gdbstub_io_binaryreply);
649 g_byte_array_set_size(gdbserver_state.last_packet, 0);
650 g_byte_array_append(gdbserver_state.last_packet,
651 (const uint8_t *) "$", 1);
652 g_byte_array_append(gdbserver_state.last_packet,
653 (const uint8_t *) buf, len);
655 for(i = 0; i < len; i++) {
659 footer[1] = tohex((csum >> 4) & 0xf);
660 footer[2] = tohex((csum) & 0xf);
661 g_byte_array_append(gdbserver_state.last_packet, footer, 3);
663 put_buffer(gdbserver_state.last_packet->data,
664 gdbserver_state.last_packet->len);
666 #ifdef CONFIG_USER_ONLY
679 /* return -1 if error, 0 if OK */
680 static int put_packet(const char *buf)
682 trace_gdbstub_io_reply(buf);
684 return put_packet_binary(buf, strlen(buf), false);
687 static void put_strbuf(void)
689 put_packet(gdbserver_state.str_buf->str);
692 /* Encode data using the encoding for 'x' packets. */
693 static void memtox(GString *buf, const char *mem, int len)
700 case '#': case '$': case '*': case '}':
701 g_string_append_c(buf, '}');
702 g_string_append_c(buf, c ^ 0x20);
705 g_string_append_c(buf, c);
711 static uint32_t gdb_get_cpu_pid(CPUState *cpu)
713 /* TODO: In user mode, we should use the task state PID */
714 if (cpu->cluster_index == UNASSIGNED_CLUSTER_INDEX) {
715 /* Return the default process' PID */
716 int index = gdbserver_state.process_num - 1;
717 return gdbserver_state.processes[index].pid;
719 return cpu->cluster_index + 1;
722 static GDBProcess *gdb_get_process(uint32_t pid)
727 /* 0 means any process, we take the first one */
728 return &gdbserver_state.processes[0];
731 for (i = 0; i < gdbserver_state.process_num; i++) {
732 if (gdbserver_state.processes[i].pid == pid) {
733 return &gdbserver_state.processes[i];
740 static GDBProcess *gdb_get_cpu_process(CPUState *cpu)
742 return gdb_get_process(gdb_get_cpu_pid(cpu));
745 static CPUState *find_cpu(uint32_t thread_id)
750 if (cpu_gdb_index(cpu) == thread_id) {
758 static CPUState *get_first_cpu_in_process(GDBProcess *process)
763 if (gdb_get_cpu_pid(cpu) == process->pid) {
771 static CPUState *gdb_next_cpu_in_process(CPUState *cpu)
773 uint32_t pid = gdb_get_cpu_pid(cpu);
777 if (gdb_get_cpu_pid(cpu) == pid) {
787 /* Return the cpu following @cpu, while ignoring unattached processes. */
788 static CPUState *gdb_next_attached_cpu(CPUState *cpu)
793 if (gdb_get_cpu_process(cpu)->attached) {
803 /* Return the first attached cpu */
804 static CPUState *gdb_first_attached_cpu(void)
806 CPUState *cpu = first_cpu;
807 GDBProcess *process = gdb_get_cpu_process(cpu);
809 if (!process->attached) {
810 return gdb_next_attached_cpu(cpu);
816 static CPUState *gdb_get_cpu(uint32_t pid, uint32_t tid)
822 /* 0 means any process/thread, we take the first attached one */
823 return gdb_first_attached_cpu();
824 } else if (pid && !tid) {
825 /* any thread in a specific process */
826 process = gdb_get_process(pid);
828 if (process == NULL) {
832 if (!process->attached) {
836 return get_first_cpu_in_process(process);
838 /* a specific thread */
845 process = gdb_get_cpu_process(cpu);
847 if (pid && process->pid != pid) {
851 if (!process->attached) {
859 static const char *get_feature_xml(const char *p, const char **newp,
865 CPUState *cpu = get_first_cpu_in_process(process);
866 CPUClass *cc = CPU_GET_CLASS(cpu);
869 while (p[len] && p[len] != ':')
874 if (strncmp(p, "target.xml", len) == 0) {
875 char *buf = process->target_xml;
876 const size_t buf_sz = sizeof(process->target_xml);
878 /* Generate the XML description for this CPU. */
883 "<?xml version=\"1.0\"?>"
884 "<!DOCTYPE target SYSTEM \"gdb-target.dtd\">"
886 if (cc->gdb_arch_name) {
887 gchar *arch = cc->gdb_arch_name(cpu);
888 pstrcat(buf, buf_sz, "<architecture>");
889 pstrcat(buf, buf_sz, arch);
890 pstrcat(buf, buf_sz, "</architecture>");
893 pstrcat(buf, buf_sz, "<xi:include href=\"");
894 pstrcat(buf, buf_sz, cc->gdb_core_xml_file);
895 pstrcat(buf, buf_sz, "\"/>");
896 for (r = cpu->gdb_regs; r; r = r->next) {
897 pstrcat(buf, buf_sz, "<xi:include href=\"");
898 pstrcat(buf, buf_sz, r->xml);
899 pstrcat(buf, buf_sz, "\"/>");
901 pstrcat(buf, buf_sz, "</target>");
905 if (cc->gdb_get_dynamic_xml) {
906 char *xmlname = g_strndup(p, len);
907 const char *xml = cc->gdb_get_dynamic_xml(cpu, xmlname);
915 name = xml_builtin[i][0];
916 if (!name || (strncmp(name, p, len) == 0 && strlen(name) == len))
919 return name ? xml_builtin[i][1] : NULL;
922 static int gdb_read_register(CPUState *cpu, GByteArray *buf, int reg)
924 CPUClass *cc = CPU_GET_CLASS(cpu);
925 CPUArchState *env = cpu->env_ptr;
928 if (reg < cc->gdb_num_core_regs) {
929 return cc->gdb_read_register(cpu, buf, reg);
932 for (r = cpu->gdb_regs; r; r = r->next) {
933 if (r->base_reg <= reg && reg < r->base_reg + r->num_regs) {
934 return r->get_reg(env, buf, reg - r->base_reg);
940 static int gdb_write_register(CPUState *cpu, uint8_t *mem_buf, int reg)
942 CPUClass *cc = CPU_GET_CLASS(cpu);
943 CPUArchState *env = cpu->env_ptr;
946 if (reg < cc->gdb_num_core_regs) {
947 return cc->gdb_write_register(cpu, mem_buf, reg);
950 for (r = cpu->gdb_regs; r; r = r->next) {
951 if (r->base_reg <= reg && reg < r->base_reg + r->num_regs) {
952 return r->set_reg(env, mem_buf, reg - r->base_reg);
958 /* Register a supplemental set of CPU registers. If g_pos is nonzero it
959 specifies the first register number and these registers are included in
960 a standard "g" packet. Direction is relative to gdb, i.e. get_reg is
961 gdb reading a CPU register, and set_reg is gdb modifying a CPU register.
964 void gdb_register_coprocessor(CPUState *cpu,
965 gdb_get_reg_cb get_reg, gdb_set_reg_cb set_reg,
966 int num_regs, const char *xml, int g_pos)
969 GDBRegisterState **p;
973 /* Check for duplicates. */
974 if (strcmp((*p)->xml, xml) == 0)
979 s = g_new0(GDBRegisterState, 1);
980 s->base_reg = cpu->gdb_num_regs;
981 s->num_regs = num_regs;
982 s->get_reg = get_reg;
983 s->set_reg = set_reg;
986 /* Add to end of list. */
987 cpu->gdb_num_regs += num_regs;
990 if (g_pos != s->base_reg) {
991 error_report("Error: Bad gdb register numbering for '%s', "
992 "expected %d got %d", xml, g_pos, s->base_reg);
994 cpu->gdb_num_g_regs = cpu->gdb_num_regs;
999 #ifndef CONFIG_USER_ONLY
1000 /* Translate GDB watchpoint type to a flags value for cpu_watchpoint_* */
1001 static inline int xlat_gdb_type(CPUState *cpu, int gdbtype)
1003 static const int xlat[] = {
1004 [GDB_WATCHPOINT_WRITE] = BP_GDB | BP_MEM_WRITE,
1005 [GDB_WATCHPOINT_READ] = BP_GDB | BP_MEM_READ,
1006 [GDB_WATCHPOINT_ACCESS] = BP_GDB | BP_MEM_ACCESS,
1009 CPUClass *cc = CPU_GET_CLASS(cpu);
1010 int cputype = xlat[gdbtype];
1012 if (cc->gdb_stop_before_watchpoint) {
1013 cputype |= BP_STOP_BEFORE_ACCESS;
1019 static int gdb_breakpoint_insert(int type, target_ulong addr, target_ulong len)
1024 if (kvm_enabled()) {
1025 return kvm_insert_breakpoint(gdbserver_state.c_cpu, addr, len, type);
1029 case GDB_BREAKPOINT_SW:
1030 case GDB_BREAKPOINT_HW:
1032 err = cpu_breakpoint_insert(cpu, addr, BP_GDB, NULL);
1038 #ifndef CONFIG_USER_ONLY
1039 case GDB_WATCHPOINT_WRITE:
1040 case GDB_WATCHPOINT_READ:
1041 case GDB_WATCHPOINT_ACCESS:
1043 err = cpu_watchpoint_insert(cpu, addr, len,
1044 xlat_gdb_type(cpu, type), NULL);
1056 static int gdb_breakpoint_remove(int type, target_ulong addr, target_ulong len)
1061 if (kvm_enabled()) {
1062 return kvm_remove_breakpoint(gdbserver_state.c_cpu, addr, len, type);
1066 case GDB_BREAKPOINT_SW:
1067 case GDB_BREAKPOINT_HW:
1069 err = cpu_breakpoint_remove(cpu, addr, BP_GDB);
1075 #ifndef CONFIG_USER_ONLY
1076 case GDB_WATCHPOINT_WRITE:
1077 case GDB_WATCHPOINT_READ:
1078 case GDB_WATCHPOINT_ACCESS:
1080 err = cpu_watchpoint_remove(cpu, addr, len,
1081 xlat_gdb_type(cpu, type));
1092 static inline void gdb_cpu_breakpoint_remove_all(CPUState *cpu)
1094 cpu_breakpoint_remove_all(cpu, BP_GDB);
1095 #ifndef CONFIG_USER_ONLY
1096 cpu_watchpoint_remove_all(cpu, BP_GDB);
1100 static void gdb_process_breakpoint_remove_all(GDBProcess *p)
1102 CPUState *cpu = get_first_cpu_in_process(p);
1105 gdb_cpu_breakpoint_remove_all(cpu);
1106 cpu = gdb_next_cpu_in_process(cpu);
1110 static void gdb_breakpoint_remove_all(void)
1114 if (kvm_enabled()) {
1115 kvm_remove_all_breakpoints(gdbserver_state.c_cpu);
1120 gdb_cpu_breakpoint_remove_all(cpu);
1124 static void gdb_set_cpu_pc(target_ulong pc)
1126 CPUState *cpu = gdbserver_state.c_cpu;
1128 cpu_synchronize_state(cpu);
1129 cpu_set_pc(cpu, pc);
1132 static void gdb_append_thread_id(CPUState *cpu, GString *buf)
1134 if (gdbserver_state.multiprocess) {
1135 g_string_append_printf(buf, "p%02x.%02x",
1136 gdb_get_cpu_pid(cpu), cpu_gdb_index(cpu));
1138 g_string_append_printf(buf, "%02x", cpu_gdb_index(cpu));
1142 typedef enum GDBThreadIdKind {
1144 GDB_ALL_THREADS, /* One process, all threads */
1149 static GDBThreadIdKind read_thread_id(const char *buf, const char **end_buf,
1150 uint32_t *pid, uint32_t *tid)
1157 ret = qemu_strtoul(buf, &buf, 16, &p);
1160 return GDB_READ_THREAD_ERR;
1169 ret = qemu_strtoul(buf, &buf, 16, &t);
1172 return GDB_READ_THREAD_ERR;
1178 return GDB_ALL_PROCESSES;
1186 return GDB_ALL_THREADS;
1193 return GDB_ONE_THREAD;
1197 * gdb_handle_vcont - Parses and handles a vCont packet.
1198 * returns -ENOTSUP if a command is unsupported, -EINVAL or -ERANGE if there is
1199 * a format error, 0 on success.
1201 static int gdb_handle_vcont(const char *p)
1203 int res, signal = 0;
1208 GDBProcess *process;
1210 GDBThreadIdKind kind;
1211 #ifdef CONFIG_USER_ONLY
1212 int max_cpus = 1; /* global variable max_cpus exists only in system mode */
1215 max_cpus = max_cpus <= cpu->cpu_index ? cpu->cpu_index + 1 : max_cpus;
1218 MachineState *ms = MACHINE(qdev_get_machine());
1219 unsigned int max_cpus = ms->smp.max_cpus;
1221 /* uninitialised CPUs stay 0 */
1222 newstates = g_new0(char, max_cpus);
1224 /* mark valid CPUs with 1 */
1226 newstates[cpu->cpu_index] = 1;
1230 * res keeps track of what error we are returning, with -ENOTSUP meaning
1231 * that the command is unknown or unsupported, thus returning an empty
1232 * packet, while -EINVAL and -ERANGE cause an E22 packet, due to invalid,
1233 * or incorrect parameters passed.
1243 if (cur_action == 'C' || cur_action == 'S') {
1244 cur_action = qemu_tolower(cur_action);
1245 res = qemu_strtoul(p, &p, 16, &tmp);
1249 signal = gdb_signal_to_target(tmp);
1250 } else if (cur_action != 'c' && cur_action != 's') {
1251 /* unknown/invalid/unsupported command */
1256 if (*p == '\0' || *p == ';') {
1258 * No thread specifier, action is on "all threads". The
1259 * specification is unclear regarding the process to act on. We
1260 * choose all processes.
1262 kind = GDB_ALL_PROCESSES;
1263 } else if (*p++ == ':') {
1264 kind = read_thread_id(p, &p, &pid, &tid);
1271 case GDB_READ_THREAD_ERR:
1275 case GDB_ALL_PROCESSES:
1276 cpu = gdb_first_attached_cpu();
1278 if (newstates[cpu->cpu_index] == 1) {
1279 newstates[cpu->cpu_index] = cur_action;
1282 cpu = gdb_next_attached_cpu(cpu);
1286 case GDB_ALL_THREADS:
1287 process = gdb_get_process(pid);
1289 if (!process->attached) {
1294 cpu = get_first_cpu_in_process(process);
1296 if (newstates[cpu->cpu_index] == 1) {
1297 newstates[cpu->cpu_index] = cur_action;
1300 cpu = gdb_next_cpu_in_process(cpu);
1304 case GDB_ONE_THREAD:
1305 cpu = gdb_get_cpu(pid, tid);
1307 /* invalid CPU/thread specified */
1313 /* only use if no previous match occourred */
1314 if (newstates[cpu->cpu_index] == 1) {
1315 newstates[cpu->cpu_index] = cur_action;
1320 gdbserver_state.signal = signal;
1321 gdb_continue_partial(newstates);
1329 typedef union GdbCmdVariant {
1332 unsigned long val_ul;
1333 unsigned long long val_ull;
1335 GDBThreadIdKind kind;
1341 #define get_param(p, i) (&g_array_index(p, GdbCmdVariant, i))
1343 static const char *cmd_next_param(const char *param, const char delimiter)
1345 static const char all_delimiters[] = ",;:=";
1346 char curr_delimiters[2] = {0};
1347 const char *delimiters;
1349 if (delimiter == '?') {
1350 delimiters = all_delimiters;
1351 } else if (delimiter == '0') {
1352 return strchr(param, '\0');
1353 } else if (delimiter == '.' && *param) {
1356 curr_delimiters[0] = delimiter;
1357 delimiters = curr_delimiters;
1360 param += strcspn(param, delimiters);
1367 static int cmd_parse_params(const char *data, const char *schema,
1370 const char *curr_schema, *curr_data;
1373 g_assert(params->len == 0);
1375 curr_schema = schema;
1377 while (curr_schema[0] && curr_schema[1] && *curr_data) {
1378 GdbCmdVariant this_param;
1380 switch (curr_schema[0]) {
1382 if (qemu_strtoul(curr_data, &curr_data, 16,
1383 &this_param.val_ul)) {
1386 curr_data = cmd_next_param(curr_data, curr_schema[1]);
1387 g_array_append_val(params, this_param);
1390 if (qemu_strtou64(curr_data, &curr_data, 16,
1391 (uint64_t *)&this_param.val_ull)) {
1394 curr_data = cmd_next_param(curr_data, curr_schema[1]);
1395 g_array_append_val(params, this_param);
1398 this_param.data = curr_data;
1399 curr_data = cmd_next_param(curr_data, curr_schema[1]);
1400 g_array_append_val(params, this_param);
1403 this_param.opcode = *(uint8_t *)curr_data;
1404 curr_data = cmd_next_param(curr_data, curr_schema[1]);
1405 g_array_append_val(params, this_param);
1408 this_param.thread_id.kind =
1409 read_thread_id(curr_data, &curr_data,
1410 &this_param.thread_id.pid,
1411 &this_param.thread_id.tid);
1412 curr_data = cmd_next_param(curr_data, curr_schema[1]);
1413 g_array_append_val(params, this_param);
1416 curr_data = cmd_next_param(curr_data, curr_schema[1]);
1427 typedef void (*GdbCmdHandler)(GArray *params, void *user_ctx);
1430 * cmd_startswith -> cmd is compared using startswith
1433 * schema definitions:
1434 * Each schema parameter entry consists of 2 chars,
1435 * the first char represents the parameter type handling
1436 * the second char represents the delimiter for the next parameter
1438 * Currently supported schema types:
1439 * 'l' -> unsigned long (stored in .val_ul)
1440 * 'L' -> unsigned long long (stored in .val_ull)
1441 * 's' -> string (stored in .data)
1442 * 'o' -> single char (stored in .opcode)
1443 * 't' -> thread id (stored in .thread_id)
1444 * '?' -> skip according to delimiter
1446 * Currently supported delimiters:
1447 * '?' -> Stop at any delimiter (",;:=\0")
1448 * '0' -> Stop at "\0"
1449 * '.' -> Skip 1 char unless reached "\0"
1450 * Any other value is treated as the delimiter value itself
1452 typedef struct GdbCmdParseEntry {
1453 GdbCmdHandler handler;
1455 bool cmd_startswith;
1459 static inline int startswith(const char *string, const char *pattern)
1461 return !strncmp(string, pattern, strlen(pattern));
1464 static int process_string_cmd(void *user_ctx, const char *data,
1465 const GdbCmdParseEntry *cmds, int num_cmds)
1468 g_autoptr(GArray) params = g_array_new(false, true, sizeof(GdbCmdVariant));
1474 for (i = 0; i < num_cmds; i++) {
1475 const GdbCmdParseEntry *cmd = &cmds[i];
1476 g_assert(cmd->handler && cmd->cmd);
1478 if ((cmd->cmd_startswith && !startswith(data, cmd->cmd)) ||
1479 (!cmd->cmd_startswith && strcmp(cmd->cmd, data))) {
1484 if (cmd_parse_params(&data[strlen(cmd->cmd)],
1485 cmd->schema, params)) {
1490 cmd->handler(params, user_ctx);
1497 static void run_cmd_parser(const char *data, const GdbCmdParseEntry *cmd)
1503 g_string_set_size(gdbserver_state.str_buf, 0);
1504 g_byte_array_set_size(gdbserver_state.mem_buf, 0);
1506 /* In case there was an error during the command parsing we must
1507 * send a NULL packet to indicate the command is not supported */
1508 if (process_string_cmd(NULL, data, cmd, 1)) {
1513 static void handle_detach(GArray *params, void *user_ctx)
1515 GDBProcess *process;
1518 if (gdbserver_state.multiprocess) {
1524 pid = get_param(params, 0)->val_ul;
1527 process = gdb_get_process(pid);
1528 gdb_process_breakpoint_remove_all(process);
1529 process->attached = false;
1531 if (pid == gdb_get_cpu_pid(gdbserver_state.c_cpu)) {
1532 gdbserver_state.c_cpu = gdb_first_attached_cpu();
1535 if (pid == gdb_get_cpu_pid(gdbserver_state.g_cpu)) {
1536 gdbserver_state.g_cpu = gdb_first_attached_cpu();
1539 if (!gdbserver_state.c_cpu) {
1540 /* No more process attached */
1541 gdb_syscall_mode = GDB_SYS_DISABLED;
1547 static void handle_thread_alive(GArray *params, void *user_ctx)
1556 if (get_param(params, 0)->thread_id.kind == GDB_READ_THREAD_ERR) {
1561 cpu = gdb_get_cpu(get_param(params, 0)->thread_id.pid,
1562 get_param(params, 0)->thread_id.tid);
1571 static void handle_continue(GArray *params, void *user_ctx)
1574 gdb_set_cpu_pc(get_param(params, 0)->val_ull);
1577 gdbserver_state.signal = 0;
1581 static void handle_cont_with_sig(GArray *params, void *user_ctx)
1583 unsigned long signal = 0;
1586 * Note: C sig;[addr] is currently unsupported and we simply
1587 * omit the addr parameter
1590 signal = get_param(params, 0)->val_ul;
1593 gdbserver_state.signal = gdb_signal_to_target(signal);
1594 if (gdbserver_state.signal == -1) {
1595 gdbserver_state.signal = 0;
1600 static void handle_set_thread(GArray *params, void *user_ctx)
1604 if (params->len != 2) {
1609 if (get_param(params, 1)->thread_id.kind == GDB_READ_THREAD_ERR) {
1614 if (get_param(params, 1)->thread_id.kind != GDB_ONE_THREAD) {
1619 cpu = gdb_get_cpu(get_param(params, 1)->thread_id.pid,
1620 get_param(params, 1)->thread_id.tid);
1627 * Note: This command is deprecated and modern gdb's will be using the
1628 * vCont command instead.
1630 switch (get_param(params, 0)->opcode) {
1632 gdbserver_state.c_cpu = cpu;
1636 gdbserver_state.g_cpu = cpu;
1645 static void handle_insert_bp(GArray *params, void *user_ctx)
1649 if (params->len != 3) {
1654 res = gdb_breakpoint_insert(get_param(params, 0)->val_ul,
1655 get_param(params, 1)->val_ull,
1656 get_param(params, 2)->val_ull);
1660 } else if (res == -ENOSYS) {
1668 static void handle_remove_bp(GArray *params, void *user_ctx)
1672 if (params->len != 3) {
1677 res = gdb_breakpoint_remove(get_param(params, 0)->val_ul,
1678 get_param(params, 1)->val_ull,
1679 get_param(params, 2)->val_ull);
1683 } else if (res == -ENOSYS) {
1692 * handle_set/get_reg
1694 * Older gdb are really dumb, and don't use 'G/g' if 'P/p' is available.
1695 * This works, but can be very slow. Anything new enough to understand
1696 * XML also knows how to use this properly. However to use this we
1697 * need to define a local XML file as well as be talking to a
1698 * reasonably modern gdb. Responding with an empty packet will cause
1699 * the remote gdb to fallback to older methods.
1702 static void handle_set_reg(GArray *params, void *user_ctx)
1711 if (params->len != 2) {
1716 reg_size = strlen(get_param(params, 1)->data) / 2;
1717 hextomem(gdbserver_state.mem_buf, get_param(params, 1)->data, reg_size);
1718 gdb_write_register(gdbserver_state.g_cpu, gdbserver_state.mem_buf->data,
1719 get_param(params, 0)->val_ull);
1723 static void handle_get_reg(GArray *params, void *user_ctx)
1737 reg_size = gdb_read_register(gdbserver_state.g_cpu,
1738 gdbserver_state.mem_buf,
1739 get_param(params, 0)->val_ull);
1744 g_byte_array_set_size(gdbserver_state.mem_buf, reg_size);
1747 memtohex(gdbserver_state.str_buf, gdbserver_state.mem_buf->data, reg_size);
1751 static void handle_write_mem(GArray *params, void *user_ctx)
1753 if (params->len != 3) {
1758 /* hextomem() reads 2*len bytes */
1759 if (get_param(params, 1)->val_ull >
1760 strlen(get_param(params, 2)->data) / 2) {
1765 hextomem(gdbserver_state.mem_buf, get_param(params, 2)->data,
1766 get_param(params, 1)->val_ull);
1767 if (target_memory_rw_debug(gdbserver_state.g_cpu,
1768 get_param(params, 0)->val_ull,
1769 gdbserver_state.mem_buf->data,
1770 gdbserver_state.mem_buf->len, true)) {
1778 static void handle_read_mem(GArray *params, void *user_ctx)
1780 if (params->len != 2) {
1785 /* memtohex() doubles the required space */
1786 if (get_param(params, 1)->val_ull > MAX_PACKET_LENGTH / 2) {
1791 g_byte_array_set_size(gdbserver_state.mem_buf,
1792 get_param(params, 1)->val_ull);
1794 if (target_memory_rw_debug(gdbserver_state.g_cpu,
1795 get_param(params, 0)->val_ull,
1796 gdbserver_state.mem_buf->data,
1797 gdbserver_state.mem_buf->len, false)) {
1802 memtohex(gdbserver_state.str_buf, gdbserver_state.mem_buf->data,
1803 gdbserver_state.mem_buf->len);
1807 static void handle_write_all_regs(GArray *params, void *user_ctx)
1809 target_ulong addr, len;
1817 cpu_synchronize_state(gdbserver_state.g_cpu);
1818 len = strlen(get_param(params, 0)->data) / 2;
1819 hextomem(gdbserver_state.mem_buf, get_param(params, 0)->data, len);
1820 registers = gdbserver_state.mem_buf->data;
1821 for (addr = 0; addr < gdbserver_state.g_cpu->gdb_num_g_regs && len > 0;
1823 reg_size = gdb_write_register(gdbserver_state.g_cpu, registers, addr);
1825 registers += reg_size;
1830 static void handle_read_all_regs(GArray *params, void *user_ctx)
1832 target_ulong addr, len;
1834 cpu_synchronize_state(gdbserver_state.g_cpu);
1835 g_byte_array_set_size(gdbserver_state.mem_buf, 0);
1837 for (addr = 0; addr < gdbserver_state.g_cpu->gdb_num_g_regs; addr++) {
1838 len += gdb_read_register(gdbserver_state.g_cpu,
1839 gdbserver_state.mem_buf,
1842 g_assert(len == gdbserver_state.mem_buf->len);
1844 memtohex(gdbserver_state.str_buf, gdbserver_state.mem_buf->data, len);
1848 static void handle_file_io(GArray *params, void *user_ctx)
1850 if (params->len >= 1 && gdbserver_state.current_syscall_cb) {
1851 target_ulong ret, err;
1853 ret = (target_ulong)get_param(params, 0)->val_ull;
1854 if (params->len >= 2) {
1855 err = (target_ulong)get_param(params, 1)->val_ull;
1859 gdbserver_state.current_syscall_cb(gdbserver_state.c_cpu, ret, err);
1860 gdbserver_state.current_syscall_cb = NULL;
1863 if (params->len >= 3 && get_param(params, 2)->opcode == (uint8_t)'C') {
1871 static void handle_step(GArray *params, void *user_ctx)
1874 gdb_set_cpu_pc((target_ulong)get_param(params, 0)->val_ull);
1877 cpu_single_step(gdbserver_state.c_cpu, get_sstep_flags());
1881 static void handle_backward(GArray *params, void *user_ctx)
1883 if (replay_mode != REPLAY_MODE_PLAY) {
1886 if (params->len == 1) {
1887 switch (get_param(params, 0)->opcode) {
1889 if (replay_reverse_step()) {
1896 if (replay_reverse_continue()) {
1905 /* Default invalid command */
1909 static void handle_v_cont_query(GArray *params, void *user_ctx)
1911 put_packet("vCont;c;C;s;S");
1914 static void handle_v_cont(GArray *params, void *user_ctx)
1922 res = gdb_handle_vcont(get_param(params, 0)->data);
1923 if ((res == -EINVAL) || (res == -ERANGE)) {
1930 static void handle_v_attach(GArray *params, void *user_ctx)
1932 GDBProcess *process;
1935 g_string_assign(gdbserver_state.str_buf, "E22");
1940 process = gdb_get_process(get_param(params, 0)->val_ul);
1945 cpu = get_first_cpu_in_process(process);
1950 process->attached = true;
1951 gdbserver_state.g_cpu = cpu;
1952 gdbserver_state.c_cpu = cpu;
1954 g_string_printf(gdbserver_state.str_buf, "T%02xthread:", GDB_SIGNAL_TRAP);
1955 gdb_append_thread_id(cpu, gdbserver_state.str_buf);
1956 g_string_append_c(gdbserver_state.str_buf, ';');
1961 static void handle_v_kill(GArray *params, void *user_ctx)
1963 /* Kill the target */
1965 error_report("QEMU: Terminated via GDBstub");
1970 static const GdbCmdParseEntry gdb_v_commands_table[] = {
1971 /* Order is important if has same prefix */
1973 .handler = handle_v_cont_query,
1978 .handler = handle_v_cont,
1980 .cmd_startswith = 1,
1984 .handler = handle_v_attach,
1986 .cmd_startswith = 1,
1990 .handler = handle_v_kill,
1996 static void handle_v_commands(GArray *params, void *user_ctx)
2002 if (process_string_cmd(NULL, get_param(params, 0)->data,
2003 gdb_v_commands_table,
2004 ARRAY_SIZE(gdb_v_commands_table))) {
2009 static void handle_query_qemu_sstepbits(GArray *params, void *user_ctx)
2011 g_string_printf(gdbserver_state.str_buf, "ENABLE=%x,NOIRQ=%x,NOTIMER=%x",
2012 SSTEP_ENABLE, SSTEP_NOIRQ, SSTEP_NOTIMER);
2016 static void handle_set_qemu_sstep(GArray *params, void *user_ctx)
2022 sstep_flags = get_param(params, 0)->val_ul;
2026 static void handle_query_qemu_sstep(GArray *params, void *user_ctx)
2028 g_string_printf(gdbserver_state.str_buf, "0x%x", sstep_flags);
2032 static void handle_query_curr_tid(GArray *params, void *user_ctx)
2035 GDBProcess *process;
2038 * "Current thread" remains vague in the spec, so always return
2039 * the first thread of the current process (gdb returns the
2042 process = gdb_get_cpu_process(gdbserver_state.g_cpu);
2043 cpu = get_first_cpu_in_process(process);
2044 g_string_assign(gdbserver_state.str_buf, "QC");
2045 gdb_append_thread_id(cpu, gdbserver_state.str_buf);
2049 static void handle_query_threads(GArray *params, void *user_ctx)
2051 if (!gdbserver_state.query_cpu) {
2056 g_string_assign(gdbserver_state.str_buf, "m");
2057 gdb_append_thread_id(gdbserver_state.query_cpu, gdbserver_state.str_buf);
2059 gdbserver_state.query_cpu = gdb_next_attached_cpu(gdbserver_state.query_cpu);
2062 static void handle_query_first_threads(GArray *params, void *user_ctx)
2064 gdbserver_state.query_cpu = gdb_first_attached_cpu();
2065 handle_query_threads(params, user_ctx);
2068 static void handle_query_thread_extra(GArray *params, void *user_ctx)
2070 g_autoptr(GString) rs = g_string_new(NULL);
2074 get_param(params, 0)->thread_id.kind == GDB_READ_THREAD_ERR) {
2079 cpu = gdb_get_cpu(get_param(params, 0)->thread_id.pid,
2080 get_param(params, 0)->thread_id.tid);
2085 cpu_synchronize_state(cpu);
2087 if (gdbserver_state.multiprocess && (gdbserver_state.process_num > 1)) {
2088 /* Print the CPU model and name in multiprocess mode */
2089 ObjectClass *oc = object_get_class(OBJECT(cpu));
2090 const char *cpu_model = object_class_get_name(oc);
2091 const char *cpu_name =
2092 object_get_canonical_path_component(OBJECT(cpu));
2093 g_string_printf(rs, "%s %s [%s]", cpu_model, cpu_name,
2094 cpu->halted ? "halted " : "running");
2096 g_string_printf(rs, "CPU#%d [%s]", cpu->cpu_index,
2097 cpu->halted ? "halted " : "running");
2099 trace_gdbstub_op_extra_info(rs->str);
2100 memtohex(gdbserver_state.str_buf, (uint8_t *)rs->str, rs->len);
2104 #ifdef CONFIG_USER_ONLY
2105 static void handle_query_offsets(GArray *params, void *user_ctx)
2109 ts = gdbserver_state.c_cpu->opaque;
2110 g_string_printf(gdbserver_state.str_buf,
2111 "Text=" TARGET_ABI_FMT_lx
2112 ";Data=" TARGET_ABI_FMT_lx
2113 ";Bss=" TARGET_ABI_FMT_lx,
2114 ts->info->code_offset,
2115 ts->info->data_offset,
2116 ts->info->data_offset);
2120 static void handle_query_rcmd(GArray *params, void *user_ctx)
2122 const guint8 zero = 0;
2130 len = strlen(get_param(params, 0)->data);
2136 g_assert(gdbserver_state.mem_buf->len == 0);
2138 hextomem(gdbserver_state.mem_buf, get_param(params, 0)->data, len);
2139 g_byte_array_append(gdbserver_state.mem_buf, &zero, 1);
2140 qemu_chr_be_write(gdbserver_state.mon_chr, gdbserver_state.mem_buf->data,
2141 gdbserver_state.mem_buf->len);
2146 static void handle_query_supported(GArray *params, void *user_ctx)
2150 g_string_printf(gdbserver_state.str_buf, "PacketSize=%x", MAX_PACKET_LENGTH);
2151 cc = CPU_GET_CLASS(first_cpu);
2152 if (cc->gdb_core_xml_file) {
2153 g_string_append(gdbserver_state.str_buf, ";qXfer:features:read+");
2156 if (replay_mode == REPLAY_MODE_PLAY) {
2157 g_string_append(gdbserver_state.str_buf,
2158 ";ReverseStep+;ReverseContinue+");
2161 #ifdef CONFIG_USER_ONLY
2162 if (gdbserver_state.c_cpu->opaque) {
2163 g_string_append(gdbserver_state.str_buf, ";qXfer:auxv:read+");
2168 strstr(get_param(params, 0)->data, "multiprocess+")) {
2169 gdbserver_state.multiprocess = true;
2172 g_string_append(gdbserver_state.str_buf, ";vContSupported+;multiprocess+");
2176 static void handle_query_xfer_features(GArray *params, void *user_ctx)
2178 GDBProcess *process;
2180 unsigned long len, total_len, addr;
2184 if (params->len < 3) {
2189 process = gdb_get_cpu_process(gdbserver_state.g_cpu);
2190 cc = CPU_GET_CLASS(gdbserver_state.g_cpu);
2191 if (!cc->gdb_core_xml_file) {
2197 p = get_param(params, 0)->data;
2198 xml = get_feature_xml(p, &p, process);
2204 addr = get_param(params, 1)->val_ul;
2205 len = get_param(params, 2)->val_ul;
2206 total_len = strlen(xml);
2207 if (addr > total_len) {
2212 if (len > (MAX_PACKET_LENGTH - 5) / 2) {
2213 len = (MAX_PACKET_LENGTH - 5) / 2;
2216 if (len < total_len - addr) {
2217 g_string_assign(gdbserver_state.str_buf, "m");
2218 memtox(gdbserver_state.str_buf, xml + addr, len);
2220 g_string_assign(gdbserver_state.str_buf, "l");
2221 memtox(gdbserver_state.str_buf, xml + addr, total_len - addr);
2224 put_packet_binary(gdbserver_state.str_buf->str,
2225 gdbserver_state.str_buf->len, true);
2228 #if defined(CONFIG_USER_ONLY) && defined(CONFIG_LINUX_USER)
2229 static void handle_query_xfer_auxv(GArray *params, void *user_ctx)
2232 unsigned long offset, len, saved_auxv, auxv_len;
2234 if (params->len < 2) {
2239 offset = get_param(params, 0)->val_ul;
2240 len = get_param(params, 1)->val_ul;
2241 ts = gdbserver_state.c_cpu->opaque;
2242 saved_auxv = ts->info->saved_auxv;
2243 auxv_len = ts->info->auxv_len;
2245 if (offset >= auxv_len) {
2250 if (len > (MAX_PACKET_LENGTH - 5) / 2) {
2251 len = (MAX_PACKET_LENGTH - 5) / 2;
2254 if (len < auxv_len - offset) {
2255 g_string_assign(gdbserver_state.str_buf, "m");
2257 g_string_assign(gdbserver_state.str_buf, "l");
2258 len = auxv_len - offset;
2261 g_byte_array_set_size(gdbserver_state.mem_buf, len);
2262 if (target_memory_rw_debug(gdbserver_state.g_cpu, saved_auxv + offset,
2263 gdbserver_state.mem_buf->data, len, false)) {
2268 memtox(gdbserver_state.str_buf,
2269 (const char *)gdbserver_state.mem_buf->data, len);
2270 put_packet_binary(gdbserver_state.str_buf->str,
2271 gdbserver_state.str_buf->len, true);
2275 static void handle_query_attached(GArray *params, void *user_ctx)
2277 put_packet(GDB_ATTACHED);
2280 static void handle_query_qemu_supported(GArray *params, void *user_ctx)
2282 g_string_printf(gdbserver_state.str_buf, "sstepbits;sstep");
2283 #ifndef CONFIG_USER_ONLY
2284 g_string_append(gdbserver_state.str_buf, ";PhyMemMode");
2289 #ifndef CONFIG_USER_ONLY
2290 static void handle_query_qemu_phy_mem_mode(GArray *params,
2293 g_string_printf(gdbserver_state.str_buf, "%d", phy_memory_mode);
2297 static void handle_set_qemu_phy_mem_mode(GArray *params, void *user_ctx)
2304 if (!get_param(params, 0)->val_ul) {
2305 phy_memory_mode = 0;
2307 phy_memory_mode = 1;
2313 static const GdbCmdParseEntry gdb_gen_query_set_common_table[] = {
2314 /* Order is important if has same prefix */
2316 .handler = handle_query_qemu_sstepbits,
2317 .cmd = "qemu.sstepbits",
2320 .handler = handle_query_qemu_sstep,
2321 .cmd = "qemu.sstep",
2324 .handler = handle_set_qemu_sstep,
2325 .cmd = "qemu.sstep=",
2326 .cmd_startswith = 1,
2331 static const GdbCmdParseEntry gdb_gen_query_table[] = {
2333 .handler = handle_query_curr_tid,
2337 .handler = handle_query_threads,
2338 .cmd = "sThreadInfo",
2341 .handler = handle_query_first_threads,
2342 .cmd = "fThreadInfo",
2345 .handler = handle_query_thread_extra,
2346 .cmd = "ThreadExtraInfo,",
2347 .cmd_startswith = 1,
2350 #ifdef CONFIG_USER_ONLY
2352 .handler = handle_query_offsets,
2357 .handler = handle_query_rcmd,
2359 .cmd_startswith = 1,
2364 .handler = handle_query_supported,
2365 .cmd = "Supported:",
2366 .cmd_startswith = 1,
2370 .handler = handle_query_supported,
2375 .handler = handle_query_xfer_features,
2376 .cmd = "Xfer:features:read:",
2377 .cmd_startswith = 1,
2380 #if defined(CONFIG_USER_ONLY) && defined(CONFIG_LINUX_USER)
2382 .handler = handle_query_xfer_auxv,
2383 .cmd = "Xfer:auxv:read::",
2384 .cmd_startswith = 1,
2389 .handler = handle_query_attached,
2394 .handler = handle_query_attached,
2398 .handler = handle_query_qemu_supported,
2399 .cmd = "qemu.Supported",
2401 #ifndef CONFIG_USER_ONLY
2403 .handler = handle_query_qemu_phy_mem_mode,
2404 .cmd = "qemu.PhyMemMode",
2409 static const GdbCmdParseEntry gdb_gen_set_table[] = {
2410 /* Order is important if has same prefix */
2412 .handler = handle_set_qemu_sstep,
2413 .cmd = "qemu.sstep:",
2414 .cmd_startswith = 1,
2417 #ifndef CONFIG_USER_ONLY
2419 .handler = handle_set_qemu_phy_mem_mode,
2420 .cmd = "qemu.PhyMemMode:",
2421 .cmd_startswith = 1,
2427 static void handle_gen_query(GArray *params, void *user_ctx)
2433 if (!process_string_cmd(NULL, get_param(params, 0)->data,
2434 gdb_gen_query_set_common_table,
2435 ARRAY_SIZE(gdb_gen_query_set_common_table))) {
2439 if (process_string_cmd(NULL, get_param(params, 0)->data,
2440 gdb_gen_query_table,
2441 ARRAY_SIZE(gdb_gen_query_table))) {
2446 static void handle_gen_set(GArray *params, void *user_ctx)
2452 if (!process_string_cmd(NULL, get_param(params, 0)->data,
2453 gdb_gen_query_set_common_table,
2454 ARRAY_SIZE(gdb_gen_query_set_common_table))) {
2458 if (process_string_cmd(NULL, get_param(params, 0)->data,
2460 ARRAY_SIZE(gdb_gen_set_table))) {
2465 static void handle_target_halt(GArray *params, void *user_ctx)
2467 g_string_printf(gdbserver_state.str_buf, "T%02xthread:", GDB_SIGNAL_TRAP);
2468 gdb_append_thread_id(gdbserver_state.c_cpu, gdbserver_state.str_buf);
2469 g_string_append_c(gdbserver_state.str_buf, ';');
2472 * Remove all the breakpoints when this query is issued,
2473 * because gdb is doing an initial connect and the state
2474 * should be cleaned up.
2476 gdb_breakpoint_remove_all();
2479 static int gdb_handle_packet(const char *line_buf)
2481 const GdbCmdParseEntry *cmd_parser = NULL;
2483 trace_gdbstub_io_command(line_buf);
2485 switch (line_buf[0]) {
2491 static const GdbCmdParseEntry target_halted_cmd_desc = {
2492 .handler = handle_target_halt,
2496 cmd_parser = &target_halted_cmd_desc;
2501 static const GdbCmdParseEntry continue_cmd_desc = {
2502 .handler = handle_continue,
2504 .cmd_startswith = 1,
2507 cmd_parser = &continue_cmd_desc;
2512 static const GdbCmdParseEntry cont_with_sig_cmd_desc = {
2513 .handler = handle_cont_with_sig,
2515 .cmd_startswith = 1,
2518 cmd_parser = &cont_with_sig_cmd_desc;
2523 static const GdbCmdParseEntry v_cmd_desc = {
2524 .handler = handle_v_commands,
2526 .cmd_startswith = 1,
2529 cmd_parser = &v_cmd_desc;
2533 /* Kill the target */
2534 error_report("QEMU: Terminated via GDBstub");
2539 static const GdbCmdParseEntry detach_cmd_desc = {
2540 .handler = handle_detach,
2542 .cmd_startswith = 1,
2545 cmd_parser = &detach_cmd_desc;
2550 static const GdbCmdParseEntry step_cmd_desc = {
2551 .handler = handle_step,
2553 .cmd_startswith = 1,
2556 cmd_parser = &step_cmd_desc;
2561 static const GdbCmdParseEntry backward_cmd_desc = {
2562 .handler = handle_backward,
2564 .cmd_startswith = 1,
2567 cmd_parser = &backward_cmd_desc;
2572 static const GdbCmdParseEntry file_io_cmd_desc = {
2573 .handler = handle_file_io,
2575 .cmd_startswith = 1,
2578 cmd_parser = &file_io_cmd_desc;
2583 static const GdbCmdParseEntry read_all_regs_cmd_desc = {
2584 .handler = handle_read_all_regs,
2588 cmd_parser = &read_all_regs_cmd_desc;
2593 static const GdbCmdParseEntry write_all_regs_cmd_desc = {
2594 .handler = handle_write_all_regs,
2596 .cmd_startswith = 1,
2599 cmd_parser = &write_all_regs_cmd_desc;
2604 static const GdbCmdParseEntry read_mem_cmd_desc = {
2605 .handler = handle_read_mem,
2607 .cmd_startswith = 1,
2610 cmd_parser = &read_mem_cmd_desc;
2615 static const GdbCmdParseEntry write_mem_cmd_desc = {
2616 .handler = handle_write_mem,
2618 .cmd_startswith = 1,
2621 cmd_parser = &write_mem_cmd_desc;
2626 static const GdbCmdParseEntry get_reg_cmd_desc = {
2627 .handler = handle_get_reg,
2629 .cmd_startswith = 1,
2632 cmd_parser = &get_reg_cmd_desc;
2637 static const GdbCmdParseEntry set_reg_cmd_desc = {
2638 .handler = handle_set_reg,
2640 .cmd_startswith = 1,
2643 cmd_parser = &set_reg_cmd_desc;
2648 static const GdbCmdParseEntry insert_bp_cmd_desc = {
2649 .handler = handle_insert_bp,
2651 .cmd_startswith = 1,
2654 cmd_parser = &insert_bp_cmd_desc;
2659 static const GdbCmdParseEntry remove_bp_cmd_desc = {
2660 .handler = handle_remove_bp,
2662 .cmd_startswith = 1,
2665 cmd_parser = &remove_bp_cmd_desc;
2670 static const GdbCmdParseEntry set_thread_cmd_desc = {
2671 .handler = handle_set_thread,
2673 .cmd_startswith = 1,
2676 cmd_parser = &set_thread_cmd_desc;
2681 static const GdbCmdParseEntry thread_alive_cmd_desc = {
2682 .handler = handle_thread_alive,
2684 .cmd_startswith = 1,
2687 cmd_parser = &thread_alive_cmd_desc;
2692 static const GdbCmdParseEntry gen_query_cmd_desc = {
2693 .handler = handle_gen_query,
2695 .cmd_startswith = 1,
2698 cmd_parser = &gen_query_cmd_desc;
2703 static const GdbCmdParseEntry gen_set_cmd_desc = {
2704 .handler = handle_gen_set,
2706 .cmd_startswith = 1,
2709 cmd_parser = &gen_set_cmd_desc;
2713 /* put empty packet */
2719 run_cmd_parser(line_buf, cmd_parser);
2725 void gdb_set_stop_cpu(CPUState *cpu)
2727 GDBProcess *p = gdb_get_cpu_process(cpu);
2731 * Having a stop CPU corresponding to a process that is not attached
2732 * confuses GDB. So we ignore the request.
2737 gdbserver_state.c_cpu = cpu;
2738 gdbserver_state.g_cpu = cpu;
2741 #ifndef CONFIG_USER_ONLY
2742 static void gdb_vm_state_change(void *opaque, bool running, RunState state)
2744 CPUState *cpu = gdbserver_state.c_cpu;
2745 g_autoptr(GString) buf = g_string_new(NULL);
2746 g_autoptr(GString) tid = g_string_new(NULL);
2750 if (running || gdbserver_state.state == RS_INACTIVE) {
2753 /* Is there a GDB syscall waiting to be sent? */
2754 if (gdbserver_state.current_syscall_cb) {
2755 put_packet(gdbserver_state.syscall_buf);
2760 /* No process attached */
2764 gdb_append_thread_id(cpu, tid);
2767 case RUN_STATE_DEBUG:
2768 if (cpu->watchpoint_hit) {
2769 switch (cpu->watchpoint_hit->flags & BP_MEM_ACCESS) {
2780 trace_gdbstub_hit_watchpoint(type, cpu_gdb_index(cpu),
2781 (target_ulong)cpu->watchpoint_hit->vaddr);
2782 g_string_printf(buf, "T%02xthread:%s;%swatch:" TARGET_FMT_lx ";",
2783 GDB_SIGNAL_TRAP, tid->str, type,
2784 (target_ulong)cpu->watchpoint_hit->vaddr);
2785 cpu->watchpoint_hit = NULL;
2788 trace_gdbstub_hit_break();
2791 ret = GDB_SIGNAL_TRAP;
2793 case RUN_STATE_PAUSED:
2794 trace_gdbstub_hit_paused();
2795 ret = GDB_SIGNAL_INT;
2797 case RUN_STATE_SHUTDOWN:
2798 trace_gdbstub_hit_shutdown();
2799 ret = GDB_SIGNAL_QUIT;
2801 case RUN_STATE_IO_ERROR:
2802 trace_gdbstub_hit_io_error();
2803 ret = GDB_SIGNAL_IO;
2805 case RUN_STATE_WATCHDOG:
2806 trace_gdbstub_hit_watchdog();
2807 ret = GDB_SIGNAL_ALRM;
2809 case RUN_STATE_INTERNAL_ERROR:
2810 trace_gdbstub_hit_internal_error();
2811 ret = GDB_SIGNAL_ABRT;
2813 case RUN_STATE_SAVE_VM:
2814 case RUN_STATE_RESTORE_VM:
2816 case RUN_STATE_FINISH_MIGRATE:
2817 ret = GDB_SIGNAL_XCPU;
2820 trace_gdbstub_hit_unknown(state);
2821 ret = GDB_SIGNAL_UNKNOWN;
2824 gdb_set_stop_cpu(cpu);
2825 g_string_printf(buf, "T%02xthread:%s;", ret, tid->str);
2828 put_packet(buf->str);
2830 /* disable single step if it was enabled */
2831 cpu_single_step(cpu, 0);
2835 /* Send a gdb syscall request.
2836 This accepts limited printf-style format specifiers, specifically:
2837 %x - target_ulong argument printed in hex.
2838 %lx - 64-bit argument printed in hex.
2839 %s - string pointer (target_ulong) and length (int) pair. */
2840 void gdb_do_syscallv(gdb_syscall_complete_cb cb, const char *fmt, va_list va)
2847 if (!gdbserver_state.init) {
2851 gdbserver_state.current_syscall_cb = cb;
2852 #ifndef CONFIG_USER_ONLY
2853 vm_stop(RUN_STATE_DEBUG);
2855 p = &gdbserver_state.syscall_buf[0];
2856 p_end = &gdbserver_state.syscall_buf[sizeof(gdbserver_state.syscall_buf)];
2863 addr = va_arg(va, target_ulong);
2864 p += snprintf(p, p_end - p, TARGET_FMT_lx, addr);
2867 if (*(fmt++) != 'x')
2869 i64 = va_arg(va, uint64_t);
2870 p += snprintf(p, p_end - p, "%" PRIx64, i64);
2873 addr = va_arg(va, target_ulong);
2874 p += snprintf(p, p_end - p, TARGET_FMT_lx "/%x",
2875 addr, va_arg(va, int));
2879 error_report("gdbstub: Bad syscall format string '%s'",
2888 #ifdef CONFIG_USER_ONLY
2889 put_packet(gdbserver_state.syscall_buf);
2890 /* Return control to gdb for it to process the syscall request.
2891 * Since the protocol requires that gdb hands control back to us
2892 * using a "here are the results" F packet, we don't need to check
2893 * gdb_handlesig's return value (which is the signal to deliver if
2894 * execution was resumed via a continue packet).
2896 gdb_handlesig(gdbserver_state.c_cpu, 0);
2898 /* In this case wait to send the syscall packet until notification that
2899 the CPU has stopped. This must be done because if the packet is sent
2900 now the reply from the syscall request could be received while the CPU
2901 is still in the running state, which can cause packets to be dropped
2902 and state transition 'T' packets to be sent while the syscall is still
2904 qemu_cpu_kick(gdbserver_state.c_cpu);
2908 void gdb_do_syscall(gdb_syscall_complete_cb cb, const char *fmt, ...)
2913 gdb_do_syscallv(cb, fmt, va);
2917 static void gdb_read_byte(uint8_t ch)
2921 #ifndef CONFIG_USER_ONLY
2922 if (gdbserver_state.last_packet->len) {
2923 /* Waiting for a response to the last packet. If we see the start
2924 of a new command then abandon the previous response. */
2926 trace_gdbstub_err_got_nack();
2927 put_buffer(gdbserver_state.last_packet->data,
2928 gdbserver_state.last_packet->len);
2929 } else if (ch == '+') {
2930 trace_gdbstub_io_got_ack();
2932 trace_gdbstub_io_got_unexpected(ch);
2935 if (ch == '+' || ch == '$') {
2936 g_byte_array_set_size(gdbserver_state.last_packet, 0);
2941 if (runstate_is_running()) {
2942 /* when the CPU is running, we cannot do anything except stop
2943 it when receiving a char */
2944 vm_stop(RUN_STATE_PAUSED);
2948 switch(gdbserver_state.state) {
2951 /* start of command packet */
2952 gdbserver_state.line_buf_index = 0;
2953 gdbserver_state.line_sum = 0;
2954 gdbserver_state.state = RS_GETLINE;
2956 trace_gdbstub_err_garbage(ch);
2961 /* start escape sequence */
2962 gdbserver_state.state = RS_GETLINE_ESC;
2963 gdbserver_state.line_sum += ch;
2964 } else if (ch == '*') {
2965 /* start run length encoding sequence */
2966 gdbserver_state.state = RS_GETLINE_RLE;
2967 gdbserver_state.line_sum += ch;
2968 } else if (ch == '#') {
2969 /* end of command, start of checksum*/
2970 gdbserver_state.state = RS_CHKSUM1;
2971 } else if (gdbserver_state.line_buf_index >= sizeof(gdbserver_state.line_buf) - 1) {
2972 trace_gdbstub_err_overrun();
2973 gdbserver_state.state = RS_IDLE;
2975 /* unescaped command character */
2976 gdbserver_state.line_buf[gdbserver_state.line_buf_index++] = ch;
2977 gdbserver_state.line_sum += ch;
2980 case RS_GETLINE_ESC:
2982 /* unexpected end of command in escape sequence */
2983 gdbserver_state.state = RS_CHKSUM1;
2984 } else if (gdbserver_state.line_buf_index >= sizeof(gdbserver_state.line_buf) - 1) {
2985 /* command buffer overrun */
2986 trace_gdbstub_err_overrun();
2987 gdbserver_state.state = RS_IDLE;
2989 /* parse escaped character and leave escape state */
2990 gdbserver_state.line_buf[gdbserver_state.line_buf_index++] = ch ^ 0x20;
2991 gdbserver_state.line_sum += ch;
2992 gdbserver_state.state = RS_GETLINE;
2995 case RS_GETLINE_RLE:
2997 * Run-length encoding is explained in "Debugging with GDB /
2998 * Appendix E GDB Remote Serial Protocol / Overview".
3000 if (ch < ' ' || ch == '#' || ch == '$' || ch > 126) {
3001 /* invalid RLE count encoding */
3002 trace_gdbstub_err_invalid_repeat(ch);
3003 gdbserver_state.state = RS_GETLINE;
3005 /* decode repeat length */
3006 int repeat = ch - ' ' + 3;
3007 if (gdbserver_state.line_buf_index + repeat >= sizeof(gdbserver_state.line_buf) - 1) {
3008 /* that many repeats would overrun the command buffer */
3009 trace_gdbstub_err_overrun();
3010 gdbserver_state.state = RS_IDLE;
3011 } else if (gdbserver_state.line_buf_index < 1) {
3012 /* got a repeat but we have nothing to repeat */
3013 trace_gdbstub_err_invalid_rle();
3014 gdbserver_state.state = RS_GETLINE;
3016 /* repeat the last character */
3017 memset(gdbserver_state.line_buf + gdbserver_state.line_buf_index,
3018 gdbserver_state.line_buf[gdbserver_state.line_buf_index - 1], repeat);
3019 gdbserver_state.line_buf_index += repeat;
3020 gdbserver_state.line_sum += ch;
3021 gdbserver_state.state = RS_GETLINE;
3026 /* get high hex digit of checksum */
3027 if (!isxdigit(ch)) {
3028 trace_gdbstub_err_checksum_invalid(ch);
3029 gdbserver_state.state = RS_GETLINE;
3032 gdbserver_state.line_buf[gdbserver_state.line_buf_index] = '\0';
3033 gdbserver_state.line_csum = fromhex(ch) << 4;
3034 gdbserver_state.state = RS_CHKSUM2;
3037 /* get low hex digit of checksum */
3038 if (!isxdigit(ch)) {
3039 trace_gdbstub_err_checksum_invalid(ch);
3040 gdbserver_state.state = RS_GETLINE;
3043 gdbserver_state.line_csum |= fromhex(ch);
3045 if (gdbserver_state.line_csum != (gdbserver_state.line_sum & 0xff)) {
3046 trace_gdbstub_err_checksum_incorrect(gdbserver_state.line_sum, gdbserver_state.line_csum);
3047 /* send NAK reply */
3049 put_buffer(&reply, 1);
3050 gdbserver_state.state = RS_IDLE;
3052 /* send ACK reply */
3054 put_buffer(&reply, 1);
3055 gdbserver_state.state = gdb_handle_packet(gdbserver_state.line_buf);
3064 /* Tell the remote gdb that the process has exited. */
3065 void gdb_exit(int code)
3069 if (!gdbserver_state.init) {
3072 #ifdef CONFIG_USER_ONLY
3073 if (gdbserver_state.socket_path) {
3074 unlink(gdbserver_state.socket_path);
3076 if (gdbserver_state.fd < 0) {
3081 trace_gdbstub_op_exiting((uint8_t)code);
3083 snprintf(buf, sizeof(buf), "W%02x", (uint8_t)code);
3086 #ifndef CONFIG_USER_ONLY
3087 qemu_chr_fe_deinit(&gdbserver_state.chr, true);
3092 * Create the process that will contain all the "orphan" CPUs (that are not
3093 * part of a CPU cluster). Note that if this process contains no CPUs, it won't
3094 * be attachable and thus will be invisible to the user.
3096 static void create_default_process(GDBState *s)
3098 GDBProcess *process;
3101 if (gdbserver_state.process_num) {
3102 max_pid = s->processes[s->process_num - 1].pid;
3105 s->processes = g_renew(GDBProcess, s->processes, ++s->process_num);
3106 process = &s->processes[s->process_num - 1];
3108 /* We need an available PID slot for this process */
3109 assert(max_pid < UINT32_MAX);
3111 process->pid = max_pid + 1;
3112 process->attached = false;
3113 process->target_xml[0] = '\0';
3116 #ifdef CONFIG_USER_ONLY
3118 gdb_handlesig(CPUState *cpu, int sig)
3123 if (!gdbserver_state.init || gdbserver_state.fd < 0) {
3127 /* disable single step if it was enabled */
3128 cpu_single_step(cpu, 0);
3132 snprintf(buf, sizeof(buf), "S%02x", target_signal_to_gdb(sig));
3135 /* put_packet() might have detected that the peer terminated the
3137 if (gdbserver_state.fd < 0) {
3142 gdbserver_state.state = RS_IDLE;
3143 gdbserver_state.running_state = 0;
3144 while (gdbserver_state.running_state == 0) {
3145 n = read(gdbserver_state.fd, buf, 256);
3149 for (i = 0; i < n; i++) {
3150 gdb_read_byte(buf[i]);
3153 /* XXX: Connection closed. Should probably wait for another
3154 connection before continuing. */
3156 close(gdbserver_state.fd);
3158 gdbserver_state.fd = -1;
3162 sig = gdbserver_state.signal;
3163 gdbserver_state.signal = 0;
3167 /* Tell the remote gdb that the process has exited due to SIG. */
3168 void gdb_signalled(CPUArchState *env, int sig)
3172 if (!gdbserver_state.init || gdbserver_state.fd < 0) {
3176 snprintf(buf, sizeof(buf), "X%02x", target_signal_to_gdb(sig));
3180 static void gdb_accept_init(int fd)
3182 init_gdbserver_state();
3183 create_default_process(&gdbserver_state);
3184 gdbserver_state.processes[0].attached = true;
3185 gdbserver_state.c_cpu = gdb_first_attached_cpu();
3186 gdbserver_state.g_cpu = gdbserver_state.c_cpu;
3187 gdbserver_state.fd = fd;
3188 gdb_has_xml = false;
3191 static bool gdb_accept_socket(int gdb_fd)
3196 fd = accept(gdb_fd, NULL, NULL);
3197 if (fd < 0 && errno != EINTR) {
3198 perror("accept socket");
3200 } else if (fd >= 0) {
3201 qemu_set_cloexec(fd);
3206 gdb_accept_init(fd);
3210 static int gdbserver_open_socket(const char *path)
3212 struct sockaddr_un sockaddr;
3215 fd = socket(AF_UNIX, SOCK_STREAM, 0);
3217 perror("create socket");
3221 sockaddr.sun_family = AF_UNIX;
3222 pstrcpy(sockaddr.sun_path, sizeof(sockaddr.sun_path) - 1, path);
3223 ret = bind(fd, (struct sockaddr *)&sockaddr, sizeof(sockaddr));
3225 perror("bind socket");
3229 ret = listen(fd, 1);
3231 perror("listen socket");
3239 static bool gdb_accept_tcp(int gdb_fd)
3241 struct sockaddr_in sockaddr;
3246 len = sizeof(sockaddr);
3247 fd = accept(gdb_fd, (struct sockaddr *)&sockaddr, &len);
3248 if (fd < 0 && errno != EINTR) {
3251 } else if (fd >= 0) {
3252 qemu_set_cloexec(fd);
3257 /* set short latency */
3258 if (socket_set_nodelay(fd)) {
3259 perror("setsockopt");
3264 gdb_accept_init(fd);
3268 static int gdbserver_open_port(int port)
3270 struct sockaddr_in sockaddr;
3273 fd = socket(PF_INET, SOCK_STREAM, 0);
3278 qemu_set_cloexec(fd);
3280 socket_set_fast_reuse(fd);
3282 sockaddr.sin_family = AF_INET;
3283 sockaddr.sin_port = htons(port);
3284 sockaddr.sin_addr.s_addr = 0;
3285 ret = bind(fd, (struct sockaddr *)&sockaddr, sizeof(sockaddr));
3291 ret = listen(fd, 1);
3301 int gdbserver_start(const char *port_or_path)
3303 int port = g_ascii_strtoull(port_or_path, NULL, 10);
3307 gdb_fd = gdbserver_open_port(port);
3309 gdb_fd = gdbserver_open_socket(port_or_path);
3316 if (port > 0 && gdb_accept_tcp(gdb_fd)) {
3318 } else if (gdb_accept_socket(gdb_fd)) {
3319 gdbserver_state.socket_path = g_strdup(port_or_path);
3328 /* Disable gdb stub for child processes. */
3329 void gdbserver_fork(CPUState *cpu)
3331 if (!gdbserver_state.init || gdbserver_state.fd < 0) {
3334 close(gdbserver_state.fd);
3335 gdbserver_state.fd = -1;
3336 cpu_breakpoint_remove_all(cpu, BP_GDB);
3337 cpu_watchpoint_remove_all(cpu, BP_GDB);
3340 static int gdb_chr_can_receive(void *opaque)
3342 /* We can handle an arbitrarily large amount of data.
3343 Pick the maximum packet size, which is as good as anything. */
3344 return MAX_PACKET_LENGTH;
3347 static void gdb_chr_receive(void *opaque, const uint8_t *buf, int size)
3351 for (i = 0; i < size; i++) {
3352 gdb_read_byte(buf[i]);
3356 static void gdb_chr_event(void *opaque, QEMUChrEvent event)
3359 GDBState *s = (GDBState *) opaque;
3362 case CHR_EVENT_OPENED:
3363 /* Start with first process attached, others detached */
3364 for (i = 0; i < s->process_num; i++) {
3365 s->processes[i].attached = !i;
3368 s->c_cpu = gdb_first_attached_cpu();
3369 s->g_cpu = s->c_cpu;
3371 vm_stop(RUN_STATE_PAUSED);
3372 replay_gdb_attached();
3373 gdb_has_xml = false;
3380 static int gdb_monitor_write(Chardev *chr, const uint8_t *buf, int len)
3382 g_autoptr(GString) hex_buf = g_string_new("O");
3383 memtohex(hex_buf, buf, len);
3384 put_packet(hex_buf->str);
3389 static void gdb_sigterm_handler(int signal)
3391 if (runstate_is_running()) {
3392 vm_stop(RUN_STATE_PAUSED);
3397 static void gdb_monitor_open(Chardev *chr, ChardevBackend *backend,
3398 bool *be_opened, Error **errp)
3403 static void char_gdb_class_init(ObjectClass *oc, void *data)
3405 ChardevClass *cc = CHARDEV_CLASS(oc);
3407 cc->internal = true;
3408 cc->open = gdb_monitor_open;
3409 cc->chr_write = gdb_monitor_write;
3412 #define TYPE_CHARDEV_GDB "chardev-gdb"
3414 static const TypeInfo char_gdb_type_info = {
3415 .name = TYPE_CHARDEV_GDB,
3416 .parent = TYPE_CHARDEV,
3417 .class_init = char_gdb_class_init,
3420 static int find_cpu_clusters(Object *child, void *opaque)
3422 if (object_dynamic_cast(child, TYPE_CPU_CLUSTER)) {
3423 GDBState *s = (GDBState *) opaque;
3424 CPUClusterState *cluster = CPU_CLUSTER(child);
3425 GDBProcess *process;
3427 s->processes = g_renew(GDBProcess, s->processes, ++s->process_num);
3429 process = &s->processes[s->process_num - 1];
3432 * GDB process IDs -1 and 0 are reserved. To avoid subtle errors at
3433 * runtime, we enforce here that the machine does not use a cluster ID
3434 * that would lead to PID 0.
3436 assert(cluster->cluster_id != UINT32_MAX);
3437 process->pid = cluster->cluster_id + 1;
3438 process->attached = false;
3439 process->target_xml[0] = '\0';
3444 return object_child_foreach(child, find_cpu_clusters, opaque);
3447 static int pid_order(const void *a, const void *b)
3449 GDBProcess *pa = (GDBProcess *) a;
3450 GDBProcess *pb = (GDBProcess *) b;
3452 if (pa->pid < pb->pid) {
3454 } else if (pa->pid > pb->pid) {
3461 static void create_processes(GDBState *s)
3463 object_child_foreach(object_get_root(), find_cpu_clusters, s);
3465 if (gdbserver_state.processes) {
3467 qsort(gdbserver_state.processes, gdbserver_state.process_num, sizeof(gdbserver_state.processes[0]), pid_order);
3470 create_default_process(s);
3473 int gdbserver_start(const char *device)
3475 trace_gdbstub_op_start(device);
3477 char gdbstub_device_name[128];
3478 Chardev *chr = NULL;
3482 error_report("gdbstub: meaningless to attach gdb to a "
3483 "machine without any CPU.");
3489 if (strcmp(device, "none") != 0) {
3490 if (strstart(device, "tcp:", NULL)) {
3491 /* enforce required TCP attributes */
3492 snprintf(gdbstub_device_name, sizeof(gdbstub_device_name),
3493 "%s,wait=off,nodelay=on,server=on", device);
3494 device = gdbstub_device_name;
3497 else if (strcmp(device, "stdio") == 0) {
3498 struct sigaction act;
3500 memset(&act, 0, sizeof(act));
3501 act.sa_handler = gdb_sigterm_handler;
3502 sigaction(SIGINT, &act, NULL);
3506 * FIXME: it's a bit weird to allow using a mux chardev here
3507 * and implicitly setup a monitor. We may want to break this.
3509 chr = qemu_chr_new_noreplay("gdb", device, true, NULL);
3514 if (!gdbserver_state.init) {
3515 init_gdbserver_state();
3517 qemu_add_vm_change_state_handler(gdb_vm_state_change, NULL);
3519 /* Initialize a monitor terminal for gdb */
3520 mon_chr = qemu_chardev_new(NULL, TYPE_CHARDEV_GDB,
3521 NULL, NULL, &error_abort);
3522 monitor_init_hmp(mon_chr, false, &error_abort);
3524 qemu_chr_fe_deinit(&gdbserver_state.chr, true);
3525 mon_chr = gdbserver_state.mon_chr;
3526 reset_gdbserver_state();
3529 create_processes(&gdbserver_state);
3532 qemu_chr_fe_init(&gdbserver_state.chr, chr, &error_abort);
3533 qemu_chr_fe_set_handlers(&gdbserver_state.chr, gdb_chr_can_receive,
3534 gdb_chr_receive, gdb_chr_event,
3535 NULL, &gdbserver_state, NULL, true);
3537 gdbserver_state.state = chr ? RS_IDLE : RS_INACTIVE;
3538 gdbserver_state.mon_chr = mon_chr;
3539 gdbserver_state.current_syscall_cb = NULL;
3544 static void register_types(void)
3546 type_register_static(&char_gdb_type_info);
3549 type_init(register_types);