gdbstub: move str_buf to GDBState and use GString
[qemu/ar7.git] / gdbstub.c
blobf6b42825445cf4e57c52d3f3e50d343feddb3c9c
1 /*
2 * gdb server stub
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-root.h"
34 #ifdef CONFIG_USER_ONLY
35 #include "qemu.h"
36 #else
37 #include "monitor/monitor.h"
38 #include "chardev/char.h"
39 #include "chardev/char-fe.h"
40 #include "sysemu/sysemu.h"
41 #include "exec/gdbstub.h"
42 #include "hw/cpu/cluster.h"
43 #include "hw/boards.h"
44 #endif
46 #define MAX_PACKET_LENGTH 4096
48 #include "qemu/sockets.h"
49 #include "sysemu/hw_accel.h"
50 #include "sysemu/kvm.h"
51 #include "sysemu/runstate.h"
52 #include "hw/semihosting/semihost.h"
53 #include "exec/exec-all.h"
55 #ifdef CONFIG_USER_ONLY
56 #define GDB_ATTACHED "0"
57 #else
58 #define GDB_ATTACHED "1"
59 #endif
61 #ifndef CONFIG_USER_ONLY
62 static int phy_memory_mode;
63 #endif
65 static inline int target_memory_rw_debug(CPUState *cpu, target_ulong addr,
66 uint8_t *buf, int len, bool is_write)
68 CPUClass *cc;
70 #ifndef CONFIG_USER_ONLY
71 if (phy_memory_mode) {
72 if (is_write) {
73 cpu_physical_memory_write(addr, buf, len);
74 } else {
75 cpu_physical_memory_read(addr, buf, len);
77 return 0;
79 #endif
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;
97 return ts->ts_tid;
98 #else
99 return cpu->cpu_index + 1;
100 #endif
103 enum {
104 GDB_SIGNAL_0 = 0,
105 GDB_SIGNAL_INT = 2,
106 GDB_SIGNAL_QUIT = 3,
107 GDB_SIGNAL_TRAP = 5,
108 GDB_SIGNAL_ABRT = 6,
109 GDB_SIGNAL_ALRM = 14,
110 GDB_SIGNAL_IO = 23,
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[] = {
124 TARGET_SIGHUP,
125 TARGET_SIGINT,
126 TARGET_SIGQUIT,
127 TARGET_SIGILL,
128 TARGET_SIGTRAP,
129 TARGET_SIGABRT,
130 -1, /* SIGEMT */
131 TARGET_SIGFPE,
132 TARGET_SIGKILL,
133 TARGET_SIGBUS,
134 TARGET_SIGSEGV,
135 TARGET_SIGSYS,
136 TARGET_SIGPIPE,
137 TARGET_SIGALRM,
138 TARGET_SIGTERM,
139 TARGET_SIGURG,
140 TARGET_SIGSTOP,
141 TARGET_SIGTSTP,
142 TARGET_SIGCONT,
143 TARGET_SIGCHLD,
144 TARGET_SIGTTIN,
145 TARGET_SIGTTOU,
146 TARGET_SIGIO,
147 TARGET_SIGXCPU,
148 TARGET_SIGXFSZ,
149 TARGET_SIGVTALRM,
150 TARGET_SIGPROF,
151 TARGET_SIGWINCH,
152 -1, /* SIGLOST */
153 TARGET_SIGUSR1,
154 TARGET_SIGUSR2,
155 #ifdef TARGET_SIGPWR
156 TARGET_SIGPWR,
157 #else
159 #endif
160 -1, /* SIGPOLL */
172 #ifdef __SIGRTMIN
173 __SIGRTMIN + 1,
174 __SIGRTMIN + 2,
175 __SIGRTMIN + 3,
176 __SIGRTMIN + 4,
177 __SIGRTMIN + 5,
178 __SIGRTMIN + 6,
179 __SIGRTMIN + 7,
180 __SIGRTMIN + 8,
181 __SIGRTMIN + 9,
182 __SIGRTMIN + 10,
183 __SIGRTMIN + 11,
184 __SIGRTMIN + 12,
185 __SIGRTMIN + 13,
186 __SIGRTMIN + 14,
187 __SIGRTMIN + 15,
188 __SIGRTMIN + 16,
189 __SIGRTMIN + 17,
190 __SIGRTMIN + 18,
191 __SIGRTMIN + 19,
192 __SIGRTMIN + 20,
193 __SIGRTMIN + 21,
194 __SIGRTMIN + 22,
195 __SIGRTMIN + 23,
196 __SIGRTMIN + 24,
197 __SIGRTMIN + 25,
198 __SIGRTMIN + 26,
199 __SIGRTMIN + 27,
200 __SIGRTMIN + 28,
201 __SIGRTMIN + 29,
202 __SIGRTMIN + 30,
203 __SIGRTMIN + 31,
204 -1, /* SIGCANCEL */
205 __SIGRTMIN,
206 __SIGRTMIN + 32,
207 __SIGRTMIN + 33,
208 __SIGRTMIN + 34,
209 __SIGRTMIN + 35,
210 __SIGRTMIN + 36,
211 __SIGRTMIN + 37,
212 __SIGRTMIN + 38,
213 __SIGRTMIN + 39,
214 __SIGRTMIN + 40,
215 __SIGRTMIN + 41,
216 __SIGRTMIN + 42,
217 __SIGRTMIN + 43,
218 __SIGRTMIN + 44,
219 __SIGRTMIN + 45,
220 __SIGRTMIN + 46,
221 __SIGRTMIN + 47,
222 __SIGRTMIN + 48,
223 __SIGRTMIN + 49,
224 __SIGRTMIN + 50,
225 __SIGRTMIN + 51,
226 __SIGRTMIN + 52,
227 __SIGRTMIN + 53,
228 __SIGRTMIN + 54,
229 __SIGRTMIN + 55,
230 __SIGRTMIN + 56,
231 __SIGRTMIN + 57,
232 __SIGRTMIN + 58,
233 __SIGRTMIN + 59,
234 __SIGRTMIN + 60,
235 __SIGRTMIN + 61,
236 __SIGRTMIN + 62,
237 __SIGRTMIN + 63,
238 __SIGRTMIN + 64,
239 __SIGRTMIN + 65,
240 __SIGRTMIN + 66,
241 __SIGRTMIN + 67,
242 __SIGRTMIN + 68,
243 __SIGRTMIN + 69,
244 __SIGRTMIN + 70,
245 __SIGRTMIN + 71,
246 __SIGRTMIN + 72,
247 __SIGRTMIN + 73,
248 __SIGRTMIN + 74,
249 __SIGRTMIN + 75,
250 __SIGRTMIN + 76,
251 __SIGRTMIN + 77,
252 __SIGRTMIN + 78,
253 __SIGRTMIN + 79,
254 __SIGRTMIN + 80,
255 __SIGRTMIN + 81,
256 __SIGRTMIN + 82,
257 __SIGRTMIN + 83,
258 __SIGRTMIN + 84,
259 __SIGRTMIN + 85,
260 __SIGRTMIN + 86,
261 __SIGRTMIN + 87,
262 __SIGRTMIN + 88,
263 __SIGRTMIN + 89,
264 __SIGRTMIN + 90,
265 __SIGRTMIN + 91,
266 __SIGRTMIN + 92,
267 __SIGRTMIN + 93,
268 __SIGRTMIN + 94,
269 __SIGRTMIN + 95,
270 -1, /* SIGINFO */
271 -1, /* UNKNOWN */
272 -1, /* DEFAULT */
279 #endif
281 #else
282 /* In system mode we only need SIGINT and SIGTRAP; other signals
283 are not yet supported. */
285 enum {
286 TARGET_SIGINT = 2,
287 TARGET_SIGTRAP = 5
290 static int gdb_signal_table[] = {
293 TARGET_SIGINT,
296 TARGET_SIGTRAP
298 #endif
300 #ifdef CONFIG_USER_ONLY
301 static int target_signal_to_gdb (int sig)
303 int i;
304 for (i = 0; i < ARRAY_SIZE (gdb_signal_table); i++)
305 if (gdb_signal_table[i] == sig)
306 return i;
307 return GDB_SIGNAL_UNKNOWN;
309 #endif
311 static int gdb_signal_to_target (int sig)
313 if (sig < ARRAY_SIZE (gdb_signal_table))
314 return gdb_signal_table[sig];
315 else
316 return -1;
319 typedef struct GDBRegisterState {
320 int base_reg;
321 int num_regs;
322 gdb_reg_cb get_reg;
323 gdb_reg_cb set_reg;
324 const char *xml;
325 struct GDBRegisterState *next;
326 } GDBRegisterState;
328 typedef struct GDBProcess {
329 uint32_t pid;
330 bool attached;
332 char target_xml[1024];
333 } GDBProcess;
335 enum RSState {
336 RS_INACTIVE,
337 RS_IDLE,
338 RS_GETLINE,
339 RS_GETLINE_ESC,
340 RS_GETLINE_RLE,
341 RS_CHKSUM1,
342 RS_CHKSUM2,
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];
351 int line_buf_index;
352 int line_sum; /* running checksum */
353 int line_csum; /* checksum at the end of the packet */
354 uint8_t last_packet[MAX_PACKET_LENGTH + 4];
355 int last_packet_len;
356 int signal;
357 #ifdef CONFIG_USER_ONLY
358 int fd;
359 int running_state;
360 #else
361 CharBackend chr;
362 Chardev *mon_chr;
363 #endif
364 bool multiprocess;
365 GDBProcess *processes;
366 int process_num;
367 char syscall_buf[256];
368 gdb_syscall_complete_cb current_syscall_cb;
369 GString *str_buf;
370 } GDBState;
372 /* By default use no IRQs and no timers while single stepping so as to
373 * make single stepping like an ICE HW step.
375 static int sstep_flags = SSTEP_ENABLE|SSTEP_NOIRQ|SSTEP_NOTIMER;
377 static GDBState gdbserver_state;
379 static void init_gdbserver_state(void)
381 g_assert(!gdbserver_state.init);
382 memset(&gdbserver_state, 0, sizeof(GDBState));
383 gdbserver_state.init = true;
384 gdbserver_state.str_buf = g_string_new(NULL);
387 #ifndef CONFIG_USER_ONLY
388 static void reset_gdbserver_state(void)
390 g_free(gdbserver_state.processes);
391 gdbserver_state.processes = NULL;
392 gdbserver_state.process_num = 0;
394 #endif
396 bool gdb_has_xml;
398 #ifdef CONFIG_USER_ONLY
399 /* XXX: This is not thread safe. Do we care? */
400 static int gdbserver_fd = -1;
402 static int get_char(void)
404 uint8_t ch;
405 int ret;
407 for(;;) {
408 ret = qemu_recv(gdbserver_state.fd, &ch, 1, 0);
409 if (ret < 0) {
410 if (errno == ECONNRESET)
411 gdbserver_state.fd = -1;
412 if (errno != EINTR)
413 return -1;
414 } else if (ret == 0) {
415 close(gdbserver_state.fd);
416 gdbserver_state.fd = -1;
417 return -1;
418 } else {
419 break;
422 return ch;
424 #endif
426 static enum {
427 GDB_SYS_UNKNOWN,
428 GDB_SYS_ENABLED,
429 GDB_SYS_DISABLED,
430 } gdb_syscall_mode;
432 /* Decide if either remote gdb syscalls or native file IO should be used. */
433 int use_gdb_syscalls(void)
435 SemihostingTarget target = semihosting_get_target();
436 if (target == SEMIHOSTING_TARGET_NATIVE) {
437 /* -semihosting-config target=native */
438 return false;
439 } else if (target == SEMIHOSTING_TARGET_GDB) {
440 /* -semihosting-config target=gdb */
441 return true;
444 /* -semihosting-config target=auto */
445 /* On the first call check if gdb is connected and remember. */
446 if (gdb_syscall_mode == GDB_SYS_UNKNOWN) {
447 gdb_syscall_mode = gdbserver_state.init ?
448 GDB_SYS_ENABLED : GDB_SYS_DISABLED;
450 return gdb_syscall_mode == GDB_SYS_ENABLED;
453 /* Resume execution. */
454 static inline void gdb_continue(void)
457 #ifdef CONFIG_USER_ONLY
458 gdbserver_state.running_state = 1;
459 trace_gdbstub_op_continue();
460 #else
461 if (!runstate_needs_reset()) {
462 trace_gdbstub_op_continue();
463 vm_start();
465 #endif
469 * Resume execution, per CPU actions. For user-mode emulation it's
470 * equivalent to gdb_continue.
472 static int gdb_continue_partial(char *newstates)
474 CPUState *cpu;
475 int res = 0;
476 #ifdef CONFIG_USER_ONLY
478 * This is not exactly accurate, but it's an improvement compared to the
479 * previous situation, where only one CPU would be single-stepped.
481 CPU_FOREACH(cpu) {
482 if (newstates[cpu->cpu_index] == 's') {
483 trace_gdbstub_op_stepping(cpu->cpu_index);
484 cpu_single_step(cpu, sstep_flags);
487 gdbserver_state.running_state = 1;
488 #else
489 int flag = 0;
491 if (!runstate_needs_reset()) {
492 if (vm_prepare_start()) {
493 return 0;
496 CPU_FOREACH(cpu) {
497 switch (newstates[cpu->cpu_index]) {
498 case 0:
499 case 1:
500 break; /* nothing to do here */
501 case 's':
502 trace_gdbstub_op_stepping(cpu->cpu_index);
503 cpu_single_step(cpu, sstep_flags);
504 cpu_resume(cpu);
505 flag = 1;
506 break;
507 case 'c':
508 trace_gdbstub_op_continue_cpu(cpu->cpu_index);
509 cpu_resume(cpu);
510 flag = 1;
511 break;
512 default:
513 res = -1;
514 break;
518 if (flag) {
519 qemu_clock_enable(QEMU_CLOCK_VIRTUAL, true);
521 #endif
522 return res;
525 static void put_buffer(const uint8_t *buf, int len)
527 #ifdef CONFIG_USER_ONLY
528 int ret;
530 while (len > 0) {
531 ret = send(gdbserver_state.fd, buf, len, 0);
532 if (ret < 0) {
533 if (errno != EINTR)
534 return;
535 } else {
536 buf += ret;
537 len -= ret;
540 #else
541 /* XXX this blocks entire thread. Rewrite to use
542 * qemu_chr_fe_write and background I/O callbacks */
543 qemu_chr_fe_write_all(&gdbserver_state.chr, buf, len);
544 #endif
547 static inline int fromhex(int v)
549 if (v >= '0' && v <= '9')
550 return v - '0';
551 else if (v >= 'A' && v <= 'F')
552 return v - 'A' + 10;
553 else if (v >= 'a' && v <= 'f')
554 return v - 'a' + 10;
555 else
556 return 0;
559 static inline int tohex(int v)
561 if (v < 10)
562 return v + '0';
563 else
564 return v - 10 + 'a';
567 /* writes 2*len+1 bytes in buf */
568 static void memtohex(GString *buf, const uint8_t *mem, int len)
570 int i, c;
571 for(i = 0; i < len; i++) {
572 c = mem[i];
573 g_string_append_c(buf, tohex(c >> 4));
574 g_string_append_c(buf, tohex(c & 0xf));
576 g_string_append_c(buf, '\0');
579 static void hextomem(uint8_t *mem, const char *buf, int len)
581 int i;
583 for(i = 0; i < len; i++) {
584 mem[i] = (fromhex(buf[0]) << 4) | fromhex(buf[1]);
585 buf += 2;
589 static void hexdump(const char *buf, int len,
590 void (*trace_fn)(size_t ofs, char const *text))
592 char line_buffer[3 * 16 + 4 + 16 + 1];
594 size_t i;
595 for (i = 0; i < len || (i & 0xF); ++i) {
596 size_t byte_ofs = i & 15;
598 if (byte_ofs == 0) {
599 memset(line_buffer, ' ', 3 * 16 + 4 + 16);
600 line_buffer[3 * 16 + 4 + 16] = 0;
603 size_t col_group = (i >> 2) & 3;
604 size_t hex_col = byte_ofs * 3 + col_group;
605 size_t txt_col = 3 * 16 + 4 + byte_ofs;
607 if (i < len) {
608 char value = buf[i];
610 line_buffer[hex_col + 0] = tohex((value >> 4) & 0xF);
611 line_buffer[hex_col + 1] = tohex((value >> 0) & 0xF);
612 line_buffer[txt_col + 0] = (value >= ' ' && value < 127)
613 ? value
614 : '.';
617 if (byte_ofs == 0xF)
618 trace_fn(i & -16, line_buffer);
622 /* return -1 if error, 0 if OK */
623 static int put_packet_binary(const char *buf, int len, bool dump)
625 int csum, i;
626 uint8_t *p;
627 uint8_t *ps = &gdbserver_state.last_packet[0];
629 if (dump && trace_event_get_state_backends(TRACE_GDBSTUB_IO_BINARYREPLY)) {
630 hexdump(buf, len, trace_gdbstub_io_binaryreply);
633 for(;;) {
634 p = ps;
635 *(p++) = '$';
636 memcpy(p, buf, len);
637 p += len;
638 csum = 0;
639 for(i = 0; i < len; i++) {
640 csum += buf[i];
642 *(p++) = '#';
643 *(p++) = tohex((csum >> 4) & 0xf);
644 *(p++) = tohex((csum) & 0xf);
646 gdbserver_state.last_packet_len = p - ps;
647 put_buffer(ps, gdbserver_state.last_packet_len);
649 #ifdef CONFIG_USER_ONLY
650 i = get_char();
651 if (i < 0)
652 return -1;
653 if (i == '+')
654 break;
655 #else
656 break;
657 #endif
659 return 0;
662 /* return -1 if error, 0 if OK */
663 static int put_packet(const char *buf)
665 trace_gdbstub_io_reply(buf);
667 return put_packet_binary(buf, strlen(buf), false);
670 static void put_strbuf(void)
672 put_packet(gdbserver_state.str_buf->str);
675 /* Encode data using the encoding for 'x' packets. */
676 static void memtox(GString *buf, const char *mem, int len)
678 char c;
680 while (len--) {
681 c = *(mem++);
682 switch (c) {
683 case '#': case '$': case '*': case '}':
684 g_string_append_c(buf, '}');
685 g_string_append_c(buf, c ^ 0x20);
686 break;
687 default:
688 g_string_append_c(buf, c);
689 break;
694 static uint32_t gdb_get_cpu_pid(CPUState *cpu)
696 /* TODO: In user mode, we should use the task state PID */
697 if (cpu->cluster_index == UNASSIGNED_CLUSTER_INDEX) {
698 /* Return the default process' PID */
699 int index = gdbserver_state.process_num - 1;
700 return gdbserver_state.processes[index].pid;
702 return cpu->cluster_index + 1;
705 static GDBProcess *gdb_get_process(uint32_t pid)
707 int i;
709 if (!pid) {
710 /* 0 means any process, we take the first one */
711 return &gdbserver_state.processes[0];
714 for (i = 0; i < gdbserver_state.process_num; i++) {
715 if (gdbserver_state.processes[i].pid == pid) {
716 return &gdbserver_state.processes[i];
720 return NULL;
723 static GDBProcess *gdb_get_cpu_process(CPUState *cpu)
725 return gdb_get_process(gdb_get_cpu_pid(cpu));
728 static CPUState *find_cpu(uint32_t thread_id)
730 CPUState *cpu;
732 CPU_FOREACH(cpu) {
733 if (cpu_gdb_index(cpu) == thread_id) {
734 return cpu;
738 return NULL;
741 static CPUState *get_first_cpu_in_process(GDBProcess *process)
743 CPUState *cpu;
745 CPU_FOREACH(cpu) {
746 if (gdb_get_cpu_pid(cpu) == process->pid) {
747 return cpu;
751 return NULL;
754 static CPUState *gdb_next_cpu_in_process(CPUState *cpu)
756 uint32_t pid = gdb_get_cpu_pid(cpu);
757 cpu = CPU_NEXT(cpu);
759 while (cpu) {
760 if (gdb_get_cpu_pid(cpu) == pid) {
761 break;
764 cpu = CPU_NEXT(cpu);
767 return cpu;
770 /* Return the cpu following @cpu, while ignoring unattached processes. */
771 static CPUState *gdb_next_attached_cpu(CPUState *cpu)
773 cpu = CPU_NEXT(cpu);
775 while (cpu) {
776 if (gdb_get_cpu_process(cpu)->attached) {
777 break;
780 cpu = CPU_NEXT(cpu);
783 return cpu;
786 /* Return the first attached cpu */
787 static CPUState *gdb_first_attached_cpu(void)
789 CPUState *cpu = first_cpu;
790 GDBProcess *process = gdb_get_cpu_process(cpu);
792 if (!process->attached) {
793 return gdb_next_attached_cpu(cpu);
796 return cpu;
799 static CPUState *gdb_get_cpu(uint32_t pid, uint32_t tid)
801 GDBProcess *process;
802 CPUState *cpu;
804 if (!pid && !tid) {
805 /* 0 means any process/thread, we take the first attached one */
806 return gdb_first_attached_cpu();
807 } else if (pid && !tid) {
808 /* any thread in a specific process */
809 process = gdb_get_process(pid);
811 if (process == NULL) {
812 return NULL;
815 if (!process->attached) {
816 return NULL;
819 return get_first_cpu_in_process(process);
820 } else {
821 /* a specific thread */
822 cpu = find_cpu(tid);
824 if (cpu == NULL) {
825 return NULL;
828 process = gdb_get_cpu_process(cpu);
830 if (pid && process->pid != pid) {
831 return NULL;
834 if (!process->attached) {
835 return NULL;
838 return cpu;
842 static const char *get_feature_xml(const char *p, const char **newp,
843 GDBProcess *process)
845 size_t len;
846 int i;
847 const char *name;
848 CPUState *cpu = get_first_cpu_in_process(process);
849 CPUClass *cc = CPU_GET_CLASS(cpu);
851 len = 0;
852 while (p[len] && p[len] != ':')
853 len++;
854 *newp = p + len;
856 name = NULL;
857 if (strncmp(p, "target.xml", len) == 0) {
858 char *buf = process->target_xml;
859 const size_t buf_sz = sizeof(process->target_xml);
861 /* Generate the XML description for this CPU. */
862 if (!buf[0]) {
863 GDBRegisterState *r;
865 pstrcat(buf, buf_sz,
866 "<?xml version=\"1.0\"?>"
867 "<!DOCTYPE target SYSTEM \"gdb-target.dtd\">"
868 "<target>");
869 if (cc->gdb_arch_name) {
870 gchar *arch = cc->gdb_arch_name(cpu);
871 pstrcat(buf, buf_sz, "<architecture>");
872 pstrcat(buf, buf_sz, arch);
873 pstrcat(buf, buf_sz, "</architecture>");
874 g_free(arch);
876 pstrcat(buf, buf_sz, "<xi:include href=\"");
877 pstrcat(buf, buf_sz, cc->gdb_core_xml_file);
878 pstrcat(buf, buf_sz, "\"/>");
879 for (r = cpu->gdb_regs; r; r = r->next) {
880 pstrcat(buf, buf_sz, "<xi:include href=\"");
881 pstrcat(buf, buf_sz, r->xml);
882 pstrcat(buf, buf_sz, "\"/>");
884 pstrcat(buf, buf_sz, "</target>");
886 return buf;
888 if (cc->gdb_get_dynamic_xml) {
889 char *xmlname = g_strndup(p, len);
890 const char *xml = cc->gdb_get_dynamic_xml(cpu, xmlname);
892 g_free(xmlname);
893 if (xml) {
894 return xml;
897 for (i = 0; ; i++) {
898 name = xml_builtin[i][0];
899 if (!name || (strncmp(name, p, len) == 0 && strlen(name) == len))
900 break;
902 return name ? xml_builtin[i][1] : NULL;
905 static int gdb_read_register(CPUState *cpu, uint8_t *mem_buf, int reg)
907 CPUClass *cc = CPU_GET_CLASS(cpu);
908 CPUArchState *env = cpu->env_ptr;
909 GDBRegisterState *r;
911 if (reg < cc->gdb_num_core_regs) {
912 return cc->gdb_read_register(cpu, mem_buf, reg);
915 for (r = cpu->gdb_regs; r; r = r->next) {
916 if (r->base_reg <= reg && reg < r->base_reg + r->num_regs) {
917 return r->get_reg(env, mem_buf, reg - r->base_reg);
920 return 0;
923 static int gdb_write_register(CPUState *cpu, uint8_t *mem_buf, int reg)
925 CPUClass *cc = CPU_GET_CLASS(cpu);
926 CPUArchState *env = cpu->env_ptr;
927 GDBRegisterState *r;
929 if (reg < cc->gdb_num_core_regs) {
930 return cc->gdb_write_register(cpu, mem_buf, reg);
933 for (r = cpu->gdb_regs; r; r = r->next) {
934 if (r->base_reg <= reg && reg < r->base_reg + r->num_regs) {
935 return r->set_reg(env, mem_buf, reg - r->base_reg);
938 return 0;
941 /* Register a supplemental set of CPU registers. If g_pos is nonzero it
942 specifies the first register number and these registers are included in
943 a standard "g" packet. Direction is relative to gdb, i.e. get_reg is
944 gdb reading a CPU register, and set_reg is gdb modifying a CPU register.
947 void gdb_register_coprocessor(CPUState *cpu,
948 gdb_reg_cb get_reg, gdb_reg_cb set_reg,
949 int num_regs, const char *xml, int g_pos)
951 GDBRegisterState *s;
952 GDBRegisterState **p;
954 p = &cpu->gdb_regs;
955 while (*p) {
956 /* Check for duplicates. */
957 if (strcmp((*p)->xml, xml) == 0)
958 return;
959 p = &(*p)->next;
962 s = g_new0(GDBRegisterState, 1);
963 s->base_reg = cpu->gdb_num_regs;
964 s->num_regs = num_regs;
965 s->get_reg = get_reg;
966 s->set_reg = set_reg;
967 s->xml = xml;
969 /* Add to end of list. */
970 cpu->gdb_num_regs += num_regs;
971 *p = s;
972 if (g_pos) {
973 if (g_pos != s->base_reg) {
974 error_report("Error: Bad gdb register numbering for '%s', "
975 "expected %d got %d", xml, g_pos, s->base_reg);
976 } else {
977 cpu->gdb_num_g_regs = cpu->gdb_num_regs;
982 #ifndef CONFIG_USER_ONLY
983 /* Translate GDB watchpoint type to a flags value for cpu_watchpoint_* */
984 static inline int xlat_gdb_type(CPUState *cpu, int gdbtype)
986 static const int xlat[] = {
987 [GDB_WATCHPOINT_WRITE] = BP_GDB | BP_MEM_WRITE,
988 [GDB_WATCHPOINT_READ] = BP_GDB | BP_MEM_READ,
989 [GDB_WATCHPOINT_ACCESS] = BP_GDB | BP_MEM_ACCESS,
992 CPUClass *cc = CPU_GET_CLASS(cpu);
993 int cputype = xlat[gdbtype];
995 if (cc->gdb_stop_before_watchpoint) {
996 cputype |= BP_STOP_BEFORE_ACCESS;
998 return cputype;
1000 #endif
1002 static int gdb_breakpoint_insert(int type, target_ulong addr, target_ulong len)
1004 CPUState *cpu;
1005 int err = 0;
1007 if (kvm_enabled()) {
1008 return kvm_insert_breakpoint(gdbserver_state.c_cpu, addr, len, type);
1011 switch (type) {
1012 case GDB_BREAKPOINT_SW:
1013 case GDB_BREAKPOINT_HW:
1014 CPU_FOREACH(cpu) {
1015 err = cpu_breakpoint_insert(cpu, addr, BP_GDB, NULL);
1016 if (err) {
1017 break;
1020 return err;
1021 #ifndef CONFIG_USER_ONLY
1022 case GDB_WATCHPOINT_WRITE:
1023 case GDB_WATCHPOINT_READ:
1024 case GDB_WATCHPOINT_ACCESS:
1025 CPU_FOREACH(cpu) {
1026 err = cpu_watchpoint_insert(cpu, addr, len,
1027 xlat_gdb_type(cpu, type), NULL);
1028 if (err) {
1029 break;
1032 return err;
1033 #endif
1034 default:
1035 return -ENOSYS;
1039 static int gdb_breakpoint_remove(int type, target_ulong addr, target_ulong len)
1041 CPUState *cpu;
1042 int err = 0;
1044 if (kvm_enabled()) {
1045 return kvm_remove_breakpoint(gdbserver_state.c_cpu, addr, len, type);
1048 switch (type) {
1049 case GDB_BREAKPOINT_SW:
1050 case GDB_BREAKPOINT_HW:
1051 CPU_FOREACH(cpu) {
1052 err = cpu_breakpoint_remove(cpu, addr, BP_GDB);
1053 if (err) {
1054 break;
1057 return err;
1058 #ifndef CONFIG_USER_ONLY
1059 case GDB_WATCHPOINT_WRITE:
1060 case GDB_WATCHPOINT_READ:
1061 case GDB_WATCHPOINT_ACCESS:
1062 CPU_FOREACH(cpu) {
1063 err = cpu_watchpoint_remove(cpu, addr, len,
1064 xlat_gdb_type(cpu, type));
1065 if (err)
1066 break;
1068 return err;
1069 #endif
1070 default:
1071 return -ENOSYS;
1075 static inline void gdb_cpu_breakpoint_remove_all(CPUState *cpu)
1077 cpu_breakpoint_remove_all(cpu, BP_GDB);
1078 #ifndef CONFIG_USER_ONLY
1079 cpu_watchpoint_remove_all(cpu, BP_GDB);
1080 #endif
1083 static void gdb_process_breakpoint_remove_all(GDBProcess *p)
1085 CPUState *cpu = get_first_cpu_in_process(p);
1087 while (cpu) {
1088 gdb_cpu_breakpoint_remove_all(cpu);
1089 cpu = gdb_next_cpu_in_process(cpu);
1093 static void gdb_breakpoint_remove_all(void)
1095 CPUState *cpu;
1097 if (kvm_enabled()) {
1098 kvm_remove_all_breakpoints(gdbserver_state.c_cpu);
1099 return;
1102 CPU_FOREACH(cpu) {
1103 gdb_cpu_breakpoint_remove_all(cpu);
1107 static void gdb_set_cpu_pc(target_ulong pc)
1109 CPUState *cpu = gdbserver_state.c_cpu;
1111 cpu_synchronize_state(cpu);
1112 cpu_set_pc(cpu, pc);
1115 static void gdb_append_thread_id(CPUState *cpu, GString *buf)
1117 if (gdbserver_state.multiprocess) {
1118 g_string_append_printf(buf, "p%02x.%02x",
1119 gdb_get_cpu_pid(cpu), cpu_gdb_index(cpu));
1120 } else {
1121 g_string_append_printf(buf, "%02x", cpu_gdb_index(cpu));
1125 typedef enum GDBThreadIdKind {
1126 GDB_ONE_THREAD = 0,
1127 GDB_ALL_THREADS, /* One process, all threads */
1128 GDB_ALL_PROCESSES,
1129 GDB_READ_THREAD_ERR
1130 } GDBThreadIdKind;
1132 static GDBThreadIdKind read_thread_id(const char *buf, const char **end_buf,
1133 uint32_t *pid, uint32_t *tid)
1135 unsigned long p, t;
1136 int ret;
1138 if (*buf == 'p') {
1139 buf++;
1140 ret = qemu_strtoul(buf, &buf, 16, &p);
1142 if (ret) {
1143 return GDB_READ_THREAD_ERR;
1146 /* Skip '.' */
1147 buf++;
1148 } else {
1149 p = 1;
1152 ret = qemu_strtoul(buf, &buf, 16, &t);
1154 if (ret) {
1155 return GDB_READ_THREAD_ERR;
1158 *end_buf = buf;
1160 if (p == -1) {
1161 return GDB_ALL_PROCESSES;
1164 if (pid) {
1165 *pid = p;
1168 if (t == -1) {
1169 return GDB_ALL_THREADS;
1172 if (tid) {
1173 *tid = t;
1176 return GDB_ONE_THREAD;
1180 * gdb_handle_vcont - Parses and handles a vCont packet.
1181 * returns -ENOTSUP if a command is unsupported, -EINVAL or -ERANGE if there is
1182 * a format error, 0 on success.
1184 static int gdb_handle_vcont(const char *p)
1186 int res, signal = 0;
1187 char cur_action;
1188 char *newstates;
1189 unsigned long tmp;
1190 uint32_t pid, tid;
1191 GDBProcess *process;
1192 CPUState *cpu;
1193 GDBThreadIdKind kind;
1194 #ifdef CONFIG_USER_ONLY
1195 int max_cpus = 1; /* global variable max_cpus exists only in system mode */
1197 CPU_FOREACH(cpu) {
1198 max_cpus = max_cpus <= cpu->cpu_index ? cpu->cpu_index + 1 : max_cpus;
1200 #else
1201 MachineState *ms = MACHINE(qdev_get_machine());
1202 unsigned int max_cpus = ms->smp.max_cpus;
1203 #endif
1204 /* uninitialised CPUs stay 0 */
1205 newstates = g_new0(char, max_cpus);
1207 /* mark valid CPUs with 1 */
1208 CPU_FOREACH(cpu) {
1209 newstates[cpu->cpu_index] = 1;
1213 * res keeps track of what error we are returning, with -ENOTSUP meaning
1214 * that the command is unknown or unsupported, thus returning an empty
1215 * packet, while -EINVAL and -ERANGE cause an E22 packet, due to invalid,
1216 * or incorrect parameters passed.
1218 res = 0;
1219 while (*p) {
1220 if (*p++ != ';') {
1221 res = -ENOTSUP;
1222 goto out;
1225 cur_action = *p++;
1226 if (cur_action == 'C' || cur_action == 'S') {
1227 cur_action = qemu_tolower(cur_action);
1228 res = qemu_strtoul(p + 1, &p, 16, &tmp);
1229 if (res) {
1230 goto out;
1232 signal = gdb_signal_to_target(tmp);
1233 } else if (cur_action != 'c' && cur_action != 's') {
1234 /* unknown/invalid/unsupported command */
1235 res = -ENOTSUP;
1236 goto out;
1239 if (*p == '\0' || *p == ';') {
1241 * No thread specifier, action is on "all threads". The
1242 * specification is unclear regarding the process to act on. We
1243 * choose all processes.
1245 kind = GDB_ALL_PROCESSES;
1246 } else if (*p++ == ':') {
1247 kind = read_thread_id(p, &p, &pid, &tid);
1248 } else {
1249 res = -ENOTSUP;
1250 goto out;
1253 switch (kind) {
1254 case GDB_READ_THREAD_ERR:
1255 res = -EINVAL;
1256 goto out;
1258 case GDB_ALL_PROCESSES:
1259 cpu = gdb_first_attached_cpu();
1260 while (cpu) {
1261 if (newstates[cpu->cpu_index] == 1) {
1262 newstates[cpu->cpu_index] = cur_action;
1265 cpu = gdb_next_attached_cpu(cpu);
1267 break;
1269 case GDB_ALL_THREADS:
1270 process = gdb_get_process(pid);
1272 if (!process->attached) {
1273 res = -EINVAL;
1274 goto out;
1277 cpu = get_first_cpu_in_process(process);
1278 while (cpu) {
1279 if (newstates[cpu->cpu_index] == 1) {
1280 newstates[cpu->cpu_index] = cur_action;
1283 cpu = gdb_next_cpu_in_process(cpu);
1285 break;
1287 case GDB_ONE_THREAD:
1288 cpu = gdb_get_cpu(pid, tid);
1290 /* invalid CPU/thread specified */
1291 if (!cpu) {
1292 res = -EINVAL;
1293 goto out;
1296 /* only use if no previous match occourred */
1297 if (newstates[cpu->cpu_index] == 1) {
1298 newstates[cpu->cpu_index] = cur_action;
1300 break;
1303 gdbserver_state.signal = signal;
1304 gdb_continue_partial(newstates);
1306 out:
1307 g_free(newstates);
1309 return res;
1312 typedef union GdbCmdVariant {
1313 const char *data;
1314 uint8_t opcode;
1315 unsigned long val_ul;
1316 unsigned long long val_ull;
1317 struct {
1318 GDBThreadIdKind kind;
1319 uint32_t pid;
1320 uint32_t tid;
1321 } thread_id;
1322 } GdbCmdVariant;
1324 static const char *cmd_next_param(const char *param, const char delimiter)
1326 static const char all_delimiters[] = ",;:=";
1327 char curr_delimiters[2] = {0};
1328 const char *delimiters;
1330 if (delimiter == '?') {
1331 delimiters = all_delimiters;
1332 } else if (delimiter == '0') {
1333 return strchr(param, '\0');
1334 } else if (delimiter == '.' && *param) {
1335 return param + 1;
1336 } else {
1337 curr_delimiters[0] = delimiter;
1338 delimiters = curr_delimiters;
1341 param += strcspn(param, delimiters);
1342 if (*param) {
1343 param++;
1345 return param;
1348 static int cmd_parse_params(const char *data, const char *schema,
1349 GdbCmdVariant *params, int *num_params)
1351 int curr_param;
1352 const char *curr_schema, *curr_data;
1354 *num_params = 0;
1356 if (!schema) {
1357 return 0;
1360 curr_schema = schema;
1361 curr_param = 0;
1362 curr_data = data;
1363 while (curr_schema[0] && curr_schema[1] && *curr_data) {
1364 switch (curr_schema[0]) {
1365 case 'l':
1366 if (qemu_strtoul(curr_data, &curr_data, 16,
1367 &params[curr_param].val_ul)) {
1368 return -EINVAL;
1370 curr_param++;
1371 curr_data = cmd_next_param(curr_data, curr_schema[1]);
1372 break;
1373 case 'L':
1374 if (qemu_strtou64(curr_data, &curr_data, 16,
1375 (uint64_t *)&params[curr_param].val_ull)) {
1376 return -EINVAL;
1378 curr_param++;
1379 curr_data = cmd_next_param(curr_data, curr_schema[1]);
1380 break;
1381 case 's':
1382 params[curr_param].data = curr_data;
1383 curr_param++;
1384 curr_data = cmd_next_param(curr_data, curr_schema[1]);
1385 break;
1386 case 'o':
1387 params[curr_param].opcode = *(uint8_t *)curr_data;
1388 curr_param++;
1389 curr_data = cmd_next_param(curr_data, curr_schema[1]);
1390 break;
1391 case 't':
1392 params[curr_param].thread_id.kind =
1393 read_thread_id(curr_data, &curr_data,
1394 &params[curr_param].thread_id.pid,
1395 &params[curr_param].thread_id.tid);
1396 curr_param++;
1397 curr_data = cmd_next_param(curr_data, curr_schema[1]);
1398 break;
1399 case '?':
1400 curr_data = cmd_next_param(curr_data, curr_schema[1]);
1401 break;
1402 default:
1403 return -EINVAL;
1405 curr_schema += 2;
1408 *num_params = curr_param;
1409 return 0;
1412 typedef struct GdbCmdContext {
1413 GdbCmdVariant *params;
1414 int num_params;
1415 uint8_t mem_buf[MAX_PACKET_LENGTH];
1416 } GdbCmdContext;
1418 typedef void (*GdbCmdHandler)(GdbCmdContext *gdb_ctx, void *user_ctx);
1421 * cmd_startswith -> cmd is compared using startswith
1424 * schema definitions:
1425 * Each schema parameter entry consists of 2 chars,
1426 * the first char represents the parameter type handling
1427 * the second char represents the delimiter for the next parameter
1429 * Currently supported schema types:
1430 * 'l' -> unsigned long (stored in .val_ul)
1431 * 'L' -> unsigned long long (stored in .val_ull)
1432 * 's' -> string (stored in .data)
1433 * 'o' -> single char (stored in .opcode)
1434 * 't' -> thread id (stored in .thread_id)
1435 * '?' -> skip according to delimiter
1437 * Currently supported delimiters:
1438 * '?' -> Stop at any delimiter (",;:=\0")
1439 * '0' -> Stop at "\0"
1440 * '.' -> Skip 1 char unless reached "\0"
1441 * Any other value is treated as the delimiter value itself
1443 typedef struct GdbCmdParseEntry {
1444 GdbCmdHandler handler;
1445 const char *cmd;
1446 bool cmd_startswith;
1447 const char *schema;
1448 } GdbCmdParseEntry;
1450 static inline int startswith(const char *string, const char *pattern)
1452 return !strncmp(string, pattern, strlen(pattern));
1455 static int process_string_cmd(void *user_ctx, const char *data,
1456 const GdbCmdParseEntry *cmds, int num_cmds)
1458 int i, schema_len, max_num_params = 0;
1459 GdbCmdContext gdb_ctx;
1461 if (!cmds) {
1462 return -1;
1465 for (i = 0; i < num_cmds; i++) {
1466 const GdbCmdParseEntry *cmd = &cmds[i];
1467 g_assert(cmd->handler && cmd->cmd);
1469 if ((cmd->cmd_startswith && !startswith(data, cmd->cmd)) ||
1470 (!cmd->cmd_startswith && strcmp(cmd->cmd, data))) {
1471 continue;
1474 if (cmd->schema) {
1475 schema_len = strlen(cmd->schema);
1476 if (schema_len % 2) {
1477 return -2;
1480 max_num_params = schema_len / 2;
1483 gdb_ctx.params =
1484 (GdbCmdVariant *)alloca(sizeof(*gdb_ctx.params) * max_num_params);
1485 memset(gdb_ctx.params, 0, sizeof(*gdb_ctx.params) * max_num_params);
1487 if (cmd_parse_params(&data[strlen(cmd->cmd)], cmd->schema,
1488 gdb_ctx.params, &gdb_ctx.num_params)) {
1489 return -1;
1492 cmd->handler(&gdb_ctx, user_ctx);
1493 return 0;
1496 return -1;
1499 static void run_cmd_parser(const char *data, const GdbCmdParseEntry *cmd)
1501 if (!data) {
1502 return;
1505 g_string_set_size(gdbserver_state.str_buf, 0);
1507 /* In case there was an error during the command parsing we must
1508 * send a NULL packet to indicate the command is not supported */
1509 if (process_string_cmd(NULL, data, cmd, 1)) {
1510 put_packet("");
1514 static void handle_detach(GdbCmdContext *gdb_ctx, void *user_ctx)
1516 GDBProcess *process;
1517 uint32_t pid = 1;
1519 if (gdbserver_state.multiprocess) {
1520 if (!gdb_ctx->num_params) {
1521 put_packet("E22");
1522 return;
1525 pid = gdb_ctx->params[0].val_ul;
1528 process = gdb_get_process(pid);
1529 gdb_process_breakpoint_remove_all(process);
1530 process->attached = false;
1532 if (pid == gdb_get_cpu_pid(gdbserver_state.c_cpu)) {
1533 gdbserver_state.c_cpu = gdb_first_attached_cpu();
1536 if (pid == gdb_get_cpu_pid(gdbserver_state.g_cpu)) {
1537 gdbserver_state.g_cpu = gdb_first_attached_cpu();
1540 if (!gdbserver_state.c_cpu) {
1541 /* No more process attached */
1542 gdb_syscall_mode = GDB_SYS_DISABLED;
1543 gdb_continue();
1545 put_packet("OK");
1548 static void handle_thread_alive(GdbCmdContext *gdb_ctx, void *user_ctx)
1550 CPUState *cpu;
1552 if (!gdb_ctx->num_params) {
1553 put_packet("E22");
1554 return;
1557 if (gdb_ctx->params[0].thread_id.kind == GDB_READ_THREAD_ERR) {
1558 put_packet("E22");
1559 return;
1562 cpu = gdb_get_cpu(gdb_ctx->params[0].thread_id.pid,
1563 gdb_ctx->params[0].thread_id.tid);
1564 if (!cpu) {
1565 put_packet("E22");
1566 return;
1569 put_packet("OK");
1572 static void handle_continue(GdbCmdContext *gdb_ctx, void *user_ctx)
1574 if (gdb_ctx->num_params) {
1575 gdb_set_cpu_pc(gdb_ctx->params[0].val_ull);
1578 gdbserver_state.signal = 0;
1579 gdb_continue();
1582 static void handle_cont_with_sig(GdbCmdContext *gdb_ctx, void *user_ctx)
1584 unsigned long signal = 0;
1587 * Note: C sig;[addr] is currently unsupported and we simply
1588 * omit the addr parameter
1590 if (gdb_ctx->num_params) {
1591 signal = gdb_ctx->params[0].val_ul;
1594 gdbserver_state.signal = gdb_signal_to_target(signal);
1595 if (gdbserver_state.signal == -1) {
1596 gdbserver_state.signal = 0;
1598 gdb_continue();
1601 static void handle_set_thread(GdbCmdContext *gdb_ctx, void *user_ctx)
1603 CPUState *cpu;
1605 if (gdb_ctx->num_params != 2) {
1606 put_packet("E22");
1607 return;
1610 if (gdb_ctx->params[1].thread_id.kind == GDB_READ_THREAD_ERR) {
1611 put_packet("E22");
1612 return;
1615 if (gdb_ctx->params[1].thread_id.kind != GDB_ONE_THREAD) {
1616 put_packet("OK");
1617 return;
1620 cpu = gdb_get_cpu(gdb_ctx->params[1].thread_id.pid,
1621 gdb_ctx->params[1].thread_id.tid);
1622 if (!cpu) {
1623 put_packet("E22");
1624 return;
1628 * Note: This command is deprecated and modern gdb's will be using the
1629 * vCont command instead.
1631 switch (gdb_ctx->params[0].opcode) {
1632 case 'c':
1633 gdbserver_state.c_cpu = cpu;
1634 put_packet("OK");
1635 break;
1636 case 'g':
1637 gdbserver_state.g_cpu = cpu;
1638 put_packet("OK");
1639 break;
1640 default:
1641 put_packet("E22");
1642 break;
1646 static void handle_insert_bp(GdbCmdContext *gdb_ctx, void *user_ctx)
1648 int res;
1650 if (gdb_ctx->num_params != 3) {
1651 put_packet("E22");
1652 return;
1655 res = gdb_breakpoint_insert(gdb_ctx->params[0].val_ul,
1656 gdb_ctx->params[1].val_ull,
1657 gdb_ctx->params[2].val_ull);
1658 if (res >= 0) {
1659 put_packet("OK");
1660 return;
1661 } else if (res == -ENOSYS) {
1662 put_packet("");
1663 return;
1666 put_packet("E22");
1669 static void handle_remove_bp(GdbCmdContext *gdb_ctx, void *user_ctx)
1671 int res;
1673 if (gdb_ctx->num_params != 3) {
1674 put_packet("E22");
1675 return;
1678 res = gdb_breakpoint_remove(gdb_ctx->params[0].val_ul,
1679 gdb_ctx->params[1].val_ull,
1680 gdb_ctx->params[2].val_ull);
1681 if (res >= 0) {
1682 put_packet("OK");
1683 return;
1684 } else if (res == -ENOSYS) {
1685 put_packet("");
1686 return;
1689 put_packet("E22");
1693 * handle_set/get_reg
1695 * Older gdb are really dumb, and don't use 'G/g' if 'P/p' is available.
1696 * This works, but can be very slow. Anything new enough to understand
1697 * XML also knows how to use this properly. However to use this we
1698 * need to define a local XML file as well as be talking to a
1699 * reasonably modern gdb. Responding with an empty packet will cause
1700 * the remote gdb to fallback to older methods.
1703 static void handle_set_reg(GdbCmdContext *gdb_ctx, void *user_ctx)
1705 int reg_size;
1707 if (!gdb_has_xml) {
1708 put_packet("");
1709 return;
1712 if (gdb_ctx->num_params != 2) {
1713 put_packet("E22");
1714 return;
1717 reg_size = strlen(gdb_ctx->params[1].data) / 2;
1718 hextomem(gdb_ctx->mem_buf, gdb_ctx->params[1].data, reg_size);
1719 gdb_write_register(gdbserver_state.g_cpu, gdb_ctx->mem_buf,
1720 gdb_ctx->params[0].val_ull);
1721 put_packet("OK");
1724 static void handle_get_reg(GdbCmdContext *gdb_ctx, void *user_ctx)
1726 int reg_size;
1728 if (!gdb_has_xml) {
1729 put_packet("");
1730 return;
1733 if (!gdb_ctx->num_params) {
1734 put_packet("E14");
1735 return;
1738 reg_size = gdb_read_register(gdbserver_state.g_cpu, gdb_ctx->mem_buf,
1739 gdb_ctx->params[0].val_ull);
1740 if (!reg_size) {
1741 put_packet("E14");
1742 return;
1745 memtohex(gdbserver_state.str_buf, gdb_ctx->mem_buf, reg_size);
1746 put_strbuf();
1749 static void handle_write_mem(GdbCmdContext *gdb_ctx, void *user_ctx)
1751 if (gdb_ctx->num_params != 3) {
1752 put_packet("E22");
1753 return;
1756 /* hextomem() reads 2*len bytes */
1757 if (gdb_ctx->params[1].val_ull > strlen(gdb_ctx->params[2].data) / 2) {
1758 put_packet("E22");
1759 return;
1762 hextomem(gdb_ctx->mem_buf, gdb_ctx->params[2].data,
1763 gdb_ctx->params[1].val_ull);
1764 if (target_memory_rw_debug(gdbserver_state.g_cpu, gdb_ctx->params[0].val_ull,
1765 gdb_ctx->mem_buf,
1766 gdb_ctx->params[1].val_ull, true)) {
1767 put_packet("E14");
1768 return;
1771 put_packet("OK");
1774 static void handle_read_mem(GdbCmdContext *gdb_ctx, void *user_ctx)
1776 if (gdb_ctx->num_params != 2) {
1777 put_packet("E22");
1778 return;
1781 /* memtohex() doubles the required space */
1782 if (gdb_ctx->params[1].val_ull > MAX_PACKET_LENGTH / 2) {
1783 put_packet("E22");
1784 return;
1787 if (target_memory_rw_debug(gdbserver_state.g_cpu, gdb_ctx->params[0].val_ull,
1788 gdb_ctx->mem_buf,
1789 gdb_ctx->params[1].val_ull, false)) {
1790 put_packet("E14");
1791 return;
1794 memtohex(gdbserver_state.str_buf, gdb_ctx->mem_buf, gdb_ctx->params[1].val_ull);
1795 put_strbuf();
1798 static void handle_write_all_regs(GdbCmdContext *gdb_ctx, void *user_ctx)
1800 target_ulong addr, len;
1801 uint8_t *registers;
1802 int reg_size;
1804 if (!gdb_ctx->num_params) {
1805 return;
1808 cpu_synchronize_state(gdbserver_state.g_cpu);
1809 registers = gdb_ctx->mem_buf;
1810 len = strlen(gdb_ctx->params[0].data) / 2;
1811 hextomem(registers, gdb_ctx->params[0].data, len);
1812 for (addr = 0; addr < gdbserver_state.g_cpu->gdb_num_g_regs && len > 0;
1813 addr++) {
1814 reg_size = gdb_write_register(gdbserver_state.g_cpu, registers, addr);
1815 len -= reg_size;
1816 registers += reg_size;
1818 put_packet("OK");
1821 static void handle_read_all_regs(GdbCmdContext *gdb_ctx, void *user_ctx)
1823 target_ulong addr, len;
1825 cpu_synchronize_state(gdbserver_state.g_cpu);
1826 len = 0;
1827 for (addr = 0; addr < gdbserver_state.g_cpu->gdb_num_g_regs; addr++) {
1828 len += gdb_read_register(gdbserver_state.g_cpu, gdb_ctx->mem_buf + len,
1829 addr);
1832 memtohex(gdbserver_state.str_buf, gdb_ctx->mem_buf, len);
1833 put_strbuf();
1836 static void handle_file_io(GdbCmdContext *gdb_ctx, void *user_ctx)
1838 if (gdb_ctx->num_params >= 1 && gdbserver_state.current_syscall_cb) {
1839 target_ulong ret, err;
1841 ret = (target_ulong)gdb_ctx->params[0].val_ull;
1842 if (gdb_ctx->num_params >= 2) {
1843 err = (target_ulong)gdb_ctx->params[1].val_ull;
1844 } else {
1845 err = 0;
1847 gdbserver_state.current_syscall_cb(gdbserver_state.c_cpu, ret, err);
1848 gdbserver_state.current_syscall_cb = NULL;
1851 if (gdb_ctx->num_params >= 3 && gdb_ctx->params[2].opcode == (uint8_t)'C') {
1852 put_packet("T02");
1853 return;
1856 gdb_continue();
1859 static void handle_step(GdbCmdContext *gdb_ctx, void *user_ctx)
1861 if (gdb_ctx->num_params) {
1862 gdb_set_cpu_pc((target_ulong)gdb_ctx->params[0].val_ull);
1865 cpu_single_step(gdbserver_state.c_cpu, sstep_flags);
1866 gdb_continue();
1869 static void handle_v_cont_query(GdbCmdContext *gdb_ctx, void *user_ctx)
1871 put_packet("vCont;c;C;s;S");
1874 static void handle_v_cont(GdbCmdContext *gdb_ctx, void *user_ctx)
1876 int res;
1878 if (!gdb_ctx->num_params) {
1879 return;
1882 res = gdb_handle_vcont(gdb_ctx->params[0].data);
1883 if ((res == -EINVAL) || (res == -ERANGE)) {
1884 put_packet("E22");
1885 } else if (res) {
1886 put_packet("");
1890 static void handle_v_attach(GdbCmdContext *gdb_ctx, void *user_ctx)
1892 GDBProcess *process;
1893 CPUState *cpu;
1895 g_string_assign(gdbserver_state.str_buf, "E22");
1896 if (!gdb_ctx->num_params) {
1897 goto cleanup;
1900 process = gdb_get_process(gdb_ctx->params[0].val_ul);
1901 if (!process) {
1902 goto cleanup;
1905 cpu = get_first_cpu_in_process(process);
1906 if (!cpu) {
1907 goto cleanup;
1910 process->attached = true;
1911 gdbserver_state.g_cpu = cpu;
1912 gdbserver_state.c_cpu = cpu;
1914 g_string_printf(gdbserver_state.str_buf, "T%02xthread:", GDB_SIGNAL_TRAP);
1915 gdb_append_thread_id(cpu, gdbserver_state.str_buf);
1916 g_string_append_c(gdbserver_state.str_buf, ';');
1917 cleanup:
1918 put_strbuf();
1921 static void handle_v_kill(GdbCmdContext *gdb_ctx, void *user_ctx)
1923 /* Kill the target */
1924 put_packet("OK");
1925 error_report("QEMU: Terminated via GDBstub");
1926 exit(0);
1929 static GdbCmdParseEntry gdb_v_commands_table[] = {
1930 /* Order is important if has same prefix */
1932 .handler = handle_v_cont_query,
1933 .cmd = "Cont?",
1934 .cmd_startswith = 1
1937 .handler = handle_v_cont,
1938 .cmd = "Cont",
1939 .cmd_startswith = 1,
1940 .schema = "s0"
1943 .handler = handle_v_attach,
1944 .cmd = "Attach;",
1945 .cmd_startswith = 1,
1946 .schema = "l0"
1949 .handler = handle_v_kill,
1950 .cmd = "Kill;",
1951 .cmd_startswith = 1
1955 static void handle_v_commands(GdbCmdContext *gdb_ctx, void *user_ctx)
1957 if (!gdb_ctx->num_params) {
1958 return;
1961 if (process_string_cmd(NULL, gdb_ctx->params[0].data,
1962 gdb_v_commands_table,
1963 ARRAY_SIZE(gdb_v_commands_table))) {
1964 put_packet("");
1968 static void handle_query_qemu_sstepbits(GdbCmdContext *gdb_ctx, void *user_ctx)
1970 g_string_printf(gdbserver_state.str_buf, "ENABLE=%x,NOIRQ=%x,NOTIMER=%x",
1971 SSTEP_ENABLE, SSTEP_NOIRQ, SSTEP_NOTIMER);
1972 put_strbuf();
1975 static void handle_set_qemu_sstep(GdbCmdContext *gdb_ctx, void *user_ctx)
1977 if (!gdb_ctx->num_params) {
1978 return;
1981 sstep_flags = gdb_ctx->params[0].val_ul;
1982 put_packet("OK");
1985 static void handle_query_qemu_sstep(GdbCmdContext *gdb_ctx, void *user_ctx)
1987 g_string_printf(gdbserver_state.str_buf, "0x%x", sstep_flags);
1988 put_strbuf();
1991 static void handle_query_curr_tid(GdbCmdContext *gdb_ctx, void *user_ctx)
1993 CPUState *cpu;
1994 GDBProcess *process;
1997 * "Current thread" remains vague in the spec, so always return
1998 * the first thread of the current process (gdb returns the
1999 * first thread).
2001 process = gdb_get_cpu_process(gdbserver_state.g_cpu);
2002 cpu = get_first_cpu_in_process(process);
2003 g_string_assign(gdbserver_state.str_buf, "QC");
2004 gdb_append_thread_id(cpu, gdbserver_state.str_buf);
2005 put_strbuf();
2008 static void handle_query_threads(GdbCmdContext *gdb_ctx, void *user_ctx)
2010 if (!gdbserver_state.query_cpu) {
2011 put_packet("l");
2012 return;
2015 g_string_assign(gdbserver_state.str_buf, "m");
2016 gdb_append_thread_id(gdbserver_state.query_cpu, gdbserver_state.str_buf);
2017 put_strbuf();
2018 gdbserver_state.query_cpu = gdb_next_attached_cpu(gdbserver_state.query_cpu);
2021 static void handle_query_first_threads(GdbCmdContext *gdb_ctx, void *user_ctx)
2023 gdbserver_state.query_cpu = gdb_first_attached_cpu();
2024 handle_query_threads(gdb_ctx, user_ctx);
2027 static void handle_query_thread_extra(GdbCmdContext *gdb_ctx, void *user_ctx)
2029 g_autoptr(GString) rs = g_string_new(NULL);
2030 CPUState *cpu;
2032 if (!gdb_ctx->num_params ||
2033 gdb_ctx->params[0].thread_id.kind == GDB_READ_THREAD_ERR) {
2034 put_packet("E22");
2035 return;
2038 cpu = gdb_get_cpu(gdb_ctx->params[0].thread_id.pid,
2039 gdb_ctx->params[0].thread_id.tid);
2040 if (!cpu) {
2041 return;
2044 cpu_synchronize_state(cpu);
2046 if (gdbserver_state.multiprocess && (gdbserver_state.process_num > 1)) {
2047 /* Print the CPU model and name in multiprocess mode */
2048 ObjectClass *oc = object_get_class(OBJECT(cpu));
2049 const char *cpu_model = object_class_get_name(oc);
2050 g_autofree char *cpu_name;
2051 cpu_name = object_get_canonical_path_component(OBJECT(cpu));
2052 g_string_printf(rs, "%s %s [%s]", cpu_model, cpu_name,
2053 cpu->halted ? "halted " : "running");
2054 } else {
2055 g_string_printf(rs, "CPU#%d [%s]", cpu->cpu_index,
2056 cpu->halted ? "halted " : "running");
2058 trace_gdbstub_op_extra_info(rs->str);
2059 memtohex(gdbserver_state.str_buf, (uint8_t *)rs->str, rs->len);
2060 put_strbuf();
2063 #ifdef CONFIG_USER_ONLY
2064 static void handle_query_offsets(GdbCmdContext *gdb_ctx, void *user_ctx)
2066 TaskState *ts;
2068 ts = gdbserver_state.c_cpu->opaque;
2069 g_string_printf(gdbserver_state.str_buf,
2070 "Text=" TARGET_ABI_FMT_lx
2071 ";Data=" TARGET_ABI_FMT_lx
2072 ";Bss=" TARGET_ABI_FMT_lx,
2073 ts->info->code_offset,
2074 ts->info->data_offset,
2075 ts->info->data_offset);
2076 put_strbuf();
2078 #else
2079 static void handle_query_rcmd(GdbCmdContext *gdb_ctx, void *user_ctx)
2081 int len;
2083 if (!gdb_ctx->num_params) {
2084 put_packet("E22");
2085 return;
2088 len = strlen(gdb_ctx->params[0].data);
2089 if (len % 2) {
2090 put_packet("E01");
2091 return;
2094 len = len / 2;
2095 hextomem(gdb_ctx->mem_buf, gdb_ctx->params[0].data, len);
2096 gdb_ctx->mem_buf[len++] = 0;
2097 qemu_chr_be_write(gdbserver_state.mon_chr, gdb_ctx->mem_buf, len);
2098 put_packet("OK");
2101 #endif
2103 static void handle_query_supported(GdbCmdContext *gdb_ctx, void *user_ctx)
2105 CPUClass *cc;
2107 g_string_printf(gdbserver_state.str_buf, "PacketSize=%x", MAX_PACKET_LENGTH);
2108 cc = CPU_GET_CLASS(first_cpu);
2109 if (cc->gdb_core_xml_file) {
2110 g_string_append(gdbserver_state.str_buf, ";qXfer:features:read+");
2113 if (gdb_ctx->num_params &&
2114 strstr(gdb_ctx->params[0].data, "multiprocess+")) {
2115 gdbserver_state.multiprocess = true;
2118 g_string_append(gdbserver_state.str_buf, ";multiprocess+");
2119 put_strbuf();
2122 static void handle_query_xfer_features(GdbCmdContext *gdb_ctx, void *user_ctx)
2124 GDBProcess *process;
2125 CPUClass *cc;
2126 unsigned long len, total_len, addr;
2127 const char *xml;
2128 const char *p;
2130 if (gdb_ctx->num_params < 3) {
2131 put_packet("E22");
2132 return;
2135 process = gdb_get_cpu_process(gdbserver_state.g_cpu);
2136 cc = CPU_GET_CLASS(gdbserver_state.g_cpu);
2137 if (!cc->gdb_core_xml_file) {
2138 put_packet("");
2139 return;
2142 gdb_has_xml = true;
2143 p = gdb_ctx->params[0].data;
2144 xml = get_feature_xml(p, &p, process);
2145 if (!xml) {
2146 put_packet("E00");
2147 return;
2150 addr = gdb_ctx->params[1].val_ul;
2151 len = gdb_ctx->params[2].val_ul;
2152 total_len = strlen(xml);
2153 if (addr > total_len) {
2154 put_packet("E00");
2155 return;
2158 if (len > (MAX_PACKET_LENGTH - 5) / 2) {
2159 len = (MAX_PACKET_LENGTH - 5) / 2;
2162 if (len < total_len - addr) {
2163 g_string_assign(gdbserver_state.str_buf, "m");
2164 memtox(gdbserver_state.str_buf, xml + addr, len);
2165 } else {
2166 g_string_assign(gdbserver_state.str_buf, "l");
2167 memtox(gdbserver_state.str_buf, xml + addr, total_len - addr);
2170 put_packet_binary(gdbserver_state.str_buf->str,
2171 gdbserver_state.str_buf->len, true);
2174 static void handle_query_attached(GdbCmdContext *gdb_ctx, void *user_ctx)
2176 put_packet(GDB_ATTACHED);
2179 static void handle_query_qemu_supported(GdbCmdContext *gdb_ctx, void *user_ctx)
2181 g_string_printf(gdbserver_state.str_buf, "sstepbits;sstep");
2182 #ifndef CONFIG_USER_ONLY
2183 g_string_append(gdbserver_state.str_buf, ";PhyMemMode");
2184 #endif
2185 put_strbuf();
2188 #ifndef CONFIG_USER_ONLY
2189 static void handle_query_qemu_phy_mem_mode(GdbCmdContext *gdb_ctx,
2190 void *user_ctx)
2192 g_string_printf(gdbserver_state.str_buf, "%d", phy_memory_mode);
2193 put_strbuf();
2196 static void handle_set_qemu_phy_mem_mode(GdbCmdContext *gdb_ctx, void *user_ctx)
2198 if (!gdb_ctx->num_params) {
2199 put_packet("E22");
2200 return;
2203 if (!gdb_ctx->params[0].val_ul) {
2204 phy_memory_mode = 0;
2205 } else {
2206 phy_memory_mode = 1;
2208 put_packet("OK");
2210 #endif
2212 static GdbCmdParseEntry gdb_gen_query_set_common_table[] = {
2213 /* Order is important if has same prefix */
2215 .handler = handle_query_qemu_sstepbits,
2216 .cmd = "qemu.sstepbits",
2219 .handler = handle_query_qemu_sstep,
2220 .cmd = "qemu.sstep",
2223 .handler = handle_set_qemu_sstep,
2224 .cmd = "qemu.sstep=",
2225 .cmd_startswith = 1,
2226 .schema = "l0"
2230 static GdbCmdParseEntry gdb_gen_query_table[] = {
2232 .handler = handle_query_curr_tid,
2233 .cmd = "C",
2236 .handler = handle_query_threads,
2237 .cmd = "sThreadInfo",
2240 .handler = handle_query_first_threads,
2241 .cmd = "fThreadInfo",
2244 .handler = handle_query_thread_extra,
2245 .cmd = "ThreadExtraInfo,",
2246 .cmd_startswith = 1,
2247 .schema = "t0"
2249 #ifdef CONFIG_USER_ONLY
2251 .handler = handle_query_offsets,
2252 .cmd = "Offsets",
2254 #else
2256 .handler = handle_query_rcmd,
2257 .cmd = "Rcmd,",
2258 .cmd_startswith = 1,
2259 .schema = "s0"
2261 #endif
2263 .handler = handle_query_supported,
2264 .cmd = "Supported:",
2265 .cmd_startswith = 1,
2266 .schema = "s0"
2269 .handler = handle_query_supported,
2270 .cmd = "Supported",
2271 .schema = "s0"
2274 .handler = handle_query_xfer_features,
2275 .cmd = "Xfer:features:read:",
2276 .cmd_startswith = 1,
2277 .schema = "s:l,l0"
2280 .handler = handle_query_attached,
2281 .cmd = "Attached:",
2282 .cmd_startswith = 1
2285 .handler = handle_query_attached,
2286 .cmd = "Attached",
2289 .handler = handle_query_qemu_supported,
2290 .cmd = "qemu.Supported",
2292 #ifndef CONFIG_USER_ONLY
2294 .handler = handle_query_qemu_phy_mem_mode,
2295 .cmd = "qemu.PhyMemMode",
2297 #endif
2300 static GdbCmdParseEntry gdb_gen_set_table[] = {
2301 /* Order is important if has same prefix */
2303 .handler = handle_set_qemu_sstep,
2304 .cmd = "qemu.sstep:",
2305 .cmd_startswith = 1,
2306 .schema = "l0"
2308 #ifndef CONFIG_USER_ONLY
2310 .handler = handle_set_qemu_phy_mem_mode,
2311 .cmd = "qemu.PhyMemMode:",
2312 .cmd_startswith = 1,
2313 .schema = "l0"
2315 #endif
2318 static void handle_gen_query(GdbCmdContext *gdb_ctx, void *user_ctx)
2320 if (!gdb_ctx->num_params) {
2321 return;
2324 if (!process_string_cmd(NULL, gdb_ctx->params[0].data,
2325 gdb_gen_query_set_common_table,
2326 ARRAY_SIZE(gdb_gen_query_set_common_table))) {
2327 return;
2330 if (process_string_cmd(NULL, gdb_ctx->params[0].data,
2331 gdb_gen_query_table,
2332 ARRAY_SIZE(gdb_gen_query_table))) {
2333 put_packet("");
2337 static void handle_gen_set(GdbCmdContext *gdb_ctx, void *user_ctx)
2339 if (!gdb_ctx->num_params) {
2340 return;
2343 if (!process_string_cmd(NULL, gdb_ctx->params[0].data,
2344 gdb_gen_query_set_common_table,
2345 ARRAY_SIZE(gdb_gen_query_set_common_table))) {
2346 return;
2349 if (process_string_cmd(NULL, gdb_ctx->params[0].data,
2350 gdb_gen_set_table,
2351 ARRAY_SIZE(gdb_gen_set_table))) {
2352 put_packet("");
2356 static void handle_target_halt(GdbCmdContext *gdb_ctx, void *user_ctx)
2358 g_string_printf(gdbserver_state.str_buf, "T%02xthread:", GDB_SIGNAL_TRAP);
2359 gdb_append_thread_id(gdbserver_state.c_cpu, gdbserver_state.str_buf);
2360 g_string_append_c(gdbserver_state.str_buf, ';');
2361 put_strbuf();
2363 * Remove all the breakpoints when this query is issued,
2364 * because gdb is doing an initial connect and the state
2365 * should be cleaned up.
2367 gdb_breakpoint_remove_all();
2370 static int gdb_handle_packet(const char *line_buf)
2372 const GdbCmdParseEntry *cmd_parser = NULL;
2374 trace_gdbstub_io_command(line_buf);
2376 switch (line_buf[0]) {
2377 case '!':
2378 put_packet("OK");
2379 break;
2380 case '?':
2382 static const GdbCmdParseEntry target_halted_cmd_desc = {
2383 .handler = handle_target_halt,
2384 .cmd = "?",
2385 .cmd_startswith = 1
2387 cmd_parser = &target_halted_cmd_desc;
2389 break;
2390 case 'c':
2392 static const GdbCmdParseEntry continue_cmd_desc = {
2393 .handler = handle_continue,
2394 .cmd = "c",
2395 .cmd_startswith = 1,
2396 .schema = "L0"
2398 cmd_parser = &continue_cmd_desc;
2400 break;
2401 case 'C':
2403 static const GdbCmdParseEntry cont_with_sig_cmd_desc = {
2404 .handler = handle_cont_with_sig,
2405 .cmd = "C",
2406 .cmd_startswith = 1,
2407 .schema = "l0"
2409 cmd_parser = &cont_with_sig_cmd_desc;
2411 break;
2412 case 'v':
2414 static const GdbCmdParseEntry v_cmd_desc = {
2415 .handler = handle_v_commands,
2416 .cmd = "v",
2417 .cmd_startswith = 1,
2418 .schema = "s0"
2420 cmd_parser = &v_cmd_desc;
2422 break;
2423 case 'k':
2424 /* Kill the target */
2425 error_report("QEMU: Terminated via GDBstub");
2426 exit(0);
2427 case 'D':
2429 static const GdbCmdParseEntry detach_cmd_desc = {
2430 .handler = handle_detach,
2431 .cmd = "D",
2432 .cmd_startswith = 1,
2433 .schema = "?.l0"
2435 cmd_parser = &detach_cmd_desc;
2437 break;
2438 case 's':
2440 static const GdbCmdParseEntry step_cmd_desc = {
2441 .handler = handle_step,
2442 .cmd = "s",
2443 .cmd_startswith = 1,
2444 .schema = "L0"
2446 cmd_parser = &step_cmd_desc;
2448 break;
2449 case 'F':
2451 static const GdbCmdParseEntry file_io_cmd_desc = {
2452 .handler = handle_file_io,
2453 .cmd = "F",
2454 .cmd_startswith = 1,
2455 .schema = "L,L,o0"
2457 cmd_parser = &file_io_cmd_desc;
2459 break;
2460 case 'g':
2462 static const GdbCmdParseEntry read_all_regs_cmd_desc = {
2463 .handler = handle_read_all_regs,
2464 .cmd = "g",
2465 .cmd_startswith = 1
2467 cmd_parser = &read_all_regs_cmd_desc;
2469 break;
2470 case 'G':
2472 static const GdbCmdParseEntry write_all_regs_cmd_desc = {
2473 .handler = handle_write_all_regs,
2474 .cmd = "G",
2475 .cmd_startswith = 1,
2476 .schema = "s0"
2478 cmd_parser = &write_all_regs_cmd_desc;
2480 break;
2481 case 'm':
2483 static const GdbCmdParseEntry read_mem_cmd_desc = {
2484 .handler = handle_read_mem,
2485 .cmd = "m",
2486 .cmd_startswith = 1,
2487 .schema = "L,L0"
2489 cmd_parser = &read_mem_cmd_desc;
2491 break;
2492 case 'M':
2494 static const GdbCmdParseEntry write_mem_cmd_desc = {
2495 .handler = handle_write_mem,
2496 .cmd = "M",
2497 .cmd_startswith = 1,
2498 .schema = "L,L:s0"
2500 cmd_parser = &write_mem_cmd_desc;
2502 break;
2503 case 'p':
2505 static const GdbCmdParseEntry get_reg_cmd_desc = {
2506 .handler = handle_get_reg,
2507 .cmd = "p",
2508 .cmd_startswith = 1,
2509 .schema = "L0"
2511 cmd_parser = &get_reg_cmd_desc;
2513 break;
2514 case 'P':
2516 static const GdbCmdParseEntry set_reg_cmd_desc = {
2517 .handler = handle_set_reg,
2518 .cmd = "P",
2519 .cmd_startswith = 1,
2520 .schema = "L?s0"
2522 cmd_parser = &set_reg_cmd_desc;
2524 break;
2525 case 'Z':
2527 static const GdbCmdParseEntry insert_bp_cmd_desc = {
2528 .handler = handle_insert_bp,
2529 .cmd = "Z",
2530 .cmd_startswith = 1,
2531 .schema = "l?L?L0"
2533 cmd_parser = &insert_bp_cmd_desc;
2535 break;
2536 case 'z':
2538 static const GdbCmdParseEntry remove_bp_cmd_desc = {
2539 .handler = handle_remove_bp,
2540 .cmd = "z",
2541 .cmd_startswith = 1,
2542 .schema = "l?L?L0"
2544 cmd_parser = &remove_bp_cmd_desc;
2546 break;
2547 case 'H':
2549 static const GdbCmdParseEntry set_thread_cmd_desc = {
2550 .handler = handle_set_thread,
2551 .cmd = "H",
2552 .cmd_startswith = 1,
2553 .schema = "o.t0"
2555 cmd_parser = &set_thread_cmd_desc;
2557 break;
2558 case 'T':
2560 static const GdbCmdParseEntry thread_alive_cmd_desc = {
2561 .handler = handle_thread_alive,
2562 .cmd = "T",
2563 .cmd_startswith = 1,
2564 .schema = "t0"
2566 cmd_parser = &thread_alive_cmd_desc;
2568 break;
2569 case 'q':
2571 static const GdbCmdParseEntry gen_query_cmd_desc = {
2572 .handler = handle_gen_query,
2573 .cmd = "q",
2574 .cmd_startswith = 1,
2575 .schema = "s0"
2577 cmd_parser = &gen_query_cmd_desc;
2579 break;
2580 case 'Q':
2582 static const GdbCmdParseEntry gen_set_cmd_desc = {
2583 .handler = handle_gen_set,
2584 .cmd = "Q",
2585 .cmd_startswith = 1,
2586 .schema = "s0"
2588 cmd_parser = &gen_set_cmd_desc;
2590 break;
2591 default:
2592 /* put empty packet */
2593 put_packet("");
2594 break;
2597 if (cmd_parser) {
2598 run_cmd_parser(line_buf, cmd_parser);
2601 return RS_IDLE;
2604 void gdb_set_stop_cpu(CPUState *cpu)
2606 GDBProcess *p = gdb_get_cpu_process(cpu);
2608 if (!p->attached) {
2610 * Having a stop CPU corresponding to a process that is not attached
2611 * confuses GDB. So we ignore the request.
2613 return;
2616 gdbserver_state.c_cpu = cpu;
2617 gdbserver_state.g_cpu = cpu;
2620 #ifndef CONFIG_USER_ONLY
2621 static void gdb_vm_state_change(void *opaque, int running, RunState state)
2623 CPUState *cpu = gdbserver_state.c_cpu;
2624 g_autoptr(GString) buf = g_string_new(NULL);
2625 g_autoptr(GString) tid = g_string_new(NULL);
2626 const char *type;
2627 int ret;
2629 if (running || gdbserver_state.state == RS_INACTIVE) {
2630 return;
2632 /* Is there a GDB syscall waiting to be sent? */
2633 if (gdbserver_state.current_syscall_cb) {
2634 put_packet(gdbserver_state.syscall_buf);
2635 return;
2638 if (cpu == NULL) {
2639 /* No process attached */
2640 return;
2643 gdb_append_thread_id(cpu, tid);
2645 switch (state) {
2646 case RUN_STATE_DEBUG:
2647 if (cpu->watchpoint_hit) {
2648 switch (cpu->watchpoint_hit->flags & BP_MEM_ACCESS) {
2649 case BP_MEM_READ:
2650 type = "r";
2651 break;
2652 case BP_MEM_ACCESS:
2653 type = "a";
2654 break;
2655 default:
2656 type = "";
2657 break;
2659 trace_gdbstub_hit_watchpoint(type, cpu_gdb_index(cpu),
2660 (target_ulong)cpu->watchpoint_hit->vaddr);
2661 g_string_printf(buf, "T%02xthread:%s;%swatch:" TARGET_FMT_lx ";",
2662 GDB_SIGNAL_TRAP, tid->str, type,
2663 (target_ulong)cpu->watchpoint_hit->vaddr);
2664 cpu->watchpoint_hit = NULL;
2665 goto send_packet;
2666 } else {
2667 trace_gdbstub_hit_break();
2669 tb_flush(cpu);
2670 ret = GDB_SIGNAL_TRAP;
2671 break;
2672 case RUN_STATE_PAUSED:
2673 trace_gdbstub_hit_paused();
2674 ret = GDB_SIGNAL_INT;
2675 break;
2676 case RUN_STATE_SHUTDOWN:
2677 trace_gdbstub_hit_shutdown();
2678 ret = GDB_SIGNAL_QUIT;
2679 break;
2680 case RUN_STATE_IO_ERROR:
2681 trace_gdbstub_hit_io_error();
2682 ret = GDB_SIGNAL_IO;
2683 break;
2684 case RUN_STATE_WATCHDOG:
2685 trace_gdbstub_hit_watchdog();
2686 ret = GDB_SIGNAL_ALRM;
2687 break;
2688 case RUN_STATE_INTERNAL_ERROR:
2689 trace_gdbstub_hit_internal_error();
2690 ret = GDB_SIGNAL_ABRT;
2691 break;
2692 case RUN_STATE_SAVE_VM:
2693 case RUN_STATE_RESTORE_VM:
2694 return;
2695 case RUN_STATE_FINISH_MIGRATE:
2696 ret = GDB_SIGNAL_XCPU;
2697 break;
2698 default:
2699 trace_gdbstub_hit_unknown(state);
2700 ret = GDB_SIGNAL_UNKNOWN;
2701 break;
2703 gdb_set_stop_cpu(cpu);
2704 g_string_printf(buf, "T%02xthread:%s;", ret, tid->str);
2706 send_packet:
2707 put_packet(buf->str);
2709 /* disable single step if it was enabled */
2710 cpu_single_step(cpu, 0);
2712 #endif
2714 /* Send a gdb syscall request.
2715 This accepts limited printf-style format specifiers, specifically:
2716 %x - target_ulong argument printed in hex.
2717 %lx - 64-bit argument printed in hex.
2718 %s - string pointer (target_ulong) and length (int) pair. */
2719 void gdb_do_syscallv(gdb_syscall_complete_cb cb, const char *fmt, va_list va)
2721 char *p;
2722 char *p_end;
2723 target_ulong addr;
2724 uint64_t i64;
2726 if (!gdbserver_state.init) {
2727 return;
2730 gdbserver_state.current_syscall_cb = cb;
2731 #ifndef CONFIG_USER_ONLY
2732 vm_stop(RUN_STATE_DEBUG);
2733 #endif
2734 p = &gdbserver_state.syscall_buf[0];
2735 p_end = &gdbserver_state.syscall_buf[sizeof(gdbserver_state.syscall_buf)];
2736 *(p++) = 'F';
2737 while (*fmt) {
2738 if (*fmt == '%') {
2739 fmt++;
2740 switch (*fmt++) {
2741 case 'x':
2742 addr = va_arg(va, target_ulong);
2743 p += snprintf(p, p_end - p, TARGET_FMT_lx, addr);
2744 break;
2745 case 'l':
2746 if (*(fmt++) != 'x')
2747 goto bad_format;
2748 i64 = va_arg(va, uint64_t);
2749 p += snprintf(p, p_end - p, "%" PRIx64, i64);
2750 break;
2751 case 's':
2752 addr = va_arg(va, target_ulong);
2753 p += snprintf(p, p_end - p, TARGET_FMT_lx "/%x",
2754 addr, va_arg(va, int));
2755 break;
2756 default:
2757 bad_format:
2758 error_report("gdbstub: Bad syscall format string '%s'",
2759 fmt - 1);
2760 break;
2762 } else {
2763 *(p++) = *(fmt++);
2766 *p = 0;
2767 #ifdef CONFIG_USER_ONLY
2768 put_packet(gdbserver_state.syscall_buf);
2769 /* Return control to gdb for it to process the syscall request.
2770 * Since the protocol requires that gdb hands control back to us
2771 * using a "here are the results" F packet, we don't need to check
2772 * gdb_handlesig's return value (which is the signal to deliver if
2773 * execution was resumed via a continue packet).
2775 gdb_handlesig(gdbserver_state.c_cpu, 0);
2776 #else
2777 /* In this case wait to send the syscall packet until notification that
2778 the CPU has stopped. This must be done because if the packet is sent
2779 now the reply from the syscall request could be received while the CPU
2780 is still in the running state, which can cause packets to be dropped
2781 and state transition 'T' packets to be sent while the syscall is still
2782 being processed. */
2783 qemu_cpu_kick(gdbserver_state.c_cpu);
2784 #endif
2787 void gdb_do_syscall(gdb_syscall_complete_cb cb, const char *fmt, ...)
2789 va_list va;
2791 va_start(va, fmt);
2792 gdb_do_syscallv(cb, fmt, va);
2793 va_end(va);
2796 static void gdb_read_byte(uint8_t ch)
2798 uint8_t reply;
2800 #ifndef CONFIG_USER_ONLY
2801 if (gdbserver_state.last_packet_len) {
2802 /* Waiting for a response to the last packet. If we see the start
2803 of a new command then abandon the previous response. */
2804 if (ch == '-') {
2805 trace_gdbstub_err_got_nack();
2806 put_buffer((uint8_t *)gdbserver_state.last_packet, gdbserver_state.last_packet_len);
2807 } else if (ch == '+') {
2808 trace_gdbstub_io_got_ack();
2809 } else {
2810 trace_gdbstub_io_got_unexpected(ch);
2813 if (ch == '+' || ch == '$')
2814 gdbserver_state.last_packet_len = 0;
2815 if (ch != '$')
2816 return;
2818 if (runstate_is_running()) {
2819 /* when the CPU is running, we cannot do anything except stop
2820 it when receiving a char */
2821 vm_stop(RUN_STATE_PAUSED);
2822 } else
2823 #endif
2825 switch(gdbserver_state.state) {
2826 case RS_IDLE:
2827 if (ch == '$') {
2828 /* start of command packet */
2829 gdbserver_state.line_buf_index = 0;
2830 gdbserver_state.line_sum = 0;
2831 gdbserver_state.state = RS_GETLINE;
2832 } else {
2833 trace_gdbstub_err_garbage(ch);
2835 break;
2836 case RS_GETLINE:
2837 if (ch == '}') {
2838 /* start escape sequence */
2839 gdbserver_state.state = RS_GETLINE_ESC;
2840 gdbserver_state.line_sum += ch;
2841 } else if (ch == '*') {
2842 /* start run length encoding sequence */
2843 gdbserver_state.state = RS_GETLINE_RLE;
2844 gdbserver_state.line_sum += ch;
2845 } else if (ch == '#') {
2846 /* end of command, start of checksum*/
2847 gdbserver_state.state = RS_CHKSUM1;
2848 } else if (gdbserver_state.line_buf_index >= sizeof(gdbserver_state.line_buf) - 1) {
2849 trace_gdbstub_err_overrun();
2850 gdbserver_state.state = RS_IDLE;
2851 } else {
2852 /* unescaped command character */
2853 gdbserver_state.line_buf[gdbserver_state.line_buf_index++] = ch;
2854 gdbserver_state.line_sum += ch;
2856 break;
2857 case RS_GETLINE_ESC:
2858 if (ch == '#') {
2859 /* unexpected end of command in escape sequence */
2860 gdbserver_state.state = RS_CHKSUM1;
2861 } else if (gdbserver_state.line_buf_index >= sizeof(gdbserver_state.line_buf) - 1) {
2862 /* command buffer overrun */
2863 trace_gdbstub_err_overrun();
2864 gdbserver_state.state = RS_IDLE;
2865 } else {
2866 /* parse escaped character and leave escape state */
2867 gdbserver_state.line_buf[gdbserver_state.line_buf_index++] = ch ^ 0x20;
2868 gdbserver_state.line_sum += ch;
2869 gdbserver_state.state = RS_GETLINE;
2871 break;
2872 case RS_GETLINE_RLE:
2874 * Run-length encoding is explained in "Debugging with GDB /
2875 * Appendix E GDB Remote Serial Protocol / Overview".
2877 if (ch < ' ' || ch == '#' || ch == '$' || ch > 126) {
2878 /* invalid RLE count encoding */
2879 trace_gdbstub_err_invalid_repeat(ch);
2880 gdbserver_state.state = RS_GETLINE;
2881 } else {
2882 /* decode repeat length */
2883 int repeat = ch - ' ' + 3;
2884 if (gdbserver_state.line_buf_index + repeat >= sizeof(gdbserver_state.line_buf) - 1) {
2885 /* that many repeats would overrun the command buffer */
2886 trace_gdbstub_err_overrun();
2887 gdbserver_state.state = RS_IDLE;
2888 } else if (gdbserver_state.line_buf_index < 1) {
2889 /* got a repeat but we have nothing to repeat */
2890 trace_gdbstub_err_invalid_rle();
2891 gdbserver_state.state = RS_GETLINE;
2892 } else {
2893 /* repeat the last character */
2894 memset(gdbserver_state.line_buf + gdbserver_state.line_buf_index,
2895 gdbserver_state.line_buf[gdbserver_state.line_buf_index - 1], repeat);
2896 gdbserver_state.line_buf_index += repeat;
2897 gdbserver_state.line_sum += ch;
2898 gdbserver_state.state = RS_GETLINE;
2901 break;
2902 case RS_CHKSUM1:
2903 /* get high hex digit of checksum */
2904 if (!isxdigit(ch)) {
2905 trace_gdbstub_err_checksum_invalid(ch);
2906 gdbserver_state.state = RS_GETLINE;
2907 break;
2909 gdbserver_state.line_buf[gdbserver_state.line_buf_index] = '\0';
2910 gdbserver_state.line_csum = fromhex(ch) << 4;
2911 gdbserver_state.state = RS_CHKSUM2;
2912 break;
2913 case RS_CHKSUM2:
2914 /* get low hex digit of checksum */
2915 if (!isxdigit(ch)) {
2916 trace_gdbstub_err_checksum_invalid(ch);
2917 gdbserver_state.state = RS_GETLINE;
2918 break;
2920 gdbserver_state.line_csum |= fromhex(ch);
2922 if (gdbserver_state.line_csum != (gdbserver_state.line_sum & 0xff)) {
2923 trace_gdbstub_err_checksum_incorrect(gdbserver_state.line_sum, gdbserver_state.line_csum);
2924 /* send NAK reply */
2925 reply = '-';
2926 put_buffer(&reply, 1);
2927 gdbserver_state.state = RS_IDLE;
2928 } else {
2929 /* send ACK reply */
2930 reply = '+';
2931 put_buffer(&reply, 1);
2932 gdbserver_state.state = gdb_handle_packet(gdbserver_state.line_buf);
2934 break;
2935 default:
2936 abort();
2941 /* Tell the remote gdb that the process has exited. */
2942 void gdb_exit(CPUArchState *env, int code)
2944 char buf[4];
2946 if (!gdbserver_state.init) {
2947 return;
2949 #ifdef CONFIG_USER_ONLY
2950 if (gdbserver_fd < 0 || gdbserver_state.fd < 0) {
2951 return;
2953 #endif
2955 trace_gdbstub_op_exiting((uint8_t)code);
2957 snprintf(buf, sizeof(buf), "W%02x", (uint8_t)code);
2958 put_packet(buf);
2960 #ifndef CONFIG_USER_ONLY
2961 qemu_chr_fe_deinit(&gdbserver_state.chr, true);
2962 #endif
2966 * Create the process that will contain all the "orphan" CPUs (that are not
2967 * part of a CPU cluster). Note that if this process contains no CPUs, it won't
2968 * be attachable and thus will be invisible to the user.
2970 static void create_default_process(GDBState *s)
2972 GDBProcess *process;
2973 int max_pid = 0;
2975 if (gdbserver_state.process_num) {
2976 max_pid = s->processes[s->process_num - 1].pid;
2979 s->processes = g_renew(GDBProcess, s->processes, ++s->process_num);
2980 process = &s->processes[s->process_num - 1];
2982 /* We need an available PID slot for this process */
2983 assert(max_pid < UINT32_MAX);
2985 process->pid = max_pid + 1;
2986 process->attached = false;
2987 process->target_xml[0] = '\0';
2990 #ifdef CONFIG_USER_ONLY
2992 gdb_handlesig(CPUState *cpu, int sig)
2994 char buf[256];
2995 int n;
2997 if (gdbserver_fd < 0 || gdbserver_state.fd < 0) {
2998 return sig;
3001 /* disable single step if it was enabled */
3002 cpu_single_step(cpu, 0);
3003 tb_flush(cpu);
3005 if (sig != 0) {
3006 snprintf(buf, sizeof(buf), "S%02x", target_signal_to_gdb(sig));
3007 put_packet(buf);
3009 /* put_packet() might have detected that the peer terminated the
3010 connection. */
3011 if (gdbserver_state.fd < 0) {
3012 return sig;
3015 sig = 0;
3016 gdbserver_state.state = RS_IDLE;
3017 gdbserver_state.running_state = 0;
3018 while (gdbserver_state.running_state == 0) {
3019 n = read(gdbserver_state.fd, buf, 256);
3020 if (n > 0) {
3021 int i;
3023 for (i = 0; i < n; i++) {
3024 gdb_read_byte(buf[i]);
3026 } else {
3027 /* XXX: Connection closed. Should probably wait for another
3028 connection before continuing. */
3029 if (n == 0) {
3030 close(gdbserver_state.fd);
3032 gdbserver_state.fd = -1;
3033 return sig;
3036 sig = gdbserver_state.signal;
3037 gdbserver_state.signal = 0;
3038 return sig;
3041 /* Tell the remote gdb that the process has exited due to SIG. */
3042 void gdb_signalled(CPUArchState *env, int sig)
3044 char buf[4];
3046 if (gdbserver_fd < 0 || gdbserver_state.fd < 0) {
3047 return;
3050 snprintf(buf, sizeof(buf), "X%02x", target_signal_to_gdb(sig));
3051 put_packet(buf);
3054 static bool gdb_accept(void)
3056 struct sockaddr_in sockaddr;
3057 socklen_t len;
3058 int fd;
3060 for(;;) {
3061 len = sizeof(sockaddr);
3062 fd = accept(gdbserver_fd, (struct sockaddr *)&sockaddr, &len);
3063 if (fd < 0 && errno != EINTR) {
3064 perror("accept");
3065 return false;
3066 } else if (fd >= 0) {
3067 qemu_set_cloexec(fd);
3068 break;
3072 /* set short latency */
3073 if (socket_set_nodelay(fd)) {
3074 perror("setsockopt");
3075 close(fd);
3076 return false;
3079 init_gdbserver_state();
3080 create_default_process(&gdbserver_state);
3081 gdbserver_state.processes[0].attached = true;
3082 gdbserver_state.c_cpu = gdb_first_attached_cpu();
3083 gdbserver_state.g_cpu = gdbserver_state.c_cpu;
3084 gdbserver_state.fd = fd;
3085 gdb_has_xml = false;
3086 return true;
3089 static int gdbserver_open(int port)
3091 struct sockaddr_in sockaddr;
3092 int fd, ret;
3094 fd = socket(PF_INET, SOCK_STREAM, 0);
3095 if (fd < 0) {
3096 perror("socket");
3097 return -1;
3099 qemu_set_cloexec(fd);
3101 socket_set_fast_reuse(fd);
3103 sockaddr.sin_family = AF_INET;
3104 sockaddr.sin_port = htons(port);
3105 sockaddr.sin_addr.s_addr = 0;
3106 ret = bind(fd, (struct sockaddr *)&sockaddr, sizeof(sockaddr));
3107 if (ret < 0) {
3108 perror("bind");
3109 close(fd);
3110 return -1;
3112 ret = listen(fd, 1);
3113 if (ret < 0) {
3114 perror("listen");
3115 close(fd);
3116 return -1;
3118 return fd;
3121 int gdbserver_start(int port)
3123 gdbserver_fd = gdbserver_open(port);
3124 if (gdbserver_fd < 0)
3125 return -1;
3126 /* accept connections */
3127 if (!gdb_accept()) {
3128 close(gdbserver_fd);
3129 gdbserver_fd = -1;
3130 return -1;
3132 return 0;
3135 /* Disable gdb stub for child processes. */
3136 void gdbserver_fork(CPUState *cpu)
3138 if (gdbserver_fd < 0 || gdbserver_state.fd < 0) {
3139 return;
3141 close(gdbserver_state.fd);
3142 gdbserver_state.fd = -1;
3143 cpu_breakpoint_remove_all(cpu, BP_GDB);
3144 cpu_watchpoint_remove_all(cpu, BP_GDB);
3146 #else
3147 static int gdb_chr_can_receive(void *opaque)
3149 /* We can handle an arbitrarily large amount of data.
3150 Pick the maximum packet size, which is as good as anything. */
3151 return MAX_PACKET_LENGTH;
3154 static void gdb_chr_receive(void *opaque, const uint8_t *buf, int size)
3156 int i;
3158 for (i = 0; i < size; i++) {
3159 gdb_read_byte(buf[i]);
3163 static void gdb_chr_event(void *opaque, QEMUChrEvent event)
3165 int i;
3166 GDBState *s = (GDBState *) opaque;
3168 switch (event) {
3169 case CHR_EVENT_OPENED:
3170 /* Start with first process attached, others detached */
3171 for (i = 0; i < s->process_num; i++) {
3172 s->processes[i].attached = !i;
3175 s->c_cpu = gdb_first_attached_cpu();
3176 s->g_cpu = s->c_cpu;
3178 vm_stop(RUN_STATE_PAUSED);
3179 gdb_has_xml = false;
3180 break;
3181 default:
3182 break;
3186 static void gdb_monitor_output(const char *msg, int len)
3188 g_autoptr(GString) buf = g_string_new("O");
3189 memtohex(buf, (uint8_t *)msg, len);
3190 put_packet(buf->str);
3193 static int gdb_monitor_write(Chardev *chr, const uint8_t *buf, int len)
3195 const char *p = (const char *)buf;
3196 int max_sz;
3198 max_sz = (sizeof(gdbserver_state.last_packet) - 2) / 2;
3199 for (;;) {
3200 if (len <= max_sz) {
3201 gdb_monitor_output(p, len);
3202 break;
3204 gdb_monitor_output(p, max_sz);
3205 p += max_sz;
3206 len -= max_sz;
3208 return len;
3211 #ifndef _WIN32
3212 static void gdb_sigterm_handler(int signal)
3214 if (runstate_is_running()) {
3215 vm_stop(RUN_STATE_PAUSED);
3218 #endif
3220 static void gdb_monitor_open(Chardev *chr, ChardevBackend *backend,
3221 bool *be_opened, Error **errp)
3223 *be_opened = false;
3226 static void char_gdb_class_init(ObjectClass *oc, void *data)
3228 ChardevClass *cc = CHARDEV_CLASS(oc);
3230 cc->internal = true;
3231 cc->open = gdb_monitor_open;
3232 cc->chr_write = gdb_monitor_write;
3235 #define TYPE_CHARDEV_GDB "chardev-gdb"
3237 static const TypeInfo char_gdb_type_info = {
3238 .name = TYPE_CHARDEV_GDB,
3239 .parent = TYPE_CHARDEV,
3240 .class_init = char_gdb_class_init,
3243 static int find_cpu_clusters(Object *child, void *opaque)
3245 if (object_dynamic_cast(child, TYPE_CPU_CLUSTER)) {
3246 GDBState *s = (GDBState *) opaque;
3247 CPUClusterState *cluster = CPU_CLUSTER(child);
3248 GDBProcess *process;
3250 s->processes = g_renew(GDBProcess, s->processes, ++s->process_num);
3252 process = &s->processes[s->process_num - 1];
3255 * GDB process IDs -1 and 0 are reserved. To avoid subtle errors at
3256 * runtime, we enforce here that the machine does not use a cluster ID
3257 * that would lead to PID 0.
3259 assert(cluster->cluster_id != UINT32_MAX);
3260 process->pid = cluster->cluster_id + 1;
3261 process->attached = false;
3262 process->target_xml[0] = '\0';
3264 return 0;
3267 return object_child_foreach(child, find_cpu_clusters, opaque);
3270 static int pid_order(const void *a, const void *b)
3272 GDBProcess *pa = (GDBProcess *) a;
3273 GDBProcess *pb = (GDBProcess *) b;
3275 if (pa->pid < pb->pid) {
3276 return -1;
3277 } else if (pa->pid > pb->pid) {
3278 return 1;
3279 } else {
3280 return 0;
3284 static void create_processes(GDBState *s)
3286 object_child_foreach(object_get_root(), find_cpu_clusters, s);
3288 if (gdbserver_state.processes) {
3289 /* Sort by PID */
3290 qsort(gdbserver_state.processes, gdbserver_state.process_num, sizeof(gdbserver_state.processes[0]), pid_order);
3293 create_default_process(s);
3296 int gdbserver_start(const char *device)
3298 trace_gdbstub_op_start(device);
3300 char gdbstub_device_name[128];
3301 Chardev *chr = NULL;
3302 Chardev *mon_chr;
3304 if (!first_cpu) {
3305 error_report("gdbstub: meaningless to attach gdb to a "
3306 "machine without any CPU.");
3307 return -1;
3310 if (!device)
3311 return -1;
3312 if (strcmp(device, "none") != 0) {
3313 if (strstart(device, "tcp:", NULL)) {
3314 /* enforce required TCP attributes */
3315 snprintf(gdbstub_device_name, sizeof(gdbstub_device_name),
3316 "%s,nowait,nodelay,server", device);
3317 device = gdbstub_device_name;
3319 #ifndef _WIN32
3320 else if (strcmp(device, "stdio") == 0) {
3321 struct sigaction act;
3323 memset(&act, 0, sizeof(act));
3324 act.sa_handler = gdb_sigterm_handler;
3325 sigaction(SIGINT, &act, NULL);
3327 #endif
3329 * FIXME: it's a bit weird to allow using a mux chardev here
3330 * and implicitly setup a monitor. We may want to break this.
3332 chr = qemu_chr_new_noreplay("gdb", device, true, NULL);
3333 if (!chr)
3334 return -1;
3337 if (!gdbserver_state.init) {
3338 init_gdbserver_state();
3340 qemu_add_vm_change_state_handler(gdb_vm_state_change, NULL);
3342 /* Initialize a monitor terminal for gdb */
3343 mon_chr = qemu_chardev_new(NULL, TYPE_CHARDEV_GDB,
3344 NULL, NULL, &error_abort);
3345 monitor_init_hmp(mon_chr, false, &error_abort);
3346 } else {
3347 qemu_chr_fe_deinit(&gdbserver_state.chr, true);
3348 mon_chr = gdbserver_state.mon_chr;
3349 reset_gdbserver_state();
3352 create_processes(&gdbserver_state);
3354 if (chr) {
3355 qemu_chr_fe_init(&gdbserver_state.chr, chr, &error_abort);
3356 qemu_chr_fe_set_handlers(&gdbserver_state.chr, gdb_chr_can_receive,
3357 gdb_chr_receive, gdb_chr_event,
3358 NULL, &gdbserver_state, NULL, true);
3360 gdbserver_state.state = chr ? RS_IDLE : RS_INACTIVE;
3361 gdbserver_state.mon_chr = mon_chr;
3362 gdbserver_state.current_syscall_cb = NULL;
3364 return 0;
3367 void gdbserver_cleanup(void)
3369 if (gdbserver_state.init) {
3370 put_packet("W00");
3374 static void register_types(void)
3376 type_register_static(&char_gdb_type_info);
3379 type_init(register_types);
3380 #endif